Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Finish architecture boundaries and regression coverage

Bitti0e6173fb1c48
diff --git a/docs/rust-architecture.md b/docs/rust-architecture.md
new file mode 100644
index 0000000..d66c47d
--- /dev/null
+++ b/docs/rust-architecture.md
@@ -0,0 +1,83 @@
+# Rust architecture
+
+The four former files over 1,000 lines (`lib.rs`, `slopfab.rs`, `agent.rs`, and
+`agent_commands.rs`) are split by responsibility. Existing IPC names, project
+JSON, JSONL commands, event payloads, and reference import policies are preserved.
+
+| Area | Responsibilities |
+| --- | --- |
+| `app.rs`, `window.rs`, `commands/` | Tauri setup, window lifecycle, dialogs, IPC and event delivery |
+| `project/` | Document types, compatibility migrations, ordered validation, persistence and lifecycle |
+| `project/commands/` | Restricted command vocabulary, JSONL parsing, transactional batches and domain handlers |
+| `media/`, `storage/` | Format catalog, session access, confined project artifacts and atomic replacement |
+| `agent/` | Turn protocol, correction budget, semantic policy, cancellation and provider discovery |
+| `agent/providers/` | Claude/Codex CLI adapters and compatible HTTP endpoints behind one turn interface |
+| `generation/models/` | Model defaults, capabilities, authoring instructions and shot-setting validation |
+| `slopfab/` | Native runtime configuration, planning, serial generation queue, icons and references |
+| `slopfab/ffi/` | Private ABI bindings, library ownership, handles, callbacks and output access |
+
+## Adding a generation model
+
+1. Define a `ModelDefinition` under `generation/models/` and register its persisted
+ ID in `find`. Specify scene defaults, generation limits, authoring instructions,
+ vocabulary and shot-setting validation. Unknown IDs remain readable data and
+ do not acquire H3 authoring instructions; unregistered documents retain the
+ existing v1 validation limits.
+2. Use `SceneDefaults` with the command batch executor and `GenerationJob::draft`.
+ Individual command handlers do not need model-specific constructors. Existing
+ callers select the default model; a model-selection feature must pass the same
+ selected defaults during both agent validation and command execution.
+3. Implement the engine mapping separately. H3/Animate request construction is
+ in `slopfab/h3.rs`; the queue, cancellation, events, file services and native
+ ownership code are reusable. Registering a profile alone does not add a native
+ engine, model download configuration, or frontend prompt compiler.
+4. Update the frontend's model selection, schema limits and compiler as appropriate.
+ H3's shot vocabulary now has one source in
+ `shared/models/minimax-h3-shot-tags.json`, consumed by both Rust and TypeScript.
+ Preserve the persisted IDs when changing labels or adding options.
+
+Agent transport providers are a separate concern from generation models.
+`AgentProvider::run_turn` gives CLI and HTTP transports the same sanitized project
+context, cancellation flag, deadline and event callback. Provider settings are
+removed from model context; credentials remain in the selected transport session.
+
+## Ownership and compatibility
+
+- `ProjectRoot` checks canonical containment before writing through each directory
+ component. `MediaAccess`, `ProviderDiscovery` and prepared native reference
+ registries belong to application state instead of process-wide registries.
+- Atomic writes create a unique sibling with `create_new`, sync it, replace the
+ destination, and clean up only that owned temporary file on failure.
+- Command batches mutate a clone, collect derived effects, then validate. Missing,
+ null and populated patch fields have explicit `Patch<T>` variants. Validators
+ run in the original normalization/migration order. Correction budgets use
+ structured issue keys, with a per-issue limit and an overall limit.
+- Starting a native generation consumes its request. The generation retains the
+ request, callback and DLL; error cleanup cancels and joins before destruction.
+ Only completed generations can enter the render store. Raw pointers stay in
+ `ffi`, and Rust output snapshots contain owned audio and scalar metadata.
+- Video remains native-owned until encoding finishes; the existing frame-at-a-time
+ RGBA transfer to WebCodecs is preserved. This refactor adds neither a new GPU
+ interop path nor a different decoder/encoder. There is no FFmpeg dependency.
+
+## Verification
+
+Run `cargo test --manifest-path src-tauri/Cargo.toml`, `npm test`, and `npm run build`.
+Native tests exercise the bundled DLL's ABI, planning, reference snapshots and
+handle ownership without loading model weights. They do not verify a full GPU
+render; that requires installed weights and suitable hardware.
+
+Ordinary tests compare serialized documents with committed frontend fixtures and
+do not rewrite them. To deliberately update the wire fixtures in PowerShell:
+
+```powershell
+$env:SLOPUS_UPDATE_FIXTURES = '1'
+try {
+ cargo test --manifest-path src-tauri/Cargo.toml serialized_wire_format_matches_frontend_fixtures
+} finally {
+ Remove-Item Env:SLOPUS_UPDATE_FIXTURES
+}
+npm test
+```
+
+Review the fixture diff before committing any wire-format change.
diff --git a/src-tauri/src/agent/cancellation.rs b/src-tauri/src/agent/cancellation.rs
index ec8c836..5e7fc5c 100644
--- a/src-tauri/src/agent/cancellation.rs
+++ b/src-tauri/src/agent/cancellation.rs
@@ -1,4 +1,10 @@
-use std::{collections::BTreeMap, sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}};
+use std::{
+ collections::BTreeMap,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc, Mutex,
+ },
+};
#[derive(Clone, Default)]
pub(super) struct CancellationRegistry(Arc<Mutex<BTreeMap<String, Arc<AtomicBool>>>>);
@@ -6,15 +12,27 @@ pub(super) struct CancellationRegistry(Arc<Mutex<BTreeMap<String, Arc<AtomicBool
impl CancellationRegistry {
pub(super) fn register(&self, id: &str) -> Result<RunningTurn, String> {
let mut running = self.0.lock().map_err(|_| "Agent runtime lock failed.")?;
- if running.contains_key(id) { return Err("This agent request is already running.".into()); }
+ if running.contains_key(id) {
+ return Err("This agent request is already running.".into());
+ }
let flag = Arc::new(AtomicBool::new(false));
running.insert(id.to_owned(), flag.clone());
- Ok(RunningTurn { registry: self.clone(), id: id.to_owned(), flag })
+ Ok(RunningTurn {
+ registry: self.clone(),
+ id: id.to_owned(),
+ flag,
+ })
}
pub(super) fn cancel(&self, id: &str) -> bool {
- self.0.lock().ok().and_then(|running| running.get(id).cloned())
- .is_some_and(|flag| { flag.store(true, Ordering::Release); true })
+ self.0
+ .lock()
+ .ok()
+ .and_then(|running| running.get(id).cloned())
+ .is_some_and(|flag| {
+ flag.store(true, Ordering::Release);
+ true
+ })
}
}
@@ -26,7 +44,11 @@ pub(super) struct RunningTurn {
impl Drop for RunningTurn {
fn drop(&mut self) {
- let mut running = self.registry.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ let mut running = self
+ .registry
+ .0
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
running.remove(&self.id);
}
}
diff --git a/src-tauri/src/agent/discovery.rs b/src-tauri/src/agent/discovery.rs
index 732294d..2fc2f54 100644
--- a/src-tauri/src/agent/discovery.rs
+++ b/src-tauri/src/agent/discovery.rs
@@ -1,7 +1,17 @@
use super::types::*;
+use super::{
+ process::probe_command, providers::compatible::compatible_setting_is_configured,
+ providers::options::*, providers::*,
+};
use crate::project::*;
-use std::{collections::BTreeMap, env, ffi::OsString, path::{Path, PathBuf}, sync::Mutex, time::{Duration, Instant}};
-use super::{providers::*, providers::compatible::compatible_setting_is_configured, process::probe_command, providers::options::*};
+use std::{
+ collections::BTreeMap,
+ env,
+ ffi::OsString,
+ path::{Path, PathBuf},
+ sync::Mutex,
+ time::{Duration, Instant},
+};
/// The last answer the probe sweep gave, kept so it is not paid for twice.
///
/// One sweep is four child processes — a version check and an auth check per
@@ -19,7 +29,9 @@ pub(super) struct CachedProbe {
}
#[derive(Clone, Default)]
-pub(crate) struct ProviderDiscovery { cache: std::sync::Arc<Mutex<Option<CachedProbe>>> }
+pub(crate) struct ProviderDiscovery {
+ cache: std::sync::Arc<Mutex<Option<CachedProbe>>>,
+}
pub(super) const PROVIDER_PROBE_TTL: Duration = Duration::from_secs(120);
/// What the answer depends on: the settings for the agent CLIs themselves.
@@ -67,7 +79,10 @@ where
statuses
}
-pub fn provider_statuses(discovery: &ProviderDiscovery, settings: &BTreeMap<String, ProviderSetting>) -> Vec<ProviderStatus> {
+pub fn provider_statuses(
+ discovery: &ProviderDiscovery,
+ settings: &BTreeMap<String, ProviderSetting>,
+) -> Vec<ProviderStatus> {
let mut statuses = cached_or_probe(
&discovery.cache,
provider_probe_key(settings),
@@ -95,7 +110,9 @@ pub fn provider_statuses(discovery: &ProviderDiscovery, settings: &BTreeMap<Stri
statuses
}
-pub(super) fn probe_provider_statuses(settings: &BTreeMap<String, ProviderSetting>) -> Vec<ProviderStatus> {
+pub(super) fn probe_provider_statuses(
+ settings: &BTreeMap<String, ProviderSetting>,
+) -> Vec<ProviderStatus> {
[ProviderId::Claude, ProviderId::Codex]
.into_iter()
.map(|id| {
@@ -181,9 +198,14 @@ pub(super) fn confined_project_root(folder: &Path) -> Result<PathBuf, String> {
// and a third-party CLI has no reason to understand the verbatim form. The
// rest of the app already reports project folders through `display_path`,
// so the agent hands the CLIs the same spelling the user sees.
- Ok(PathBuf::from(crate::project::paths::display_path(&canonical)))
+ Ok(PathBuf::from(crate::project::paths::display_path(
+ &canonical,
+ )))
}
-pub(super) fn discover_executable(name: &str, setting: Option<&ProviderSetting>) -> Option<PathBuf> {
+pub(super) fn discover_executable(
+ name: &str,
+ setting: Option<&ProviderSetting>,
+) -> Option<PathBuf> {
if let Some(configured) = setting.and_then(|value| option_string(value, "executable")) {
let path = PathBuf::from(configured);
#[cfg(windows)]
diff --git a/src-tauri/src/agent/mod.rs b/src-tauri/src/agent/mod.rs
index 96b6d80..7c57c67 100644
--- a/src-tauri/src/agent/mod.rs
+++ b/src-tauri/src/agent/mod.rs
@@ -1,18 +1,20 @@
//! Agent turn orchestration; provider transports never mutate the project.
-mod types;
-mod runtime;
mod cancellation;
mod discovery;
-mod prompt;
mod policy;
-mod protocol;
mod process;
-mod retry;
+mod prompt;
+mod protocol;
mod providers;
-pub(crate) use types::*;
-pub(crate) use runtime::AgentRuntime;
+mod retry;
+mod runtime;
+mod types;
pub(crate) use discovery::{provider_statuses, ProviderDiscovery};
-pub(crate) use providers::compatible::compatible_models;
pub(crate) use policy::validate_agent_scene_conventions;
+pub(crate) use providers::compatible::compatible_models;
+pub(crate) use runtime::AgentRuntime;
+pub(crate) use types::*;
#[cfg(test)]
mod tests;
+#[cfg(test)]
+mod tests_transport;
diff --git a/src-tauri/src/agent/policy.rs b/src-tauri/src/agent/policy.rs
index 6a6fa7e..67580b3 100644
--- a/src-tauri/src/agent/policy.rs
+++ b/src-tauri/src/agent/policy.rs
@@ -1,6 +1,7 @@
+use crate::project::reference_tokens::action_reference_ids;
+use crate::project::validation::issue::ValidationIssue;
use crate::project::*;
use std::collections::BTreeSet;
-use crate::project::reference_tokens::action_reference_ids;
/** Agent-only semantic checks. The project validator intentionally permits
* blank references and free-form action text because the editor must be able
@@ -12,6 +13,13 @@ pub(crate) fn validate_agent_scene_conventions(
before: &ProjectConfig,
next: &ProjectConfig,
) -> Result<(), String> {
+ validate_scene_policy(before, next).map_err(|issue| issue.message)
+}
+
+pub(super) fn validate_scene_policy(
+ before: &ProjectConfig,
+ next: &ProjectConfig,
+) -> Result<(), ValidationIssue> {
let new_reference_ids = next
.references
.iter()
@@ -30,10 +38,10 @@ pub(crate) fn validate_agent_scene_conventions(
.filter(|reference| new_reference_ids.contains(reference.id.as_str()))
{
if reference.kind != "text" {
- return Err(format!(
+ return Err(ValidationIssue::new("reference.kind", Some(reference.id.clone()), "kind", format!(
"Agent-created reference '{}' must be a text reference. Do not invent a file-backed reference or file path.",
reference.id
- ));
+ )));
}
let definition = reference
.content
@@ -41,16 +49,16 @@ pub(crate) fn validate_agent_scene_conventions(
.filter(|value| !value.trim().is_empty())
.unwrap_or(reference.description.as_str());
if definition.trim().is_empty() {
- return Err(format!(
+ return Err(ValidationIssue::new("reference.description", Some(reference.id.clone()), "description", format!(
"Agent-created reference '{}' needs a complete visual description before it is used in shots.",
reference.id
- ));
+ )));
}
if reference.intended_use.is_empty() {
- return Err(format!(
+ return Err(ValidationIssue::new("reference.usage", Some(reference.id.clone()), "intendedUse", format!(
"Agent-created reference '{}' needs an intendedUse such as character, animal, location, or product.",
reference.id
- ));
+ )));
}
}
@@ -70,18 +78,33 @@ pub(crate) fn validate_agent_scene_conventions(
};
changed_scene = true;
let model = crate::generation::models::for_scene(job.provider_id.as_deref());
- let duration = job.duration_seconds.unwrap_or_else(|| model.unwrap_or_else(crate::generation::models::default_model).defaults.duration_seconds);
+ let duration = job.duration_seconds.unwrap_or_else(|| {
+ model
+ .unwrap_or_else(crate::generation::models::default_model)
+ .defaults
+ .duration_seconds
+ });
if shots.first().is_none_or(|shot| shot.start_seconds != 0.0) {
- return Err(format!(
- "Scene '{}' must have a first shot that starts at 0 seconds.",
- job.id
+ return Err(ValidationIssue::new(
+ "scene.first_shot",
+ Some(job.id.clone()),
+ "shots",
+ format!(
+ "Scene '{}' must have a first shot that starts at 0 seconds.",
+ job.id
+ ),
));
}
for pair in shots.windows(2) {
if pair[1].start_seconds <= pair[0].start_seconds {
- return Err(format!(
- "Shot '{}' in scene '{}' must start after the preceding shot.",
- pair[1].id, job.id
+ return Err(ValidationIssue::new(
+ "shot.order",
+ Some(pair[1].id.clone()),
+ "startSeconds",
+ format!(
+ "Shot '{}' in scene '{}' must start after the preceding shot.",
+ pair[1].id, job.id
+ ),
));
}
}
@@ -90,9 +113,14 @@ pub(crate) fn validate_agent_scene_conventions(
.skip(1)
.find(|shot| shot.start_seconds >= duration)
{
- return Err(format!(
+ return Err(ValidationIssue::new(
+ "shot.range",
+ Some(shot.id.clone()),
+ "startSeconds",
+ format!(
"Shot '{}' in scene '{}' must start before the scene ends at {duration} seconds.",
shot.id, job.id
+ ),
));
}
let earliest_shot_id = shots
@@ -104,12 +132,23 @@ pub(crate) fn validate_agent_scene_conventions(
let before_shot = before_job
.and_then(|existing| existing.shots.as_ref())
.and_then(|existing| existing.iter().find(|candidate| candidate.id == shot.id));
- if let Some(model) = model { (model.validate_shot_settings)(before_shot, shot, earliest_shot_id)?; }
+ if let Some(model) = model {
+ (model.validate_shot_settings)(before_shot, shot, earliest_shot_id).map_err(
+ |message| {
+ ValidationIssue::new(
+ "shot.settings",
+ Some(shot.id.clone()),
+ "settings",
+ message,
+ )
+ },
+ )?;
+ }
if action_contains_dialogue(&shot.action) {
- return Err(format!(
+ return Err(ValidationIssue::new("shot.dialogue", Some(shot.id.clone()), "action", format!(
"Shot '{}' in scene '{}' contains dialogue in action. Keep action visual-only and move the exact spoken words into shot.speech with shot.speechLanguage.",
shot.id, job.id
- ));
+ )));
}
if shot
.speech
@@ -117,27 +156,29 @@ pub(crate) fn validate_agent_scene_conventions(
.is_some_and(|speech| !speech.trim().is_empty())
&& shot.speech_language.is_none()
{
- return Err(format!(
+ return Err(ValidationIssue::new("shot.language", Some(shot.id.clone()), "speechLanguage", format!(
"Shot '{}' in scene '{}' has speech but no speechLanguage. Keep the spoken line in shot.speech and set its language.",
shot.id, job.id
- ));
+ )));
}
- for reference_id in action_reference_ids(&shot.action)? {
+ for reference_id in action_reference_ids(&shot.action).map_err(|message| {
+ ValidationIssue::new("shot.citation", Some(shot.id.clone()), "action", message)
+ })? {
let reference = next
.references
.iter()
.find(|reference| reference.id == reference_id)
.ok_or_else(|| {
- format!(
+ ValidationIssue::new("shot.unknown_reference", Some(shot.id.clone()), "action", format!(
"Shot '{}' cites unknown reference '{}'. Create the reference first or remove the citation.",
shot.id, reference_id
- )
+ ))
})?;
if !job.reference_ids.iter().any(|id| id == reference_id) {
- return Err(format!(
+ return Err(ValidationIssue::new("shot.binding", Some(shot.id.clone()), "referenceIds", format!(
"Shot '{}' cites reference '{}', but scene '{}' does not include it in referenceIds.",
shot.id, reference_id, job.id
- ));
+ )));
}
if reference.kind == "text"
&& reference.images.is_empty()
@@ -147,10 +188,10 @@ pub(crate) fn validate_agent_scene_conventions(
.as_deref()
.is_none_or(|content| content.trim().is_empty())
{
- return Err(format!(
+ return Err(ValidationIssue::new("reference.description", Some(reference.id.clone()), "description", format!(
"Shot '{}' cites text reference '{}', but that reference has no visual description.",
shot.id, reference_id
- ));
+ )));
}
if new_reference_ids.contains(reference_id) {
cited_new_references.insert(reference_id);
@@ -162,23 +203,24 @@ pub(crate) fn validate_agent_scene_conventions(
if changed_scene {
for reference in next.references.iter().filter(|reference| {
new_reference_ids.contains(reference.id.as_str())
- && reference
- .intended_use
- .iter()
- .any(|usage| matches!(usage.as_str(), "character" | "animal" | "location" | "product"))
+ && reference.intended_use.iter().any(|usage| {
+ matches!(
+ usage.as_str(),
+ "character" | "animal" | "location" | "product"
+ )
+ })
}) {
if !cited_new_references.contains(reference.id.as_str()) {
- return Err(format!(
+ return Err(ValidationIssue::new("reference.uncited", Some(reference.id.clone()), "action", format!(
"Agent-created {} reference '{}' is not used by any changed shot. Cite it in shot.action as '@[ref:{}]' and include it in the scene's referenceIds.",
reference.intended_use[0], reference.id, reference.id
- ));
+ )));
}
}
}
Ok(())
}
-
fn action_contains_dialogue(action: &str) -> bool {
let lower = action.to_lowercase();
if [
diff --git a/src-tauri/src/agent/process.rs b/src-tauri/src/agent/process.rs
index 54a85b3..90cd674 100644
--- a/src-tauri/src/agent/process.rs
+++ b/src-tauri/src/agent/process.rs
@@ -1,8 +1,19 @@
+use super::providers::output::{extract_provider_output, structured_failure};
use super::types::*;
-use std::{ffi::OsString, io::{BufRead, BufReader, Write}, path::{Path, PathBuf}, process::{Command, Stdio}, sync::{atomic::{AtomicBool, Ordering}, mpsc, Arc}, thread, time::{Duration, Instant}};
-use super::providers::output::{structured_failure, extract_provider_output};
#[cfg(windows)]
use std::os::windows::process::CommandExt;
+use std::{
+ ffi::OsString,
+ io::{BufRead, BufReader, Write},
+ path::{Path, PathBuf},
+ process::{Command, Stdio},
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ mpsc, Arc,
+ },
+ thread,
+ time::{Duration, Instant},
+};
pub(super) struct CommandSpec {
pub(crate) executable: PathBuf,
pub(crate) args: Vec<OsString>,
@@ -39,21 +50,25 @@ pub(super) fn run_subprocess(
timeout: Duration,
on_event: &dyn Fn(&AgentEvent),
) -> Result<(Vec<AgentEvent>, String), String> {
- if cancel.load(Ordering::Acquire) { return Err("Agent turn cancelled.".into()); }
+ if cancel.load(Ordering::Acquire) {
+ return Err("Agent turn cancelled.".into());
+ }
let started = Instant::now();
let has_stdin_payload = spec.stdin_payload.is_some();
- let mut child = ChildGuard(Some(quiet_command(&spec.executable)
- .args(&spec.args)
- .current_dir(&spec.current_dir)
- .stdin(if has_stdin_payload {
- Stdio::piped()
- } else {
- Stdio::null()
- })
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- .map_err(|error| format!("Could not start agent provider: {error}"))?));
+ let mut child = ChildGuard(Some(
+ quiet_command(&spec.executable)
+ .args(&spec.args)
+ .current_dir(&spec.current_dir)
+ .stdin(if has_stdin_payload {
+ Stdio::piped()
+ } else {
+ Stdio::null()
+ })
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|error| format!("Could not start agent provider: {error}"))?,
+ ));
let (sender, receiver) = mpsc::channel::<(bool, String)>();
let stdout_sender = sender.clone();
let stdout = child.stdout.take().expect("configured child stdout");
@@ -73,7 +88,9 @@ pub(super) fn run_subprocess(
let (input_tx, input_rx) = mpsc::channel();
if let Some(payload) = spec.stdin_payload {
let mut stdin = child.stdin.take().expect("configured child stdin");
- thread::spawn(move || { let _ = input_tx.send(stdin.write_all(payload.as_bytes())); });
+ thread::spawn(move || {
+ let _ = input_tx.send(stdin.write_all(payload.as_bytes()));
+ });
}
let mut lines = Vec::new();
@@ -81,7 +98,9 @@ pub(super) fn run_subprocess(
on_event(&started_event);
let mut events = vec![started_event];
let status = loop {
- if let Ok(Err(error)) = input_rx.try_recv() { return Err(format!("Could not send request to agent provider: {error}")); }
+ if let Ok(Err(error)) = input_rx.try_recv() {
+ return Err(format!("Could not send request to agent provider: {error}"));
+ }
while let Ok((stderr, line)) = receiver.try_recv() {
if stderr {
if is_benign_provider_diagnostic(provider, &line) {
@@ -156,30 +175,56 @@ pub(super) fn run_subprocess(
let output = extract_provider_output(&lines)?;
Ok((events, output))
}
-pub(super) fn probe_command(executable: &Path, args: &[&str], timeout: Duration) -> Result<String, String> {
- let mut child = ChildGuard(Some(quiet_command(executable)
- .args(args)
- .stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- .map_err(|error| format!("Could not launch provider: {error}"))?));
+pub(super) fn probe_command(
+ executable: &Path,
+ args: &[&str],
+ timeout: Duration,
+) -> Result<String, String> {
+ let mut child = ChildGuard(Some(
+ quiet_command(executable)
+ .args(args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|error| format!("Could not launch provider: {error}"))?,
+ ));
let start = Instant::now();
+ // Drain both pipes while the child runs. Waiting before reading can fill a
+ // pipe and deadlock even a successful version/authentication probe.
+ let (sender, receiver) = mpsc::channel();
+ drain_probe_pipe(
+ child.stdout.take().expect("configured stdout"),
+ false,
+ sender.clone(),
+ );
+ drain_probe_pipe(
+ child.stderr.take().expect("configured stderr"),
+ true,
+ sender,
+ );
+ let mut status = None;
+ let mut stdout = None;
+ let mut stderr = None;
loop {
- if let Some(status) = child
- .try_wait()
- .map_err(|error| format!("Could not inspect provider: {error}"))?
- {
- let output = child.0.take().expect("owned child")
- .wait_with_output()
- .map_err(|error| format!("Could not read provider version: {error}"))?;
- let text = String::from_utf8_lossy(if output.stdout.is_empty() {
- &output.stderr
+ if status.is_none() {
+ status = child
+ .try_wait()
+ .map_err(|error| format!("Could not inspect provider: {error}"))?;
+ }
+ while let Ok((is_stderr, bytes)) = receiver.try_recv() {
+ let bytes =
+ bytes.map_err(|error| format!("Could not read provider version: {error}"))?;
+ if is_stderr {
+ stderr = Some(bytes);
} else {
- &output.stdout
- })
- .trim()
- .to_string();
+ stdout = Some(bytes);
+ }
+ }
+ if let (Some(status), Some(stdout), Some(stderr)) = (&status, &stdout, &stderr) {
+ let text = String::from_utf8_lossy(if stdout.is_empty() { stderr } else { stdout })
+ .trim()
+ .to_string();
return status
.success()
.then_some(text)
@@ -194,10 +239,50 @@ pub(super) fn probe_command(executable: &Path, args: &[&str], timeout: Duration)
}
}
+fn drain_probe_pipe(
+ mut pipe: impl std::io::Read + Send + 'static,
+ is_stderr: bool,
+ sender: mpsc::Sender<(bool, std::io::Result<Vec<u8>>)>,
+) {
+ thread::spawn(move || {
+ let result = (|| {
+ let mut bytes = Vec::new();
+ let mut buffer = [0_u8; 4096];
+ loop {
+ let count = pipe.read(&mut buffer)?;
+ if count == 0 {
+ break;
+ }
+ // Keep a bounded diagnostic, but drain all remaining bytes.
+ let keep = count.min(65_536_usize.saturating_sub(bytes.len()));
+ bytes.extend_from_slice(&buffer[..keep]);
+ }
+ Ok(bytes)
+ })();
+ let _ = sender.send((is_stderr, result));
+ });
+}
+
/// Every error path reaps the child, including I/O inspection failures.
struct ChildGuard(Option<std::process::Child>);
-impl std::ops::Deref for ChildGuard { type Target = std::process::Child; fn deref(&self) -> &Self::Target { self.0.as_ref().expect("owned child") } }
-impl std::ops::DerefMut for ChildGuard { fn deref_mut(&mut self) -> &mut Self::Target { self.0.as_mut().expect("owned child") } }
+impl std::ops::Deref for ChildGuard {
+ type Target = std::process::Child;
+ fn deref(&self) -> &Self::Target {
+ self.0.as_ref().expect("owned child")
+ }
+}
+impl std::ops::DerefMut for ChildGuard {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ self.0.as_mut().expect("owned child")
+ }
+}
impl Drop for ChildGuard {
- fn drop(&mut self) { if let Some(child) = &mut self.0 { if !matches!(child.try_wait(), Ok(Some(_))) { let _ = child.kill(); } let _ = child.wait(); } }
+ fn drop(&mut self) {
+ if let Some(child) = &mut self.0 {
+ if !matches!(child.try_wait(), Ok(Some(_))) {
+ let _ = child.kill();
+ }
+ let _ = child.wait();
+ }
+ }
}
diff --git a/src-tauri/src/agent/prompt.rs b/src-tauri/src/agent/prompt.rs
index a06655f..68db59b 100644
--- a/src-tauri/src/agent/prompt.rs
+++ b/src-tauri/src/agent/prompt.rs
@@ -5,7 +5,10 @@ pub(super) fn full_agent_system_prompt() -> String {
}
pub(super) fn system_prompt_for(model: &crate::generation::models::ModelDefinition) -> String {
let catalog = (model.shot_catalog)();
- format!("{AGENT_SYSTEM_PROMPT}\n\n{}\n\nSupported shot.settings catalog:\n{catalog}", model.agent_instructions)
+ format!(
+ "{AGENT_SYSTEM_PROMPT}\n\n{}\n\nSupported shot.settings catalog:\n{catalog}",
+ model.agent_instructions
+ )
}
pub(super) fn context_prompt(config: &ProjectConfig, prompt: &str) -> Result<String, String> {
let conversation = serde_json::to_string(&config.agent_conversation.messages)
@@ -24,12 +27,26 @@ pub(super) fn context_prompt(config: &ProjectConfig, prompt: &str) -> Result<Str
/// project gets the default policy; unknown persisted models remain inert data.
pub(super) fn project_system_prompt(config: &ProjectConfig) -> String {
let mut ids = std::collections::BTreeSet::new();
- let models: Vec<_> = config.generation_jobs.iter()
+ let models: Vec<_> = config
+ .generation_jobs
+ .iter()
.filter_map(|job| crate::generation::models::for_scene(job.provider_id.as_deref()))
.filter(|model| ids.insert(model.defaults.provider_id))
.collect();
- if models.is_empty() && config.generation_jobs.is_empty() { return full_agent_system_prompt(); }
- let policies = models.into_iter().map(|model| format!("Model {}:\n{}\nSupported shot.settings catalog:\n{}",
- model.defaults.provider_id, model.agent_instructions, (model.shot_catalog)())).collect::<Vec<_>>().join("\n\n");
+ if models.is_empty() && config.generation_jobs.is_empty() {
+ return full_agent_system_prompt();
+ }
+ let policies = models
+ .into_iter()
+ .map(|model| {
+ format!(
+ "Model {}:\n{}\nSupported shot.settings catalog:\n{}",
+ model.defaults.provider_id,
+ model.agent_instructions,
+ (model.shot_catalog)()
+ )
+ })
+ .collect::<Vec<_>>()
+ .join("\n\n");
format!("{AGENT_SYSTEM_PROMPT}\n\n{policies}")
}
diff --git a/src-tauri/src/agent/providers/claude.rs b/src-tauri/src/agent/providers/claude.rs
index 2db1f7b..2c9ab63 100644
--- a/src-tauri/src/agent/providers/claude.rs
+++ b/src-tauri/src/agent/providers/claude.rs
@@ -1,7 +1,7 @@
+use super::super::{process::CommandSpec, prompt::*};
+use super::{ClaudeProvider, CliProvider};
use crate::project::*;
use std::path::Path;
-use super::{CliProvider, ClaudeProvider};
-use super::super::{prompt::*, process::CommandSpec};
impl CliProvider for ClaudeProvider {
fn label(&self) -> &'static str {
"Claude Code"
diff --git a/src-tauri/src/agent/providers/codex.rs b/src-tauri/src/agent/providers/codex.rs
index 1fe44a1..a57ef9d 100644
--- a/src-tauri/src/agent/providers/codex.rs
+++ b/src-tauri/src/agent/providers/codex.rs
@@ -1,7 +1,7 @@
+use super::super::{process::CommandSpec, prompt::*};
+use super::{CliProvider, CodexProvider};
use crate::project::*;
use std::{ffi::OsString, path::Path};
-use super::{CliProvider, CodexProvider};
-use super::super::{prompt::*, process::CommandSpec};
impl CliProvider for CodexProvider {
fn label(&self) -> &'static str {
"Codex"
diff --git a/src-tauri/src/agent/providers/compatible.rs b/src-tauri/src/agent/providers/compatible.rs
index 0531f50..3a6979f 100644
--- a/src-tauri/src/agent/providers/compatible.rs
+++ b/src-tauri/src/agent/providers/compatible.rs
@@ -1,10 +1,19 @@
+use super::super::prompt::*;
use super::super::types::*;
+use super::options::*;
use crate::project::*;
use serde_json::Value;
-use std::{sync::{atomic::{AtomicBool, Ordering}, Arc}, time::Duration};
-use super::options::*;
-use super::super::prompt::*;
-pub(in crate::agent) fn compatible_setting_is_configured(id: ProviderId, setting: &ProviderSetting) -> bool {
+use std::{
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
+ time::Duration,
+};
+pub(in crate::agent) fn compatible_setting_is_configured(
+ id: ProviderId,
+ setting: &ProviderSetting,
+) -> bool {
setting.enabled
&& setting
.model
@@ -33,7 +42,10 @@ pub(in crate::agent) fn validate_compatible_setting(
Ok(())
}
-pub(in crate::agent) fn compatible_resource_url(setting: &ProviderSetting, resource: &str) -> Result<String, String> {
+pub(in crate::agent) fn compatible_resource_url(
+ setting: &ProviderSetting,
+ resource: &str,
+) -> Result<String, String> {
let endpoint = option_string(setting, "endpoint")
.map(str::trim)
.filter(|value| !value.is_empty())
@@ -51,7 +63,9 @@ pub(in crate::agent) fn compatible_resource_url(setting: &ProviderSetting, resou
Ok(url)
}
-pub(in crate::agent) fn compatible_client(timeout: Duration) -> Result<reqwest::blocking::Client, String> {
+pub(in crate::agent) fn compatible_client(
+ timeout: Duration,
+) -> Result<reqwest::blocking::Client, String> {
reqwest::blocking::Client::builder()
.timeout(timeout)
.user_agent("Slopus/0.1")
@@ -72,7 +86,11 @@ pub(in crate::agent) fn with_compatible_auth(
}
}
-pub(in crate::agent) fn compatible_http_error(label: &str, status: reqwest::StatusCode, body: &str) -> String {
+pub(in crate::agent) fn compatible_http_error(
+ label: &str,
+ status: reqwest::StatusCode,
+ body: &str,
+) -> String {
let detail = serde_json::from_str::<Value>(body)
.ok()
.and_then(|value| {
@@ -144,13 +162,22 @@ pub(in crate::agent) fn run_compatible_endpoint(
.as_deref()
.expect("compatible setting validated");
let body = compatible_chat_body(config, prompt, model)?;
- let client = reqwest::Client::builder().timeout(timeout).user_agent("Slopus/0.1")
- .build().map_err(|error| error.to_string())?;
+ let client = reqwest::Client::builder()
+ .timeout(timeout)
+ .user_agent("Slopus/0.1")
+ .build()
+ .map_err(|error| error.to_string())?;
let mut request = client.post(url).json(&body);
- if let Some(key) = option_string(setting, "apiKey").map(str::trim).filter(|key| !key.is_empty()) {
+ if let Some(key) = option_string(setting, "apiKey")
+ .map(str::trim)
+ .filter(|key| !key.is_empty())
+ {
request = request.bearer_auth(key);
}
- let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|error| error.to_string())?;
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .map_err(|error| error.to_string())?;
let (status, response_body) = runtime.block_on(async {
tokio::select! {
response = async {
diff --git a/src-tauri/src/agent/providers/options.rs b/src-tauri/src/agent/providers/options.rs
index 1b47706..345778e 100644
--- a/src-tauri/src/agent/providers/options.rs
+++ b/src-tauri/src/agent/providers/options.rs
@@ -1,5 +1,8 @@
-use crate::project::{ProviderSetting, ProviderOption};
-pub(in crate::agent) fn option_string<'a>(setting: &'a ProviderSetting, key: &str) -> Option<&'a str> {
+use crate::project::{ProviderOption, ProviderSetting};
+pub(in crate::agent) fn option_string<'a>(
+ setting: &'a ProviderSetting,
+ key: &str,
+) -> Option<&'a str> {
match setting.options.get(key) {
Some(ProviderOption::String(value)) => Some(value),
_ => None,
diff --git a/src-tauri/src/agent/providers/session.rs b/src-tauri/src/agent/providers/session.rs
index 550cfc5..a55e51d 100644
--- a/src-tauri/src/agent/providers/session.rs
+++ b/src-tauri/src/agent/providers/session.rs
@@ -1,7 +1,19 @@
-use super::{CliProvider, cli_provider_for, compatible::{run_compatible_endpoint, validate_compatible_setting}};
+use super::{
+ cli_provider_for,
+ compatible::{run_compatible_endpoint, validate_compatible_setting},
+ CliProvider,
+};
+use crate::agent::{
+ discovery::discover_executable,
+ process::run_subprocess,
+ types::{AgentEvent, ProviderId},
+};
use crate::project::{ProjectConfig, ProviderSetting};
-use crate::agent::{types::{AgentEvent, ProviderId}, discovery::discover_executable, process::run_subprocess};
-use std::{path::{Path, PathBuf}, sync::{Arc, atomic::AtomicBool}, time::Duration};
+use std::{
+ path::{Path, PathBuf},
+ sync::{atomic::AtomicBool, Arc},
+ time::Duration,
+};
pub(in crate::agent) struct TurnInput<'a> {
pub root: &'a Path,
@@ -26,25 +38,59 @@ struct CliSession {
}
impl AgentProvider for CliSession {
fn run_turn(&self, input: TurnInput<'_>) -> Result<(Vec<AgentEvent>, String), String> {
- let spec = self.provider.command_spec(input.root, &self.executable, input.config, input.prompt, self.setting.as_ref())?;
- run_subprocess(spec, self.id, input.cancellation, input.timeout, input.on_event)
+ let spec = self.provider.command_spec(
+ input.root,
+ &self.executable,
+ input.config,
+ input.prompt,
+ self.setting.as_ref(),
+ )?;
+ run_subprocess(
+ spec,
+ self.id,
+ input.cancellation,
+ input.timeout,
+ input.on_event,
+ )
}
}
-struct EndpointSession { id: ProviderId, setting: ProviderSetting }
+struct EndpointSession {
+ id: ProviderId,
+ setting: ProviderSetting,
+}
impl AgentProvider for EndpointSession {
fn run_turn(&self, input: TurnInput<'_>) -> Result<(Vec<AgentEvent>, String), String> {
- run_compatible_endpoint(self.id, input.config, input.prompt, &self.setting, input.cancellation, input.timeout, input.on_event)
+ run_compatible_endpoint(
+ self.id,
+ input.config,
+ input.prompt,
+ &self.setting,
+ input.cancellation,
+ input.timeout,
+ input.on_event,
+ )
}
}
-pub(in crate::agent) fn prepare(id: ProviderId, setting: Option<ProviderSetting>) -> Result<Box<dyn AgentProvider>, String> {
+pub(in crate::agent) fn prepare(
+ id: ProviderId,
+ setting: Option<ProviderSetting>,
+) -> Result<Box<dyn AgentProvider>, String> {
if let Some(provider) = cli_provider_for(id) {
let executable = discover_executable(provider.executable_name(), setting.as_ref())
.ok_or_else(|| format!("{} is not installed or is not on PATH.", provider.label()))?;
- Ok(Box::new(CliSession { id, provider, executable, setting }))
+ Ok(Box::new(CliSession {
+ id,
+ provider,
+ executable,
+ setting,
+ }))
} else {
validate_compatible_setting(id, setting.as_ref())?;
- Ok(Box::new(EndpointSession { id, setting: setting.expect("validated endpoint settings") }))
+ Ok(Box::new(EndpointSession {
+ id,
+ setting: setting.expect("validated endpoint settings"),
+ }))
}
}
diff --git a/src-tauri/src/agent/retry.rs b/src-tauri/src/agent/retry.rs
index feff021..e523a5c 100644
--- a/src-tauri/src/agent/retry.rs
+++ b/src-tauri/src/agent/retry.rs
@@ -8,9 +8,16 @@ pub(super) struct RetryBudget {
total: usize,
}
impl RetryBudget {
- pub(super) fn correction(&mut self, issue: &crate::project::validation::issue::ValidationIssue) -> Result<usize, String> {
- if self.previous.as_ref() == Some(&issue.key) { self.round += 1; }
- else { self.previous = Some(issue.key.clone()); self.round = 1; }
+ pub(super) fn correction(
+ &mut self,
+ issue: &crate::project::validation::issue::ValidationIssue,
+ ) -> Result<usize, String> {
+ if self.previous.as_ref() == Some(&issue.key) {
+ self.round += 1;
+ } else {
+ self.previous = Some(issue.key.clone());
+ self.round = 1;
+ }
if self.round > MAX_RETRIES_PER_VALIDATION_ISSUE {
return Err(format!("Slop stopped after {MAX_RETRIES_PER_VALIDATION_ISSUE} correction rounds because the validator kept reporting the same failure: {issue}"));
}
@@ -30,14 +37,41 @@ mod tests {
fn changed_wording_does_not_reset_the_same_issue_budget() {
let mut budget = RetryBudget::default();
for round in 1..=3 {
- let issue = ValidationIssue::new("scene.invalid", Some("scene-1".into()), "duration", format!("Bad value {round}"));
+ let issue = ValidationIssue::new(
+ "scene.invalid",
+ Some("scene-1".into()),
+ "duration",
+ format!("Bad value {round}"),
+ );
assert_eq!(budget.correction(&issue).unwrap(), round);
}
- assert!(budget.correction(&ValidationIssue::new("scene.invalid", Some("scene-1".into()), "duration", "Different wording".into())).is_err());
- assert_eq!(budget.correction(&ValidationIssue::new("scene.invalid", Some("scene-1".into()), "references", "Missing reference".into())).unwrap(), 1);
+ assert!(budget
+ .correction(&ValidationIssue::new(
+ "scene.invalid",
+ Some("scene-1".into()),
+ "duration",
+ "Different wording".into()
+ ))
+ .is_err());
+ assert_eq!(
+ budget
+ .correction(&ValidationIssue::new(
+ "scene.invalid",
+ Some("scene-1".into()),
+ "references",
+ "Missing reference".into()
+ ))
+ .unwrap(),
+ 1
+ );
}
}
-pub(super) fn validation_retry_prompt(original: &str, previous: &str, failure: &str, round: usize) -> String {
+pub(super) fn validation_retry_prompt(
+ original: &str,
+ previous: &str,
+ failure: &str,
+ round: usize,
+) -> String {
format!(
"Your previous response was rejected by Slopus's project validator. Correction round {round} of {MAX_RETRIES_PER_VALIDATION_ISSUE} for this issue.\n\nValidator failure:\n<validator-error>\n{failure}\n</validator-error>\n\nOriginal user request:\n<original-request>\n{original}\n</original-request>\n\nRejected response:\n<rejected-response>\n{previous}\n</rejected-response>\n\nFix the validator failure while preserving the user's intent. Return the complete answer/question object or complete JSONL command stream again, using exactly the required turn contract."
)
diff --git a/src-tauri/src/agent/runtime.rs b/src-tauri/src/agent/runtime.rs
index 328841f..709391b 100644
--- a/src-tauri/src/agent/runtime.rs
+++ b/src-tauri/src/agent/runtime.rs
@@ -1,12 +1,12 @@
use super::cancellation::CancellationRegistry;
-use super::providers::session::{self, TurnInput};
use super::providers::options::*;
+use super::providers::session::{self, TurnInput};
use super::types::*;
-use crate::project::{*, validation::validate_and_normalize_config};
+use super::{discovery::*, policy::*, protocol::*, retry::*};
use crate::project::commands::execute_checked;
use crate::project::validation::issue::ValidationIssue;
+use crate::project::{validation::validate_and_normalize_config, *};
use std::{path::Path, time::Duration};
-use super::{discovery::*, policy::*, protocol::*, retry::*};
pub(super) const DEFAULT_TIMEOUT_SECONDS: u64 = 300;
#[derive(Clone, Default)]
pub struct AgentRuntime {
@@ -56,18 +56,31 @@ impl AgentRuntime {
let mut retries = RetryBudget::default();
let result = loop {
let (events, output) = provider.run_turn(TurnInput {
- root: &folder, config: &config, prompt: &attempt_prompt,
- cancellation: cancel.clone(), timeout: Duration::from_secs(timeout), on_event: &on_event,
+ root: &folder,
+ config: &config,
+ prompt: &attempt_prompt,
+ cancellation: cancel.clone(),
+ timeout: Duration::from_secs(timeout),
+ on_event: &on_event,
})?;
all_events.extend(events);
- let checked = parse_turn_result(&output).map_err(|message| ValidationIssue::new("turn.contract", None, "response", message)).and_then(|result| {
- if let AgentTurnResult::Commands { commands, .. } = &result {
- let next = execute_checked(&config, commands, &config.updated_at, crate::generation::models::default_model().defaults)?;
- validate_agent_scene_conventions(&config, &next).map_err(|message| ValidationIssue::new("agent.scene_policy", None, "scenes", message))?;
- }
- Ok(result)
- });
+ let checked = parse_turn_result(&output)
+ .map_err(|message| {
+ ValidationIssue::new("turn.contract", None, "response", message)
+ })
+ .and_then(|result| {
+ if let AgentTurnResult::Commands { commands, .. } = &result {
+ let next = execute_checked(
+ &config,
+ commands,
+ &config.updated_at,
+ crate::generation::models::default_model().defaults,
+ )?;
+ validate_scene_policy(&config, &next)?;
+ }
+ Ok(result)
+ });
match checked {
Ok(valid) => break valid,
Err(failure) => {
diff --git a/src-tauri/src/agent/tests.rs b/src-tauri/src/agent/tests.rs
index 6a0d366..125fedf 100644
--- a/src-tauri/src/agent/tests.rs
+++ b/src-tauri/src/agent/tests.rs
@@ -1,13 +1,21 @@
-use super::runtime::{DEFAULT_TIMEOUT_SECONDS, without_endpoint_provider_settings};
-use crate::project::storage::PROJECT_FILE_NAME;
-use crate::generation::models::h3::validate_agent_shot_settings;
-use std::{sync::atomic::Ordering, path::PathBuf};
+use super::runtime::{without_endpoint_provider_settings, DEFAULT_TIMEOUT_SECONDS};
use super::*;
-use super::{providers::*, providers::output::*, providers::compatible::*, process::*, discovery::*, protocol::*, prompt::*, retry::*};
+use super::{
+ discovery::*, process::*, prompt::*, protocol::*, providers::compatible::*,
+ providers::output::*, providers::*, retry::*,
+};
+use crate::generation::models::h3::validate_agent_shot_settings;
+use crate::project::storage::PROJECT_FILE_NAME;
use crate::project::*;
-use std::{collections::BTreeMap, path::Path, time::Duration, sync::{Mutex,Arc,atomic::AtomicBool}};
use serde_json::Value;
use std::fs;
+use std::{
+ collections::BTreeMap,
+ path::Path,
+ sync::{atomic::AtomicBool, Arc, Mutex},
+ time::Duration,
+};
+use std::{path::PathBuf, sync::atomic::Ordering};
#[test]
fn parses_answer_question_and_validates_empty_content() {
@@ -575,9 +583,7 @@ fn discovery_never_selects_a_shell_script_shim() {
for name in ["claude", "codex"] {
if let Some(path) = discover_executable(name, None) {
let extension = path.extension().unwrap_or_default().to_string_lossy();
- assert!(
- extension.eq_ignore_ascii_case("exe") || extension.eq_ignore_ascii_case("com")
- );
+ assert!(extension.eq_ignore_ascii_case("exe") || extension.eq_ignore_ascii_case("com"));
}
}
}
@@ -759,7 +765,7 @@ fn endpoint_credentials_are_removed_from_project_context() {
#[test]
fn http_turn_cancels_while_waiting_for_a_response() {
- use std::{net::TcpListener, sync::mpsc, time::Instant, thread};
+ use std::{net::TcpListener, sync::mpsc, thread, time::Instant};
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let endpoint = format!("http://{}/v1", listener.local_addr().unwrap());
let (accepted_tx, accepted_rx) = mpsc::channel();
@@ -776,13 +782,21 @@ fn http_turn_cancels_while_waiting_for_a_response() {
accepted_rx.recv_timeout(Duration::from_secs(5)).unwrap();
flag.store(true, Ordering::Release);
});
- let config = serde_json::from_str(include_str!("../../../fixtures/project-v1-complete.json")).unwrap();
+ let config =
+ serde_json::from_str(include_str!("../../../fixtures/project-v1-complete.json")).unwrap();
let started = Instant::now();
- let result = run_compatible_endpoint(ProviderId::Local, &config, "Hello", &endpoint_setting(&endpoint, "", Some("model")), cancel, Duration::from_secs(20), &|_| {});
+ let result = run_compatible_endpoint(
+ ProviderId::Local,
+ &config,
+ "Hello",
+ &endpoint_setting(&endpoint, "", Some("model")),
+ cancel,
+ Duration::from_secs(20),
+ &|_| {},
+ );
let _ = release_tx.send(());
server.join().unwrap();
canceller.join().unwrap();
assert!(result.unwrap_err().contains("cancelled"));
assert!(started.elapsed() < Duration::from_secs(5));
}
-
diff --git a/src-tauri/src/agent/tests_transport.rs b/src-tauri/src/agent/tests_transport.rs
new file mode 100644
index 0000000..0d8f2c5
--- /dev/null
+++ b/src-tauri/src/agent/tests_transport.rs
@@ -0,0 +1,66 @@
+use super::{process::probe_command, prompt::*};
+use std::{path::Path, time::Duration};
+
+#[test]
+fn probes_drain_large_output_without_filling_the_pipe() {
+ #[cfg(windows)]
+ let result = probe_command(
+ Path::new("powershell.exe"),
+ &[
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "[Console]::Out.Write(('x' * 200000))",
+ ],
+ Duration::from_secs(10),
+ );
+ #[cfg(not(windows))]
+ let result = probe_command(
+ Path::new("/bin/sh"),
+ &["-c", "head -c 200000 /dev/zero | tr '\\000' x"],
+ Duration::from_secs(10),
+ );
+ let output = result.unwrap();
+ assert_eq!(output.len(), 65_536);
+ assert!(output.bytes().all(|byte| byte == b'x'));
+}
+
+#[test]
+fn another_model_supplies_its_own_policy_and_vocabulary() {
+ use crate::generation::models::*;
+ let model = ModelDefinition {
+ defaults: SceneDefaults {
+ provider_id: "future-model",
+ duration_seconds: 8.0,
+ },
+ capabilities: ModelCapabilities {
+ max_scene_seconds: 30.0,
+ min_steps: 1,
+ max_image_references: 1,
+ max_video_references: 0,
+ max_references: 1,
+ continuation_overlap: 0,
+ frame_stride: 1,
+ },
+ agent_instructions: "Future model authoring policy.",
+ shot_catalog: || "custom-framing: wide".into(),
+ validate_shot_settings: |_, _, _| Ok(()),
+ };
+ let prompt = system_prompt_for(&model);
+ assert!(prompt.contains("Future model authoring policy."));
+ assert!(prompt.contains("custom-framing: wide"));
+ assert!(!prompt.contains(h3::MODEL.agent_instructions));
+ assert!(prompt.contains("scene.add"));
+}
+
+#[test]
+fn credentials_never_enter_model_context() {
+ let mut config: crate::project::ProjectConfig =
+ serde_json::from_str(include_str!("../../../fixtures/project-v1-created.json")).unwrap();
+ config.provider_settings = serde_json::from_value(serde_json::json!({
+ "future-provider": { "enabled": true, "model": "private-model", "options": { "apiKey": "secret-token" } }
+ })).unwrap();
+ let prompt = context_prompt(&config, "Plan a scene").unwrap();
+ assert!(!prompt.contains("secret-token"));
+ assert!(!prompt.contains("private-model"));
+}
diff --git a/src-tauri/src/agent/types.rs b/src-tauri/src/agent/types.rs
index eec03e7..07a4127 100644
--- a/src-tauri/src/agent/types.rs
+++ b/src-tauri/src/agent/types.rs
@@ -1,5 +1,5 @@
-use crate::project::*;
use crate::project::commands::ProjectCommand;
+use crate::project::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
diff --git a/src-tauri/src/app.rs b/src-tauri/src/app.rs
index 1b5069c..67bf57e 100644
--- a/src-tauri/src/app.rs
+++ b/src-tauri/src/app.rs
@@ -1,5 +1,8 @@
-use crate::{agent, app_paths, app_settings, commands, cuda_support, diagnostics, export, slopfab, weights, window};
-use crate::window::{ExitGuard, CloseDecision};
+use crate::window::{CloseDecision, ExitGuard};
+use crate::{
+ agent, app_paths, app_settings, commands, cuda_support, diagnostics, export, slopfab, weights,
+ window,
+};
use std::io;
/// Portable distributions carry a marker because Windows updates launch an
/// installer and cannot replace a portable folder in place.
@@ -8,7 +11,10 @@ fn app_updater_enabled() -> bool {
!cfg!(debug_assertions)
&& std::env::current_exe()
.ok()
- .and_then(|exe| exe.parent().map(|dir| !dir.join("slopus-portable").exists()))
+ .and_then(|exe| {
+ exe.parent()
+ .map(|dir| !dir.join("slopus-portable").exists())
+ })
.unwrap_or(false)
}
@@ -19,7 +25,12 @@ pub fn run() {
use tauri::Manager as _;
let data_directory = app_paths::prepare(app.handle())?;
app_settings::ensure_file(&data_directory)?;
- let window_config = app.config().app.windows.first().ok_or_else(|| io::Error::other("Missing main window configuration"))?;
+ let window_config = app
+ .config()
+ .app
+ .windows
+ .first()
+ .ok_or_else(|| io::Error::other("Missing main window configuration"))?;
tauri::WebviewWindowBuilder::from_config(app, window_config)?
.data_directory(data_directory)
.build()?;
diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rs
index b9278c8..297ce2c 100644
--- a/src-tauri/src/commands/agent.rs
+++ b/src-tauri/src/commands/agent.rs
@@ -1,5 +1,6 @@
-use crate::{agent, agent_commands};
-use crate::project::{*, validation::validate_and_normalize_config};
+use crate::agent;
+use crate::project::commands as agent_commands;
+use crate::project::{validation::validate_and_normalize_config, *};
use serde::Serialize;
use tauri::{AppHandle, Emitter as _};
#[tauri::command]
@@ -43,7 +44,10 @@ pub(crate) struct AgentTurnEventPayload {
}
#[tauri::command]
-pub(crate) fn cancel_agent_turn(state: tauri::State<'_, agent::AgentRuntime>, request_id: String) -> bool {
+pub(crate) fn cancel_agent_turn(
+ state: tauri::State<'_, agent::AgentRuntime>,
+ request_id: String,
+) -> bool {
state.cancel(&request_id)
}
diff --git a/src-tauri/src/commands/artifacts.rs b/src-tauri/src/commands/artifacts.rs
index 55fc618..5e108b9 100644
--- a/src-tauri/src/commands/artifacts.rs
+++ b/src-tauri/src/commands/artifacts.rs
@@ -1,8 +1,11 @@
-use crate::{app_paths, diagnostics, reference_icons, rendered};
-use crate::project::paths::*;
use crate::media::artifacts::*;
+use crate::project::paths::*;
+use crate::{app_paths, diagnostics, reference_icons, rendered};
use std::fs;
-use tauri::{ipc::{InvokeBody, Request}, AppHandle};
+use tauri::{
+ ipc::{InvokeBody, Request},
+ AppHandle,
+};
pub(crate) const GENERATED_FOLDER_HEADER: &str = "x-generated-folder";
pub(crate) const GENERATED_JOB_HEADER: &str = "x-generated-job";
pub(crate) const THUMBNAIL_FOLDER_HEADER: &str = "x-thumbnail-folder";
@@ -135,13 +138,25 @@ pub(crate) fn list_builtin_reference_icons(app: AppHandle) -> Result<Vec<String>
}
#[tauri::command]
-pub(crate) fn read_builtin_reference_icon(app: AppHandle, preset_id: String) -> Result<tauri::ipc::Response, String> {
- reference_icons::read_builtin(&app_paths::data_directory(&app), &preset_id).map(tauri::ipc::Response::new)
+pub(crate) fn read_builtin_reference_icon(
+ app: AppHandle,
+ preset_id: String,
+) -> Result<tauri::ipc::Response, String> {
+ reference_icons::read_builtin(&app_paths::data_directory(&app), &preset_id)
+ .map(tauri::ipc::Response::new)
}
#[tauri::command]
-pub(crate) fn save_builtin_reference_icon(app: AppHandle, preset_id: String, job_id: String) -> Result<(), String> {
- reference_icons::save_builtin(&app_paths::data_directory(&app), &preset_id, &reference_icon_pixels(&job_id)?)
+pub(crate) fn save_builtin_reference_icon(
+ app: AppHandle,
+ preset_id: String,
+ job_id: String,
+) -> Result<(), String> {
+ reference_icons::save_builtin(
+ &app_paths::data_directory(&app),
+ &preset_id,
+ &reference_icon_pixels(&job_id)?,
+ )
}
/// One frame of a finished render, as RGBA the webview can build a `VideoFrame`
/// from. A frame at a time because a whole render is hundreds of megabytes and
diff --git a/src-tauri/src/commands/binary.rs b/src-tauri/src/commands/binary.rs
index 332cd64..6677590 100644
--- a/src-tauri/src/commands/binary.rs
+++ b/src-tauri/src/commands/binary.rs
@@ -22,7 +22,17 @@ pub(crate) fn percent_decode(value: &str) -> Result<String, String> {
}
/// Decode the common raw-binary IPC metadata envelope once.
-pub(crate) fn decoded_header(request: &tauri::ipc::Request<'_>, name: &str) -> Result<String, String> {
- let value = request.headers().get(name).ok_or_else(|| format!("Missing {name} header."))?;
- percent_decode(value.to_str().map_err(|_| format!("Invalid {name} header."))?)
+pub(crate) fn decoded_header(
+ request: &tauri::ipc::Request<'_>,
+ name: &str,
+) -> Result<String, String> {
+ let value = request
+ .headers()
+ .get(name)
+ .ok_or_else(|| format!("Missing {name} header."))?;
+ percent_decode(
+ value
+ .to_str()
+ .map_err(|_| format!("Invalid {name} header."))?,
+ )
}
diff --git a/src-tauri/src/commands/generation.rs b/src-tauri/src/commands/generation.rs
index 8ac7813..e45a25b 100644
--- a/src-tauri/src/commands/generation.rs
+++ b/src-tauri/src/commands/generation.rs
@@ -1,39 +1,78 @@
-use crate::{diagnostics, slopfab};
-use crate::project::{*, validation::validate_and_normalize_config};
use crate::media::artifacts::*;
+use crate::project::{validation::validate_and_normalize_config, *};
+use crate::{diagnostics, slopfab};
use tauri::{AppHandle, Emitter};
#[tauri::command]
-pub(crate) fn create_reference_video(state: tauri::State<'_, slopfab::SlopfabRuntime>, duration_seconds: f64, config: ProjectConfig) -> Result<String, String> {
+pub(crate) fn create_reference_video(
+ state: tauri::State<'_, slopfab::SlopfabRuntime>,
+ duration_seconds: f64,
+ config: ProjectConfig,
+) -> Result<String, String> {
let config = validate_and_normalize_config(config)?;
- state.references.create_reference_video(duration_seconds, &config.provider_settings)
+ state
+ .references
+ .create_reference_video(duration_seconds, &config.provider_settings)
}
-pub(crate) fn reference_video_header<'a>(request: &'a tauri::ipc::Request<'_>, name: &str) -> Result<&'a str, String> {
- request.headers().get(name).and_then(|value| value.to_str().ok())
+pub(crate) fn reference_video_header<'a>(
+ request: &'a tauri::ipc::Request<'_>,
+ name: &str,
+) -> Result<&'a str, String> {
+ request
+ .headers()
+ .get(name)
+ .and_then(|value| value.to_str().ok())
.ok_or_else(|| format!("Missing or invalid {name} header."))
}
#[tauri::command]
-pub(crate) fn append_reference_video(state: tauri::State<'_, slopfab::SlopfabRuntime>, request: tauri::ipc::Request<'_>) -> Result<(), String> {
- let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else { return Err("Reference frames require a binary body.".into()); };
+pub(crate) fn append_reference_video(
+ state: tauri::State<'_, slopfab::SlopfabRuntime>,
+ request: tauri::ipc::Request<'_>,
+) -> Result<(), String> {
+ let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else {
+ return Err("Reference frames require a binary body.".into());
+ };
let id = reference_video_header(&request, "x-reference-id")?;
- let width = reference_video_header(&request, "x-reference-width")?.parse().map_err(|_| "Invalid frame width.")?;
- let height = reference_video_header(&request, "x-reference-height")?.parse().map_err(|_| "Invalid frame height.")?;
- let timestamp = reference_video_header(&request, "x-reference-time")?.parse().map_err(|_| "Invalid frame timestamp.")?;
- state.references.append_reference_video(id, bytes, width, height, timestamp)
+ let width = reference_video_header(&request, "x-reference-width")?
+ .parse()
+ .map_err(|_| "Invalid frame width.")?;
+ let height = reference_video_header(&request, "x-reference-height")?
+ .parse()
+ .map_err(|_| "Invalid frame height.")?;
+ let timestamp = reference_video_header(&request, "x-reference-time")?
+ .parse()
+ .map_err(|_| "Invalid frame timestamp.")?;
+ state
+ .references
+ .append_reference_video(id, bytes, width, height, timestamp)
}
#[tauri::command]
-pub(crate) fn set_reference_video_audio(state: tauri::State<'_, slopfab::SlopfabRuntime>, request: tauri::ipc::Request<'_>) -> Result<(), String> {
- let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else { return Err("Reference audio requires a binary body.".into()); };
+pub(crate) fn set_reference_video_audio(
+ state: tauri::State<'_, slopfab::SlopfabRuntime>,
+ request: tauri::ipc::Request<'_>,
+) -> Result<(), String> {
+ let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else {
+ return Err("Reference audio requires a binary body.".into());
+ };
let id = reference_video_header(&request, "x-reference-id")?;
- let channels = reference_video_header(&request, "x-reference-channels")?.parse().map_err(|_| "Invalid audio channels.")?;
- let rate = reference_video_header(&request, "x-reference-rate")?.parse().map_err(|_| "Invalid sample rate.")?;
- state.references.set_reference_video_audio(id, bytes, channels, rate)
+ let channels = reference_video_header(&request, "x-reference-channels")?
+ .parse()
+ .map_err(|_| "Invalid audio channels.")?;
+ let rate = reference_video_header(&request, "x-reference-rate")?
+ .parse()
+ .map_err(|_| "Invalid sample rate.")?;
+ state
+ .references
+ .set_reference_video_audio(id, bytes, channels, rate)
}
#[tauri::command]
-pub(crate) fn release_reference_videos(state: tauri::State<'_, slopfab::SlopfabRuntime>, ids: Vec<String>) -> Result<(), String> {
+pub(crate) fn release_reference_videos(
+ state: tauri::State<'_, slopfab::SlopfabRuntime>,
+ ids: Vec<String>,
+) -> Result<(), String> {
state.references.release_reference_videos(&ids)
}
@@ -56,8 +95,9 @@ pub(crate) fn resolve_slopfab_plan(
"Generation plan requested.",
context.clone(),
);
- let result = validate_and_normalize_config(config)
- .and_then(|config| slopfab::resolve_plan(&request, &config.provider_settings, &state.references));
+ let result = validate_and_normalize_config(config).and_then(|config| {
+ slopfab::resolve_plan(&request, &config.provider_settings, &state.references)
+ });
match &result {
Ok(plan) => diagnostics::info(
"slopfab",
@@ -85,13 +125,20 @@ pub(crate) fn enqueue_slopfab_generation(
prepare_continuation_path(&mut request, Some(&folder_path))?;
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(std::sync::Arc::new(move |event| {
- match event {
- slopfab::NativeEvent::Job(value) => { let _ = app.emit("slopfab-job", value); }
- slopfab::NativeEvent::Progress(value) => { let _ = app.emit("slopfab-progress", value); }
- }
- }), request, &config.provider_settings));
+ let result = validate_and_normalize_config(config).and_then(|config| {
+ state.enqueue(
+ std::sync::Arc::new(move |event| match event {
+ slopfab::NativeEvent::Job(value) => {
+ let _ = app.emit("slopfab-job", value);
+ }
+ slopfab::NativeEvent::Progress(value) => {
+ let _ = app.emit("slopfab-progress", value);
+ }
+ }),
+ request,
+ &config.provider_settings,
+ )
+ });
if let Err(error) = &result {
diagnostics::error(
"slopfab",
diff --git a/src-tauri/src/commands/media.rs b/src-tauri/src/commands/media.rs
index a3e215e..50696c1 100644
--- a/src-tauri/src/commands/media.rs
+++ b/src-tauri/src/commands/media.rs
@@ -1,11 +1,13 @@
use crate::media::formats::*;
-use crate::project::paths::*;
use crate::media::{access::*, import::*};
+use crate::project::paths::*;
use std::{fs, path::PathBuf};
use tauri::AppHandle;
use tauri_plugin_dialog::DialogExt;
#[tauri::command]
-pub(crate) fn choose_initial_reference_images(app: AppHandle) -> Result<Vec<PendingReferenceImage>, String> {
+pub(crate) fn choose_initial_reference_images(
+ app: AppHandle,
+) -> Result<Vec<PendingReferenceImage>, String> {
let selected = app
.dialog()
.file()
@@ -156,7 +158,8 @@ pub(crate) fn read_project_file(
/// What it deliberately does NOT do is trust the caller's string: an argument
/// the project does not name is refused whatever it points at.
#[tauri::command]
-pub(crate) fn read_external_media_file(access: tauri::State<'_, MediaAccess>,
+pub(crate) fn read_external_media_file(
+ access: tauri::State<'_, MediaAccess>,
folder_path: String,
source_path: String,
) -> Result<tauri::ipc::Response, String> {
@@ -166,7 +169,8 @@ pub(crate) fn read_external_media_file(access: tauri::State<'_, MediaAccess>,
/// Adds the chosen files to the project: images are copied in, video and audio
/// are recorded where they already are. An empty list means the user cancelled.
#[tauri::command]
-pub(crate) fn import_media_files(access: tauri::State<'_, MediaAccess>,
+pub(crate) fn import_media_files(
+ access: tauri::State<'_, MediaAccess>,
app: AppHandle,
folder_path: String,
) -> Result<Vec<ImportedMediaFile>, String> {
@@ -193,23 +197,50 @@ pub(crate) fn import_media_files(access: tauri::State<'_, MediaAccess>,
.collect()
}
#[tauri::command]
-pub(crate) fn choose_reference_video(access: tauri::State<'_, MediaAccess>, app: AppHandle, folder_path: String) -> Result<Option<String>, String> {
+pub(crate) fn choose_reference_video(
+ access: tauri::State<'_, MediaAccess>,
+ app: AppHandle,
+ folder_path: String,
+) -> Result<Option<String>, String> {
let root = project_root(&folder_path)?;
- let picked = app.dialog().file().set_title("Add a video reference")
- .add_filter("MP4 video", &video_extensions()).blocking_pick_file();
- let Some(picked) = picked else { return Ok(None); };
- let path = picked.into_path().map_err(|error| format!("Could not access selected video: {error}"))?;
- if !path.is_file() { return Err("The selected video does not exist.".into()); }
+ let picked = app
+ .dialog()
+ .file()
+ .set_title("Add a video reference")
+ .add_filter("MP4 video", &video_extensions())
+ .blocking_pick_file();
+ let Some(picked) = picked else {
+ return Ok(None);
+ };
+ let path = picked
+ .into_path()
+ .map_err(|error| format!("Could not access selected video: {error}"))?;
+ if !path.is_file() {
+ return Err("The selected video does not exist.".into());
+ }
picked_external_source_path(&access, &path, &root).map(Some)
}
#[tauri::command]
-pub(crate) fn choose_reference_files(access: tauri::State<'_, MediaAccess>, app: AppHandle, folder_path: String) -> Result<Vec<ImportedReference>, String> {
+pub(crate) fn choose_reference_files(
+ access: tauri::State<'_, MediaAccess>,
+ app: AppHandle,
+ folder_path: String,
+) -> Result<Vec<ImportedReference>, String> {
let root = project_root(&folder_path)?;
- let selected = app.dialog().file().set_title("Add reference files")
+ let selected = app
+ .dialog()
+ .file()
+ .set_title("Add reference files")
.add_filter("Images, videos and refmods", &reference_extensions())
- .blocking_pick_files().unwrap_or_default();
- let paths = selected.into_iter().map(|path| path.into_path().map_err(|error| format!("Could not access selected file: {error}")))
+ .blocking_pick_files()
+ .unwrap_or_default();
+ let paths = selected
+ .into_iter()
+ .map(|path| {
+ path.into_path()
+ .map_err(|error| format!("Could not access selected file: {error}"))
+ })
.collect::<Result<Vec<_>, _>>()?;
import_reference_attachments(&access, &root, &paths)
}
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 520721e..e557842 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -1,8 +1,8 @@
-pub(crate) mod project;
-pub(crate) mod media;
-pub(crate) mod runtime;
pub(crate) mod agent;
-pub(crate) mod generation;
pub(crate) mod artifacts;
-pub(crate) mod diagnostics;
pub(crate) mod binary;
+pub(crate) mod diagnostics;
+pub(crate) mod generation;
+pub(crate) mod media;
+pub(crate) mod project;
+pub(crate) mod runtime;
diff --git a/src-tauri/src/commands/project.rs b/src-tauri/src/commands/project.rs
index 0dff368..6ff7f8e 100644
--- a/src-tauri/src/commands/project.rs
+++ b/src-tauri/src/commands/project.rs
@@ -1,4 +1,4 @@
-use crate::project::{*, storage::*, lifecycle::*, validation::validate_and_normalize_config};
+use crate::project::{lifecycle::*, storage::*, validation::validate_and_normalize_config, *};
use std::path::{Path, PathBuf};
use tauri::AppHandle;
use tauri_plugin_dialog::DialogExt;
diff --git a/src-tauri/src/commands/runtime.rs b/src-tauri/src/commands/runtime.rs
index ff83a7b..4575416 100644
--- a/src-tauri/src/commands/runtime.rs
+++ b/src-tauri/src/commands/runtime.rs
@@ -1,5 +1,5 @@
+use crate::project::{paths::*, *};
use crate::{agent, diagnostics, slopfab};
-use crate::project::{*, paths::*};
use serde::Serialize;
use std::collections::BTreeMap;
use tauri::AppHandle;
@@ -15,7 +15,9 @@ pub(crate) struct RuntimeStatus {
/// has no project in hand — engine paths belong to the machine, not to a
/// project file — so it cannot go through `runtime_status`.
#[tauri::command]
-pub(crate) fn slopfab_status(settings: BTreeMap<String, ProviderSetting>) -> slopfab::SlopfabStatus {
+pub(crate) fn slopfab_status(
+ settings: BTreeMap<String, ProviderSetting>,
+) -> slopfab::SlopfabStatus {
let status = slopfab::status(&settings);
diagnostics::info(
"runtime",
@@ -106,4 +108,3 @@ pub(crate) async fn runtime_status(
}
result
}
-
diff --git a/src-tauri/src/export.rs b/src-tauri/src/export.rs
index 90560f4..4d11938 100644
--- a/src-tauri/src/export.rs
+++ b/src-tauri/src/export.rs
@@ -49,7 +49,6 @@ fn safe_file_name(value: &str) -> String {
/// headers for the same reason: a raw body leaves nowhere else to put them.
pub(crate) use crate::commands::binary::percent_decode;
-
/// Destinations the save dialog returned in THIS run.
///
/// The path makes a round trip through the webview between the dialog and the
@@ -137,7 +136,6 @@ fn authorized_destination(value: &str) -> Result<PathBuf, String> {
/// used to be. Flush the complete file before atomically publishing it.
pub(crate) use crate::storage::atomic::write_atomically;
-
/// Opens the platform's save dialog. `Ok(None)` means the user cancelled, which
/// is not an error.
#[tauri::command]
diff --git a/src-tauri/src/generation/models/h3.rs b/src-tauri/src/generation/models/h3.rs
index 7cdd846..4c27d84 100644
--- a/src-tauri/src/generation/models/h3.rs
+++ b/src-tauri/src/generation/models/h3.rs
@@ -1,9 +1,12 @@
+use super::{ModelCapabilities, ModelDefinition, SceneDefaults};
use crate::project::SceneShot;
use std::sync::LazyLock;
-use super::{ModelCapabilities, ModelDefinition, SceneDefaults};
pub(crate) static MODEL: ModelDefinition = ModelDefinition {
- defaults: SceneDefaults { provider_id: "minimax-h3", duration_seconds: 6.0 },
+ defaults: SceneDefaults {
+ provider_id: "minimax-h3",
+ duration_seconds: 6.0,
+ },
capabilities: ModelCapabilities {
max_scene_seconds: 15.0,
min_steps: 2,
@@ -20,15 +23,52 @@ pub(crate) static MODEL: ModelDefinition = ModelDefinition {
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
-struct ShotGroup { id: String, multiple: bool, #[serde(default)] scene_wide: bool, options: Vec<ShotOption> }
+struct ShotGroup {
+ id: String,
+ multiple: bool,
+ #[serde(default)]
+ scene_wide: bool,
+ options: Vec<ShotOption>,
+}
#[derive(serde::Deserialize)]
-struct ShotOption { id: String }
-static GROUPS: LazyLock<Vec<ShotGroup>> = LazyLock::new(|| serde_json::from_str(include_str!("../../../../shared/models/minimax-h3-shot-tags.json")).expect("bundled H3 vocabulary"));
+struct ShotOption {
+ id: String,
+}
+static GROUPS: LazyLock<Vec<ShotGroup>> = LazyLock::new(|| {
+ serde_json::from_str(include_str!(
+ "../../../../shared/models/minimax-h3-shot-tags.json"
+ ))
+ .expect("bundled H3 vocabulary")
+});
pub(crate) fn shot_catalog() -> String {
- GROUPS.iter().map(|group| format!("- {}: {}", group.id, group.options.iter().map(|option| option.id.as_str()).collect::<Vec<_>>().join(", "))).collect::<Vec<_>>().join("\n")
+ GROUPS
+ .iter()
+ .map(|group| {
+ format!(
+ "- {}: {}",
+ group.id,
+ group
+ .options
+ .iter()
+ .map(|option| option.id.as_str())
+ .collect::<Vec<_>>()
+ .join(", ")
+ )
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
}
fn agent_setting_options(group: &str) -> Option<Vec<&'static str>> {
- GROUPS.iter().find(|candidate| candidate.id == group).map(|group| group.options.iter().map(|option| option.id.as_str()).collect())
+ GROUPS
+ .iter()
+ .find(|candidate| candidate.id == group)
+ .map(|group| {
+ group
+ .options
+ .iter()
+ .map(|option| option.id.as_str())
+ .collect()
+ })
}
fn shot_setting_values<'a>(shot: Option<&'a SceneShot>, group: &str) -> &'a [String] {
shot.and_then(|value| value.settings.as_ref())
@@ -67,13 +107,23 @@ pub(crate) fn validate_agent_shot_settings(
));
}
}
- if !GROUPS.iter().find(|candidate| candidate.id == *group).is_some_and(|group| group.multiple) && values.len() > 1 {
+ if !GROUPS
+ .iter()
+ .find(|candidate| candidate.id == *group)
+ .is_some_and(|group| group.multiple)
+ && values.len() > 1
+ {
return Err(format!(
"Shot '{}' gives single-choice Settings group '{}' more than one option.",
shot.id, group
));
}
- if GROUPS.iter().find(|candidate| candidate.id == *group).is_some_and(|group| group.scene_wide) && shot.id != earliest_shot_id {
+ if GROUPS
+ .iter()
+ .find(|candidate| candidate.id == *group)
+ .is_some_and(|group| group.scene_wide)
+ && shot.id != earliest_shot_id
+ {
return Err(format!(
"Shot '{}' puts scene Look on a later shot. Store visualStyle on the earliest shot only.",
shot.id
diff --git a/src-tauri/src/generation/models/mod.rs b/src-tauri/src/generation/models/mod.rs
index 293b58b..4a8f477 100644
--- a/src-tauri/src/generation/models/mod.rs
+++ b/src-tauri/src/generation/models/mod.rs
@@ -22,15 +22,24 @@ pub(crate) struct ModelDefinition {
pub capabilities: ModelCapabilities,
pub agent_instructions: &'static str,
pub shot_catalog: fn() -> String,
- pub validate_shot_settings: fn(Option<&crate::project::SceneShot>, &crate::project::SceneShot, &str) -> Result<(), String>,
+ pub validate_shot_settings: fn(
+ Option<&crate::project::SceneShot>,
+ &crate::project::SceneShot,
+ &str,
+ ) -> Result<(), String>,
}
-pub(crate) fn default_model() -> &'static ModelDefinition { &h3::MODEL }
+pub(crate) fn default_model() -> &'static ModelDefinition {
+ &h3::MODEL
+}
/// Unknown persisted provider ids remain readable. They do not silently acquire
/// H3 authoring rules; a backend must explicitly register support before use.
pub(crate) fn find(id: &str) -> Option<&'static ModelDefinition> {
- match id { "minimax-h3" => Some(&h3::MODEL), _ => None }
+ match id {
+ "minimax-h3" => Some(&h3::MODEL),
+ _ => None,
+ }
}
pub(crate) fn for_scene(id: Option<&str>) -> Option<&'static ModelDefinition> {
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 05eee8c..7c5d46c 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1,26 +1,26 @@
mod agent;
-use project::commands as agent_commands;
+mod app;
mod app_paths;
mod app_settings;
-mod cuda_support;
+mod commands;
mod conditioning;
+mod cuda_support;
mod diagnostics;
mod export;
-mod reference_icons;
-mod rendered;
-mod slopfab;
-mod weights;
-mod app;
mod generation;
-mod commands;
mod media;
mod project;
+mod reference_icons;
+mod rendered;
+mod slopfab;
mod storage;
+mod weights;
mod window;
pub use app::run;
-pub use slopfab::{default_dll_path, generate_reference_icon_batch, ReferenceIconBatchConfig, ReferenceIconSpec};
-
+pub use slopfab::{
+ default_dll_path, generate_reference_icon_batch, ReferenceIconBatchConfig, ReferenceIconSpec,
+};
#[cfg(test)]
mod tests;
diff --git a/src-tauri/src/media/access.rs b/src-tauri/src/media/access.rs
index c1f27f6..0589f46 100644
--- a/src-tauri/src/media/access.rs
+++ b/src-tauri/src/media/access.rs
@@ -1,6 +1,10 @@
-use crate::project::{*, paths::*, storage::read_project};
-use std::{fs, path::{Path, PathBuf}, collections::{BTreeMap, BTreeSet}};
use super::import::media_kind_and_mime;
+use crate::project::{paths::*, storage::read_project, *};
+use std::{
+ collections::{BTreeMap, BTreeSet},
+ fs,
+ path::{Path, PathBuf},
+};
/// Files the user chose from the OS picker in THIS run, canonicalised, keyed by
/// the canonical folder of the project they were picked FOR.
///
@@ -17,7 +21,9 @@ use super::import::media_kind_and_mime;
/// pick belonged to. Entries are never written to disk and never survive a
/// restart; the project file does that.
#[derive(Default)]
-pub(crate) struct MediaAccess { picked: std::sync::Mutex<BTreeMap<PathBuf, BTreeSet<PathBuf>>> }
+pub(crate) struct MediaAccess {
+ picked: std::sync::Mutex<BTreeMap<PathBuf, BTreeSet<PathBuf>>>,
+}
/// The identity a project folder is remembered by. Canonical, so one folder
/// spelled two ways is one key. `None` when the folder cannot be resolved, in
@@ -40,11 +46,16 @@ pub(crate) fn remember_picked_file(access: &MediaAccess, project_folder: &Path,
/// Was this file picked in this run *for this project*? A pick made while a
/// different project was open is not an answer here.
-pub(crate) fn was_picked_for_project(access: &MediaAccess, project_folder: &Path, canonical: &Path) -> bool {
+pub(crate) fn was_picked_for_project(
+ access: &MediaAccess,
+ project_folder: &Path,
+ canonical: &Path,
+) -> bool {
let Some(key) = session_key(project_folder) else {
return false;
};
- access.picked
+ access
+ .picked
.lock()
.map(|picked| {
picked
@@ -70,7 +81,11 @@ pub(crate) fn external_source_path(source: &Path) -> Result<String, String> {
/// project — so its preview works before the project has been saved. Only the
/// import paths call this, and they only run on what came back from a native
/// picker.
-pub(crate) fn picked_external_source_path(access: &MediaAccess, source: &Path, project_folder: &Path) -> Result<String, String> {
+pub(crate) fn picked_external_source_path(
+ access: &MediaAccess,
+ source: &Path,
+ project_folder: &Path,
+) -> Result<String, String> {
let path = external_source_path(source)?;
remember_picked_file(access, project_folder, source);
Ok(path)
@@ -92,7 +107,11 @@ pub(crate) fn recorded_external_paths(config: &ProjectConfig) -> Vec<String> {
)
.collect()
}
-pub(crate) fn external_media_bytes(access: &MediaAccess, folder_path: &str, source_path: &str) -> Result<Vec<u8>, String> {
+pub(crate) fn external_media_bytes(
+ access: &MediaAccess,
+ folder_path: &str,
+ source_path: &str,
+) -> Result<Vec<u8>, String> {
let root = project_root(folder_path)?;
let project = read_project(&root)?;
let requested = PathBuf::from(&source_path)
diff --git a/src-tauri/src/media/artifacts.rs b/src-tauri/src/media/artifacts.rs
index 9dfcf69..e0529f9 100644
--- a/src-tauri/src/media/artifacts.rs
+++ b/src-tauri/src/media/artifacts.rs
@@ -1,8 +1,8 @@
use crate::project::paths::*;
-use std::path::PathBuf;
-use serde::Serialize;
-use crate::{slopfab, rendered, reference_icons};
use crate::storage::atomic::write_atomically;
+use crate::{reference_icons, rendered, slopfab};
+use serde::Serialize;
+use std::path::PathBuf;
/// Where a rendered scene lands, relative to the project root. Created by
/// `create_project` along with the rest of the folder layout.
pub(crate) const GENERATED_DIRECTORY: &str = "media/generated";
@@ -57,21 +57,32 @@ pub(crate) struct GeneratedVideoFile {
pub(crate) relative_path: String,
pub(crate) bytes: u64,
}
-pub(crate) fn generated_latent_destination(folder_path: &str, job_id: &str) -> Result<PathBuf, String> {
+pub(crate) fn generated_latent_destination(
+ folder_path: &str,
+ job_id: &str,
+) -> Result<PathBuf, String> {
let root = ProjectRoot::open(folder_path)?;
let stem = generated_file_stem(job_id)?;
let directory = root.directory("latents")?;
let destination = directory.join(format!("{stem}.safetensors"));
if destination.exists() {
- return Err("Latents already exist for this generation. Start a new generation to preserve them.".into());
+ return Err(
+ "Latents already exist for this generation. Start a new generation to preserve them."
+ .into(),
+ );
}
Ok(destination)
}
-pub(crate) fn prepare_continuation_path(request: &mut slopfab::GenerationRequest, folder_path: Option<&str>) -> Result<(), String> {
+pub(crate) fn prepare_continuation_path(
+ request: &mut slopfab::GenerationRequest,
+ folder_path: Option<&str>,
+) -> Result<(), String> {
request.continuation_path = None;
if let Some(relative) = &request.continuation_relative_path {
- let root = ProjectRoot::open(folder_path.ok_or("A project folder is required to continue a scene.")?)?;
+ let root = ProjectRoot::open(
+ folder_path.ok_or("A project folder is required to continue a scene.")?,
+ )?;
let path = root.existing(relative)?;
if !path.is_file() {
return Err("Previous scene latents must be a file inside this project.".into());
@@ -83,12 +94,19 @@ pub(crate) fn prepare_continuation_path(request: &mut slopfab::GenerationRequest
pub(crate) fn reference_icon_pixels(job_id: &str) -> Result<Vec<u8>, String> {
let summary = rendered::summary(&job_id).ok_or("The reference icon is no longer available.")?;
- if summary.width != reference_icons::RENDER_SIZE || summary.height != reference_icons::RENDER_SIZE || summary.frame_count != 1 {
+ if summary.width != reference_icons::RENDER_SIZE
+ || summary.height != reference_icons::RENDER_SIZE
+ || summary.frame_count != 1
+ {
return Err("A reference icon must be a single 768x768 frame.".into());
}
rendered::frame(job_id, 0)?.ok_or_else(|| "The reference icon has no image.".into())
}
-pub(crate) fn write_reference_icon_frame(folder_path: &str, job_id: &str, rgba: &[u8]) -> Result<String, String> {
+pub(crate) fn write_reference_icon_frame(
+ folder_path: &str,
+ job_id: &str,
+ rgba: &[u8],
+) -> Result<String, String> {
let bytes = reference_icons::encode_jpeg(rgba)?;
let root = ProjectRoot::open(folder_path)?;
let stem = generated_file_stem(job_id)?;
diff --git a/src-tauri/src/media/formats.rs b/src-tauri/src/media/formats.rs
index e12bc11..1204962 100644
--- a/src-tauri/src/media/formats.rs
+++ b/src-tauri/src/media/formats.rs
@@ -1,30 +1,153 @@
//! Media format classification and explicit per-use policies.
-pub(crate) struct Format { pub extension: &'static str, pub kind: &'static str, pub mime: &'static str, pub reference: bool }
+pub(crate) struct Format {
+ pub extension: &'static str,
+ pub kind: &'static str,
+ pub mime: &'static str,
+ pub reference: bool,
+}
pub(crate) const FORMATS: &[Format] = &[
- Format { extension: "mp4", kind: "video", mime: "video/mp4", reference: true },
- Format { extension: "m4v", kind: "video", mime: "video/mp4", reference: true },
- Format { extension: "mov", kind: "video", mime: "video/quicktime", reference: true },
- Format { extension: "webm", kind: "video", mime: "video/webm", reference: false },
- Format { extension: "mkv", kind: "video", mime: "video/x-matroska", reference: false },
- Format { extension: "mp3", kind: "audio", mime: "audio/mpeg", reference: false },
- Format { extension: "m4a", kind: "audio", mime: "audio/mp4", reference: false },
- Format { extension: "aac", kind: "audio", mime: "audio/mp4", reference: false },
- Format { extension: "wav", kind: "audio", mime: "audio/wav", reference: false },
- Format { extension: "flac", kind: "audio", mime: "audio/flac", reference: false },
- Format { extension: "ogg", kind: "audio", mime: "audio/ogg", reference: false },
- Format { extension: "oga", kind: "audio", mime: "audio/ogg", reference: false },
- Format { extension: "png", kind: "image", mime: "image/png", reference: true },
- Format { extension: "jpg", kind: "image", mime: "image/jpeg", reference: true },
- Format { extension: "jpeg", kind: "image", mime: "image/jpeg", reference: true },
- Format { extension: "webp", kind: "image", mime: "image/webp", reference: true },
- Format { extension: "gif", kind: "image", mime: "image/gif", reference: false },
- Format { extension: "safetensors", kind: "refmod", mime: "application/octet-stream", reference: true },
+ Format {
+ extension: "mp4",
+ kind: "video",
+ mime: "video/mp4",
+ reference: true,
+ },
+ Format {
+ extension: "m4v",
+ kind: "video",
+ mime: "video/mp4",
+ reference: true,
+ },
+ Format {
+ extension: "mov",
+ kind: "video",
+ mime: "video/quicktime",
+ reference: true,
+ },
+ Format {
+ extension: "webm",
+ kind: "video",
+ mime: "video/webm",
+ reference: false,
+ },
+ Format {
+ extension: "mkv",
+ kind: "video",
+ mime: "video/x-matroska",
+ reference: false,
+ },
+ Format {
+ extension: "mp3",
+ kind: "audio",
+ mime: "audio/mpeg",
+ reference: false,
+ },
+ Format {
+ extension: "m4a",
+ kind: "audio",
+ mime: "audio/mp4",
+ reference: false,
+ },
+ Format {
+ extension: "aac",
+ kind: "audio",
+ mime: "audio/mp4",
+ reference: false,
+ },
+ Format {
+ extension: "wav",
+ kind: "audio",
+ mime: "audio/wav",
+ reference: false,
+ },
+ Format {
+ extension: "flac",
+ kind: "audio",
+ mime: "audio/flac",
+ reference: false,
+ },
+ Format {
+ extension: "ogg",
+ kind: "audio",
+ mime: "audio/ogg",
+ reference: false,
+ },
+ Format {
+ extension: "oga",
+ kind: "audio",
+ mime: "audio/ogg",
+ reference: false,
+ },
+ Format {
+ extension: "png",
+ kind: "image",
+ mime: "image/png",
+ reference: true,
+ },
+ Format {
+ extension: "jpg",
+ kind: "image",
+ mime: "image/jpeg",
+ reference: true,
+ },
+ Format {
+ extension: "jpeg",
+ kind: "image",
+ mime: "image/jpeg",
+ reference: true,
+ },
+ Format {
+ extension: "webp",
+ kind: "image",
+ mime: "image/webp",
+ reference: true,
+ },
+ Format {
+ extension: "gif",
+ kind: "image",
+ mime: "image/gif",
+ reference: false,
+ },
+ Format {
+ extension: "safetensors",
+ kind: "refmod",
+ mime: "application/octet-stream",
+ reference: true,
+ },
];
-pub(crate) fn lookup(extension: &str) -> Option<&'static Format> { FORMATS.iter().find(|format| format.extension == extension) }
+pub(crate) fn lookup(extension: &str) -> Option<&'static Format> {
+ FORMATS.iter().find(|format| format.extension == extension)
+}
pub(crate) fn media_kind_and_mime(extension: &str) -> Option<(&'static str, &'static str)> {
- lookup(extension).filter(|format| format.kind != "refmod").map(|format| (format.kind, format.mime))
+ lookup(extension)
+ .filter(|format| format.kind != "refmod")
+ .map(|format| (format.kind, format.mime))
+}
+pub(crate) fn media_extensions() -> Vec<&'static str> {
+ FORMATS
+ .iter()
+ .filter(|f| f.kind != "refmod")
+ .map(|f| f.extension)
+ .collect()
+}
+pub(crate) fn reference_extensions() -> Vec<&'static str> {
+ FORMATS
+ .iter()
+ .filter(|f| f.reference)
+ .map(|f| f.extension)
+ .collect()
+}
+pub(crate) fn image_extensions() -> Vec<&'static str> {
+ FORMATS
+ .iter()
+ .filter(|f| f.reference && f.kind == "image")
+ .map(|f| f.extension)
+ .collect()
+}
+pub(crate) fn video_extensions() -> Vec<&'static str> {
+ FORMATS
+ .iter()
+ .filter(|f| f.reference && f.kind == "video")
+ .map(|f| f.extension)
+ .collect()
}
-pub(crate) fn media_extensions() -> Vec<&'static str> { FORMATS.iter().filter(|f| f.kind != "refmod").map(|f| f.extension).collect() }
-pub(crate) fn reference_extensions() -> Vec<&'static str> { FORMATS.iter().filter(|f| f.reference).map(|f| f.extension).collect() }
-pub(crate) fn image_extensions() -> Vec<&'static str> { FORMATS.iter().filter(|f| f.reference && f.kind == "image").map(|f| f.extension).collect() }
-pub(crate) fn video_extensions() -> Vec<&'static str> { FORMATS.iter().filter(|f| f.reference && f.kind == "video").map(|f| f.extension).collect() }
diff --git a/src-tauri/src/media/import.rs b/src-tauri/src/media/import.rs
index 0c5cfa7..7b384e2 100644
--- a/src-tauri/src/media/import.rs
+++ b/src-tauri/src/media/import.rs
@@ -1,8 +1,11 @@
+use super::access::{picked_external_source_path, MediaAccess};
pub(crate) use super::formats::media_kind_and_mime;
use crate::project::paths::*;
-use std::{fs, path::{Path, PathBuf}};
use serde::Serialize;
-use super::access::{MediaAccess, picked_external_source_path};
+use std::{
+ fs,
+ path::{Path, PathBuf},
+};
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ImportedReferenceImage {
@@ -46,8 +49,10 @@ pub(crate) fn validate_reference_image(source: &Path) -> Result<(String, &'stati
.and_then(|value| value.to_str())
.map(str::to_ascii_lowercase)
.ok_or_else(|| "The selected image needs a file extension.".to_string())?;
- let mime_type = super::formats::lookup(&extension).filter(|format| format.kind == "image" && format.reference)
- .map(|format| format.mime).ok_or("Choose a PNG, JPEG, or WebP image.")?;
+ let mime_type = super::formats::lookup(&extension)
+ .filter(|format| format.kind == "image" && format.reference)
+ .map(|format| format.mime)
+ .ok_or("Choose a PNG, JPEG, or WebP image.")?;
Ok((extension, mime_type))
}
@@ -91,7 +96,8 @@ pub(crate) struct ImportedReference {
/// Adds one file to a project as a reference, following the same rule the media
/// panel does: pictures are small and get copied so the folder stays portable;
/// video and audio are not copied at any size.
-pub(crate) fn import_reference_file(access: &MediaAccess,
+pub(crate) fn import_reference_file(
+ access: &MediaAccess,
source: &Path,
project_folder: &Path,
) -> Result<ImportedReference, String> {
@@ -132,7 +138,11 @@ pub(crate) fn import_reference_file(access: &MediaAccess,
/// "portable" costs the user that much disk to gain a copy they did not ask
/// for. The project records where the file already lives instead. Images are
/// small and stay copied, so a project's own artwork travels with it.
-pub(crate) fn import_media_file(access: &MediaAccess, source: &Path, project_folder: &Path) -> Result<ImportedMediaFile, String> {
+pub(crate) fn import_media_file(
+ access: &MediaAccess,
+ source: &Path,
+ project_folder: &Path,
+) -> Result<ImportedMediaFile, String> {
if !source.is_file() {
return Err(format!("{} does not exist.", source.to_string_lossy()));
}
@@ -182,27 +192,53 @@ pub(crate) fn import_media_file(access: &MediaAccess, source: &Path, project_fol
})
}
pub(crate) fn reference_attachment_kind(path: &Path) -> Result<&'static str, String> {
- let extension = path.extension().and_then(|ext| ext.to_str()).unwrap_or("").to_ascii_lowercase();
- super::formats::lookup(&extension).filter(|format| format.reference).map(|format| format.kind)
+ let extension = path
+ .extension()
+ .and_then(|ext| ext.to_str())
+ .unwrap_or("")
+ .to_ascii_lowercase();
+ super::formats::lookup(&extension)
+ .filter(|format| format.reference)
+ .map(|format| format.kind)
.ok_or_else(|| "Choose an image, MP4/MOV video, or refmod safetensors file.".into())
}
-pub(crate) fn import_reference_attachments(access: &MediaAccess, root: &Path, paths: &[PathBuf]) -> Result<Vec<ImportedReference>, String> {
- let kinds = paths.iter().map(|path| {
- if !path.is_file() { return Err("The selected reference file does not exist.".into()); }
- reference_attachment_kind(path)
- }).collect::<Result<Vec<_>, String>>()?;
+pub(crate) fn import_reference_attachments(
+ access: &MediaAccess,
+ root: &Path,
+ paths: &[PathBuf],
+) -> Result<Vec<ImportedReference>, String> {
+ let kinds = paths
+ .iter()
+ .map(|path| {
+ if !path.is_file() {
+ return Err("The selected reference file does not exist.".into());
+ }
+ reference_attachment_kind(path)
+ })
+ .collect::<Result<Vec<_>, String>>()?;
if kinds.iter().filter(|kind| **kind == "video").count() > 1 {
- return Err("Add one video per reference. Use another reference for additional videos.".into());
+ return Err(
+ "Add one video per reference. Use another reference for additional videos.".into(),
+ );
}
- paths.iter().zip(kinds).map(|(path, kind)| {
- if kind == "image" { return import_reference_file(access, path, root); }
- Ok(ImportedReference {
- kind,
- name: path.file_name().and_then(|name| name.to_str()).unwrap_or("Reference").into(),
- relative_path: None,
- source_path: Some(picked_external_source_path(access, path, root)?),
+ paths
+ .iter()
+ .zip(kinds)
+ .map(|(path, kind)| {
+ if kind == "image" {
+ return import_reference_file(access, path, root);
+ }
+ Ok(ImportedReference {
+ kind,
+ name: path
+ .file_name()
+ .and_then(|name| name.to_str())
+ .unwrap_or("Reference")
+ .into(),
+ relative_path: None,
+ source_path: Some(picked_external_source_path(access, path, root)?),
+ })
})
- }).collect()
+ .collect()
}
-
diff --git a/src-tauri/src/media/mod.rs b/src-tauri/src/media/mod.rs
index 0e6da2b..10e5b70 100644
--- a/src-tauri/src/media/mod.rs
+++ b/src-tauri/src/media/mod.rs
@@ -1,5 +1,5 @@
-pub(crate) mod import;
pub(crate) mod access;
pub(crate) mod artifacts;
+pub(crate) mod import;
pub(crate) mod formats;
diff --git a/src-tauri/src/project/commands/batch.rs b/src-tauri/src/project/commands/batch.rs
index 9bc939d..8a2801c 100644
--- a/src-tauri/src/project/commands/batch.rs
+++ b/src-tauri/src/project/commands/batch.rs
@@ -1,6 +1,6 @@
-use crate::project::validation::{validate_checked, issue::ValidationIssue};
-use crate::project::{ProjectConfig, GenerationJob};
-use super::{types::*, effects::Effects};
+use super::{effects::Effects, types::*};
+use crate::project::validation::{issue::ValidationIssue, validate_checked};
+use crate::project::{GenerationJob, ProjectConfig};
/** Apply a complete batch to a clone. Callers validate agent conventions after
* this returns; neither a command error nor a validator error mutates input. */
#[cfg(test)]
@@ -16,7 +16,12 @@ pub fn execute_commands_at(
commands: &[ProjectCommand],
timestamp: &str,
) -> Result<ProjectConfig, String> {
- execute_with_defaults(current, commands, timestamp, crate::generation::models::default_model().defaults)
+ execute_with_defaults(
+ current,
+ commands,
+ timestamp,
+ crate::generation::models::default_model().defaults,
+ )
}
pub(crate) fn execute_with_defaults(
@@ -28,31 +33,77 @@ pub(crate) fn execute_with_defaults(
execute_checked(current, commands, timestamp, defaults).map_err(|issue| issue.message)
}
-pub(crate) fn execute_checked(current: &ProjectConfig, commands: &[ProjectCommand], timestamp: &str, defaults: crate::generation::models::SceneDefaults) -> Result<ProjectConfig, ValidationIssue> {
+pub(crate) fn execute_checked(
+ current: &ProjectConfig,
+ commands: &[ProjectCommand],
+ timestamp: &str,
+ defaults: crate::generation::models::SceneDefaults,
+) -> Result<ProjectConfig, ValidationIssue> {
if commands.is_empty() {
- return Err(ValidationIssue::new("commands.empty", None, "commands", "Agent command batch cannot be empty.".into()));
+ return Err(ValidationIssue::new(
+ "commands.empty",
+ None,
+ "commands",
+ "Agent command batch cannot be empty.".into(),
+ ));
}
if commands.len() > MAX_COMMANDS_PER_TURN {
- return Err(ValidationIssue::new("commands.limit", None, "commands", format!("Agent command batch exceeds the limit of {MAX_COMMANDS_PER_TURN} commands.")));
+ return Err(ValidationIssue::new(
+ "commands.limit",
+ None,
+ "commands",
+ format!("Agent command batch exceeds the limit of {MAX_COMMANDS_PER_TURN} commands."),
+ ));
}
let mut next = current.clone();
let mut effects = Effects::new(defaults);
for (index, command) in commands.iter().enumerate() {
apply_command(&mut next, command, timestamp, &mut effects).map_err(|error| {
- ValidationIssue::new("command.invalid", Some((index + 1).to_string()), command_name(command), format!("Command {} ({}): {error}", index + 1, command_name(command)))
+ ValidationIssue::new(
+ "command.invalid",
+ Some((index + 1).to_string()),
+ command_name(command),
+ format!("Command {} ({}): {error}", index + 1, command_name(command)),
+ )
})?;
}
- effects.synchronize(&mut next).map_err(|message| ValidationIssue::new("scene.derived", None, "shots", message))?;
+ effects
+ .synchronize(&mut next)
+ .map_err(|message| ValidationIssue::new("scene.derived", None, "shots", message))?;
validate_checked(next)
}
-fn apply_command(project: &mut ProjectConfig, command: &ProjectCommand, timestamp: &str, effects: &mut Effects) -> Result<(), String> {
+fn apply_command(
+ project: &mut ProjectConfig,
+ command: &ProjectCommand,
+ timestamp: &str,
+ effects: &mut Effects,
+) -> Result<(), String> {
match command {
- ProjectCommand::ProjectSet { .. } => super::project::apply(project, command, timestamp, effects),
- ProjectCommand::ReferenceAdd { .. } | ProjectCommand::ReferenceSet { .. } | ProjectCommand::ReferenceRemove { .. } => super::references::apply(project, command, timestamp, effects),
- ProjectCommand::SceneAdd { .. } | ProjectCommand::SceneSet { .. } | ProjectCommand::SceneRemove { .. } | ProjectCommand::SceneMove { .. } => super::scenes::apply(project, command, timestamp, effects),
- ProjectCommand::ShotAdd { .. } | ProjectCommand::ShotSet { .. } | ProjectCommand::ShotRemove { .. } => super::shots::apply(project, command, timestamp, effects),
- ProjectCommand::ClipAdd { .. } | ProjectCommand::ClipSet { .. } | ProjectCommand::ClipRemove { .. } => super::clips::apply(project, command, timestamp, effects),
+ ProjectCommand::ProjectSet { .. } => {
+ super::project::apply(project, command, timestamp, effects)
+ }
+ ProjectCommand::ReferenceAdd { .. }
+ | ProjectCommand::ReferenceSet { .. }
+ | ProjectCommand::ReferenceRemove { .. } => {
+ super::references::apply(project, command, timestamp, effects)
+ }
+ ProjectCommand::SceneAdd { .. }
+ | ProjectCommand::SceneSet { .. }
+ | ProjectCommand::SceneRemove { .. }
+ | ProjectCommand::SceneMove { .. } => {
+ super::scenes::apply(project, command, timestamp, effects)
+ }
+ ProjectCommand::ShotAdd { .. }
+ | ProjectCommand::ShotSet { .. }
+ | ProjectCommand::ShotRemove { .. } => {
+ super::shots::apply(project, command, timestamp, effects)
+ }
+ ProjectCommand::ClipAdd { .. }
+ | ProjectCommand::ClipSet { .. }
+ | ProjectCommand::ClipRemove { .. } => {
+ super::clips::apply(project, command, timestamp, effects)
+ }
}
}
pub(super) fn find_scene_mut<'a>(
diff --git a/src-tauri/src/project/commands/clips.rs b/src-tauri/src/project/commands/clips.rs
index a619ecd..a13a57b 100644
--- a/src-tauri/src/project/commands/clips.rs
+++ b/src-tauri/src/project/commands/clips.rs
@@ -1,6 +1,11 @@
+use super::{batch::*, effects::Effects, types::ProjectCommand};
use crate::project::*;
-use super::{types::ProjectCommand, batch::*, effects::Effects};
-pub(super) fn apply(project: &mut ProjectConfig, command: &ProjectCommand, _timestamp: &str, effects: &mut Effects) -> Result<(), String> {
+pub(super) fn apply(
+ project: &mut ProjectConfig,
+ command: &ProjectCommand,
+ _timestamp: &str,
+ effects: &mut Effects,
+) -> Result<(), String> {
match command {
ProjectCommand::ClipAdd {
id,
@@ -35,9 +40,13 @@ pub(super) fn apply(project: &mut ProjectConfig, command: &ProjectCommand, _time
&& candidate.relative_path == job.output_relative_path
});
let frame_ms = (1000.0 / f64::from(project.settings.frame_rate)).round() as u64;
- let scene_ms =
- seconds_to_ms(job.duration_seconds.unwrap_or(effects.defaults.duration_seconds), "scene duration", true)?
- .max(frame_ms.max(1));
+ let scene_ms = seconds_to_ms(
+ job.duration_seconds
+ .unwrap_or(effects.defaults.duration_seconds),
+ "scene duration",
+ true,
+ )?
+ .max(frame_ms.max(1));
let asset_id = if let Some(index) = existing {
project.assets[index].id.clone()
} else {
@@ -249,7 +258,10 @@ pub(super) fn find_clip_location(project: &ProjectConfig, id: &str) -> Option<(u
})
}
-pub(super) fn target_track_index(project: &ProjectConfig, requested: Option<&str>) -> Result<usize, String> {
+pub(super) fn target_track_index(
+ project: &ProjectConfig,
+ requested: Option<&str>,
+) -> Result<usize, String> {
let index = match requested {
Some(id) => project
.timeline
diff --git a/src-tauri/src/project/commands/effects.rs b/src-tauri/src/project/commands/effects.rs
index 488c76c..8996883 100644
--- a/src-tauri/src/project/commands/effects.rs
+++ b/src-tauri/src/project/commands/effects.rs
@@ -1,43 +1,53 @@
-use crate::project::{ProjectConfig, reference_tokens::action_reference_ids};
+use crate::project::{reference_tokens::action_reference_ids, ProjectConfig};
use std::collections::BTreeSet;
-pub(super) struct Effects { changed_shots: BTreeSet<String>, pub(super) defaults: crate::generation::models::SceneDefaults }
+pub(super) struct Effects {
+ changed_shots: BTreeSet<String>,
+ pub(super) defaults: crate::generation::models::SceneDefaults,
+}
impl Effects {
- pub(super) fn new(defaults: crate::generation::models::SceneDefaults) -> Self { Self { changed_shots: BTreeSet::new(), defaults } }
- pub(super) fn shots_changed(&mut self, scene: &str) { self.changed_shots.insert(scene.to_string()); }
- pub(super) fn synchronize(self, project: &mut ProjectConfig) -> Result<(), String> {
- let reference_ids = project
- .references
- .iter()
- .map(|reference| reference.id.clone())
- .collect::<Vec<_>>();
- for job in &mut project.generation_jobs {
- if !self.changed_shots.contains(job.id.as_str()) {
- continue;
+ pub(super) fn new(defaults: crate::generation::models::SceneDefaults) -> Self {
+ Self {
+ changed_shots: BTreeSet::new(),
+ defaults,
}
- let Some(shots) = job.shots.as_mut() else {
- continue;
- };
- shots.sort_by(|left, right| left.start_seconds.total_cmp(&right.start_seconds));
- let text = shots
+ }
+ pub(super) fn shots_changed(&mut self, scene: &str) {
+ self.changed_shots.insert(scene.to_string());
+ }
+ pub(super) fn synchronize(self, project: &mut ProjectConfig) -> Result<(), String> {
+ let reference_ids = project
+ .references
.iter()
- .map(|shot| shot.action.trim())
- .filter(|line| !line.is_empty())
- .collect::<Vec<_>>()
- .join("\n\n");
- job.prompt = text.clone();
- job.creative_brief = text;
- job.shot_tags = None;
- for shot in shots {
- for reference_id in action_reference_ids(&shot.action)? {
- if reference_ids.iter().any(|id| id == reference_id)
- && !job.reference_ids.iter().any(|id| id == reference_id)
- {
- job.reference_ids.push(reference_id.to_string());
+ .map(|reference| reference.id.clone())
+ .collect::<Vec<_>>();
+ for job in &mut project.generation_jobs {
+ if !self.changed_shots.contains(job.id.as_str()) {
+ continue;
+ }
+ let Some(shots) = job.shots.as_mut() else {
+ continue;
+ };
+ shots.sort_by(|left, right| left.start_seconds.total_cmp(&right.start_seconds));
+ let text = shots
+ .iter()
+ .map(|shot| shot.action.trim())
+ .filter(|line| !line.is_empty())
+ .collect::<Vec<_>>()
+ .join("\n\n");
+ job.prompt = text.clone();
+ job.creative_brief = text;
+ job.shot_tags = None;
+ for shot in shots {
+ for reference_id in action_reference_ids(&shot.action)? {
+ if reference_ids.iter().any(|id| id == reference_id)
+ && !job.reference_ids.iter().any(|id| id == reference_id)
+ {
+ job.reference_ids.push(reference_id.to_string());
+ }
}
}
}
+ Ok(())
}
- Ok(())
-}
}
diff --git a/src-tauri/src/project/commands/mod.rs b/src-tauri/src/project/commands/mod.rs
index 42c45f6..eaf6336 100644
--- a/src-tauri/src/project/commands/mod.rs
+++ b/src-tauri/src/project/commands/mod.rs
@@ -1,17 +1,17 @@
//! Restricted, transactional editing operations shared by agent transports.
-mod types;
-mod patch;
-mod jsonl;
mod batch;
+mod clips;
mod effects;
+mod jsonl;
+mod patch;
mod project;
mod references;
mod scenes;
mod shots;
-mod clips;
-pub(crate) use types::{ProjectCommand, CommandBatch};
-pub(crate) use jsonl::parse_jsonl_commands;
+mod types;
pub(crate) use batch::execute_commands_at;
+pub(crate) use jsonl::parse_jsonl_commands;
+pub(crate) use types::{CommandBatch, ProjectCommand};
#[cfg(test)]
mod tests;
pub(crate) use batch::execute_checked;
diff --git a/src-tauri/src/project/commands/patch.rs b/src-tauri/src/project/commands/patch.rs
index a24f3f9..9f3ab98 100644
--- a/src-tauri/src/project/commands/patch.rs
+++ b/src-tauri/src/project/commands/patch.rs
@@ -10,8 +10,12 @@ pub(crate) enum Patch<T> {
}
impl<T> Patch<T> {
- pub(super) fn is_unchanged(&self) -> bool { matches!(self, Self::Unchanged) }
- pub(super) fn is_changed(&self) -> bool { !self.is_unchanged() }
+ pub(super) fn is_unchanged(&self) -> bool {
+ matches!(self, Self::Unchanged)
+ }
+ pub(super) fn is_changed(&self) -> bool {
+ !self.is_unchanged()
+ }
}
impl<T: Clone> Patch<T> {
@@ -27,14 +31,18 @@ impl<T: Clone> Patch<T> {
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Patch<T> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(match Option::<T>::deserialize(deserializer)? {
- Some(value) => Self::Set(value), None => Self::Clear,
+ Some(value) => Self::Set(value),
+ None => Self::Clear,
})
}
}
impl<T: Serialize> Serialize for Patch<T> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
- match self { Self::Set(value) => value.serialize(serializer), _ => serializer.serialize_none() }
+ match self {
+ Self::Set(value) => value.serialize(serializer),
+ _ => serializer.serialize_none(),
+ }
}
}
diff --git a/src-tauri/src/project/commands/project.rs b/src-tauri/src/project/commands/project.rs
index d63711d..9a4c163 100644
--- a/src-tauri/src/project/commands/project.rs
+++ b/src-tauri/src/project/commands/project.rs
@@ -1,6 +1,11 @@
+use super::{batch::*, effects::Effects, types::ProjectCommand};
use crate::project::*;
-use super::{types::ProjectCommand, batch::*, effects::Effects};
-pub(super) fn apply(project: &mut ProjectConfig, command: &ProjectCommand, _timestamp: &str, _effects: &mut Effects) -> Result<(), String> {
+pub(super) fn apply(
+ project: &mut ProjectConfig,
+ command: &ProjectCommand,
+ _timestamp: &str,
+ _effects: &mut Effects,
+) -> Result<(), String> {
match command {
ProjectCommand::ProjectSet {
name,
diff --git a/src-tauri/src/project/commands/references.rs b/src-tauri/src/project/commands/references.rs
index 607d989..77c7330 100644
--- a/src-tauri/src/project/commands/references.rs
+++ b/src-tauri/src/project/commands/references.rs
@@ -1,6 +1,11 @@
+use super::{batch::*, effects::Effects, types::ProjectCommand};
use crate::project::*;
-use super::{types::ProjectCommand, batch::*, effects::Effects};
-pub(super) fn apply(project: &mut ProjectConfig, command: &ProjectCommand, timestamp: &str, _effects: &mut Effects) -> Result<(), String> {
+pub(super) fn apply(
+ project: &mut ProjectConfig,
+ command: &ProjectCommand,
+ timestamp: &str,
+ _effects: &mut Effects,
+) -> Result<(), String> {
match command {
ProjectCommand::ReferenceAdd {
id,
diff --git a/src-tauri/src/project/commands/scenes.rs b/src-tauri/src/project/commands/scenes.rs
index 92f2585..b4dcc35 100644
--- a/src-tauri/src/project/commands/scenes.rs
+++ b/src-tauri/src/project/commands/scenes.rs
@@ -1,6 +1,11 @@
+use super::{batch::*, effects::Effects, types::ProjectCommand};
use crate::project::*;
-use super::{types::ProjectCommand, batch::*, effects::Effects};
-pub(super) fn apply(project: &mut ProjectConfig, command: &ProjectCommand, timestamp: &str, effects: &mut Effects) -> Result<(), String> {
+pub(super) fn apply(
+ project: &mut ProjectConfig,
+ command: &ProjectCommand,
+ timestamp: &str,
+ effects: &mut Effects,
+) -> Result<(), String> {
match command {
ProjectCommand::SceneAdd {
id,
diff --git a/src-tauri/src/project/commands/shots.rs b/src-tauri/src/project/commands/shots.rs
index 63e6840..eb97396 100644
--- a/src-tauri/src/project/commands/shots.rs
+++ b/src-tauri/src/project/commands/shots.rs
@@ -1,6 +1,11 @@
+use super::{batch::*, effects::Effects, types::ProjectCommand};
use crate::project::*;
-use super::{types::ProjectCommand, batch::*, effects::Effects};
-pub(super) fn apply(project: &mut ProjectConfig, command: &ProjectCommand, timestamp: &str, effects: &mut Effects) -> Result<(), String> {
+pub(super) fn apply(
+ project: &mut ProjectConfig,
+ command: &ProjectCommand,
+ timestamp: &str,
+ effects: &mut Effects,
+) -> Result<(), String> {
match command {
ProjectCommand::ShotAdd {
scene,
diff --git a/src-tauri/src/project/commands/tests.rs b/src-tauri/src/project/commands/tests.rs
index eeb0a74..2738ca1 100644
--- a/src-tauri/src/project/commands/tests.rs
+++ b/src-tauri/src/project/commands/tests.rs
@@ -1,25 +1,43 @@
-use super::*;
use super::batch::execute_commands;
+use super::*;
#[test]
fn scene_creation_uses_injected_model_defaults() {
let current = fixture();
- let batch = parse_jsonl_commands(r#"{"op":"scene.add","id":"future-scene","title":"Future model","seconds":7}
+ let batch = parse_jsonl_commands(
+ r#"{"op":"scene.add","id":"future-scene","title":"Future model","seconds":7}
{"op":"shot.add","scene":"future-scene","id":"future-shot","at":0,"action":"A bird lands."}
-{"op":"commit","summary":"Create a scene"}"#).unwrap();
- let next = super::batch::execute_with_defaults(&current, &batch.commands, &current.updated_at,
- crate::generation::models::SceneDefaults { provider_id: "future-model", duration_seconds: 7.0 }).unwrap();
- let scene = next.generation_jobs.iter().find(|scene| scene.id == "future-scene").unwrap();
+{"op":"commit","summary":"Create a scene"}"#,
+ )
+ .unwrap();
+ let next = super::batch::execute_with_defaults(
+ &current,
+ &batch.commands,
+ &current.updated_at,
+ crate::generation::models::SceneDefaults {
+ provider_id: "future-model",
+ duration_seconds: 7.0,
+ },
+ )
+ .unwrap();
+ let scene = next
+ .generation_jobs
+ .iter()
+ .find(|scene| scene.id == "future-scene")
+ .unwrap();
assert_eq!(scene.provider_id.as_deref(), Some("future-model"));
assert_eq!(scene.prompt, "A bird lands.");
assert_eq!(current, fixture());
}
-use crate::project::validation::validate_and_normalize_config;
use super::clips::find_clip_location;
+use crate::project::validation::validate_and_normalize_config;
use crate::project::*;
fn fixture() -> ProjectConfig {
- serde_json::from_str(include_str!("../../../../fixtures/project-v1-complete.json")).unwrap()
+ serde_json::from_str(include_str!(
+ "../../../../fixtures/project-v1-complete.json"
+ ))
+ .unwrap()
}
#[test]
@@ -189,8 +207,11 @@ fn a_failed_command_does_not_mutate_the_input() {
#[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 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");
@@ -199,8 +220,13 @@ fn project_video_settings_update_both_mirrors_without_retiming_media() {
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();
+ 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());
}
}
diff --git a/src-tauri/src/project/commands/types.rs b/src-tauri/src/project/commands/types.rs
index d661e56..706da5c 100644
--- a/src-tauri/src/project/commands/types.rs
+++ b/src-tauri/src/project/commands/types.rs
@@ -102,15 +102,9 @@ pub enum ProjectCommand {
steps: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
seed: Option<i64>,
- #[serde(
- default,
- skip_serializing_if = "Patch::is_unchanged"
- )]
+ #[serde(default, skip_serializing_if = "Patch::is_unchanged")]
sound: Patch<String>,
- #[serde(
- default,
- skip_serializing_if = "Patch::is_unchanged"
- )]
+ #[serde(default, skip_serializing_if = "Patch::is_unchanged")]
music: Patch<String>,
#[serde(
default,
@@ -163,25 +157,13 @@ pub enum ProjectCommand {
start_seconds: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
action: Option<String>,
- #[serde(
- default,
- skip_serializing_if = "Patch::is_unchanged"
- )]
+ #[serde(default, skip_serializing_if = "Patch::is_unchanged")]
name: Patch<String>,
- #[serde(
- default,
- skip_serializing_if = "Patch::is_unchanged"
- )]
+ #[serde(default, skip_serializing_if = "Patch::is_unchanged")]
speech: Patch<String>,
- #[serde(
- default,
- skip_serializing_if = "Patch::is_unchanged"
- )]
+ #[serde(default, skip_serializing_if = "Patch::is_unchanged")]
language: Patch<String>,
- #[serde(
- default,
- skip_serializing_if = "Patch::is_unchanged"
- )]
+ #[serde(default, skip_serializing_if = "Patch::is_unchanged")]
settings: Patch<BTreeMap<String, Vec<String>>>,
},
#[serde(rename = "shot.remove")]
@@ -222,7 +204,6 @@ pub enum ProjectCommand {
ClipRemove { id: String },
}
-
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandBatch {
diff --git a/src-tauri/src/project/lifecycle.rs b/src-tauri/src/project/lifecycle.rs
index a1db531..1bceb69 100644
--- a/src-tauri/src/project/lifecycle.rs
+++ b/src-tauri/src/project/lifecycle.rs
@@ -1,7 +1,10 @@
use super::*;
use super::{paths::*, storage::*, validation::validate_and_normalize_config};
use crate::media::import::import_reference_file;
-use std::{env, fs, path::{Path, PathBuf}};
+use std::{
+ env, fs,
+ path::{Path, PathBuf},
+};
pub(crate) const PROJECT_DIRECTORIES: [&str; 6] = [
"media/imported",
"media/generated",
@@ -19,7 +22,10 @@ pub(crate) const PROJECT_ROOT_DIRECTORIES: [&str; 5] =
* require both to still agree. Broad filesystem roots, the user's home, the
* process working directory, and symlink targets are never valid deletion
* candidates even if somebody places a project file there. */
-pub(crate) fn delete_project_folder(folder_path: &str, expected_project_id: &str) -> Result<(), String> {
+pub(crate) fn delete_project_folder(
+ folder_path: &str,
+ expected_project_id: &str,
+) -> Result<(), String> {
if expected_project_id.trim().is_empty() {
return Err("The project id to delete cannot be empty.".into());
}
@@ -64,7 +70,10 @@ pub(crate) fn delete_project_folder(folder_path: &str, expected_project_id: &str
})
}
#[cfg(test)]
-pub(crate) fn create_project_in(parent: &Path, config: &ProjectConfig) -> Result<ProjectRecord, String> {
+pub(crate) fn create_project_in(
+ parent: &Path,
+ config: &ProjectConfig,
+) -> Result<ProjectRecord, String> {
create_project_in_with_references(parent, config, &[])
}
@@ -111,7 +120,11 @@ pub(crate) fn create_project_at_with_references(
.map_err(|error| format!("Could not create {child} folder: {error}"))?;
}
for (index, source) in reference_paths.iter().enumerate() {
- let imported = import_reference_file(&crate::media::access::MediaAccess::default(), source, &project_folder)?;
+ let imported = import_reference_file(
+ &crate::media::access::MediaAccess::default(),
+ source,
+ &project_folder,
+ )?;
let mut reference_id = format!("ref-initial-{}", index + 1);
let mut suffix = 2;
while config
diff --git a/src-tauri/src/project/mod.rs b/src-tauri/src/project/mod.rs
index e02cc14..8feffad 100644
--- a/src-tauri/src/project/mod.rs
+++ b/src-tauri/src/project/mod.rs
@@ -1,13 +1,13 @@
//! Project document types and operations, independent of the desktop transport.
+pub(crate) mod lifecycle;
+pub(crate) mod migrations;
pub(crate) mod model;
-pub(crate) mod timeline;
+pub(crate) mod paths;
pub(crate) mod references;
pub(crate) mod scenes;
-pub(crate) mod validation;
-pub(crate) mod migrations;
pub(crate) mod storage;
-pub(crate) mod lifecycle;
-pub(crate) mod paths;
+pub(crate) mod timeline;
+pub(crate) mod validation;
pub(crate) use model::*;
pub(crate) use references::*;
pub(crate) use scenes::*;
diff --git a/src-tauri/src/project/model.rs b/src-tauri/src/project/model.rs
index 0001348..1a8dd8b 100644
--- a/src-tauri/src/project/model.rs
+++ b/src-tauri/src/project/model.rs
@@ -1,6 +1,6 @@
+use super::{references::*, scenes::*, timeline::*};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
-use super::{references::*, scenes::*, timeline::*};
/// Project purpose, not the types of media it contains. Only video projects
/// can currently be created; the other values reserve future format support.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
diff --git a/src-tauri/src/project/paths.rs b/src-tauri/src/project/paths.rs
index 7dada25..308c3de 100644
--- a/src-tauri/src/project/paths.rs
+++ b/src-tauri/src/project/paths.rs
@@ -1,5 +1,5 @@
-use std::path::{Path, PathBuf};
use super::storage::project_file_in;
+use std::path::{Path, PathBuf};
/// Canonical identity of an existing project. All project artifact I/O resolves
/// through this boundary, including directories redirected by junctions.
@@ -9,19 +9,29 @@ pub(crate) struct ProjectRoot(PathBuf);
impl ProjectRoot {
/// Used while creating a project, before its config file exists.
pub(crate) fn from_directory(folder: &Path) -> Result<Self, String> {
- let root = folder.canonicalize().map_err(|error| format!("Could not resolve project folder: {error}"))?;
- if !root.is_dir() { return Err("The selected project folder does not exist.".into()); }
+ let root = folder
+ .canonicalize()
+ .map_err(|error| format!("Could not resolve project folder: {error}"))?;
+ if !root.is_dir() {
+ return Err("The selected project folder does not exist.".into());
+ }
Ok(Self(root))
}
pub(crate) fn open(folder: &str) -> Result<Self, String> {
project_root(folder).map(Self)
}
- pub(crate) fn path(&self) -> &Path { &self.0 }
+ pub(crate) fn path(&self) -> &Path {
+ &self.0
+ }
pub(crate) fn existing(&self, relative: &str) -> Result<PathBuf, String> {
let relative = normalize_project_path(relative)?;
- let target = self.0.join(relative).canonicalize().map_err(|error| error.to_string())?;
+ let target = self
+ .0
+ .join(relative)
+ .canonicalize()
+ .map_err(|error| error.to_string())?;
self.check_containment(&target)?;
Ok(target)
}
@@ -34,19 +44,25 @@ impl ProjectRoot {
for component in relative.split('/') {
directory.push(component);
match std::fs::create_dir(&directory) {
- Ok(()) => {},
- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {},
+ Ok(()) => {}
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(format!("Could not prepare project directory: {error}")),
}
- directory = directory.canonicalize().map_err(|error| error.to_string())?;
+ directory = directory
+ .canonicalize()
+ .map_err(|error| error.to_string())?;
self.check_containment(&directory)?;
- if !directory.is_dir() { return Err("The project destination is not a directory.".into()); }
+ if !directory.is_dir() {
+ return Err("The project destination is not a directory.".into());
+ }
}
Ok(directory)
}
fn check_containment(&self, target: &Path) -> Result<(), String> {
- if !target.starts_with(&self.0) { return Err("Project files must stay inside the project folder.".into()); }
+ if !target.starts_with(&self.0) {
+ return Err("Project files must stay inside the project folder.".into());
+ }
Ok(())
}
}
@@ -65,7 +81,10 @@ mod tests {
std::fs::write(project.join("slopus.json"), "{}").unwrap();
let root = ProjectRoot::open(project.to_str().unwrap()).unwrap();
assert!(root.directory("../outside").is_err());
- assert!(root.directory("cache/frames").unwrap().starts_with(root.path()));
+ assert!(root
+ .directory("cache/frames")
+ .unwrap()
+ .starts_with(root.path()));
let link = project.join("media");
#[cfg(unix)]
diff --git a/src-tauri/src/project/references.rs b/src-tauri/src/project/references.rs
index d5f4ee7..28a8c71 100644
--- a/src-tauri/src/project/references.rs
+++ b/src-tauri/src/project/references.rs
@@ -61,5 +61,9 @@ pub(crate) struct ReferenceRefmod {
#[serde(default = "default_refmod_copies")]
pub(crate) copies: u32,
}
-pub(crate) fn default_refmod_strength() -> f64 { 1.0 }
-pub(crate) fn default_refmod_copies() -> u32 { 1 }
+pub(crate) fn default_refmod_strength() -> f64 {
+ 1.0
+}
+pub(crate) fn default_refmod_copies() -> u32 {
+ 1
+}
diff --git a/src-tauri/src/project/scenes.rs b/src-tauri/src/project/scenes.rs
index 884cc88..420d9bd 100644
--- a/src-tauri/src/project/scenes.rs
+++ b/src-tauri/src/project/scenes.rs
@@ -119,36 +119,41 @@ pub(crate) struct GenerationJob {
}
impl GenerationJob {
- pub(crate) fn draft(id: &str, title: &str, timestamp: &str, defaults: crate::generation::models::SceneDefaults) -> Self {
+ pub(crate) fn draft(
+ id: &str,
+ title: &str,
+ timestamp: &str,
+ defaults: crate::generation::models::SceneDefaults,
+ ) -> Self {
let now = timestamp.to_string();
Self {
- id: id.to_string(),
- title: title.to_string(),
- prompt: String::new(),
- status: "draft".into(),
- stage: "queued".into(),
- progress: 0.0,
- provider_id: Some(defaults.provider_id.into()),
- creative_brief: String::new(),
- compiled_prompt: String::new(),
- generation_snapshot: None,
- reference_ids: Vec::new(),
- start_frame_reference_id: None,
- end_frame_reference_id: None,
- use_previous_scene_last_frame: None,
- shot_tags: None,
- shots: Some(Vec::new()),
- duration_seconds: Some(defaults.duration_seconds),
- steps: None,
- seed: None,
- soundscape: None,
- music: None,
- clip_id: None,
- output_relative_path: None,
- latent_relative_path: None,
- error: None,
- created_at: now.clone(),
- updated_at: now,
+ id: id.to_string(),
+ title: title.to_string(),
+ prompt: String::new(),
+ status: "draft".into(),
+ stage: "queued".into(),
+ progress: 0.0,
+ provider_id: Some(defaults.provider_id.into()),
+ creative_brief: String::new(),
+ compiled_prompt: String::new(),
+ generation_snapshot: None,
+ reference_ids: Vec::new(),
+ start_frame_reference_id: None,
+ end_frame_reference_id: None,
+ use_previous_scene_last_frame: None,
+ shot_tags: None,
+ shots: Some(Vec::new()),
+ duration_seconds: Some(defaults.duration_seconds),
+ steps: None,
+ seed: None,
+ soundscape: None,
+ music: None,
+ clip_id: None,
+ output_relative_path: None,
+ latent_relative_path: None,
+ error: None,
+ created_at: now.clone(),
+ updated_at: now,
}
}
}
diff --git a/src-tauri/src/project/storage.rs b/src-tauri/src/project/storage.rs
index b490f04..c790dbe 100644
--- a/src-tauri/src/project/storage.rs
+++ b/src-tauri/src/project/storage.rs
@@ -1,6 +1,12 @@
-use super::{ProjectConfig, ProjectRecord, AgentConversation, validation::validate_and_normalize_config, paths::display_path};
+use super::{
+ paths::display_path, validation::validate_and_normalize_config, AgentConversation,
+ ProjectConfig, ProjectRecord,
+};
use crate::storage::atomic::atomic_replace;
-use std::{fs, io, path::{Path, PathBuf}};
+use std::{
+ fs, io,
+ path::{Path, PathBuf},
+};
pub(crate) const PROJECT_FILE_NAME: &str = "slopus.json";
/// What the file was called before, newest first. Folders written by earlier
/// builds still open; the next save writes `slopus.json` and leaves the old
@@ -62,6 +68,10 @@ where
let json = serde_json::to_string_pretty(&config)
.map_err(|error| format!("Could not serialize project: {error}"))?;
let destination = folder.join(PROJECT_FILE_NAME);
- crate::storage::atomic::write_with_replacer(&destination, format!("{json}\n").as_bytes(), replacer)
- .map_err(|error| format!("Could not write project config: {error}"))
+ crate::storage::atomic::write_with_replacer(
+ &destination,
+ format!("{json}\n").as_bytes(),
+ replacer,
+ )
+ .map_err(|error| format!("Could not write project config: {error}"))
}
diff --git a/src-tauri/src/project/validation/assets.rs b/src-tauri/src/project/validation/assets.rs
index dd9f97c..6128aa3 100644
--- a/src-tauri/src/project/validation/assets.rs
+++ b/src-tauri/src/project/validation/assets.rs
@@ -1,6 +1,6 @@
-use crate::project::*;
-use crate::project::paths::*;
use super::values::*;
+use crate::project::paths::*;
+use crate::project::*;
pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
for asset in &mut config.assets {
if asset.id.trim().is_empty() || asset.name.trim().is_empty() {
diff --git a/src-tauri/src/project/validation/issue.rs b/src-tauri/src/project/validation/issue.rs
index bd85330..a4f1e49 100644
--- a/src-tauri/src/project/validation/issue.rs
+++ b/src-tauri/src/project/validation/issue.rs
@@ -14,10 +14,24 @@ pub(crate) struct ValidationIssue {
}
impl ValidationIssue {
- pub(crate) fn new(code: &'static str, entity: Option<String>, field: &'static str, message: String) -> Self {
- Self { key: IssueKey { code, entity, field }, message }
+ pub(crate) fn new(
+ code: &'static str,
+ entity: Option<String>,
+ field: &'static str,
+ message: String,
+ ) -> Self {
+ Self {
+ key: IssueKey {
+ code,
+ entity,
+ field,
+ },
+ message,
+ }
}
}
impl std::fmt::Display for ValidationIssue {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.message) }
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.message)
+ }
}
diff --git a/src-tauri/src/project/validation/mod.rs b/src-tauri/src/project/validation/mod.rs
index d0a5e0c..e59c615 100644
--- a/src-tauri/src/project/validation/mod.rs
+++ b/src-tauri/src/project/validation/mod.rs
@@ -2,28 +2,88 @@
mod values;
#[cfg(test)]
pub(crate) use values::is_iso_datetime;
-mod settings;
mod assets;
+pub(crate) mod issue;
mod references;
-mod timeline;
+mod relationships;
mod scenes;
mod session;
-mod relationships;
-pub(crate) mod issue;
+mod settings;
+mod timeline;
use crate::project::ProjectConfig;
-pub(crate) fn validate_and_normalize_config(config: ProjectConfig) -> Result<ProjectConfig, String> {
+pub(crate) fn validate_and_normalize_config(
+ config: ProjectConfig,
+) -> Result<ProjectConfig, String> {
validate_checked(config).map_err(|issue| issue.message)
}
-pub(crate) fn validate_checked(mut config: ProjectConfig) -> Result<ProjectConfig, issue::ValidationIssue> {
- settings::validate(&mut config).map_err(|message| issue::ValidationIssue::new("project.invalid", Some(config.id.clone()), "settings", message))?;
- assets::validate(&mut config).map_err(|message| issue::ValidationIssue::new("project.invalid", Some(config.id.clone()), "assets", message))?;
- references::validate(&mut config).map_err(|message| issue::ValidationIssue::new("project.invalid", Some(config.id.clone()), "references", message))?;
- super::migrations::normalize_timeline(&mut config).map_err(|message| issue::ValidationIssue::new("project.invalid", Some(config.id.clone()), "migrations", message))?;
- timeline::validate(&mut config).map_err(|message| issue::ValidationIssue::new("project.invalid", Some(config.id.clone()), "timeline", message))?;
- scenes::validate(&mut config).map_err(|message| issue::ValidationIssue::new("project.invalid", Some(config.id.clone()), "scenes", message))?;
- session::validate(&mut config).map_err(|message| issue::ValidationIssue::new("project.invalid", Some(config.id.clone()), "session", message))?;
- relationships::validate(&mut config).map_err(|message| issue::ValidationIssue::new("project.invalid", Some(config.id.clone()), "relationships", message))?;
+pub(crate) fn validate_checked(
+ mut config: ProjectConfig,
+) -> Result<ProjectConfig, issue::ValidationIssue> {
+ settings::validate(&mut config).map_err(|message| {
+ issue::ValidationIssue::new(
+ "project.invalid",
+ Some(config.id.clone()),
+ "settings",
+ message,
+ )
+ })?;
+ assets::validate(&mut config).map_err(|message| {
+ issue::ValidationIssue::new(
+ "project.invalid",
+ Some(config.id.clone()),
+ "assets",
+ message,
+ )
+ })?;
+ references::validate(&mut config).map_err(|message| {
+ issue::ValidationIssue::new(
+ "project.invalid",
+ Some(config.id.clone()),
+ "references",
+ message,
+ )
+ })?;
+ super::migrations::normalize_timeline(&mut config).map_err(|message| {
+ issue::ValidationIssue::new(
+ "project.invalid",
+ Some(config.id.clone()),
+ "migrations",
+ message,
+ )
+ })?;
+ timeline::validate(&mut config).map_err(|message| {
+ issue::ValidationIssue::new(
+ "project.invalid",
+ Some(config.id.clone()),
+ "timeline",
+ message,
+ )
+ })?;
+ scenes::validate(&mut config).map_err(|message| {
+ issue::ValidationIssue::new(
+ "project.invalid",
+ Some(config.id.clone()),
+ "scenes",
+ message,
+ )
+ })?;
+ session::validate(&mut config).map_err(|message| {
+ issue::ValidationIssue::new(
+ "project.invalid",
+ Some(config.id.clone()),
+ "session",
+ message,
+ )
+ })?;
+ relationships::validate(&mut config).map_err(|message| {
+ issue::ValidationIssue::new(
+ "project.invalid",
+ Some(config.id.clone()),
+ "relationships",
+ message,
+ )
+ })?;
Ok(config)
}
diff --git a/src-tauri/src/project/validation/references.rs b/src-tauri/src/project/validation/references.rs
index 80e71b8..0c7e3df 100644
--- a/src-tauri/src/project/validation/references.rs
+++ b/src-tauri/src/project/validation/references.rs
@@ -1,7 +1,7 @@
-use crate::project::*;
+use super::values::*;
use crate::project::paths::*;
+use crate::project::*;
use std::collections::BTreeSet;
-use super::values::*;
pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
for reference in &mut config.references {
if reference.id.trim().is_empty() || reference.name.trim().is_empty() {
@@ -17,8 +17,11 @@ pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
.as_deref()
.map(normalize_external_path)
.transpose()?;
- reference.icon_relative_path = reference.icon_relative_path.as_deref()
- .map(normalize_project_path).transpose()?;
+ reference.icon_relative_path = reference
+ .icon_relative_path
+ .as_deref()
+ .map(normalize_project_path)
+ .transpose()?;
if reference.relative_path.is_some() && reference.source_path.is_some() {
return Err(format!(
"Reference '{}' cannot have both a project-relative path and an external source path.",
@@ -29,18 +32,40 @@ pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
let mut refmod_ids = BTreeSet::new();
for refmod in &mut reference.refmods {
let file = &mut refmod.file;
- if file.id.trim().is_empty() || file.name.trim().is_empty() || !refmod_ids.insert(file.id.clone())
- || !refmod.strength.is_finite() || !(0.0..=1.0).contains(&refmod.strength)
- || !(1..=10).contains(&refmod.copies) {
- return Err("Refmods need unique ids, names, strength 0 to 1 and copies 1 to 10.".into());
+ if file.id.trim().is_empty()
+ || file.name.trim().is_empty()
+ || !refmod_ids.insert(file.id.clone())
+ || !refmod.strength.is_finite()
+ || !(0.0..=1.0).contains(&refmod.strength)
+ || !(1..=10).contains(&refmod.copies)
+ {
+ return Err(
+ "Refmods need unique ids, names, strength 0 to 1 and copies 1 to 10.".into(),
+ );
}
- file.relative_path = file.relative_path.as_deref().map(normalize_project_path).transpose()?;
- file.source_path = file.source_path.as_deref().map(normalize_external_path).transpose()?;
- check_one_location("Refmod", file.relative_path.as_ref(), file.source_path.as_ref())?;
+ file.relative_path = file
+ .relative_path
+ .as_deref()
+ .map(normalize_project_path)
+ .transpose()?;
+ file.source_path = file
+ .source_path
+ .as_deref()
+ .map(normalize_external_path)
+ .transpose()?;
+ check_one_location(
+ "Refmod",
+ file.relative_path.as_ref(),
+ file.source_path.as_ref(),
+ )?;
}
if let Some(video) = &reference.video {
- if reference.kind != "video" || !video.start_seconds.is_finite() || video.start_seconds < 0.0
- || !video.duration_seconds.is_finite() || !(2.0..=15.0).contains(&video.duration_seconds) {
+ if reference.kind != "video"
+ || !video.start_seconds.is_finite()
+ || video.start_seconds < 0.0
+ || !video.duration_seconds.is_finite()
+ || !(2.0..=15.0).contains(&video.duration_seconds)
+ {
return Err(format!("Reference '{}' needs a nonnegative clip start and a duration of 2 to 15 seconds.", reference.id));
}
}
diff --git a/src-tauri/src/project/validation/relationships.rs b/src-tauri/src/project/validation/relationships.rs
index c6eb0c4..55a95f6 100644
--- a/src-tauri/src/project/validation/relationships.rs
+++ b/src-tauri/src/project/validation/relationships.rs
@@ -1,5 +1,5 @@
-use crate::project::*;
use super::values::*;
+use crate::project::*;
pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
let asset_ids = unique_ids(config.assets.iter().map(|asset| asset.id.as_str()), "asset")?;
let reference_ids = unique_ids(
diff --git a/src-tauri/src/project/validation/scenes.rs b/src-tauri/src/project/validation/scenes.rs
index 4fc5d33..e1d5443 100644
--- a/src-tauri/src/project/validation/scenes.rs
+++ b/src-tauri/src/project/validation/scenes.rs
@@ -1,11 +1,13 @@
-use crate::project::*;
+use super::values::*;
use crate::project::paths::*;
+use crate::project::*;
use std::collections::BTreeSet;
-use super::values::*;
pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
for job in &mut config.generation_jobs {
- let max_seconds = crate::generation::models::for_scene(job.provider_id.as_deref())
- .unwrap_or_else(crate::generation::models::default_model).capabilities.max_scene_seconds;
+ let limits = crate::generation::models::for_scene(job.provider_id.as_deref())
+ .unwrap_or_else(crate::generation::models::default_model)
+ .capabilities;
+ let max_seconds = limits.max_scene_seconds;
/* Normalise the scene BEFORE anything is judged, so both layers judge
the same thing. An empty `shots` array collapses to no key at all —
the same three-step tidy `normalize_shot_tags` performs, for the same
@@ -32,7 +34,9 @@ pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
shot.id, job.id
));
}
- if !shot.start_seconds.is_finite() || !(0.0..=max_seconds).contains(&shot.start_seconds) {
+ if !shot.start_seconds.is_finite()
+ || !(0.0..=max_seconds).contains(&shot.start_seconds)
+ {
return Err(format!(
"Shot '{}' in scene '{}' starts at {} seconds, outside the 0-{max_seconds} second scene.",
shot.id, job.id, shot.start_seconds
@@ -53,10 +57,10 @@ pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
));
}
}
- if job.steps.is_some_and(|steps| steps < 2) {
+ if job.steps.is_some_and(|steps| steps < limits.min_steps) {
return Err(format!(
- "Scene '{}' must use at least 2 generation steps.",
- job.id
+ "Scene '{}' must use at least {} generation steps.",
+ job.id, limits.min_steps
));
}
if job.seed.is_some_and(|seed| seed < -1) {
@@ -145,8 +149,11 @@ pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
.as_deref()
.map(normalize_project_path)
.transpose()?;
- job.latent_relative_path = job.latent_relative_path.as_deref()
- .map(normalize_project_path).transpose()?;
+ job.latent_relative_path = job
+ .latent_relative_path
+ .as_deref()
+ .map(normalize_project_path)
+ .transpose()?;
}
Ok(())
}
diff --git a/src-tauri/src/project/validation/session.rs b/src-tauri/src/project/validation/session.rs
index d256504..1b00414 100644
--- a/src-tauri/src/project/validation/session.rs
+++ b/src-tauri/src/project/validation/session.rs
@@ -1,5 +1,5 @@
-use crate::project::*;
use super::values::*;
+use crate::project::*;
pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
for message in &config.agent_conversation.messages {
if message.id.trim().is_empty() || message.content.trim().is_empty() {
diff --git a/src-tauri/src/project/validation/settings.rs b/src-tauri/src/project/validation/settings.rs
index f907a26..1d77e7c 100644
--- a/src-tauri/src/project/validation/settings.rs
+++ b/src-tauri/src/project/validation/settings.rs
@@ -1,6 +1,6 @@
-use crate::project::*;
-use crate::project::paths::*;
use super::values::*;
+use crate::project::paths::*;
+use crate::project::*;
pub(super) fn validate(config: &mut ProjectConfig) -> Result<(), String> {
if config.schema_version != 1 {
return Err(format!(
diff --git a/src-tauri/src/slopfab/config.rs b/src-tauri/src/slopfab/config.rs
index 5ba1420..2cb31b4 100644
--- a/src-tauri/src/slopfab/config.rs
+++ b/src-tauri/src/slopfab/config.rs
@@ -1,4 +1,7 @@
-use super::*;
+use super::{default_dll_path, platform::ComputePlatform, types::GenerationRequest};
+use crate::project::{ProviderOption, ProviderSetting};
+use serde::Deserialize;
+use std::{collections::BTreeMap, path::PathBuf};
#[derive(Debug, Clone, Deserialize)]
pub(super) struct LoraAdapter {
@@ -57,13 +60,22 @@ impl Configuration {
],
loras: match slopfab.and_then(|setting| setting.options.get("loras")) {
None => Ok(Vec::new()),
- Some(ProviderOption::String(value)) => serde_json::from_str::<Vec<LoraAdapter>>(value)
- .map_err(|error| format!("Invalid LoRA settings: {error}")),
+ Some(ProviderOption::String(value)) => {
+ serde_json::from_str::<Vec<LoraAdapter>>(value)
+ .map_err(|error| format!("Invalid LoRA settings: {error}"))
+ }
_ => Err("LoRA settings must be a JSON array of paths and strengths.".into()),
},
step_override: match slopfab.and_then(|setting| setting.options.get("stepOverride")) {
None => Ok(None),
- Some(ProviderOption::Number(value)) if value.is_finite() && value.fract() == 0.0 && *value >= 2.0 && *value <= i32::MAX as f64 => Ok(Some(*value as i32)),
+ Some(ProviderOption::Number(value))
+ if value.is_finite()
+ && value.fract() == 0.0
+ && *value >= 2.0
+ && *value <= i32::MAX as f64 =>
+ {
+ Ok(Some(*value as i32))
+ }
_ => Err("LoRA step override must be a whole number from 2 to 2147483647.".into()),
},
}
@@ -78,7 +90,9 @@ impl Configuration {
return Err("Animate requires exactly one reference video.".into());
}
if request.reference_paths.len() != 1 {
- return Err("Animate requires exactly one repainted frame of the driving scene.".into());
+ return Err(
+ "Animate requires exactly one repainted frame of the driving scene.".into(),
+ );
}
if request.continuation_path.is_some() || !request.refmods.is_empty() {
return Err("Animate does not support scene continuation or refmods.".into());
@@ -90,7 +104,9 @@ impl Configuration {
}
pub(super) fn generation_steps(&self, fallback: i32) -> Result<i32, String> {
- self.step_override.clone().map(|steps| steps.unwrap_or(fallback))
+ self.step_override
+ .clone()
+ .map(|steps| steps.unwrap_or(fallback))
}
pub(super) fn platform(&self, detected: ComputePlatform) -> ComputePlatform {
@@ -116,8 +132,22 @@ impl Configuration {
})
.collect::<Vec<_>>()
.join(";");
- let adapters = self.loras.as_ref().map(|loras| loras.iter()
- .map(|lora| format!("{}@{}", lora.path, lora.strength)).collect::<Vec<_>>().join(";")).unwrap_or_default();
- format!("slopfab={version}|platform={}|attention={}|{models}|loras={adapters}|steps={:?}", platform.label(), self.attention, self.step_override)
+ let adapters = self
+ .loras
+ .as_ref()
+ .map(|loras| {
+ loras
+ .iter()
+ .map(|lora| format!("{}@{}", lora.path, lora.strength))
+ .collect::<Vec<_>>()
+ .join(";")
+ })
+ .unwrap_or_default();
+ format!(
+ "slopfab={version}|platform={}|attention={}|{models}|loras={adapters}|steps={:?}",
+ platform.label(),
+ self.attention,
+ self.step_override
+ )
}
}
diff --git a/src-tauri/src/slopfab/events.rs b/src-tauri/src/slopfab/events.rs
index 22e27e3..c31176f 100644
--- a/src-tauri/src/slopfab/events.rs
+++ b/src-tauri/src/slopfab/events.rs
@@ -1,7 +1,13 @@
-use super::*;
+use super::ffi;
+use super::types::{JobEvent, ProgressEvent};
+use crate::diagnostics;
+use std::sync::Arc;
pub type EventSink = Arc<dyn Fn(NativeEvent) + Send + Sync>;
-pub enum NativeEvent { Job(JobEvent), Progress(ProgressEvent) }
+pub enum NativeEvent {
+ Job(JobEvent),
+ Progress(ProgressEvent),
+}
pub(super) struct CallbackContext {
pub(super) events: EventSink,
@@ -15,7 +21,7 @@ pub(super) struct CallbackContext {
}
pub(super) fn progress_sink(context: CallbackContext) -> ffi::ProgressSink {
- Box::new(move |progress| {
+ Box::new(move |progress| {
diagnostics::debug(
"slopfab",
"generation.progress",
@@ -29,23 +35,20 @@ pub(super) fn progress_sink(context: CallbackContext) -> ffi::ProgressSink {
"elapsedSeconds": progress.elapsed_seconds,
}),
);
- (context.events)(NativeEvent::Progress(
- ProgressEvent {
- job_id: context.job_id.clone(),
- stage: stage_name(progress.stage),
- step: progress.step,
- total_steps: progress.total_steps,
- planned_steps: context.planned_steps,
- elapsed_seconds: progress.elapsed_seconds,
- frames: context.frames,
- canvas_width: context.canvas_width,
- canvas_height: context.canvas_height,
- reference_count: context.reference_count,
- timing_profile: context.timing_profile.clone(),
- },
- ));
-
- })
+ (context.events)(NativeEvent::Progress(ProgressEvent {
+ job_id: context.job_id.clone(),
+ stage: stage_name(progress.stage),
+ step: progress.step,
+ total_steps: progress.total_steps,
+ planned_steps: context.planned_steps,
+ elapsed_seconds: progress.elapsed_seconds,
+ frames: context.frames,
+ canvas_width: context.canvas_width,
+ canvas_height: context.canvas_height,
+ reference_count: context.reference_count,
+ timing_profile: context.timing_profile.clone(),
+ }));
+ })
}
pub(super) fn stage_name(stage: i32) -> &'static str {
match stage {
diff --git a/src-tauri/src/slopfab/ffi/handles.rs b/src-tauri/src/slopfab/ffi/handles.rs
index fc64c2c..52be292 100644
--- a/src-tauri/src/slopfab/ffi/handles.rs
+++ b/src-tauri/src/slopfab/ffi/handles.rs
@@ -19,43 +19,69 @@ pub struct GenerationHandle {
api: Api,
pointer: NonNull<raw::Generation>,
_callback: Option<Box<Callback>>,
+ _request: RequestHandle,
terminal: bool,
succeeded: bool,
}
impl GenerationHandle {
- pub(super) fn start(request: &RequestHandle, sink: Option<ProgressSink>) -> Result<Self, String> {
+ pub(super) fn start(
+ request: RequestHandle,
+ sink: Option<ProgressSink>,
+ ) -> Result<Self, String> {
let mut callback = sink.map(|sink| Box::new(Callback(sink)));
let userdata = callback.as_mut().map_or(std::ptr::null_mut(), |value| {
(&mut **value as *mut Callback).cast()
});
let pointer = request.api.inner.start(
request.pointer.as_ptr(),
- callback.as_ref().map(|_| progress_callback as unsafe extern "C" fn(_, _)),
+ callback
+ .as_ref()
+ .map(|_| progress_callback as unsafe extern "C" fn(_, _)),
userdata,
)?;
- let pointer = NonNull::new(pointer).ok_or("Slopfab returned an empty generation handle.")?;
- Ok(Self { api: request.api.clone(), pointer, _callback: callback, terminal: false, succeeded: false })
+ let pointer =
+ NonNull::new(pointer).ok_or("Slopfab returned an empty generation handle.")?;
+ Ok(Self {
+ api: request.api.clone(),
+ pointer,
+ _callback: callback,
+ _request: request,
+ terminal: false,
+ succeeded: false,
+ })
}
- pub fn cancel(&self) { self.api.inner.cancel(self.pointer.as_ptr()); }
+ pub fn cancel(&self) {
+ self.api.inner.cancel(self.pointer.as_ptr());
+ }
/// A false result means the wait timed out; all other statuses are terminal.
pub fn wait(&mut self, timeout: i32) -> Result<bool, String> {
let code = self.api.inner.wait(self.pointer.as_ptr(), timeout);
- if code == super::super::NOT_READY { return Ok(false); }
+ if code == super::super::NOT_READY {
+ return Ok(false);
+ }
self.terminal = true;
self.succeeded = code == 0;
- if code == 0 { return Ok(true); }
+ if code == 0 {
+ return Ok(true);
+ }
if code == super::super::CANCELLED {
return Err("Generation cancelled at the next slopfab checkpoint.".into());
}
let detail = self.api.inner.generation_error(self.pointer.as_ptr());
- Err(if detail.is_empty() { format!("slopfab generation failed with status {code}.") } else { detail })
+ Err(if detail.is_empty() {
+ format!("slopfab generation failed with status {code}.")
+ } else {
+ detail
+ })
}
pub fn finish(self) -> Result<FinishedGeneration, String> {
- if !self.succeeded { return Err("Generation has not completed successfully.".into()); }
+ if !self.succeeded {
+ return Err("Generation has not completed successfully.".into());
+ }
Ok(FinishedGeneration(self))
}
}
@@ -100,25 +126,40 @@ impl FinishedGeneration {
pub fn output(&self) -> Result<Output, String> {
let value = self.0.api.inner.output(self.0.pointer.as_ptr())?;
if value.audio_float_count > isize::MAX as usize / std::mem::size_of::<f32>()
- || (value.audio.is_null() && value.audio_float_count != 0) {
+ || (value.audio.is_null() && value.audio_float_count != 0)
+ {
return Err("Slopfab returned an invalid audio buffer.".into());
}
- let audio = if value.audio_float_count == 0 { Vec::new() } else {
+ let audio = if value.audio_float_count == 0 {
+ Vec::new()
+ } else {
// The successful generation owns this buffer for the whole borrow.
unsafe { std::slice::from_raw_parts(value.audio, value.audio_float_count) }.to_vec()
};
Ok(Output {
- video_float_count: value.video_float_count, channels: value.channels,
- frames: value.frames, width: value.width, height: value.height, audio,
- audio_channels: value.audio_channels, audio_sample_rate: value.audio_sample_rate,
- fps: value.fps, seconds_conditioning: value.seconds_conditioning,
- seconds_denoise: value.seconds_denoise, seconds_video_decode: value.seconds_video_decode,
- seconds_audio_decode: value.seconds_audio_decode, seconds_total: value.seconds_total,
- steps_computed: value.steps_computed, steps_skipped: value.steps_skipped,
+ video_float_count: value.video_float_count,
+ channels: value.channels,
+ frames: value.frames,
+ width: value.width,
+ height: value.height,
+ audio,
+ audio_channels: value.audio_channels,
+ audio_sample_rate: value.audio_sample_rate,
+ fps: value.fps,
+ seconds_conditioning: value.seconds_conditioning,
+ seconds_denoise: value.seconds_denoise,
+ seconds_video_decode: value.seconds_video_decode,
+ seconds_audio_decode: value.seconds_audio_decode,
+ seconds_total: value.seconds_total,
+ steps_computed: value.steps_computed,
+ steps_skipped: value.steps_skipped,
})
}
pub fn frame_rgba8(&self, index: u32, width: u32, height: u32) -> Result<Vec<u8>, String> {
- self.0.api.inner.frame_rgba8(self.0.pointer.as_ptr(), index, width, height)
+ self.0
+ .api
+ .inner
+ .frame_rgba8(self.0.pointer.as_ptr(), index, width, height)
}
}
diff --git a/src-tauri/src/slopfab/ffi/mod.rs b/src-tauri/src/slopfab/ffi/mod.rs
index 6680a99..ef9a8e4 100644
--- a/src-tauri/src/slopfab/ffi/mod.rs
+++ b/src-tauri/src/slopfab/ffi/mod.rs
@@ -1,71 +1,194 @@
-mod raw;
mod handles;
-pub use handles::{GenerationHandle, FinishedGeneration, ProgressSink};
-pub use raw::{Plan, Progress, has_cuda_device, gpu_devices, cuda_device_names};
-use std::{path::{Path,PathBuf}, sync::Arc, ptr::NonNull};
+mod raw;
+#[cfg(test)]
+mod tests;
+pub use handles::{FinishedGeneration, GenerationHandle, ProgressSink};
+pub use raw::{cuda_device_names, gpu_devices, has_cuda_device, Plan, Progress};
+use std::{
+ path::{Path, PathBuf},
+ ptr::NonNull,
+ sync::Arc,
+};
#[derive(Clone)]
-pub struct Api { inner: Arc<raw::Api>, path: PathBuf }
+pub struct Api {
+ inner: Arc<raw::Api>,
+ path: PathBuf,
+}
impl Api {
- pub fn load(path: &Path) -> Result<Self,String> {
- let inner=raw::Api::load(path)?;
+ pub fn load(path: &Path) -> Result<Self, String> {
+ let inner = raw::Api::load(path)?;
inner.version()?;
- Ok(Self {inner:Arc::new(inner),path:path.to_owned()})
- }
- pub fn version(&self)->Result<String,String>{self.inner.version()}
- pub fn set_cuda_version(&self,v:&str)->Result<(),String>{self.inner.set_cuda_version(v)}
- pub fn cuda_loaded_major(&self)->Result<i32,String>{self.inner.cuda_loaded_major()}
- pub fn clear_reused_models(&self)->Result<(),String>{self.inner.clear_reused_models()}
- #[cfg(test)] pub fn disable_animate_for_test(&mut self) { Arc::get_mut(&mut self.inner).expect("configure API before creating handles").disable_animate_for_test(); }
- fn check(&self,r:&RequestHandle)->Result<(),String>{
- if Arc::ptr_eq(&self.inner,&r.api.inner){Ok(())}else{Err("Request belongs to a different runtime instance.".into())}
- }
-pub fn set_prompt(&self, r: &RequestHandle, v: &str) -> Result<(), String> { self.check(r)?; self.inner.set_prompt(r.pointer.as_ptr(), v) }
-pub fn set_animate(&self, r: &RequestHandle, preserve_audio: bool) -> Result<(), String> { self.check(r)?; self.inner.set_animate(r.pointer.as_ptr(), preserve_audio) }
-pub fn set_prompt_embedding(&self, r: &RequestHandle, path: &Path) -> Result<(), String> { self.check(r)?; self.inner.set_prompt_embedding(r.pointer.as_ptr(), path) }
-pub fn set_resolution(&self, r: &RequestHandle, w: i32, h: i32) -> Result<(), String> { self.check(r)?; self.inner.set_resolution(r.pointer.as_ptr(), w, h) }
-pub fn set_frames(&self, r: &RequestHandle, v: i32) -> Result<(), String> { self.check(r)?; self.inner.set_frames(r.pointer.as_ptr(), v) }
-pub fn set_still_image(&self, r: &RequestHandle) -> Result<(), String> { self.check(r)?; self.inner.set_still_image(r.pointer.as_ptr()) }
-pub fn set_save_latents(&self, r: &RequestHandle, path: &Path) -> Result<(), String> { self.check(r)?; self.inner.set_save_latents(r.pointer.as_ptr(), path) }
-pub fn set_continuation_file(&self, r: &RequestHandle, path: &Path, overlap: i32) -> Result<(), String> { self.check(r)?; self.inner.set_continuation_file(r.pointer.as_ptr(), path, overlap) }
-pub fn set_steps(&self, r: &RequestHandle, v: i32) -> Result<(), String> { self.check(r)?; self.inner.set_steps(r.pointer.as_ptr(), v) }
-pub fn set_seed(&self, r: &RequestHandle, v: u64) -> Result<(), String> { self.check(r)?; self.inner.set_seed(r.pointer.as_ptr(), v) }
-pub fn set_verbose(&self, r: &RequestHandle, v: bool) -> Result<(), String> { self.check(r)?; self.inner.set_verbose(r.pointer.as_ptr(), v) }
-pub fn set_reuse_models(&self, r: &RequestHandle, v: bool) -> Result<(), String> { self.check(r)?; self.inner.set_reuse_models(r.pointer.as_ptr(), v) }
-pub fn set_attention(&self, r: &RequestHandle, v: &str) -> Result<(), String> { self.check(r)?; self.inner.set_attention(r.pointer.as_ptr(), v) }
-pub fn set_inference_backend(&self, r: &RequestHandle, backend: i32) -> Result<(), String> { self.check(r)?; self.inner.set_inference_backend(r.pointer.as_ptr(), backend) }
-pub fn set_model(&self, r: &RequestHandle, id: i32, path: &Path) -> Result<(), String> { self.check(r)?; self.inner.set_model(r.pointer.as_ptr(), id, path) }
-pub fn add_reference(&self, r: &RequestHandle, path: &Path) -> Result<(), String> { self.check(r)?; self.inner.add_reference(r.pointer.as_ptr(), path) }
-pub fn add_lora(&self, r: &RequestHandle, path: &Path, strength: f32) -> Result<(), String> { self.check(r)?; self.inner.add_lora(r.pointer.as_ptr(), path, strength) }
-pub fn add_refmod(&self, r: &RequestHandle, path: &Path, strength: f32, copies: i32) -> Result<(), String> { self.check(r)?; self.inner.add_refmod(r.pointer.as_ptr(), path, strength, copies) }
-pub fn resolve(&self, request: &RequestHandle) -> Result<Plan, String> { self.check(request)?; self.inner.resolve(request.pointer.as_ptr()) }
-pub fn describe(&self, request: &RequestHandle) -> Result<String, String> { self.check(request)?; self.inner.describe(request.pointer.as_ptr()) }
-
+ Ok(Self {
+ inner: Arc::new(inner),
+ path: path.to_owned(),
+ })
+ }
+ pub fn version(&self) -> Result<String, String> {
+ self.inner.version()
+ }
+ pub fn set_cuda_version(&self, v: &str) -> Result<(), String> {
+ self.inner.set_cuda_version(v)
+ }
+ pub fn cuda_loaded_major(&self) -> Result<i32, String> {
+ self.inner.cuda_loaded_major()
+ }
+ pub fn clear_reused_models(&self) -> Result<(), String> {
+ self.inner.clear_reused_models()
+ }
+ #[cfg(test)]
+ pub fn disable_animate_for_test(&mut self) {
+ Arc::get_mut(&mut self.inner)
+ .expect("configure API before creating handles")
+ .disable_animate_for_test();
+ }
+ fn check(&self, r: &RequestHandle) -> Result<(), String> {
+ if Arc::ptr_eq(&self.inner, &r.api.inner) {
+ Ok(())
+ } else {
+ Err("Request belongs to a different runtime instance.".into())
+ }
+ }
+ pub fn set_prompt(&self, r: &RequestHandle, v: &str) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_prompt(r.pointer.as_ptr(), v)
+ }
+ pub fn set_animate(&self, r: &RequestHandle, preserve_audio: bool) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_animate(r.pointer.as_ptr(), preserve_audio)
+ }
+ pub fn set_prompt_embedding(&self, r: &RequestHandle, path: &Path) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_prompt_embedding(r.pointer.as_ptr(), path)
+ }
+ pub fn set_resolution(&self, r: &RequestHandle, w: i32, h: i32) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_resolution(r.pointer.as_ptr(), w, h)
+ }
+ pub fn set_frames(&self, r: &RequestHandle, v: i32) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_frames(r.pointer.as_ptr(), v)
+ }
+ pub fn set_still_image(&self, r: &RequestHandle) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_still_image(r.pointer.as_ptr())
+ }
+ pub fn set_save_latents(&self, r: &RequestHandle, path: &Path) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_save_latents(r.pointer.as_ptr(), path)
+ }
+ pub fn set_continuation_file(
+ &self,
+ r: &RequestHandle,
+ path: &Path,
+ overlap: i32,
+ ) -> Result<(), String> {
+ self.check(r)?;
+ self.inner
+ .set_continuation_file(r.pointer.as_ptr(), path, overlap)
+ }
+ pub fn set_steps(&self, r: &RequestHandle, v: i32) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_steps(r.pointer.as_ptr(), v)
+ }
+ pub fn set_seed(&self, r: &RequestHandle, v: u64) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_seed(r.pointer.as_ptr(), v)
+ }
+ pub fn set_verbose(&self, r: &RequestHandle, v: bool) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_verbose(r.pointer.as_ptr(), v)
+ }
+ pub fn set_reuse_models(&self, r: &RequestHandle, v: bool) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_reuse_models(r.pointer.as_ptr(), v)
+ }
+ pub fn set_attention(&self, r: &RequestHandle, v: &str) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_attention(r.pointer.as_ptr(), v)
+ }
+ pub fn set_inference_backend(&self, r: &RequestHandle, backend: i32) -> Result<(), String> {
+ self.check(r)?;
+ self.inner
+ .set_inference_backend(r.pointer.as_ptr(), backend)
+ }
+ pub fn set_model(&self, r: &RequestHandle, id: i32, path: &Path) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.set_model(r.pointer.as_ptr(), id, path)
+ }
+ pub fn add_reference(&self, r: &RequestHandle, path: &Path) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.add_reference(r.pointer.as_ptr(), path)
+ }
+ pub fn add_lora(&self, r: &RequestHandle, path: &Path, strength: f32) -> Result<(), String> {
+ self.check(r)?;
+ self.inner.add_lora(r.pointer.as_ptr(), path, strength)
+ }
+ pub fn add_refmod(
+ &self,
+ r: &RequestHandle,
+ path: &Path,
+ strength: f32,
+ copies: i32,
+ ) -> Result<(), String> {
+ self.check(r)?;
+ self.inner
+ .add_refmod(r.pointer.as_ptr(), path, strength, copies)
+ }
+ pub fn resolve(&self, request: &RequestHandle) -> Result<Plan, String> {
+ self.check(request)?;
+ self.inner.resolve(request.pointer.as_ptr())
+ }
+ pub fn describe(&self, request: &RequestHandle) -> Result<String, String> {
+ self.check(request)?;
+ self.inner.describe(request.pointer.as_ptr())
+ }
}
/// Owns its library; native requests cannot outlive the DLL or cross instances.
-pub struct RequestHandle { api: Api, pointer: NonNull<raw::Request> }
+pub struct RequestHandle {
+ api: Api,
+ pointer: NonNull<raw::Request>,
+}
impl RequestHandle {
- pub fn new(api:&Api)->Result<Self,String>{
- let pointer=NonNull::new(api.inner.create_request()?).ok_or("Empty native request.")?;
- Ok(Self {api:api.clone(),pointer})
+ pub fn new(api: &Api) -> Result<Self, String> {
+ let pointer = NonNull::new(api.inner.create_request()?).ok_or("Empty native request.")?;
+ Ok(Self {
+ api: api.clone(),
+ pointer,
+ })
+ }
+ pub fn start(self, callback: Option<ProgressSink>) -> Result<GenerationHandle, String> {
+ GenerationHandle::start(self, callback)
+ }
+}
+impl Drop for RequestHandle {
+ fn drop(&mut self) {
+ self.api.inner.destroy_request(self.pointer.as_ptr());
}
- pub fn start(&self,callback:Option<ProgressSink>)->Result<GenerationHandle,String>{GenerationHandle::start(self,callback)}
}
-impl Drop for RequestHandle {fn drop(&mut self){self.api.inner.destroy_request(self.pointer.as_ptr());}}
pub struct ReferenceVideoHandle(raw::ReferenceVideoHandle);
impl ReferenceVideoHandle {
- pub fn new(api:Api,duration:f64,path:PathBuf)->Result<Self,String>{
- if api.path != path {return Err("Reference video runtime mismatch.".into());}
- raw::ReferenceVideoHandle::new(api.inner,duration,path).map(Self)
+ pub fn new(api: Api, duration: f64, path: PathBuf) -> Result<Self, String> {
+ if api.path != path {
+ return Err("Reference video runtime mismatch.".into());
+ }
+ raw::ReferenceVideoHandle::new(api.inner, duration, path).map(Self)
}
- pub fn append(&mut self,bytes:&[u8],w:i32,h:i32,time:f64)->Result<(),String>{self.0.append(bytes,w,h,time)}
- pub fn set_audio(&mut self,samples:&[f32],channels:i32,rate:i32)->Result<(),String>{self.0.set_audio(samples,channels,rate)}
- pub fn has_audio(&self)->bool{self.0.has_audio()}
- pub fn attach(&self,request:&RequestHandle,path:&Path)->Result<(),String>{
- if request.api.path != path {return Err("Reference video runtime mismatch.".into());}
- self.0.attach(request.pointer.as_ptr(),path)
+ pub fn append(&mut self, bytes: &[u8], w: i32, h: i32, time: f64) -> Result<(), String> {
+ self.0.append(bytes, w, h, time)
+ }
+ pub fn set_audio(&mut self, samples: &[f32], channels: i32, rate: i32) -> Result<(), String> {
+ self.0.set_audio(samples, channels, rate)
+ }
+ pub fn has_audio(&self) -> bool {
+ self.0.has_audio()
+ }
+ pub fn attach(&self, request: &RequestHandle, path: &Path) -> Result<(), String> {
+ if request.api.path != path {
+ return Err("Reference video runtime mismatch.".into());
+ }
+ self.0.attach(request.pointer.as_ptr(), path)
}
}
-
diff --git a/src-tauri/src/slopfab/ffi/raw/device.rs b/src-tauri/src/slopfab/ffi/raw/device.rs
new file mode 100644
index 0000000..49dfc41
--- /dev/null
+++ b/src-tauri/src/slopfab/ffi/raw/device.rs
@@ -0,0 +1,100 @@
+use super::*;
+pub fn has_cuda_device() -> bool {
+ // CUDA's driver API uses the system calling convention on Windows.
+ // Keep the library alive until both calls have returned.
+ unsafe {
+ #[cfg(windows)]
+ let driver = libloading::os::windows::Library::load_with_flags(
+ "nvcuda.dll",
+ 0x00000800, // LOAD_LIBRARY_SEARCH_SYSTEM32
+ )
+ .map(Library::from);
+ #[cfg(not(windows))]
+ let driver = Library::new("libcuda.so.1");
+ let Ok(library) = driver else { return false };
+ let Ok(init) = library.get::<unsafe extern "system" fn(u32) -> i32>(b"cuInit\0") else {
+ return false;
+ };
+ let Ok(count) =
+ library.get::<unsafe extern "system" fn(*mut i32) -> i32>(b"cuDeviceGetCount\0")
+ else {
+ return false;
+ };
+ let mut devices = 0;
+ init(0) == 0 && count(&mut devices) == 0 && devices > 0
+ }
+}
+pub fn cuda_device_names() -> Vec<String> {
+ gpu_devices()
+ .into_iter()
+ .map(|device| device.name)
+ .collect()
+}
+
+pub fn gpu_devices() -> Vec<crate::slopfab::GpuDevice> {
+ // The display driver's API is available without the CUDA toolkit.
+ // Keep the library and fixed-size name buffer alive for every call.
+ unsafe {
+ #[cfg(windows)]
+ let driver = libloading::os::windows::Library::load_with_flags(
+ "nvcuda.dll",
+ 0x00000800, // LOAD_LIBRARY_SEARCH_SYSTEM32
+ )
+ .map(Library::from);
+ #[cfg(not(windows))]
+ let driver = Library::new("libcuda.so.1");
+ let Ok(library) = driver else {
+ return Vec::new();
+ };
+ let Ok(init) = library.get::<unsafe extern "system" fn(u32) -> i32>(b"cuInit\0") else {
+ return Vec::new();
+ };
+ let Ok(count) =
+ library.get::<unsafe extern "system" fn(*mut i32) -> i32>(b"cuDeviceGetCount\0")
+ else {
+ return Vec::new();
+ };
+ let Ok(get) =
+ library.get::<unsafe extern "system" fn(*mut i32, i32) -> i32>(b"cuDeviceGet\0")
+ else {
+ return Vec::new();
+ };
+ let Ok(name) = library
+ .get::<unsafe extern "system" fn(*mut c_char, i32, i32) -> i32>(b"cuDeviceGetName\0")
+ else {
+ return Vec::new();
+ };
+ let memory = library
+ .get::<unsafe extern "system" fn(*mut usize, i32) -> i32>(b"cuDeviceTotalMem_v2\0")
+ .ok();
+ let mut count_value = 0;
+ if init(0) != 0 || count(&mut count_value) != 0 {
+ return Vec::new();
+ }
+ (0..count_value)
+ .filter_map(|ordinal| {
+ let mut device = 0;
+ let mut buffer = [0u8; 256];
+ if get(&mut device, ordinal) != 0
+ || name(buffer.as_mut_ptr().cast(), buffer.len() as i32, device) != 0
+ {
+ return None;
+ }
+ let end = buffer
+ .iter()
+ .position(|byte| *byte == 0)
+ .unwrap_or(buffer.len());
+ let mut memory_bytes = 0usize;
+ if let Some(memory) = &memory {
+ if memory(&mut memory_bytes, device) != 0 {
+ memory_bytes = 0;
+ }
+ }
+ Some(crate::slopfab::GpuDevice {
+ name: String::from_utf8_lossy(&buffer[..end]).into_owned(),
+ memory_bytes: memory_bytes as u64,
+ })
+ })
+ .collect()
+ }
+}
diff --git a/src-tauri/src/slopfab/ffi/raw.rs b/src-tauri/src/slopfab/ffi/raw/mod.rs
similarity index 69%
rename from src-tauri/src/slopfab/ffi/raw.rs
rename to src-tauri/src/slopfab/ffi/raw/mod.rs
index 1ac1afd..279bd29 100644
--- a/src-tauri/src/slopfab/ffi/raw.rs
+++ b/src-tauri/src/slopfab/ffi/raw/mod.rs
@@ -6,120 +6,10 @@ use std::{
};
pub enum Request {}
-enum ReferenceVideo {}
-type VideoCreate = unsafe extern "C" fn(f64, *mut *mut ReferenceVideo) -> i32;
-type VideoDestroy = unsafe extern "C" fn(*mut ReferenceVideo);
-type VideoAppend = unsafe extern "C" fn(*mut ReferenceVideo, *const u8, usize, i32, i32, usize, f64) -> i32;
-type VideoAudio = unsafe extern "C" fn(*mut ReferenceVideo, *const f32, usize, i32, i32, f64) -> i32;
-type VideoAttach = unsafe extern "C" fn(*mut Request, *const ReferenceVideo) -> i32;
-
-pub struct ReferenceVideoHandle {
- api: std::sync::Arc<Api>,
- handle: *mut ReferenceVideo,
- destroy: VideoDestroy,
- append_rgba: VideoAppend,
- audio: VideoAudio,
- attach_video: VideoAttach,
- dll_path: std::path::PathBuf,
- frames: usize,
- has_audio: bool,
-}
-
-// The registry mutex serializes access. The DLL handle and all copied input
-// buffers outlive every call, and attached snapshots own their references.
-unsafe impl Send for ReferenceVideoHandle {}
-
-impl ReferenceVideoHandle {
- pub fn new(api: std::sync::Arc<Api>, duration: f64, dll_path: std::path::PathBuf) -> Result<Self, String> {
- unsafe {
- let missing = |error| format!("This slopfab.dll does not support video references. Update the runtime: {error}");
- let create = *api._library.get::<VideoCreate>(b"slopfab_reference_video_create\0").map_err(missing)?;
- let destroy = *api._library.get::<VideoDestroy>(b"slopfab_reference_video_destroy\0").map_err(missing)?;
- let append_rgba = *api._library.get::<VideoAppend>(b"slopfab_reference_video_append_rgba8\0").map_err(missing)?;
- let audio = *api._library.get::<VideoAudio>(b"slopfab_reference_video_set_audio_f32\0").map_err(missing)?;
- let attach_video = *api._library.get::<VideoAttach>(b"slopfab_request_add_reference_video\0").map_err(missing)?;
- let mut handle = std::ptr::null_mut();
- api.error(create(duration, &mut handle))?;
- if handle.is_null() { return Err("slopfab returned an empty reference video handle.".into()); }
- Ok(Self { api, handle, destroy, append_rgba, audio, attach_video, dll_path, frames: 0, has_audio: false })
- }
- }
- pub fn append(&mut self, bytes: &[u8], width: i32, height: i32, timestamp: f64) -> Result<(), String> {
- if width <= 0 || height <= 0 || width > 1024 || height > 1024 || self.frames >= 361 {
- return Err("Reference video preparation exceeds the frame or dimension limit.".into());
- }
- self.api.error(unsafe { (self.append_rgba)(self.handle, bytes.as_ptr(), bytes.len(), width, height, width as usize * 4, timestamp) })?;
- self.frames += 1;
- Ok(())
- }
- pub fn set_audio(&mut self, samples: &[f32], channels: i32, sample_rate: i32) -> Result<(), String> {
- self.api.error(unsafe { (self.audio)(self.handle, samples.as_ptr(), samples.len(), channels, sample_rate, 0.0) })?;
- self.has_audio = !samples.is_empty();
- Ok(())
- }
- pub fn has_audio(&self) -> bool { self.has_audio }
- pub fn attach(&self, request: *mut Request, dll_path: &Path) -> Result<(), String> {
- if dll_path != self.dll_path { return Err("Reference video and generation must use the same slopfab runtime.".into()); }
- self.api.error(unsafe { (self.attach_video)(request, self.handle) })
- }
-}
-impl Drop for ReferenceVideoHandle {
- fn drop(&mut self) { unsafe { (self.destroy)(self.handle) }; }
-}
-
-pub fn has_cuda_device() -> bool {
- // CUDA's driver API uses the system calling convention on Windows.
- // Keep the library alive until both calls have returned.
- unsafe {
- #[cfg(windows)]
- let driver = libloading::os::windows::Library::load_with_flags(
- "nvcuda.dll", 0x00000800, // LOAD_LIBRARY_SEARCH_SYSTEM32
- ).map(Library::from);
- #[cfg(not(windows))]
- let driver = Library::new("libcuda.so.1");
- let Ok(library) = driver else { return false };
- let Ok(init) = library.get::<unsafe extern "system" fn(u32) -> i32>(b"cuInit\0") else { return false };
- let Ok(count) = library.get::<unsafe extern "system" fn(*mut i32) -> i32>(b"cuDeviceGetCount\0") else { return false };
- let mut devices = 0;
- init(0) == 0 && count(&mut devices) == 0 && devices > 0
- }
-}
-pub fn cuda_device_names() -> Vec<String> {
- gpu_devices().into_iter().map(|device| device.name).collect()
-}
-
-pub fn gpu_devices() -> Vec<super::super::GpuDevice> {
- // The display driver's API is available without the CUDA toolkit.
- // Keep the library and fixed-size name buffer alive for every call.
- unsafe {
- #[cfg(windows)]
- let driver = libloading::os::windows::Library::load_with_flags(
- "nvcuda.dll", 0x00000800, // LOAD_LIBRARY_SEARCH_SYSTEM32
- ).map(Library::from);
- #[cfg(not(windows))]
- let driver = Library::new("libcuda.so.1");
- let Ok(library) = driver else { return Vec::new() };
- let Ok(init) = library.get::<unsafe extern "system" fn(u32) -> i32>(b"cuInit\0") else { return Vec::new() };
- let Ok(count) = library.get::<unsafe extern "system" fn(*mut i32) -> i32>(b"cuDeviceGetCount\0") else { return Vec::new() };
- let Ok(get) = library.get::<unsafe extern "system" fn(*mut i32, i32) -> i32>(b"cuDeviceGet\0") else { return Vec::new() };
- let Ok(name) = library.get::<unsafe extern "system" fn(*mut c_char, i32, i32) -> i32>(b"cuDeviceGetName\0") else { return Vec::new() };
- let memory = library.get::<unsafe extern "system" fn(*mut usize, i32) -> i32>(b"cuDeviceTotalMem_v2\0").ok();
- let mut count_value = 0;
- if init(0) != 0 || count(&mut count_value) != 0 { return Vec::new() }
- (0..count_value).filter_map(|ordinal| {
- let mut device = 0;
- let mut buffer = [0u8; 256];
- if get(&mut device, ordinal) != 0 || name(buffer.as_mut_ptr().cast(), buffer.len() as i32, device) != 0 {
- return None;
- }
- let end = buffer.iter().position(|byte| *byte == 0).unwrap_or(buffer.len());
- let mut memory_bytes = 0usize;
- if let Some(memory) = &memory { if memory(&mut memory_bytes, device) != 0 { memory_bytes = 0; } }
- Some(super::super::GpuDevice { name: String::from_utf8_lossy(&buffer[..end]).into_owned(), memory_bytes: memory_bytes as u64 })
- }).collect()
- }
-}
-
+mod device;
+mod reference_video;
+pub use device::{cuda_device_names, gpu_devices, has_cuda_device};
+pub use reference_video::ReferenceVideoHandle;
pub enum Generation {}
#[repr(C)]
#[derive(Clone, Copy)]
@@ -200,12 +90,8 @@ pub struct Api {
reused_models_clear: unsafe extern "C" fn() -> i32,
resolve_plan: unsafe extern "C" fn(*const Request, *mut Plan) -> i32,
describe_plan: unsafe extern "C" fn(*const Request, *mut *mut c_char) -> i32,
- generation_start: unsafe extern "C" fn(
- *const Request,
- ProgressFn,
- *mut c_void,
- *mut *mut Generation,
- ) -> i32,
+ generation_start:
+ unsafe extern "C" fn(*const Request, ProgressFn, *mut c_void, *mut *mut Generation) -> i32,
generation_cancel: unsafe extern "C" fn(*mut Generation),
generation_wait: unsafe extern "C" fn(*mut Generation, i32) -> i32,
generation_error: unsafe extern "C" fn(*const Generation) -> *const c_char,
@@ -260,11 +146,17 @@ impl Api {
unsafe extern "C" fn(*mut Request, *const c_char) -> i32
),
set_animate: library
- .get::<unsafe extern "C" fn(*mut Request, i32, i32) -> i32>(b"slopfab_request_set_animate\0")
- .ok().map(|symbol| *symbol),
+ .get::<unsafe extern "C" fn(*mut Request, i32, i32) -> i32>(
+ b"slopfab_request_set_animate\0",
+ )
+ .ok()
+ .map(|symbol| *symbol),
set_prompt_embedding: library
- .get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(b"slopfab_request_set_prompt_embedding_path\0")
- .ok().map(|symbol| *symbol),
+ .get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(
+ b"slopfab_request_set_prompt_embedding_path\0",
+ )
+ .ok()
+ .map(|symbol| *symbol),
set_resolution: symbol!(
"slopfab_request_set_resolution",
unsafe extern "C" fn(*mut Request, i32, i32) -> i32
@@ -274,8 +166,11 @@ impl Api {
unsafe extern "C" fn(*mut Request, i32) -> i32
),
set_still_image: library
- .get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(b"slopfab_request_set_still_image\0")
- .ok().map(|symbol| *symbol),
+ .get::<unsafe extern "C" fn(*mut Request, i32) -> i32>(
+ b"slopfab_request_set_still_image\0",
+ )
+ .ok()
+ .map(|symbol| *symbol),
set_steps: symbol!(
"slopfab_request_set_steps",
unsafe extern "C" fn(*mut Request, i32) -> i32
@@ -293,17 +188,29 @@ impl Api {
unsafe extern "C" fn(*mut Request, *const c_char) -> i32
),
add_lora: library
- .get::<unsafe extern "C" fn(*mut Request, *const c_char, f32) -> i32>(b"slopfab_request_add_lora\0")
- .ok().map(|symbol| *symbol),
+ .get::<unsafe extern "C" fn(*mut Request, *const c_char, f32) -> i32>(
+ b"slopfab_request_add_lora\0",
+ )
+ .ok()
+ .map(|symbol| *symbol),
set_save_latents: library
- .get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(b"slopfab_request_set_save_latents\0")
- .ok().map(|symbol| *symbol),
+ .get::<unsafe extern "C" fn(*mut Request, *const c_char) -> i32>(
+ b"slopfab_request_set_save_latents\0",
+ )
+ .ok()
+ .map(|symbol| *symbol),
set_continuation_file: library
- .get::<unsafe extern "C" fn(*mut Request, *const c_char, i32) -> i32>(b"slopfab_request_set_continuation_file\0")
- .ok().map(|symbol| *symbol),
+ .get::<unsafe extern "C" fn(*mut Request, *const c_char, i32) -> i32>(
+ b"slopfab_request_set_continuation_file\0",
+ )
+ .ok()
+ .map(|symbol| *symbol),
add_refmod: library
- .get::<unsafe extern "C" fn(*mut Request, *const c_char, f32, i32) -> i32>(b"slopfab_request_add_refmod\0")
- .ok().map(|symbol| *symbol),
+ .get::<unsafe extern "C" fn(*mut Request, *const c_char, f32, i32) -> i32>(
+ b"slopfab_request_add_refmod\0",
+ )
+ .ok()
+ .map(|symbol| *symbol),
set_attention: symbol!(
"slopfab_request_set_attention",
unsafe extern "C" fn(*mut Request, *const c_char) -> i32
@@ -373,10 +280,10 @@ impl Api {
unsafe {
let packed = (self.capi_version)();
let major = packed >> 24;
- if major != super::super::EXPECTED_CAPI_MAJOR {
+ if major != crate::slopfab::EXPECTED_CAPI_MAJOR {
return Err(format!(
"Incompatible slopfab C API major {major}; expected {}.",
- super::super::EXPECTED_CAPI_MAJOR
+ crate::slopfab::EXPECTED_CAPI_MAJOR
));
}
Ok(c_string((self.version_string)()))
@@ -406,8 +313,8 @@ impl Api {
unsafe { (self.request_destroy)(request) }
}
pub fn set_cuda_version(&self, value: &str) -> Result<(), String> {
- let value = CString::new(value)
- .map_err(|_| "CUDA version contains a null byte.".to_string())?;
+ let value =
+ CString::new(value).map_err(|_| "CUDA version contains a null byte.".to_string())?;
self.error(unsafe { (self.cuda_set_version)(value.as_ptr()) })
}
pub fn cuda_loaded_major(&self) -> Result<i32, String> {
@@ -420,13 +327,19 @@ impl Api {
self.error(unsafe { (self.set_prompt)(r, v.as_ptr()) })
}
#[cfg(test)]
- pub fn disable_animate_for_test(&mut self) { self.set_animate = None; }
+ pub fn disable_animate_for_test(&mut self) {
+ self.set_animate = None;
+ }
pub fn set_animate(&self, r: *mut Request, preserve_audio: bool) -> Result<(), String> {
- let set = self.set_animate.ok_or("Animate requires slopfab.dll API 1.10 or later. Update the runtime.")?;
+ let set = self
+ .set_animate
+ .ok_or("Animate requires slopfab.dll API 1.10 or later. Update the runtime.")?;
self.error(unsafe { set(r, 1, preserve_audio as i32) })
}
pub fn set_prompt_embedding(&self, r: *mut Request, path: &Path) -> Result<(), String> {
- let set = self.set_prompt_embedding.ok_or("This slopfab.dll does not support frozen conditioning. Update the runtime.")?;
+ let set = self
+ .set_prompt_embedding
+ .ok_or("This slopfab.dll does not support frozen conditioning. Update the runtime.")?;
let path = path_cstring(path)?;
self.error(unsafe { set(r, path.as_ptr()) })
}
@@ -441,12 +354,21 @@ impl Api {
self.error(unsafe { set(r, 1) })
}
pub fn set_save_latents(&self, r: *mut Request, path: &Path) -> Result<(), String> {
- let set = self.set_save_latents.ok_or("Saving generation latents requires slopfab.dll API 1.9 or later. Update the runtime.")?;
+ let set = self.set_save_latents.ok_or(
+ "Saving generation latents requires slopfab.dll API 1.9 or later. Update the runtime.",
+ )?;
let path = path_cstring(path)?;
self.error(unsafe { set(r, path.as_ptr()) })
}
- pub fn set_continuation_file(&self, r: *mut Request, path: &Path, overlap: i32) -> Result<(), String> {
- let set = self.set_continuation_file.ok_or("Scene continuation requires slopfab.dll API 1.9 or later. Update the runtime.")?;
+ pub fn set_continuation_file(
+ &self,
+ r: *mut Request,
+ path: &Path,
+ overlap: i32,
+ ) -> Result<(), String> {
+ let set = self.set_continuation_file.ok_or(
+ "Scene continuation requires slopfab.dll API 1.9 or later. Update the runtime.",
+ )?;
let path = path_cstring(path)?;
self.error(unsafe { set(r, path.as_ptr(), overlap) })
}
@@ -466,8 +388,7 @@ impl Api {
self.error(unsafe { (self.reused_models_clear)() })
}
pub fn set_attention(&self, r: *mut Request, v: &str) -> Result<(), String> {
- let v =
- CString::new(v).map_err(|_| "Attention mode contains a null byte.".to_string())?;
+ let v = CString::new(v).map_err(|_| "Attention mode contains a null byte.".to_string())?;
self.error(unsafe { (self.set_attention)(r, v.as_ptr()) })
}
pub fn set_inference_backend(&self, r: *mut Request, backend: i32) -> Result<(), String> {
@@ -486,7 +407,13 @@ impl Api {
let path = path_cstring(path)?;
self.error(unsafe { add(r, path.as_ptr(), strength) })
}
- pub fn add_refmod(&self, r: *mut Request, path: &Path, strength: f32, copies: i32) -> Result<(), String> {
+ pub fn add_refmod(
+ &self,
+ r: *mut Request,
+ path: &Path,
+ strength: f32,
+ copies: i32,
+ ) -> Result<(), String> {
let add = self.add_refmod.ok_or("This slopfab.dll does not support refmods. Install a build with the refmod API (1.8 or later).")?;
let path = path_cstring(path)?;
self.error(unsafe { add(r, path.as_ptr(), strength, copies) })
@@ -523,9 +450,7 @@ impl Api {
userdata: *mut c_void,
) -> Result<*mut Generation, String> {
let mut value = ptr::null_mut();
- self.error(unsafe {
- (self.generation_start)(request, callback, userdata, &mut value)
- })?;
+ self.error(unsafe { (self.generation_start)(request, callback, userdata, &mut value) })?;
Ok(value)
}
pub fn cancel(&self, generation: *mut Generation) {
@@ -614,4 +539,3 @@ unsafe fn c_string(value: *const c_char) -> String {
.into_owned()
}
}
-
diff --git a/src-tauri/src/slopfab/ffi/raw/reference_video.rs b/src-tauri/src/slopfab/ffi/raw/reference_video.rs
new file mode 100644
index 0000000..0d8cc91
--- /dev/null
+++ b/src-tauri/src/slopfab/ffi/raw/reference_video.rs
@@ -0,0 +1,133 @@
+use super::*;
+enum ReferenceVideo {}
+type VideoCreate = unsafe extern "C" fn(f64, *mut *mut ReferenceVideo) -> i32;
+type VideoDestroy = unsafe extern "C" fn(*mut ReferenceVideo);
+type VideoAppend =
+ unsafe extern "C" fn(*mut ReferenceVideo, *const u8, usize, i32, i32, usize, f64) -> i32;
+type VideoAudio =
+ unsafe extern "C" fn(*mut ReferenceVideo, *const f32, usize, i32, i32, f64) -> i32;
+type VideoAttach = unsafe extern "C" fn(*mut Request, *const ReferenceVideo) -> i32;
+
+pub struct ReferenceVideoHandle {
+ api: std::sync::Arc<Api>,
+ handle: *mut ReferenceVideo,
+ destroy: VideoDestroy,
+ append_rgba: VideoAppend,
+ audio: VideoAudio,
+ attach_video: VideoAttach,
+ dll_path: std::path::PathBuf,
+ frames: usize,
+ has_audio: bool,
+}
+
+// The registry mutex serializes access. The DLL handle and all copied input
+// buffers outlive every call, and attached snapshots own their references.
+unsafe impl Send for ReferenceVideoHandle {}
+
+impl ReferenceVideoHandle {
+ pub fn new(
+ api: std::sync::Arc<Api>,
+ duration: f64,
+ dll_path: std::path::PathBuf,
+ ) -> Result<Self, String> {
+ unsafe {
+ let missing = |error| {
+ format!("This slopfab.dll does not support video references. Update the runtime: {error}")
+ };
+ let create = *api
+ ._library
+ .get::<VideoCreate>(b"slopfab_reference_video_create\0")
+ .map_err(missing)?;
+ let destroy = *api
+ ._library
+ .get::<VideoDestroy>(b"slopfab_reference_video_destroy\0")
+ .map_err(missing)?;
+ let append_rgba = *api
+ ._library
+ .get::<VideoAppend>(b"slopfab_reference_video_append_rgba8\0")
+ .map_err(missing)?;
+ let audio = *api
+ ._library
+ .get::<VideoAudio>(b"slopfab_reference_video_set_audio_f32\0")
+ .map_err(missing)?;
+ let attach_video = *api
+ ._library
+ .get::<VideoAttach>(b"slopfab_request_add_reference_video\0")
+ .map_err(missing)?;
+ let mut handle = std::ptr::null_mut();
+ api.error(create(duration, &mut handle))?;
+ if handle.is_null() {
+ return Err("slopfab returned an empty reference video handle.".into());
+ }
+ Ok(Self {
+ api,
+ handle,
+ destroy,
+ append_rgba,
+ audio,
+ attach_video,
+ dll_path,
+ frames: 0,
+ has_audio: false,
+ })
+ }
+ }
+ pub fn append(
+ &mut self,
+ bytes: &[u8],
+ width: i32,
+ height: i32,
+ timestamp: f64,
+ ) -> Result<(), String> {
+ if width <= 0 || height <= 0 || width > 1024 || height > 1024 || self.frames >= 361 {
+ return Err("Reference video preparation exceeds the frame or dimension limit.".into());
+ }
+ self.api.error(unsafe {
+ (self.append_rgba)(
+ self.handle,
+ bytes.as_ptr(),
+ bytes.len(),
+ width,
+ height,
+ width as usize * 4,
+ timestamp,
+ )
+ })?;
+ self.frames += 1;
+ Ok(())
+ }
+ pub fn set_audio(
+ &mut self,
+ samples: &[f32],
+ channels: i32,
+ sample_rate: i32,
+ ) -> Result<(), String> {
+ self.api.error(unsafe {
+ (self.audio)(
+ self.handle,
+ samples.as_ptr(),
+ samples.len(),
+ channels,
+ sample_rate,
+ 0.0,
+ )
+ })?;
+ self.has_audio = !samples.is_empty();
+ Ok(())
+ }
+ pub fn has_audio(&self) -> bool {
+ self.has_audio
+ }
+ pub fn attach(&self, request: *mut Request, dll_path: &Path) -> Result<(), String> {
+ if dll_path != self.dll_path {
+ return Err("Reference video and generation must use the same slopfab runtime.".into());
+ }
+ self.api
+ .error(unsafe { (self.attach_video)(request, self.handle) })
+ }
+}
+impl Drop for ReferenceVideoHandle {
+ fn drop(&mut self) {
+ unsafe { (self.destroy)(self.handle) };
+ }
+}
diff --git a/src-tauri/src/slopfab/ffi/tests.rs b/src-tauri/src/slopfab/ffi/tests.rs
new file mode 100644
index 0000000..dbe36c2
--- /dev/null
+++ b/src-tauri/src/slopfab/ffi/tests.rs
@@ -0,0 +1,40 @@
+use super::*;
+
+#[test]
+fn requests_retain_the_library_and_reject_cross_instance_calls() {
+ let path = crate::slopfab::default_dll_path();
+ let first = Api::load(&path).unwrap();
+ let request = RequestHandle::new(&first).unwrap();
+ let second = Api::load(&path).unwrap();
+ assert!(second
+ .set_prompt(&request, "wrong library instance")
+ .is_err());
+ drop(first);
+ request
+ .api
+ .set_prompt(&request, "retained library")
+ .unwrap();
+ request.api.set_frames(&request, 48).unwrap();
+ request.api.set_resolution(&request, 736, 416).unwrap();
+ assert!(request.api.resolve(&request).unwrap().aligned_frames > 0);
+}
+
+#[test]
+fn reference_registries_are_independent_sessions() {
+ use crate::slopfab::references::ReferenceVideos;
+ let first = ReferenceVideos::default();
+ let second = ReferenceVideos::default();
+ let id = first
+ .create_reference_video(2.0, &Default::default())
+ .unwrap();
+ assert!(second
+ .append_reference_video(&id, &[0; 16], 2, 2, 0.0)
+ .is_err());
+ first
+ .append_reference_video(&id, &[0; 16], 2, 2, 0.0)
+ .unwrap();
+ first.release_reference_videos(&[id.clone()]).unwrap();
+ assert!(first
+ .append_reference_video(&id, &[0; 16], 2, 2, 1.0)
+ .is_err());
+}
diff --git a/src-tauri/src/slopfab/generation.rs b/src-tauri/src/slopfab/generation.rs
index 00ae4c0..0ad8355 100644
--- a/src-tauri/src/slopfab/generation.rs
+++ b/src-tauri/src/slopfab/generation.rs
@@ -1,14 +1,31 @@
-use super::*;
+use super::{
+ events::{progress_sink, CallbackContext},
+ ffi::{self, RequestHandle},
+ h3::configure_request,
+ planning::{scene_audio_offset, scene_frame_window, RequestPurpose},
+ platform::detect_platform,
+ runtime::QueueItem,
+ types::OutputMetadata,
+};
+use crate::{diagnostics, rendered};
+use std::sync::atomic::Ordering;
-struct FrameSource { generation: ffi::FinishedGeneration, frame_offset: u32 }
+struct FrameSource {
+ generation: ffi::FinishedGeneration,
+ frame_offset: u32,
+}
impl rendered::FrameSource for FrameSource {
- fn frame_rgba(&self,index:u32,width:u32,height:u32)->Result<Vec<u8>,String>{
- let index=index.checked_add(self.frame_offset).ok_or("Continuation frame index overflow.")?;
- self.generation.frame_rgba8(index,width,height)
- }
+ fn frame_rgba(&self, index: u32, width: u32, height: u32) -> Result<Vec<u8>, String> {
+ let index = index
+ .checked_add(self.frame_offset)
+ .ok_or("Continuation frame index overflow.")?;
+ self.generation.frame_rgba8(index, width, height)
+ }
}
-pub(super) fn run_generation(item: &QueueItem) -> Result<(OutputMetadata, rendered::RenderedVideo), String> {
+pub(super) fn run_generation(
+ item: &QueueItem,
+) -> Result<(OutputMetadata, rendered::RenderedVideo), String> {
if item.cancel.load(Ordering::Acquire) {
return Err("Generation was cancelled before it started.".into());
}
@@ -59,15 +76,27 @@ pub(super) fn run_generation(item: &QueueItem) -> Result<(OutputMetadata, render
serde_json::json!({ "jobId": item.request.job_id }),
);
loop {
- if item.cancel.load(Ordering::Acquire) { generation.cancel(); }
- if generation.wait(100)? { break; }
+ if item.cancel.load(Ordering::Acquire) {
+ generation.cancel();
+ }
+ if generation.wait(100)? {
+ break;
+ }
}
let generation = generation.finish()?;
let output = generation.output()?;
- drop(request);
let (frame_offset, frames) = scene_frame_window(&item.request, output.frames)?;
- let source = Box::new(FrameSource { generation, frame_offset: frame_offset as u32 });
- let audio_offset = scene_audio_offset(frame_offset, output.fps, output.audio_channels, output.audio_sample_rate, output.audio.len())?;
+ let source = Box::new(FrameSource {
+ generation,
+ frame_offset: frame_offset as u32,
+ });
+ let audio_offset = scene_audio_offset(
+ frame_offset,
+ output.fps,
+ output.audio_channels,
+ output.audio_sample_rate,
+ output.audio.len(),
+ )?;
let mut audio = output.audio;
audio.drain(..audio_offset);
let metadata = OutputMetadata {
diff --git a/src-tauri/src/slopfab/h3.rs b/src-tauri/src/slopfab/h3.rs
index 6fe85fd..8cf7a6e 100644
--- a/src-tauri/src/slopfab/h3.rs
+++ b/src-tauri/src/slopfab/h3.rs
@@ -1,5 +1,13 @@
//! H3 and Animate request recipes for the SlopFab backend.
-use super::*;
+use super::{
+ config::Configuration,
+ ffi::{self, RequestHandle},
+ planning::{generation_seed, RequestPurpose},
+ platform::ComputePlatform,
+ references::ReferenceVideos,
+ types::GenerationRequest,
+};
+use std::path::Path;
pub(super) fn configure_request(
api: &ffi::Api,
handle: &RequestHandle,
@@ -11,8 +19,12 @@ pub(super) fn configure_request(
) -> Result<(), String> {
configuration.validate_inputs(request)?;
if configuration.animate {
- let videos = references.videos.lock().map_err(|_| "Reference video lock failed.")?;
- let video = videos.get(&request.reference_video_ids[0])
+ let videos = references
+ .videos
+ .lock()
+ .map_err(|_| "Reference video lock failed.")?;
+ let video = videos
+ .get(&request.reference_video_ids[0])
.ok_or("The prepared reference video no longer exists. Please retry generation.")?;
// The setter selects Euler and four boundaries; explicit step settings follow.
api.set_animate(handle, video.has_audio())?;
@@ -21,12 +33,21 @@ pub(super) fn configure_request(
let embedding = crate::conditioning::prepare(source)?;
api.set_prompt_embedding(handle, &embedding)?;
}
- api.set_prompt(handle, if configuration.animate { ANIMATE_PROMPT } else { &request.prompt })?;
+ api.set_prompt(
+ handle,
+ if configuration.animate {
+ ANIMATE_PROMPT
+ } else {
+ &request.prompt
+ },
+ )?;
// Keep lengths within the advertised 15-second range from rounding past
// Animate's limit. Leave out-of-range requests to the DLL's validation.
let frames = if configuration.animate && request.frames <= 360 {
request.frames.min(ANIMATE_MAX_ALIGNED_FRAMES)
- } else { request.frames };
+ } else {
+ request.frames
+ };
api.set_frames(handle, frames)?;
if request.still_image {
api.set_still_image(handle)?;
@@ -38,7 +59,13 @@ pub(super) fn configure_request(
api.set_attention(handle, configuration.attention)?;
api.set_verbose(handle, false)?;
if let Some(path) = &request.continuation_path {
- api.set_continuation_file(handle, path, crate::generation::models::h3::MODEL.capabilities.continuation_overlap)?;
+ api.set_continuation_file(
+ handle,
+ path,
+ crate::generation::models::h3::MODEL
+ .capabilities
+ .continuation_overlap,
+ )?;
}
if purpose == RequestPurpose::Generate {
if let Some(path) = &request.save_latents_path {
@@ -49,7 +76,9 @@ pub(super) fn configure_request(
if lora.path.trim().is_empty() || !lora.strength.is_finite() {
return Err("LoRA paths must be nonempty and strengths finite.".into());
}
- if lora.strength == 0.0 { continue; }
+ if lora.strength == 0.0 {
+ continue;
+ }
if purpose == RequestPurpose::Generate && !Path::new(&lora.path).is_file() {
return Err(format!("LoRA file is missing: {}", lora.path));
}
@@ -58,7 +87,9 @@ pub(super) fn configure_request(
if purpose == RequestPurpose::Generate {
api.set_reuse_models(handle, true)?;
for (id, _, path) in &configuration.models {
- if configuration.animate && (*id == 1 || *id == 2) { continue; }
+ if configuration.animate && (*id == 1 || *id == 2) {
+ continue;
+ }
if request.still_image && *id == 4 {
continue;
}
@@ -71,20 +102,40 @@ pub(super) fn configure_request(
api.add_reference(handle, Path::new(path))?;
}
if !request.reference_video_ids.is_empty() {
- let videos = references.videos.lock().map_err(|_| "Reference video lock failed.")?;
+ let videos = references
+ .videos
+ .lock()
+ .map_err(|_| "Reference video lock failed.")?;
for id in &request.reference_video_ids {
- videos.get(id).ok_or("The prepared reference video no longer exists. Please retry generation.")?
+ videos
+ .get(id)
+ .ok_or("The prepared reference video no longer exists. Please retry generation.")?
.attach(handle, &configuration.dll_path)?;
}
}
for refmod in &request.refmods {
- if refmod.path.trim().is_empty() || !refmod.strength.is_finite() || !(0.0..=1.0).contains(&refmod.strength)
- || !(1..=10).contains(&refmod.copies) {
+ if refmod.path.trim().is_empty()
+ || !refmod.strength.is_finite()
+ || !(0.0..=1.0).contains(&refmod.strength)
+ || !(1..=10).contains(&refmod.copies)
+ {
return Err("Refmods need a path, strength 0 to 1 and copies 1 to 10.".into());
}
- if refmod.strength == 0.0 { continue; }
- api.add_refmod(handle, Path::new(&refmod.path), refmod.strength, refmod.copies as i32)?;
+ if refmod.strength == 0.0 {
+ continue;
+ }
+ api.add_refmod(
+ handle,
+ Path::new(&refmod.path),
+ refmod.strength,
+ refmod.copies as i32,
+ )?;
}
Ok(())
}
+// https://huggingface.co/Viggle/Viggle-Animate/raw/main/assets/fixed_prompt.txt
+pub(super) const ANIMATE_PROMPT: &str =
+ include_str!("../../assets/viggle-animate-fixed-prompt.txt");
+// SlopFab rounds up to 17*k + 5 frames but rejects Animate plans over 360.
+pub(super) const ANIMATE_MAX_ALIGNED_FRAMES: i32 = (360 - 5) / 17 * 17 + 5;
diff --git a/src-tauri/src/slopfab/icons.rs b/src-tauri/src/slopfab/icons.rs
index 809fb44..66fc74c 100644
--- a/src-tauri/src/slopfab/icons.rs
+++ b/src-tauri/src/slopfab/icons.rs
@@ -1,4 +1,14 @@
-use super::*;
+use super::{
+ config::Configuration,
+ ffi::{self, RequestHandle},
+ h3::configure_request,
+ planning::RequestPurpose,
+ platform::*,
+ references::ReferenceVideos,
+ types::GenerationRequest,
+};
+use serde::Deserialize;
+use std::path::PathBuf;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -40,14 +50,28 @@ pub(super) fn write_reference_icon(
..Default::default()
};
let handle = RequestHandle::new(api)?;
- configure_request(api, &handle, &request, configuration, platform, RequestPurpose::Generate, &ReferenceVideos::default())?;
+ configure_request(
+ api,
+ &handle,
+ &request,
+ configuration,
+ platform,
+ RequestPurpose::Generate,
+ &ReferenceVideos::default(),
+ )?;
api.resolve(&handle)?;
let mut generation = handle.start(None)?;
- while !generation.wait(-1).map_err(|error| format!("Icon '{}': {error}", spec.id))? {}
+ while !generation
+ .wait(-1)
+ .map_err(|error| format!("Icon '{}': {error}", spec.id))?
+ {}
let generation = generation.finish()?;
let output = generation.output()?;
let render_size = crate::reference_icons::RENDER_SIZE;
- if output.width != render_size as i32 || output.height != render_size as i32 || output.frames != 1 {
+ if output.width != render_size as i32
+ || output.height != render_size as i32
+ || output.frames != 1
+ {
return Err(format!(
"Icon '{}' returned {}x{} with {} frames.",
spec.id, output.width, output.height, output.frames
diff --git a/src-tauri/src/slopfab/mod.rs b/src-tauri/src/slopfab/mod.rs
index 1594628..1d974c4 100644
--- a/src-tauri/src/slopfab/mod.rs
+++ b/src-tauri/src/slopfab/mod.rs
@@ -1,41 +1,25 @@
//! Native runtime adapter. Raw ABI and resource ownership are confined to ffi.
-use crate::{diagnostics, rendered};
-use crate::project::{ProviderOption, ProviderSetting};
-use getrandom::fill as fill_random;
-use serde::{Deserialize, Serialize};
-use std::{collections::{BTreeMap, HashMap},path::{Path, PathBuf},sync::{atomic::{AtomicBool, Ordering},mpsc,Arc,Mutex},thread};
-mod types;
-mod platform;
+use std::path::{Path, PathBuf};
mod config;
-mod status;
-mod runtime;
-mod references;
-mod planning;
-mod h3;
-use h3::configure_request;
-mod generation;
-mod icons;
mod events;
mod ffi;
-pub use types::*;
+mod generation;
+mod h3;
+mod icons;
+mod planning;
+mod platform;
+mod references;
+mod runtime;
+mod status;
+mod types;
pub use runtime::SlopfabRuntime;
-pub use references::*;
+pub use types::*;
+
+pub use events::NativeEvent;
+pub use icons::{generate_reference_icon_batch, ReferenceIconBatchConfig, ReferenceIconSpec};
pub use planning::resolve_plan;
pub use status::status;
-pub use icons::{generate_reference_icon_batch, ReferenceIconBatchConfig, ReferenceIconSpec};
-pub use events::{EventSink, NativeEvent};
-use platform::*;
-use config::*;
-use planning::*;
-use runtime::QueueItem;
-use generation::run_generation;
-use events::*;
-use ffi::RequestHandle;
const DLL_FILE_NAME: &str = "slopfab.dll";
-// https://huggingface.co/Viggle/Viggle-Animate/raw/main/assets/fixed_prompt.txt
-const ANIMATE_PROMPT: &str = include_str!("../../assets/viggle-animate-fixed-prompt.txt");
-// SlopFab rounds up to 17*k + 5 frames but rejects Animate plans over 360.
-const ANIMATE_MAX_ALIGNED_FRAMES: i32 = (360 - 5) / 17 * 17 + 5;
/// Tauri stages the repository's runtime resources in development and release
/// builds. Installers and portable folders use the same relative layout.
pub fn default_dll_path() -> PathBuf {
@@ -45,11 +29,14 @@ pub fn default_dll_path() -> PathBuf {
#[cfg(test)]
let directory = if directory.file_name().is_some_and(|name| name == "deps") {
directory.parent().unwrap_or(directory)
- } else { directory };
+ } else {
+ directory
+ };
directory.join(DLL_FILE_NAME)
}
const EXPECTED_CAPI_MAJOR: u32 = 1;
const NOT_READY: i32 = -7;
const CANCELLED: i32 = -8;
-#[cfg(test)] mod tests;
+#[cfg(test)]
+mod tests;
diff --git a/src-tauri/src/slopfab/planning.rs b/src-tauri/src/slopfab/planning.rs
index 9ac1613..e3f0bdc 100644
--- a/src-tauri/src/slopfab/planning.rs
+++ b/src-tauri/src/slopfab/planning.rs
@@ -1,6 +1,19 @@
#[derive(Clone, Copy, PartialEq, Eq)]
-pub(super) enum RequestPurpose { Plan, Generate }
-use super::*;
+pub(super) enum RequestPurpose {
+ Plan,
+ Generate,
+}
+use super::{
+ config::Configuration,
+ ffi::{self, RequestHandle},
+ h3::configure_request,
+ platform::detect_platform,
+ references::ReferenceVideos,
+ types::*,
+};
+use crate::project::ProviderSetting;
+use getrandom::fill as fill_random;
+use std::collections::BTreeMap;
pub fn resolve_plan(
request: &GenerationRequest,
@@ -13,7 +26,15 @@ pub fn resolve_plan(
api.version()?;
let platform = configuration.platform(detect_platform(&api));
let handle = RequestHandle::new(&api)?;
- configure_request(&api, &handle, request, &configuration, platform, RequestPurpose::Plan, references)?;
+ configure_request(
+ &api,
+ &handle,
+ request,
+ &configuration,
+ platform,
+ RequestPurpose::Plan,
+ references,
+ )?;
let plan = api.resolve(&handle)?;
let description = api.describe(&handle)?;
let (_, frames) = scene_frame_window(request, plan.aligned_frames)?;
@@ -34,7 +55,10 @@ pub fn resolve_plan(
pub(super) fn validate_generation_controls(request: &GenerationRequest) -> Result<(), String> {
let limits = crate::generation::models::h3::MODEL.capabilities;
- if request.reference_paths.len() > limits.max_image_references || request.reference_video_ids.len() > limits.max_video_references || request.reference_count() > limits.max_references {
+ if request.reference_paths.len() > limits.max_image_references
+ || request.reference_video_ids.len() > limits.max_video_references
+ || request.reference_count() > limits.max_references
+ {
return Err("Use at most nine images and three videos per generation.".into());
}
if request.still_image && !request.reference_video_ids.is_empty() {
@@ -65,24 +89,50 @@ pub(super) fn generation_seed(value: i64) -> Result<u64, String> {
/// Continuation output is cumulative. Expose only the new scene to the editor,
/// while the DLL saves the full archive for the next continuation.
-pub(super) fn scene_frame_window(request: &GenerationRequest, total: i32) -> Result<(i32, i32), String> {
- if total <= 0 { return Err("Slopfab returned no video frames.".into()); }
- if request.continuation_path.is_none() { return Ok((0, total)); }
- if request.frames <= 0 { return Err("Continuation needs a positive frame count.".into()); }
+pub(super) fn scene_frame_window(
+ request: &GenerationRequest,
+ total: i32,
+) -> Result<(i32, i32), String> {
+ if total <= 0 {
+ return Err("Slopfab returned no video frames.".into());
+ }
+ if request.continuation_path.is_none() {
+ return Ok((0, total));
+ }
+ if request.frames <= 0 {
+ return Err("Continuation needs a positive frame count.".into());
+ }
let limits = crate::generation::models::h3::MODEL.capabilities;
- let frames = request.frames.checked_add(limits.frame_stride - 1).ok_or("Continuation frame count overflow.")? / limits.frame_stride * limits.frame_stride;
- let offset = total.checked_sub(frames).filter(|offset| *offset >= limits.continuation_overlap)
+ let frames = request
+ .frames
+ .checked_add(limits.frame_stride - 1)
+ .ok_or("Continuation frame count overflow.")?
+ / limits.frame_stride
+ * limits.frame_stride;
+ let offset = total
+ .checked_sub(frames)
+ .filter(|offset| *offset >= limits.continuation_overlap)
.ok_or("Slopfab continuation output is missing its source frames.".to_string())?;
Ok((offset, frames))
}
-pub(super) fn scene_audio_offset(frame_offset: i32, fps: f64, channels: i32, sample_rate: i32, total: usize) -> Result<usize, String> {
- if total == 0 || frame_offset == 0 { return Ok(0); }
+pub(super) fn scene_audio_offset(
+ frame_offset: i32,
+ fps: f64,
+ channels: i32,
+ sample_rate: i32,
+ total: usize,
+) -> Result<usize, String> {
+ if total == 0 || frame_offset == 0 {
+ return Ok(0);
+ }
if !fps.is_finite() || fps <= 0.0 || channels <= 0 || sample_rate <= 0 {
return Err("Slopfab returned invalid continuation audio timing.".into());
}
let samples = (frame_offset as f64 * sample_rate as f64 / fps).round();
- let offset = (samples as usize).checked_mul(channels as usize)
- .filter(|offset| *offset <= total).ok_or("Slopfab continuation audio is shorter than its source scene.")?;
+ let offset = (samples as usize)
+ .checked_mul(channels as usize)
+ .filter(|offset| *offset <= total)
+ .ok_or("Slopfab continuation audio is shorter than its source scene.")?;
Ok(offset)
}
diff --git a/src-tauri/src/slopfab/platform.rs b/src-tauri/src/slopfab/platform.rs
index 8bcc430..0e34ff2 100644
--- a/src-tauri/src/slopfab/platform.rs
+++ b/src-tauri/src/slopfab/platform.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::ffi;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ComputePlatform {
diff --git a/src-tauri/src/slopfab/references.rs b/src-tauri/src/slopfab/references.rs
index c2a6da5..6b17bea 100644
--- a/src-tauri/src/slopfab/references.rs
+++ b/src-tauri/src/slopfab/references.rs
@@ -1,44 +1,86 @@
-use super::*;
+use super::{config::Configuration, ffi};
+use crate::project::ProviderSetting;
+use std::{
+ collections::{BTreeMap, HashMap},
+ sync::{atomic::Ordering, Arc, Mutex},
+};
// A video owns its DLL and input buffers. Commands serialize mutations; the
// C API retains immutable snapshots when a plan/generation attaches a video.
#[derive(Clone, Default)]
pub struct ReferenceVideos {
- pub(super) videos: Arc<Mutex<HashMap<String, ffi::ReferenceVideoHandle>>>,
- next: Arc<std::sync::atomic::AtomicU64>,
+ pub(super) videos: Arc<Mutex<HashMap<String, ffi::ReferenceVideoHandle>>>,
+ next: Arc<std::sync::atomic::AtomicU64>,
}
impl ReferenceVideos {
-pub fn create_reference_video(&self, duration: f64, settings: &BTreeMap<String, ProviderSetting>) -> Result<String, String> {
- let configuration = Configuration::from_settings(settings);
- let api = ffi::Api::load(&configuration.dll_path)?;
- api.version()?;
- let video = ffi::ReferenceVideoHandle::new(api, duration, configuration.dll_path)?;
- let mut videos = self.videos.lock().map_err(|_| "Reference video lock failed.")?;
- if videos.len() >= 3 { return Err("At most three video references can be prepared at once.".into()); }
- let id = self.next.fetch_add(1, Ordering::Relaxed).to_string();
- videos.insert(id.clone(), video);
- Ok(id)
-}
+ pub fn create_reference_video(
+ &self,
+ duration: f64,
+ settings: &BTreeMap<String, ProviderSetting>,
+ ) -> Result<String, String> {
+ let configuration = Configuration::from_settings(settings);
+ let api = ffi::Api::load(&configuration.dll_path)?;
+ api.version()?;
+ let video = ffi::ReferenceVideoHandle::new(api, duration, configuration.dll_path)?;
+ let mut videos = self
+ .videos
+ .lock()
+ .map_err(|_| "Reference video lock failed.")?;
+ if videos.len() >= 3 {
+ return Err("At most three video references can be prepared at once.".into());
+ }
+ let id = self.next.fetch_add(1, Ordering::Relaxed).to_string();
+ videos.insert(id.clone(), video);
+ Ok(id)
+ }
-pub fn append_reference_video(&self, id: &str, bytes: &[u8], width: i32, height: i32, timestamp: f64) -> Result<(), String> {
- self.videos.lock().map_err(|_| "Reference video lock failed.")?
- .get_mut(id).ok_or("The prepared reference video no longer exists.")?
- .append(bytes, width, height, timestamp)
-}
+ pub fn append_reference_video(
+ &self,
+ id: &str,
+ bytes: &[u8],
+ width: i32,
+ height: i32,
+ timestamp: f64,
+ ) -> Result<(), String> {
+ self.videos
+ .lock()
+ .map_err(|_| "Reference video lock failed.")?
+ .get_mut(id)
+ .ok_or("The prepared reference video no longer exists.")?
+ .append(bytes, width, height, timestamp)
+ }
-pub fn set_reference_video_audio(&self, id: &str, bytes: &[u8], channels: i32, sample_rate: i32) -> Result<(), String> {
- if bytes.len() % 4 != 0 { return Err("Reference audio must contain complete float32 samples.".into()); }
- let samples: Vec<f32> = bytes.chunks_exact(4).map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap())).collect();
- self.videos.lock().map_err(|_| "Reference video lock failed.")?
- .get_mut(id).ok_or("The prepared reference video no longer exists.")?
- .set_audio(&samples, channels, sample_rate)
-}
+ pub fn set_reference_video_audio(
+ &self,
+ id: &str,
+ bytes: &[u8],
+ channels: i32,
+ sample_rate: i32,
+ ) -> Result<(), String> {
+ if bytes.len() % 4 != 0 {
+ return Err("Reference audio must contain complete float32 samples.".into());
+ }
+ let samples: Vec<f32> = bytes
+ .chunks_exact(4)
+ .map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap()))
+ .collect();
+ self.videos
+ .lock()
+ .map_err(|_| "Reference video lock failed.")?
+ .get_mut(id)
+ .ok_or("The prepared reference video no longer exists.")?
+ .set_audio(&samples, channels, sample_rate)
+ }
-pub fn release_reference_videos(&self, ids: &[String]) -> Result<(), String> {
- let mut videos = self.videos.lock().map_err(|_| "Reference video lock failed.")?;
- for id in ids { videos.remove(id); }
- Ok(())
-
-}
+ pub fn release_reference_videos(&self, ids: &[String]) -> Result<(), String> {
+ let mut videos = self
+ .videos
+ .lock()
+ .map_err(|_| "Reference video lock failed.")?;
+ for id in ids {
+ videos.remove(id);
+ }
+ Ok(())
+ }
}
diff --git a/src-tauri/src/slopfab/runtime.rs b/src-tauri/src/slopfab/runtime.rs
index 1c1397f..b39f474 100644
--- a/src-tauri/src/slopfab/runtime.rs
+++ b/src-tauri/src/slopfab/runtime.rs
@@ -1,4 +1,21 @@
-use super::*;
+use super::{
+ config::Configuration,
+ events::{EventSink, NativeEvent},
+ ffi,
+ generation::run_generation,
+ planning::validate_generation_controls,
+ references::ReferenceVideos,
+ types::*,
+};
+use crate::{diagnostics, project::ProviderSetting, rendered};
+use std::{
+ collections::{BTreeMap, HashMap},
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ mpsc, Arc, Mutex,
+ },
+ thread,
+};
#[derive(Clone)]
pub struct SlopfabRuntime {
@@ -139,14 +156,12 @@ impl SlopfabRuntime {
flags.insert(request.job_id.clone(), cancel.clone());
drop(flags);
let queued_id = request.job_id.clone();
- events(NativeEvent::Job(
- JobEvent {
- job_id: queued_id.clone(),
- state: "queued",
- detail: "Queued behind any active slopfab generation.".into(),
- output: None,
- },
- ));
+ events(NativeEvent::Job(JobEvent {
+ job_id: queued_id.clone(),
+ state: "queued",
+ detail: "Queued behind any active slopfab generation.".into(),
+ output: None,
+ }));
if self
.sender
.send(QueueItem {
@@ -206,4 +221,3 @@ pub(super) struct QueueItem {
pub(super) configuration: Configuration,
pub(super) cancel: Arc<AtomicBool>,
}
-
diff --git a/src-tauri/src/slopfab/status.rs b/src-tauri/src/slopfab/status.rs
index fdac017..0bb035f 100644
--- a/src-tauri/src/slopfab/status.rs
+++ b/src-tauri/src/slopfab/status.rs
@@ -1,4 +1,6 @@
-use super::*;
+use super::{config::Configuration, ffi, platform::*, types::*};
+use crate::project::ProviderSetting;
+use std::{collections::BTreeMap, path::Path};
pub fn status(settings: &BTreeMap<String, ProviderSetting>) -> SlopfabStatus {
let configuration = Configuration::from_settings(settings);
@@ -17,9 +19,16 @@ pub fn status(settings: &BTreeMap<String, ProviderSetting>) -> SlopfabStatus {
.collect::<Vec<_>>();
if configuration.animate {
models.push(ModelStatus {
- id: "promptEmbedding", configured: configuration.prompt_embedding.is_some(),
- available: configuration.prompt_embedding.as_deref().is_some_and(Path::is_file),
- path: configuration.prompt_embedding.as_ref().map(|path| path.to_string_lossy().into_owned()),
+ id: "promptEmbedding",
+ configured: configuration.prompt_embedding.is_some(),
+ available: configuration
+ .prompt_embedding
+ .as_deref()
+ .is_some_and(Path::is_file),
+ path: configuration
+ .prompt_embedding
+ .as_ref()
+ .map(|path| path.to_string_lossy().into_owned()),
});
}
let dll_path = configuration.dll_path.to_string_lossy().into_owned();
diff --git a/src-tauri/src/slopfab/tests.rs b/src-tauri/src/slopfab/tests.rs
index 391e498..d29ae9b 100644
--- a/src-tauri/src/slopfab/tests.rs
+++ b/src-tauri/src/slopfab/tests.rs
@@ -1,18 +1,32 @@
-use super::*;
+use super::{
+ config::*, events::stage_name, ffi::RequestHandle, h3::*, planning::*, platform::*,
+ references::ReferenceVideos, *,
+};
+use crate::project::{ProviderOption, ProviderSetting};
+use std::collections::BTreeMap;
#[test]
fn animate_requires_video_and_prompt_mode_requires_text() {
let mut configuration = Configuration::from_settings(&BTreeMap::new());
let mut request = GenerationRequest::default();
- assert!(configuration.validate_inputs(&request).unwrap_err().contains("prompt"));
+ assert!(configuration
+ .validate_inputs(&request)
+ .unwrap_err()
+ .contains("prompt"));
configuration.animate = true;
- assert!(configuration.validate_inputs(&request).unwrap_err().contains("reference video"));
+ assert!(configuration
+ .validate_inputs(&request)
+ .unwrap_err()
+ .contains("reference video"));
request.reference_paths.push("image.png".into());
assert!(configuration.validate_inputs(&request).is_err());
request.reference_video_ids.push("video".into());
configuration.validate_inputs(&request).unwrap();
request.still_image = true;
- assert!(configuration.validate_inputs(&request).unwrap_err().contains("video generation"));
+ assert!(configuration
+ .validate_inputs(&request)
+ .unwrap_err()
+ .contains("video generation"));
}
#[test]
@@ -21,23 +35,38 @@ fn animate_recipe_and_audio_selection_reach_bundled_dll() {
let root = tempfile::tempdir().unwrap();
let embedding = root.path().join("conditioning.safetensors");
crate::conditioning::fixture(&embedding);
- let settings = BTreeMap::from([("slopfab".into(), ProviderSetting {
- enabled: true, model: None,
- options: BTreeMap::from([
- ("generationMode".into(), ProviderOption::String("animate".into())),
- ("promptEmbedding".into(), ProviderOption::String(embedding.to_string_lossy().into_owned())),
- ("stepOverride".into(), ProviderOption::Number(4.0)),
- ]),
- })]);
+ let settings = BTreeMap::from([(
+ "slopfab".into(),
+ ProviderSetting {
+ enabled: true,
+ model: None,
+ options: BTreeMap::from([
+ (
+ "generationMode".into(),
+ ProviderOption::String("animate".into()),
+ ),
+ (
+ "promptEmbedding".into(),
+ ProviderOption::String(embedding.to_string_lossy().into_owned()),
+ ),
+ ("stepOverride".into(), ProviderOption::Number(4.0)),
+ ]),
+ },
+ )]);
let configuration = Configuration::from_settings(&settings);
let api = ffi::Api::load(&configuration.dll_path).unwrap();
let id = references.create_reference_video(2.0, &settings).unwrap();
let result = (|| -> Result<(), String> {
references.append_reference_video(&id, &vec![127; 64 * 64 * 4], 64, 64, 0.0)?;
let request = GenerationRequest {
- job_id: "animate-test".into(), frames: 48, steps: 20, seed: 1,
+ job_id: "animate-test".into(),
+ frames: 48,
+ steps: 20,
+ seed: 1,
prompt: "This scene prompt must be ignored by Animate.".into(),
- canvas_width: 736, canvas_height: 416, reference_video_ids: vec![id.clone()],
+ canvas_width: 736,
+ canvas_height: 416,
+ reference_video_ids: vec![id.clone()],
reference_paths: vec!["repainted.png".into()],
..Default::default()
};
@@ -48,14 +77,30 @@ fn animate_recipe_and_audio_selection_reach_bundled_dll() {
for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {
for purpose in [RequestPurpose::Plan, RequestPurpose::Generate] {
let handle = RequestHandle::new(&api)?;
- configure_request(&api, &handle, &request, &configuration, platform, purpose, &references)?;
+ configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ platform,
+ purpose,
+ &references,
+ )?;
assert_eq!(api.resolve(&handle)?.num_model_evaluations, 3);
let description = api.describe(&handle)?;
- assert!(description.contains("fixed 362-token embedding; video then repainted image"));
+ assert!(description
+ .contains("fixed 362-token embedding; video then repainted image"));
assert!(description.contains("reference short edge 416"));
assert!(description.contains("video 1.000000 .. 0.600000 (shift 3.0)"));
- assert!(description.contains(if preserve_audio { "pinned driving soundtrack" } else { "generated; driving reference soundtrack omitted" }));
- assert!(description.contains(&format!("prompt {} characters", ANIMATE_PROMPT.len())));
+ assert!(description.contains(if preserve_audio {
+ "pinned driving soundtrack"
+ } else {
+ "generated; driving reference soundtrack omitted"
+ }));
+ assert!(description.contains(&format!(
+ "prompt {} characters",
+ ANIMATE_PROMPT.len()
+ )));
}
}
}
@@ -80,34 +125,77 @@ fn animate_duration_limit_resolves_with_bundled_dll() {
let result = (|| -> Result<(), String> {
references.append_reference_video(&id, &vec![127; 64 * 64 * 4], 64, 64, 0.0)?;
let mut request = GenerationRequest {
- prompt: "A dancer.".into(), steps: 4, seed: 1,
- canvas_width: 736, canvas_height: 416, reference_video_ids: vec![id.clone()],
+ prompt: "A dancer.".into(),
+ steps: 4,
+ seed: 1,
+ canvas_width: 736,
+ canvas_height: 416,
+ reference_video_ids: vec![id.clone()],
reference_paths: vec!["repainted.png".into()],
..Default::default()
};
for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {
for purpose in [RequestPurpose::Plan, RequestPurpose::Generate] {
- for (frames, expected) in [(48, 56), (336, 345), (345, 345), (346, 345), (348, 345), (359, 345), (360, 345)] {
+ for (frames, expected) in [
+ (48, 56),
+ (336, 345),
+ (345, 345),
+ (346, 345),
+ (348, 345),
+ (359, 345),
+ (360, 345),
+ ] {
request.frames = frames;
let handle = RequestHandle::new(&api)?;
- configure_request(&api, &handle, &request, &configuration, platform, purpose, &references)?;
+ configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ platform,
+ purpose,
+ &references,
+ )?;
let plan = api.resolve(&handle)?;
assert_eq!(plan.aligned_frames, expected, "requested {frames} frames");
assert_eq!(plan.duration_seconds, f64::from(expected) / 24.0);
- assert_eq!(scene_frame_window(&request, plan.aligned_frames)?, (0, expected));
+ assert_eq!(
+ scene_frame_window(&request, plan.aligned_frames)?,
+ (0, expected)
+ );
}
}
}
request.frames = 361;
let handle = RequestHandle::new(&api)?;
- configure_request(&api, &handle, &request, &configuration, ComputePlatform::Cuda13, RequestPurpose::Plan, &references)?;
- assert!(api.resolve(&handle).err().unwrap().contains("at most 15 seconds"));
+ configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ ComputePlatform::Cuda13,
+ RequestPurpose::Plan,
+ &references,
+ )?;
+ assert!(api
+ .resolve(&handle)
+ .err()
+ .unwrap()
+ .contains("at most 15 seconds"));
// Other generators keep their existing upward alignment at 15 s.
configuration.animate = false;
request.frames = 360;
let handle = RequestHandle::new(&api)?;
- configure_request(&api, &handle, &request, &configuration, ComputePlatform::Cuda13, RequestPurpose::Plan, &references)?;
+ configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ ComputePlatform::Cuda13,
+ RequestPurpose::Plan,
+ &references,
+ )?;
assert_eq!(api.resolve(&handle)?.aligned_frames, 362);
Ok(())
})();
@@ -137,15 +225,23 @@ fn continuation_uses_22_frames_and_plans_only_the_new_scene() {
"video_rows": { "dtype": "F32", "shape": [24, 96], "data_offsets": [0, video_bytes] },
"audio_rows": { "dtype": "F32", "shape": [130, 32], "data_offsets": [video_bytes, video_bytes + audio_bytes] },
}).to_string();
- while header.len() % 8 != 0 { header.push(' '); }
+ while header.len() % 8 != 0 {
+ header.push(' ');
+ }
let mut bytes = (header.len() as u64).to_le_bytes().to_vec();
bytes.extend_from_slice(header.as_bytes());
bytes.resize(bytes.len() + video_bytes + audio_bytes, 0);
std::fs::write(&path, bytes).unwrap();
let mut request = GenerationRequest {
- job_id: "continued".into(), prompt: "The camera keeps moving.".into(),
- frames: 18, steps: 4, seed: 1, canvas_width: 64, canvas_height: 32,
- continuation_path: Some(path.clone()), save_latents_path: Some(root.path().join("next.safetensors")),
+ job_id: "continued".into(),
+ prompt: "The camera keeps moving.".into(),
+ frames: 18,
+ steps: 4,
+ seed: 1,
+ canvas_width: 64,
+ canvas_height: 32,
+ continuation_path: Some(path.clone()),
+ save_latents_path: Some(root.path().join("next.safetensors")),
..Default::default()
};
let settings = BTreeMap::new();
@@ -153,11 +249,23 @@ fn continuation_uses_22_frames_and_plans_only_the_new_scene() {
let api = ffi::Api::load(&configuration.dll_path).unwrap();
for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {
let handle = RequestHandle::new(&api).unwrap();
- configure_request(&api, &handle, &request, &configuration, platform, RequestPurpose::Generate, &references).unwrap();
+ configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ platform,
+ RequestPurpose::Generate,
+ &references,
+ )
+ .unwrap();
let raw = api.resolve(&handle).unwrap();
assert_eq!(raw.aligned_frames, 73);
assert_eq!(raw.latent_frames, 17); // 56-frame window, including 22 overlap.
- assert_eq!(scene_frame_window(&request, raw.aligned_frames).unwrap(), (39, 34));
+ assert_eq!(
+ scene_frame_window(&request, raw.aligned_frames).unwrap(),
+ (39, 34)
+ );
}
let plan = resolve_plan(&request, &settings, &references).unwrap();
assert_eq!(plan.aligned_frames, 34);
@@ -172,12 +280,22 @@ fn continuation_uses_22_frames_and_plans_only_the_new_scene() {
#[test]
fn continuation_video_and_audio_skip_the_cumulative_source() {
- let mut request = GenerationRequest { frames: 119, continuation_path: Some("source".into()), ..Default::default() };
+ let mut request = GenerationRequest {
+ frames: 119,
+ continuation_path: Some("source".into()),
+ ..Default::default()
+ };
assert_eq!(scene_frame_window(&request, 243).unwrap(), (124, 119));
// A further continuation skips the full joined source, not just its last scene.
assert_eq!(scene_frame_window(&request, 362).unwrap(), (243, 119));
- assert_eq!(scene_audio_offset(124, 24.0, 2, 48_000, 972_000).unwrap(), 496_000);
- assert_eq!(scene_audio_offset(243, 24.0, 2, 44_100, 2_000_000).unwrap(), 893_026);
+ assert_eq!(
+ scene_audio_offset(124, 24.0, 2, 48_000, 972_000).unwrap(),
+ 496_000
+ );
+ assert_eq!(
+ scene_audio_offset(243, 24.0, 2, 44_100, 2_000_000).unwrap(),
+ 893_026
+ );
assert_eq!(scene_audio_offset(124, 24.0, 0, 0, 0).unwrap(), 0);
assert!(scene_audio_offset(124, 24.0, 2, 48_000, 100).is_err());
assert!(scene_frame_window(&request, 120).is_err());
@@ -198,21 +316,46 @@ fn refmods_attach_for_plans_and_icons_or_report_an_older_dll() {
}).to_string();
let mut bytes = (header.len() as u64).to_le_bytes().to_vec();
bytes.extend_from_slice(header.as_bytes());
- for _ in 0..96 { bytes.extend_from_slice(&0.25_f32.to_le_bytes()); }
+ for _ in 0..96 {
+ bytes.extend_from_slice(&0.25_f32.to_le_bytes());
+ }
std::fs::write(&file, bytes).unwrap();
let mut request = GenerationRequest {
- job_id: "refmod-test".into(), prompt: "A portrait.".into(), still_image: true, frames: 1,
- steps: 20, seed: 1, canvas_width: 768, canvas_height: 768,
- reference_paths: Vec::new(), reference_video_ids: Vec::new(),
- refmods: vec![RefmodInput { path: file.to_string_lossy().into_owned(), strength: 0.7, copies: 2 }],
+ job_id: "refmod-test".into(),
+ prompt: "A portrait.".into(),
+ still_image: true,
+ frames: 1,
+ steps: 20,
+ seed: 1,
+ canvas_width: 768,
+ canvas_height: 768,
+ reference_paths: Vec::new(),
+ reference_video_ids: Vec::new(),
+ refmods: vec![RefmodInput {
+ path: file.to_string_lossy().into_owned(),
+ strength: 0.7,
+ copies: 2,
+ }],
..Default::default()
};
let probe = RequestHandle::new(&api).unwrap();
let added = api.add_refmod(&probe, &file, 0.7, 2);
if let Err(error) = &added {
assert!(error.contains("does not support refmods"), "{error}");
- eprintln!("Refmod export not yet available in the installed DLL; checked compatibility error.");
- assert!(configure_request(&api, &probe, &request, &configuration, ComputePlatform::Vulkan, RequestPurpose::Plan, &references).unwrap_err().contains("does not support refmods"));
+ eprintln!(
+ "Refmod export not yet available in the installed DLL; checked compatibility error."
+ );
+ assert!(configure_request(
+ &api,
+ &probe,
+ &request,
+ &configuration,
+ ComputePlatform::Vulkan,
+ RequestPurpose::Plan,
+ &references
+ )
+ .unwrap_err()
+ .contains("does not support refmods"));
} else {
for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {
for still_image in [false, true] {
@@ -220,7 +363,16 @@ fn refmods_attach_for_plans_and_icons_or_report_an_older_dll() {
request.frames = if still_image { 1 } else { 120 };
for purpose in [RequestPurpose::Plan, RequestPurpose::Generate] {
let handle = RequestHandle::new(&api).unwrap();
- configure_request(&api, &handle, &request, &configuration, platform, purpose, &references).unwrap();
+ configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ platform,
+ purpose,
+ &references,
+ )
+ .unwrap();
let plan = api.resolve(&handle).unwrap();
assert!(plan.aligned_frames >= request.frames);
}
@@ -230,75 +382,155 @@ fn refmods_attach_for_plans_and_icons_or_report_an_older_dll() {
request.refmods[0].strength = 0.0;
std::fs::remove_file(&file).unwrap();
let handle = RequestHandle::new(&api).unwrap();
- configure_request(&api, &handle, &request, &configuration, ComputePlatform::Vulkan, RequestPurpose::Generate, &references).unwrap();
+ configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ ComputePlatform::Vulkan,
+ RequestPurpose::Generate,
+ &references,
+ )
+ .unwrap();
request.refmods[0].copies = 11;
- assert!(configure_request(&api, &handle, &request, &configuration, ComputePlatform::Vulkan, RequestPurpose::Plan, &references).is_err());
+ assert!(configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ ComputePlatform::Vulkan,
+ RequestPurpose::Plan,
+ &references
+ )
+ .is_err());
}
#[test]
fn ordered_loras_and_step_override_reach_cuda_and_vulkan_requests() {
let references = ReferenceVideos::default();
let root = tempfile::tempdir().unwrap();
- let paths = [root.path().join("style.safetensors"), root.path().join("TaoMate.safetensors")];
- for path in &paths { std::fs::write(path, b"planning does not load weights").unwrap(); }
- let settings = BTreeMap::from([("slopfab".into(), ProviderSetting {
- enabled: true, model: None,
- options: BTreeMap::from([
- ("loras".into(), ProviderOption::String(serde_json::json!([
- { "path": paths[0], "strength": -0.5 },
- { "path": paths[1], "strength": 1.0 },
- ]).to_string())),
- ("stepOverride".into(), ProviderOption::Number(8.0)),
- ]),
- })]);
+ let paths = [
+ root.path().join("style.safetensors"),
+ root.path().join("TaoMate.safetensors"),
+ ];
+ for path in &paths {
+ std::fs::write(path, b"planning does not load weights").unwrap();
+ }
+ let settings = BTreeMap::from([(
+ "slopfab".into(),
+ ProviderSetting {
+ enabled: true,
+ model: None,
+ options: BTreeMap::from([
+ (
+ "loras".into(),
+ ProviderOption::String(
+ serde_json::json!([
+ { "path": paths[0], "strength": -0.5 },
+ { "path": paths[1], "strength": 1.0 },
+ ])
+ .to_string(),
+ ),
+ ),
+ ("stepOverride".into(), ProviderOption::Number(8.0)),
+ ]),
+ },
+ )]);
let configuration = Configuration::from_settings(&settings);
let api = ffi::Api::load(&configuration.dll_path).unwrap();
let request = GenerationRequest {
- job_id: "lora-test".into(), prompt: "A quiet harbour.".into(),
- frames: 120, still_image: false, steps: 20, seed: 1,
- canvas_width: 736, canvas_height: 416,
- reference_paths: Vec::new(), reference_video_ids: Vec::new(),
+ job_id: "lora-test".into(),
+ prompt: "A quiet harbour.".into(),
+ frames: 120,
+ still_image: false,
+ steps: 20,
+ seed: 1,
+ canvas_width: 736,
+ canvas_height: 416,
+ reference_paths: Vec::new(),
+ reference_video_ids: Vec::new(),
refmods: Vec::new(),
..Default::default()
};
for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {
for purpose in [RequestPurpose::Plan, RequestPurpose::Generate] {
let handle = RequestHandle::new(&api).unwrap();
- configure_request(&api, &handle, &request, &configuration, platform, purpose, &references).unwrap();
+ configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ platform,
+ purpose,
+ &references,
+ )
+ .unwrap();
assert_eq!(api.resolve(&handle).unwrap().num_model_evaluations, 7);
let description = api.describe(&handle).unwrap();
assert!(!description.contains("taomate-3step"));
- assert!(description.find("style.safetensors").unwrap() < description.find("TaoMate.safetensors").unwrap());
+ assert!(
+ description.find("style.safetensors").unwrap()
+ < description.find("TaoMate.safetensors").unwrap()
+ );
assert!(description.contains("strength -0.5"));
}
}
- let invalid = BTreeMap::from([("slopfab".into(), ProviderSetting {
- enabled: true, model: None,
- options: BTreeMap::from([("loras".into(), ProviderOption::String("invalid JSON".into()))]),
- })]);
+ let invalid = BTreeMap::from([(
+ "slopfab".into(),
+ ProviderSetting {
+ enabled: true,
+ model: None,
+ options: BTreeMap::from([(
+ "loras".into(),
+ ProviderOption::String("invalid JSON".into()),
+ )]),
+ },
+ )]);
assert!(Configuration::from_settings(&invalid).loras.is_err());
std::fs::remove_file(&paths[0]).unwrap();
let handle = RequestHandle::new(&api).unwrap();
- assert!(configure_request(&api, &handle, &request, &configuration, ComputePlatform::Vulkan, RequestPurpose::Generate, &references).unwrap_err().contains("LoRA file is missing"));
+ assert!(configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ ComputePlatform::Vulkan,
+ RequestPurpose::Generate,
+ &references
+ )
+ .unwrap_err()
+ .contains("LoRA file is missing"));
}
#[test]
fn vulkan_video_references_prepare_and_attach_for_planning_and_generation() {
let references = ReferenceVideos::default();
- let settings = BTreeMap::from([("slopfab".into(), ProviderSetting {
- enabled: true,
- model: None,
- options: BTreeMap::from([("inferenceBackend".into(), ProviderOption::String("vulkan".into()))]),
- })]);
+ let settings = BTreeMap::from([(
+ "slopfab".into(),
+ ProviderSetting {
+ enabled: true,
+ model: None,
+ options: BTreeMap::from([(
+ "inferenceBackend".into(),
+ ProviderOption::String("vulkan".into()),
+ )]),
+ },
+ )]);
let id = references.create_reference_video(2.0, &settings).unwrap();
let result = (|| -> Result<(), String> {
references.append_reference_video(&id, &vec![127; 64 * 64 * 4], 64, 64, 0.0)?;
references.set_reference_video_audio(&id, &vec![0; 32_000 * 2 * 4], 1, 32_000)?;
let request = GenerationRequest {
- job_id: "vulkan-reference-test".into(), prompt: "A scene using <Video 1>.".into(),
- frames: 120, still_image: false, steps: 12, seed: 1,
- canvas_width: 736, canvas_height: 416,
- reference_paths: Vec::new(), reference_video_ids: vec![id.clone()],
+ job_id: "vulkan-reference-test".into(),
+ prompt: "A scene using <Video 1>.".into(),
+ frames: 120,
+ still_image: false,
+ steps: 12,
+ seed: 1,
+ canvas_width: 736,
+ canvas_height: 416,
+ reference_paths: Vec::new(),
+ reference_video_ids: vec![id.clone()],
refmods: Vec::new(),
..Default::default()
};
@@ -306,7 +538,15 @@ fn vulkan_video_references_prepare_and_attach_for_planning_and_generation() {
let api = ffi::Api::load(&configuration.dll_path)?;
for purpose in [RequestPurpose::Plan, RequestPurpose::Generate] {
let handle = RequestHandle::new(&api)?;
- configure_request(&api, &handle, &request, &configuration, ComputePlatform::Vulkan, purpose, &references)?;
+ configure_request(
+ &api,
+ &handle,
+ &request,
+ &configuration,
+ ComputePlatform::Vulkan,
+ purpose,
+ &references,
+ )?;
assert!(api.resolve(&handle)?.aligned_frames > 0);
}
Ok(())
@@ -320,10 +560,12 @@ fn video_reference_c_api_copies_inputs_and_retains_attached_snapshot() {
let path = default_dll_path();
let api = ffi::Api::load(&path).unwrap();
let request = RequestHandle::new(&api).unwrap();
- api.set_prompt(&request, "A scene using <Video 1>.").unwrap();
+ api.set_prompt(&request, "A scene using <Video 1>.")
+ .unwrap();
api.set_frames(&request, 120).unwrap();
api.set_resolution(&request, 736, 416).unwrap();
- let mut video = ffi::ReferenceVideoHandle::new(ffi::Api::load(&path).unwrap(), 2.0, path.clone()).unwrap();
+ let mut video =
+ ffi::ReferenceVideoHandle::new(ffi::Api::load(&path).unwrap(), 2.0, path.clone()).unwrap();
let pixels = vec![127_u8; 64 * 64 * 4];
video.append(&pixels, 64, 64, 0.0).unwrap();
assert!(video.append(&pixels, 64, 64, 0.0).is_err());
@@ -377,29 +619,52 @@ fn platform_selection_prefers_supported_cuda_majors_and_falls_back_to_vulkan() {
#[test]
fn backend_preference_cannot_enable_cuda_without_cuda_hardware() {
let mut config = Configuration::from_settings(&BTreeMap::new());
- assert_eq!(config.platform(ComputePlatform::Cuda13), ComputePlatform::Cuda13);
- assert_eq!(config.platform(ComputePlatform::Cuda12), ComputePlatform::Cuda12);
- assert_eq!(config.platform(ComputePlatform::Vulkan), ComputePlatform::Vulkan);
+ assert_eq!(
+ config.platform(ComputePlatform::Cuda13),
+ ComputePlatform::Cuda13
+ );
+ assert_eq!(
+ config.platform(ComputePlatform::Cuda12),
+ ComputePlatform::Cuda12
+ );
+ assert_eq!(
+ config.platform(ComputePlatform::Vulkan),
+ ComputePlatform::Vulkan
+ );
config.vulkan = true;
- for detected in [ComputePlatform::Cuda13, ComputePlatform::Cuda12, ComputePlatform::Vulkan] {
+ for detected in [
+ ComputePlatform::Cuda13,
+ ComputePlatform::Cuda12,
+ ComputePlatform::Vulkan,
+ ] {
assert_eq!(config.platform(detected), ComputePlatform::Vulkan);
}
}
#[test]
fn attention_defaults_to_sage_and_is_independent_of_backend() {
- assert_eq!(Configuration::from_settings(&BTreeMap::new()).attention, "sage2");
+ assert_eq!(
+ Configuration::from_settings(&BTreeMap::new()).attention,
+ "sage2"
+ );
for backend in ["cuda", "vulkan"] {
for attention in ["exact", "flash2", "sage2", "invalid"] {
let settings = serde_json::from_value(serde_json::json!({
"slopfab": { "enabled": true, "model": null,
"options": { "inferenceBackend": backend, "attention": attention } }
- })).unwrap();
+ }))
+ .unwrap();
let config = Configuration::from_settings(&settings);
- let expected = if attention == "invalid" { "sage2" } else { attention };
+ let expected = if attention == "invalid" {
+ "sage2"
+ } else {
+ attention
+ };
assert_eq!(config.attention, expected);
assert_eq!(config.vulkan, backend == "vulkan");
- assert!(config.timing_profile("1.4.0", ComputePlatform::Vulkan).contains(&format!("attention={expected}|")));
+ assert!(config
+ .timing_profile("1.4.0", ComputePlatform::Vulkan)
+ .contains(&format!("attention={expected}|")));
}
}
}
@@ -407,7 +672,10 @@ fn attention_defaults_to_sage_and_is_independent_of_backend() {
#[test]
#[cfg(windows)]
fn bundled_dll_reports_a_compatible_api() {
- assert!(default_dll_path().is_file(), "The build must stage slopfab.dll beside the executable.");
+ assert!(
+ default_dll_path().is_file(),
+ "The build must stage slopfab.dll beside the executable."
+ );
let runtime = status(&BTreeMap::new());
assert_ne!(runtime.state, "runtimeMissing", "{}", runtime.detail);
assert_ne!(runtime.state, "incompatible", "{}", runtime.detail);
@@ -429,11 +697,14 @@ fn stage_ids_are_normalized_without_assuming_an_enum() {
#[test]
fn installed_dll_resolves_icons_as_one_still_frame_when_present() {
let references = ReferenceVideos::default();
- if !default_dll_path().is_file() { return; }
+ if !default_dll_path().is_file() {
+ return;
+ }
let request: GenerationRequest = serde_json::from_value(serde_json::json!({
"jobId": "icon-plan", "prompt": "A red toy car", "frames": 1, "stillImage": true,
"steps": 20, "seed": 1, "canvasWidth": 768, "canvasHeight": 768
- })).unwrap();
+ }))
+ .unwrap();
let plan = resolve_plan(&request, &BTreeMap::new(), &references).unwrap();
assert_eq!(plan.aligned_frames, 1);
assert_eq!(plan.latent_frames, 1);
@@ -443,18 +714,30 @@ fn installed_dll_resolves_icons_as_one_still_frame_when_present() {
#[test]
fn bundled_dll_accepts_all_attention_modes_on_both_backends() {
let references = ReferenceVideos::default();
- if !default_dll_path().is_file() { return; }
+ if !default_dll_path().is_file() {
+ return;
+ }
let api = ffi::Api::load(&default_dll_path()).unwrap();
let request: GenerationRequest = serde_json::from_value(serde_json::json!({
"jobId": "attention-plan", "prompt": "A red toy car", "frames": 1, "stillImage": true,
"steps": 20, "seed": 1, "canvasWidth": 768, "canvasHeight": 768
- })).unwrap();
+ }))
+ .unwrap();
let mut config = Configuration::from_settings(&BTreeMap::new());
for platform in [ComputePlatform::Cuda13, ComputePlatform::Vulkan] {
for attention in ["exact", "flash2", "sage2"] {
config.attention = attention;
let handle = RequestHandle::new(&api).unwrap();
- configure_request(&api, &handle, &request, &config, platform, RequestPurpose::Plan, &references).unwrap();
+ configure_request(
+ &api,
+ &handle,
+ &request,
+ &config,
+ platform,
+ RequestPurpose::Plan,
+ &references,
+ )
+ .unwrap();
assert_eq!(api.resolve(&handle).unwrap().aligned_frames, 1);
}
}
diff --git a/src-tauri/src/slopfab/types.rs b/src-tauri/src/slopfab/types.rs
index 87ead92..22119b2 100644
--- a/src-tauri/src/slopfab/types.rs
+++ b/src-tauri/src/slopfab/types.rs
@@ -1,4 +1,6 @@
-use super::*;
+use super::ffi;
+use serde::{Deserialize, Serialize};
+use std::path::PathBuf;
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -29,7 +31,9 @@ pub struct GpuDevice {
pub memory_bytes: u64,
}
-pub fn gpu_devices() -> Vec<GpuDevice> { ffi::gpu_devices() }
+pub fn gpu_devices() -> Vec<GpuDevice> {
+ ffi::gpu_devices()
+}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -139,4 +143,3 @@ pub(super) struct OutputMetadata {
pub(super) duration_seconds: f64,
pub(super) boundary: &'static str,
}
-
diff --git a/src-tauri/src/storage/atomic.rs b/src-tauri/src/storage/atomic.rs
index e6ca465..6d44946 100644
--- a/src-tauri/src/storage/atomic.rs
+++ b/src-tauri/src/storage/atomic.rs
@@ -1,4 +1,7 @@
-use std::{fs, io, path::{Path, PathBuf}};
+use std::{
+ fs, io,
+ path::{Path, PathBuf},
+};
#[cfg(not(windows))]
pub(crate) fn atomic_replace(temporary: &Path, destination: &Path) -> io::Result<()> {
fs::rename(temporary, destination)?;
@@ -47,24 +50,44 @@ pub(crate) fn atomic_replace(temporary: &Path, destination: &Path) -> io::Result
}
}
-
static NEXT_TEMPORARY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
struct TemporaryFile(PathBuf);
impl Drop for TemporaryFile {
- fn drop(&mut self) { let _ = fs::remove_file(&self.0); }
+ fn drop(&mut self) {
+ let _ = fs::remove_file(&self.0);
+ }
}
-pub(crate) fn write_with_replacer<F>(destination: &Path, bytes: &[u8], replacer: F) -> io::Result<()>
-where F: FnOnce(&Path, &Path) -> io::Result<()> {
+pub(crate) fn write_with_replacer<F>(
+ destination: &Path,
+ bytes: &[u8],
+ replacer: F,
+) -> io::Result<()>
+where
+ F: FnOnce(&Path, &Path) -> io::Result<()>,
+{
use io::Write;
use std::sync::atomic::Ordering;
- let parent = destination.parent().ok_or_else(|| io::Error::other("Destination has no parent"))?;
- let name = destination.file_name().ok_or_else(|| io::Error::other("Destination has no filename"))?;
+ let parent = destination
+ .parent()
+ .ok_or_else(|| io::Error::other("Destination has no parent"))?;
+ let name = destination
+ .file_name()
+ .ok_or_else(|| io::Error::other("Destination has no filename"))?;
let (temporary, mut file) = loop {
let sequence = NEXT_TEMPORARY.fetch_add(1, Ordering::Relaxed);
- let path = parent.join(format!(".{}.{}.{}.tmp", name.to_string_lossy(), std::process::id(), sequence));
- match fs::OpenOptions::new().write(true).create_new(true).open(&path) {
+ let path = parent.join(format!(
+ ".{}.{}.{}.tmp",
+ name.to_string_lossy(),
+ std::process::id(),
+ sequence
+ ));
+ match fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&path)
+ {
Ok(file) => break (TemporaryFile(path), file),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
diff --git a/src-tauri/src/tests/artifacts.rs b/src-tauri/src/tests/artifacts.rs
new file mode 100644
index 0000000..044343a
--- /dev/null
+++ b/src-tauri/src/tests/artifacts.rs
@@ -0,0 +1,106 @@
+use super::*;
+
+#[test]
+fn a_rendered_scene_lands_in_the_project_under_its_own_id() {
+ let folder = project_folder();
+ let (destination, relative) =
+ generated_video_destination(&folder.path().to_string_lossy(), "job-initial-brief").unwrap();
+ assert_eq!(relative, "media/generated/job-initial-brief.mp4");
+ assert!(destination.ends_with("media/generated/job-initial-brief.mp4"));
+ // The folder is made, so the write that follows has somewhere to go.
+ assert!(destination.parent().unwrap().is_dir());
+ // And it really is inside the project, not merely named as though it were.
+ assert!(destination.starts_with(folder.path().canonicalize().unwrap()));
+}
+
+#[test]
+fn latent_archives_are_unique_and_confined_to_the_project() {
+ let folder = project_folder();
+ let root = folder.path().to_string_lossy();
+ let destination = generated_latent_destination(&root, "work-one").unwrap();
+ assert!(destination.ends_with("latents/work-one.safetensors"));
+ fs::write(&destination, b"archive").unwrap();
+ assert!(generated_latent_destination(&root, "work-one").is_err());
+ assert!(generated_latent_destination(&root, "../escape").is_err());
+ let mut request: slopfab::GenerationRequest = serde_json::from_value(serde_json::json!({
+ "jobId": "next", "prompt": "Continue", "frames": 119, "steps": 4, "seed": 1,
+ "canvasWidth": 736, "canvasHeight": 416,
+ "continuationRelativePath": "latents/work-one.safetensors",
+ "saveLatentsPath": "C:/outside.safetensors", "continuationPath": "C:/outside.safetensors",
+ }))
+ .unwrap();
+ assert!(request.save_latents_path.is_none());
+ assert!(request.continuation_path.is_none());
+ assert!(prepare_continuation_path(&mut request, None).is_err());
+ prepare_continuation_path(&mut request, Some(&root)).unwrap();
+ assert_eq!(request.continuation_path, Some(destination));
+ for invalid in [
+ "../outside.safetensors",
+ "C:/outside.safetensors",
+ "latents/missing.safetensors",
+ ] {
+ request.continuation_relative_path = Some(invalid.into());
+ assert!(prepare_continuation_path(&mut request, Some(&root)).is_err());
+ }
+ let mut config = created_fixture();
+ config.generation_jobs[0].latent_relative_path = Some("latents/work-one.safetensors".into());
+ assert!(validate_and_normalize_config(config.clone()).is_ok());
+ config.generation_jobs[0].latent_relative_path = Some("../outside.safetensors".into());
+ assert!(validate_and_normalize_config(config).is_err());
+}
+
+#[test]
+fn purging_timeline_thumbnails_removes_only_the_named_scene() {
+ let folder = project_folder();
+ let first = folder.path().join("thumbnails/timeline/job-first");
+ let second = folder.path().join("thumbnails/timeline/job-second");
+ fs::create_dir_all(&first).unwrap();
+ fs::create_dir_all(&second).unwrap();
+ fs::write(first.join("00000000.jpg"), b"first").unwrap();
+ fs::write(second.join("00000000.jpg"), b"second").unwrap();
+
+ purge_timeline_thumbnails(
+ folder.path().to_string_lossy().into_owned(),
+ "job-first".into(),
+ )
+ .unwrap();
+
+ assert!(!first.exists());
+ assert!(second.join("00000000.jpg").is_file());
+}
+
+#[test]
+fn a_scene_id_that_is_not_a_scene_id_is_refused_rather_than_scrubbed() {
+ let folder = project_folder();
+ let root = folder.path().to_string_lossy().into_owned();
+ for hostile in [
+ "../../etc/passwd",
+ "..",
+ ".",
+ "job/../../escape",
+ r"job\..\escape",
+ "job:stream",
+ "job.mp4",
+ "",
+ " ",
+ &"j".repeat(65),
+ ] {
+ assert!(
+ generated_video_destination(&root, hostile).is_err(),
+ "'{hostile}' must not name a file"
+ );
+ }
+ // A dot is refused too — nothing Slopus generates has one, and
+ // allowing it is how a second extension gets in.
+ assert!(generated_file_stem("job-01_A").is_ok());
+ assert!(generated_file_stem("job.01").is_err());
+}
+
+#[test]
+fn a_folder_that_holds_no_project_gets_no_writer() {
+ // The same rule every other command that takes a folderPath follows:
+ // confining a name against an unchecked folder confines nothing.
+ let empty = tempfile::tempdir().unwrap();
+ assert!(generated_video_destination(&empty.path().to_string_lossy(), "job-01").is_err());
+ assert!(generated_video_destination("", "job-01").is_err());
+}
diff --git a/src-tauri/src/tests/group_2.rs b/src-tauri/src/tests/group_2.rs
deleted file mode 100644
index 5424f18..0000000
--- a/src-tauri/src/tests/group_2.rs
+++ /dev/null
@@ -1,556 +0,0 @@
-// S1: the perimeter this command actually has, pinned so nobody has to
-// take the docstring's word for it. The actor that opens a file here is
-// the PROJECT FILE, not the person — a `slopus.json` the user merely
-// opened can name any media file on the disk and get its bytes. That
-// follows from trusting any project file the user opens; the unbuilt
-// narrowing is a per-installation approval list (see the command's
-// docstring). What it IS bounded by is asserted here too.
-use super::*;
-#[test]
-fn a_project_the_user_only_opened_reads_any_media_file_it_names() {
- let access = MediaAccess::default();
- let root = tempfile::tempdir().unwrap();
- let pictures = root.path().join("Pictures");
- fs::create_dir(&pictures).unwrap();
- let private_photo = pictures.join("private.jpg");
- fs::write(&private_photo, b"PRIVATE PHOTO BYTES").unwrap();
- let diary = pictures.join("diary.txt");
- fs::write(&diary, b"DIARY").unwrap();
- let unnamed = pictures.join("holiday.jpg");
- fs::write(&unnamed, b"ANOTHER PHOTO").unwrap();
-
- // A project file the user did not write: a template a colleague sent,
- // an unzipped folder. Nobody picked these paths in any dialog.
- let mut config = created_fixture();
- for (index, (id, file)) in [("named", &private_photo), ("crafted", &diary)]
- .into_iter()
- .enumerate()
- {
- config.assets.push(ProjectAsset {
- id: format!("asset-{id}"),
- kind: "image".into(),
- name: format!("Shared {index}"),
- relative_path: None,
- source_path: Some(external_source_path(file).unwrap()),
- mime_type: "image/jpeg".into(),
- duration_ms: None,
- width: None,
- height: None,
- has_audio: None,
- created_at: config.created_at.clone(),
- });
- }
- let shared = root.path().join("Shared project");
- fs::create_dir(&shared).unwrap();
- write_project(&shared, &config).unwrap();
- let folder = shared.to_string_lossy().into_owned();
-
- // The rule, stated plainly: the project names it, so it is served.
- let named = config.assets[0].source_path.clone().unwrap();
- assert_eq!(
- external_media_bytes(&access, &folder, &named).unwrap(),
- b"PRIVATE PHOTO BYTES",
- "this is the documented perimeter, not a wish about it"
- );
-
- // And the two things that DO bound it. Media extensions only, checked
- // on the canonical path — a project file cannot name credentials.
- let crafted = config.assets[1].source_path.clone().unwrap();
- assert!(external_media_bytes(&access, &folder, &crafted)
- .unwrap_err()
- .contains("not a media file"));
- // And only what the project names: not the whole folder around it.
- assert!(external_media_bytes(&access, &folder, &unnamed.to_string_lossy())
- .unwrap_err()
- .contains("not one of the files this project points at"));
-}
-
-// S2: a file picked while project A was open is not project B's to read.
-// The session list used to be process-global, so opening a colleague's
-// project after importing your own rushes handed their project file a
-// reader for your footage — no hand-editing required, the paths were
-// already in memory.
-#[test]
-fn one_project_s_picks_are_not_another_project_s_to_read() {
- let access = MediaAccess::default();
- let root = tempfile::tempdir().unwrap();
- let rushes = root.path().join("Rushes");
- fs::create_dir(&rushes).unwrap();
- let footage = rushes.join("my footage.mp4");
- fs::write(&footage, b"A's footage").unwrap();
-
- let mine = project_folder_at(&root.path().join("Mine"));
- let theirs = project_folder_at(&root.path().join("Theirs"));
-
- // Imported into MY project, and not saved yet: only the session list
- // knows about it.
- let imported = import_media_file(&access, &footage, &mine).unwrap();
- let source = imported.source_path.unwrap();
- assert!(recorded_external_paths(&read_project(&mine).unwrap().config).is_empty());
-
- assert_eq!(
- external_media_bytes(&access, &mine.to_string_lossy(), &source).unwrap(),
- b"A's footage",
- "the project the clip was imported into must still preview it"
- );
- let error = external_media_bytes(&access, &theirs.to_string_lossy(), &source).unwrap_err();
- assert!(
- error.contains("not one of the files this project points at"),
- "another project read a file picked for this one: {error}"
- );
-}
-
-// S3: `read_project_file` confines the relative path against the folder it
-// is handed, and nothing used to check that the folder was a project. The
-// pair was the hole: every check passed while pointing at `.ssh`.
-#[test]
-fn reading_a_project_file_requires_the_folder_to_hold_a_project() {
- let access = MediaAccess::default();
- let root = tempfile::tempdir().unwrap();
- let ssh = root.path().join(".ssh");
- fs::create_dir(&ssh).unwrap();
- fs::write(ssh.join("id_rsa"), b"BEGIN OPENSSH PRIVATE KEY").unwrap();
-
- // `tauri::ipc::Response` is not `Debug`, so the error comes out by hand.
- let read = |folder: &Path, relative: &str| {
- read_project_file(folder.to_string_lossy().into_owned(), relative.into())
- .map(|_| ())
- .err()
- };
- let error = read(&ssh, "id_rsa").expect("a folder with no project was read");
- assert!(
- error.contains("does not hold a Slopus project"),
- "unexpected error: {error}"
- );
- // Same shape for the external read, which takes the folder too.
- assert!(external_media_bytes(&access,
- &ssh.to_string_lossy(),
- &ssh.join("id_rsa").to_string_lossy()
- )
- .unwrap_err()
- .contains("does not hold a Slopus project"));
-
- // A real project still reads its own files.
- let project = project_folder_at(&root.path().join("project"));
- fs::create_dir_all(project.join("references")).unwrap();
- fs::write(project.join("references/harbor.png"), b"\x89PNG\r\n\x1a\n").unwrap();
- assert_eq!(read(&project, "references/harbor.png"), None);
- // ...and still cannot climb out of itself.
- assert!(read(&project, "../.ssh/id_rsa").is_some());
-}
-
-#[test]
-fn a_project_file_only_yields_media_a_hand_edit_cannot_widen() {
- let access = MediaAccess::default();
- // Belt and braces for the direction the allow-list alone cannot cover:
- // a HAND-EDITED project file naming something that is not media. The
- // path is recorded, so the allow-list passes — the extension check is
- // what refuses it.
- let root = tempfile::tempdir().unwrap();
- let secret = root.path().join("id_rsa");
- fs::write(&secret, b"private key").unwrap();
-
- let mut config = created_fixture();
- config.assets.push(ProjectAsset {
- id: "asset-crafted".into(),
- kind: "video".into(),
- name: "Not a clip".into(),
- relative_path: None,
- source_path: Some(external_source_path(&secret).unwrap()),
- mime_type: "video/mp4".into(),
- duration_ms: None,
- width: None,
- height: None,
- has_audio: None,
- created_at: config.created_at.clone(),
- });
- let created = create_project_in(root.path(), &config).unwrap();
- let recorded = created.config.assets[0].source_path.clone().unwrap();
- let error = external_media_bytes(&access, &created.folder_path, &recorded).unwrap_err();
- assert!(
- error.contains("not a media file"),
- "unexpected error: {error}"
- );
-}
-
-#[test]
-fn every_stored_location_is_one_place_and_only_one() {
- let external = external_fixture();
- let normalized = validate_and_normalize_config(external.clone()).unwrap();
- assert_eq!(
- normalized.assets[0].source_path.as_deref(),
- Some(r"D:\tmp\news\News broadcast\rush-01.mp4"),
- "an external path is stored verbatim, not rewritten as a relative one"
- );
- assert!(normalized.assets[0].relative_path.is_none());
-
- // Both at once is not a location, and neither is neither.
- let mut both = external_fixture();
- both.assets[0].relative_path = Some("media/rush-01.mp4".into());
- assert!(validate_and_normalize_config(both)
- .unwrap_err()
- .contains("cannot have both"));
- let mut neither = external_fixture();
- neither.assets[0].source_path = None;
- assert!(validate_and_normalize_config(neither)
- .unwrap_err()
- .contains("must have either"));
-
- // A Generator scene can be arranged before its render exists. It still
- // has an asset id for timeline integrity, and gains its path when the
- // generated file is saved.
- let mut waiting_scene = external_fixture();
- waiting_scene.assets[0].kind = "generated".into();
- waiting_scene.assets[0].source_path = None;
- assert!(validate_and_normalize_config(waiting_scene).is_ok());
-
- // A "source path" that is not absolute resolves against nothing.
- for path in [
- "Footage\\clip.mp4",
- "media/clip.mp4",
- "..\\..\\clip.mp4",
- "D:\\..\\clip.mp4",
- "",
- ] {
- let mut relative = external_fixture();
- relative.assets[0].source_path = Some(path.into());
- assert!(
- validate_and_normalize_config(relative).is_err(),
- "accepted '{path}' as an absolute source path"
- );
- }
- // Every absolute form is accepted on every platform: a project file
- // written on Windows is still read on Linux and back.
- for path in [
- "D:\\Footage\\clip.mp4",
- "D:/Footage/clip.mp4",
- "/home/nn/clip.mp4",
- "\\\\nas\\share\\clip.mp4",
- ] {
- let mut absolute = external_fixture();
- absolute.assets[0].source_path = Some(path.into());
- assert!(
- validate_and_normalize_config(absolute).is_ok(),
- "rejected the absolute path '{path}'"
- );
- }
-
- // References follow the same rule, and a file-backed one still needs
- // its file.
- let mut both_on_reference = external_fixture();
- both_on_reference.references[1].relative_path = Some("references/cut.mov".into());
- assert!(validate_and_normalize_config(both_on_reference).is_err());
- let mut nowhere = external_fixture();
- nowhere.references[1].source_path = None;
- assert!(validate_and_normalize_config(nowhere).is_err());
-}
-
-#[test]
-fn the_settings_file_is_slopus_json_and_the_older_names_still_open() {
- assert_eq!(PROJECT_FILE_NAME, "slopus.json");
- let root = tempfile::tempdir().unwrap();
- let created = create_project_in(root.path(), &fixture()).unwrap();
- let folder = PathBuf::from(&created.folder_path);
- assert!(folder.join("slopus.json").is_file());
-
- // Every older name still opens, one folder per name, because a project
- // written by an earlier build must not become unopenable.
- for legacy in LEGACY_PROJECT_FILE_NAMES {
- let old = root.path().join(format!("old-{legacy}"));
- fs::create_dir(&old).unwrap();
- fs::copy(folder.join(PROJECT_FILE_NAME), old.join(legacy)).unwrap();
- assert_eq!(
- read_project(&old).unwrap().config,
- created.config,
- "a project stored as {legacy} failed to open"
- );
- // Saving migrates the name and leaves the old file where it is, so
- // the build that wrote it can still read the project.
- write_project(&old, &created.config).unwrap();
- assert!(old.join(PROJECT_FILE_NAME).is_file());
- assert!(old.join(legacy).is_file());
- // The new name wins once both exist.
- assert_eq!(project_file_in(&old), old.join(PROJECT_FILE_NAME));
- }
-}
-
-#[test]
-fn sanitizes_folder_names() {
- assert_eq!(safe_folder_name(" Launch: Film? "), "Launch- Film-");
- assert_eq!(safe_folder_name("..."), "Untitled video");
-}
-
-#[test]
-fn blank_text_references_never_block_a_project_save() {
- // The workspace creates an empty text reference the instant "New
- // definition" is clicked, before the user has typed anything. Rejecting
- // it here failed the whole save and blocked every unrelated edit in the
- // project — a regression that shipped once already. A blank text
- // reference must stay valid; do not tighten this without a UI change.
- let mut config = fixture();
- config.references.push(ReusableReference {
- id: "reference-blank".into(),
- kind: "text".into(),
- name: "New definition".into(),
- description: String::new(),
- content: None,
- relative_path: None,
- source_path: None,
- images: Vec::new(),
- refmods: Vec::new(),
- video: None,
- intended_use: Vec::new(),
- subcategory: None,
- icon_relative_path: None,
- created_at: "2026-01-01T00:07:00.000Z".into(),
- });
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "a blank text reference must never block saving the project"
- );
-}
-
-#[test]
-fn refmod_attachments_round_trip_and_validate_ranges_and_paths() {
- let mut value = serde_json::to_value(fixture()).unwrap();
- value["references"][0]["refmods"] = serde_json::json!([
- { "id": "latent", "name": "Person", "sourcePath": "D:/person.safetensors", "strength": 0.7, "copies": 2 }
- ]);
- let config = validate_and_normalize_config(serde_json::from_value(value.clone()).unwrap()).unwrap();
- let root = tempfile::tempdir().unwrap();
- let created = create_project_in(root.path(), &config).unwrap();
- let folder = Path::new(&created.folder_path);
- write_project(folder, &created.config).unwrap();
- assert_eq!(read_project(folder).unwrap().config.references[0].refmods, config.references[0].refmods);
- for (key, invalid) in [
- ("strength", serde_json::json!(-0.1)), ("strength", serde_json::json!(1.1)),
- ("copies", serde_json::json!(0)), ("copies", serde_json::json!(11)),
- ("sourcePath", serde_json::json!("../outside.safetensors")),
- ("sourcePath", serde_json::Value::Null),
- ] {
- let mut broken = value.clone();
- broken["references"][0]["refmods"][0][key] = invalid;
- assert!(serde_json::from_value(broken).map_err(|error| error.to_string()).and_then(validate_and_normalize_config).is_err());
- }
-}
-
-#[test]
-fn unified_reference_import_copies_images_and_keeps_video_and_refmod_sources() {
- let access = MediaAccess::default();
- let root = tempfile::tempdir().unwrap();
- let project = root.path().join("project");
- fs::create_dir_all(&project).unwrap();
- let paths = [root.path().join("photo.png"), root.path().join("motion.mp4"), root.path().join("person.safetensors")];
- for path in &paths { fs::write(path, b"source").unwrap(); }
- let imported = import_reference_attachments(&access, &project, &paths).unwrap();
- assert_eq!(imported.iter().map(|file| file.kind).collect::<Vec<_>>(), ["image", "video", "refmod"]);
- assert!(project.join(imported[0].relative_path.as_ref().unwrap()).is_file());
- assert!(imported[2].relative_path.is_none());
- assert_eq!(imported[2].source_path.as_deref(), Some(external_source_path(&paths[2]).unwrap().as_str()));
- assert!(paths.iter().all(|path| path.is_file()));
- assert!(import_reference_attachments(&access, &project, &[paths[1].clone(), paths[1].clone()]).unwrap_err().contains("one video"));
- assert!(reference_attachment_kind(Path::new("script.exe")).is_err());
-}
-
-#[test]
-fn video_reference_clip_settings_survive_save_and_reopen() {
- let mut config = fixture();
- let reference = &mut config.references[0];
- reference.kind = "video".into();
- reference.relative_path = Some("media/reference.mp4".into());
- reference.source_path = None;
- reference.video = Some(ReferenceVideoOptions { start_seconds: 3.5, duration_seconds: 4.0, include_audio: false });
- let config = validate_and_normalize_config(config).unwrap();
- let value = serde_json::to_value(&config).unwrap();
- assert_eq!(value["references"][0]["video"]["startSeconds"], 3.5);
- let reopened: ProjectConfig = serde_json::from_value(value).unwrap();
- assert_eq!(reopened.references[0].video, config.references[0].video);
- let mut invalid = reopened;
- invalid.references[0].video.as_mut().unwrap().duration_seconds = 16.0;
- assert!(validate_and_normalize_config(invalid).is_err());
-}
-
-#[test]
-fn scene_frame_settings_survive_save_and_reopen_and_validate_images() {
- let mut config = fixture();
- let image_id = config
- .references
- .iter()
- .find(|reference| reference.kind == "image")
- .unwrap()
- .id
- .clone();
- config.generation_jobs[0].end_frame_reference_id = Some(image_id.clone());
- config.generation_jobs[0].use_previous_scene_last_frame = Some(true);
- let folder = tempfile::tempdir().unwrap();
- write_project(folder.path(), &config).unwrap();
- let restored = read_project(folder.path()).unwrap().config;
- assert_eq!(
- restored.generation_jobs[0]
- .end_frame_reference_id
- .as_deref(),
- Some(image_id.as_str())
- );
- assert_eq!(
- restored.generation_jobs[0].use_previous_scene_last_frame,
- Some(true)
- );
- config.generation_jobs[0].end_frame_reference_id = Some("missing".into());
- assert!(validate_and_normalize_config(config.clone())
- .unwrap_err()
- .contains("unknown end-frame"));
- config.generation_jobs[0].end_frame_reference_id = Some(
- config
- .references
- .iter()
- .find(|reference| reference.kind == "text")
- .unwrap()
- .id
- .clone(),
- );
- assert!(validate_and_normalize_config(config)
- .unwrap_err()
- .contains("is not an image"));
-}
-
-#[test]
-fn reference_images_are_attachments_and_derived_state_is_not_serialized() {
- let mut config = fixture();
- config.references[0].images = vec![
- ReferenceImage {
- id: "tone-front".into(),
- name: "Front".into(),
- relative_path: Some("references/front.png".into()),
- source_path: None,
- },
- ReferenceImage {
- id: "tone-side".into(),
- name: "Side".into(),
- relative_path: Some("references/side.png".into()),
- source_path: None,
- },
- ];
- let config = validate_and_normalize_config(config).unwrap();
- let value = serde_json::to_value(&config).unwrap();
- assert_eq!(
- value["references"][0]["images"].as_array().unwrap().len(),
- 2
- );
- assert!(value.get("agentConversation").is_none());
- assert!(value["generationJobs"][0].get("compiledPrompt").is_none());
-}
-
-#[test]
-fn blank_brief_is_a_valid_empty_project() {
- let mut config = fixture();
- config.brief.prompt.clear();
- config.generation_jobs.clear();
- assert!(validate_and_normalize_config(config).is_ok());
-}
-
-#[test]
-fn validator_rejects_what_the_frontend_schema_rejects() {
- // Configs arriving from the agent subprocess are written to disk before
- // the frontend ever parses them, so anything zod refuses has to be
- // refused here too or a project lands on disk that cannot be reopened.
- fn rejects(case: &str, break_config: impl FnOnce(&mut ProjectConfig)) {
- let mut config = fixture();
- break_config(&mut config);
- assert!(
- validate_and_normalize_config(config).is_err(),
- "accepted a config the frontend schema rejects: {case}"
- );
- }
-
- rejects("name longer than 120 characters", |config| {
- config.name = "n".repeat(200);
- });
- rejects("unsupported settings aspect ratio", |config| {
- config.settings.aspect_ratio = "21:9".into();
- });
- rejects("unsupported settings resolution", |config| {
- config.settings.resolution = "8k".into();
- });
- rejects("unsupported frame rate", |config| {
- config.settings.frame_rate = 48;
- });
- rejects("named background color", |config| {
- config.settings.background_color = "black".into();
- });
- rejects("shorthand background color", |config| {
- config.settings.background_color = "#fff".into();
- });
- rejects("non-hex digit in background color", |config| {
- config.settings.background_color = "#10131g".into();
- });
- rejects("unsupported brief status", |config| {
- config.brief.status = "done".into();
- });
- rejects("target duration above 600 seconds", |config| {
- config.brief.target_duration_seconds = 900;
- });
- rejects("unsupported brief aspect ratio", |config| {
- config.brief.aspect_ratio = "21:9".into();
- });
- rejects("unsupported brief resolution", |config| {
- config.brief.resolution = "8k".into();
- });
- rejects("unsupported asset kind", |config| {
- config.assets[0].kind = "clip".into();
- });
- rejects("empty asset mime type", |config| {
- config.assets[0].mime_type = String::new();
- });
- rejects("zero asset width", |config| {
- config.assets[0].width = Some(0);
- });
- rejects("zero asset height", |config| {
- config.assets[0].height = Some(0);
- });
- rejects("unsupported track kind", |config| {
- config.timeline.tracks[0].kind = "text".into();
- });
- rejects("empty track name", |config| {
- config.timeline.tracks[0].name = String::new();
- });
- rejects("empty clip label", |config| {
- config.timeline.tracks[0].clips[0].label = String::new();
- });
- rejects("zero clip duration", |config| {
- config.timeline.tracks[0].clips[0].duration_ms = 0;
- });
- rejects("unsupported clip status", |config| {
- config.timeline.tracks[0].clips[0].status = "final".into();
- });
- rejects("empty reference content", |config| {
- config.references[0].content = Some(String::new());
- });
- rejects("unsupported reference intended use", |config| {
- config.references[0].intended_use = vec!["mood".into()];
- });
- rejects("empty generation job provider id", |config| {
- config.generation_jobs[0].provider_id = Some(String::new());
- });
- rejects("empty generation job error", |config| {
- config.generation_jobs[0].error = Some(String::new());
- });
- rejects("shot tag group id the frontend regex refuses", |config| {
- config.generation_jobs[0].shot_tags = Some(BTreeMap::from([(
- "Camera Movement".into(),
- vec!["push-in".into()],
- )]));
- });
- rejects("shot tag id the frontend regex refuses", |config| {
- config.generation_jobs[0].shot_tags = Some(BTreeMap::from([(
- "cameraMovement".into(),
- vec!["Push In".into()],
- )]));
- });
- rejects("empty shot tag id", |config| {
- config.generation_jobs[0].shot_tags = Some(BTreeMap::from([(
- "cameraMovement".into(),
- vec![String::new()],
- )]));
- });
-}
-
diff --git a/src-tauri/src/tests/group_1.rs b/src-tauri/src/tests/media_access.rs
similarity index 54%
rename from src-tauri/src/tests/group_1.rs
rename to src-tauri/src/tests/media_access.rs
index 99cf463..395d52a 100644
--- a/src-tauri/src/tests/group_1.rs
+++ b/src-tauri/src/tests/media_access.rs
@@ -1,212 +1,4 @@
use super::*;
-#[test]
-fn stored_paths_are_normalized_and_escaping_paths_are_rejected() {
- let mut normalized = fixture();
- normalized.assets[0].relative_path = Some(".\\media\\imported//macro.mp4".into());
- assert_eq!(
- validate_and_normalize_config(normalized).unwrap().assets[0]
- .relative_path
- .as_deref(),
- Some("media/imported/macro.mp4")
- );
-
- for path in [
- "/etc/passwd",
- "\\Windows\\system.ini",
- "C:\\Users\\creator\\clip.mp4",
- "https://example.com/clip.mp4",
- "media/../../outside.mp4",
- "references/../outside.png",
- ] {
- let mut escaping = fixture();
- escaping.assets[0].relative_path = Some(path.into());
- assert!(
- validate_and_normalize_config(escaping).is_err(),
- "accepted escaping path {path}"
- );
- }
-
- let mut thumbnail = fixture();
- thumbnail.thumbnail = Some("../thumbnail.webp".into());
- let mut reference = fixture();
- reference.references[1].relative_path = Some("../product.png".into());
- let mut job = fixture();
- job.generation_jobs[0].output_relative_path = Some("C:\\output.mp4".into());
- for config in [thumbnail, reference, job] {
- assert!(validate_and_normalize_config(config).is_err());
- }
-}
-
-#[test]
-fn replacement_failure_preserves_original_project_json() {
- let root = tempfile::tempdir().unwrap();
- let original = fixture();
- write_project(root.path(), &original).unwrap();
- let destination = root.path().join(PROJECT_FILE_NAME);
- let original_bytes = fs::read(&destination).unwrap();
-
- let mut changed = original.clone();
- changed.name = "This must not replace the original".into();
- let error = write_project_with_replacer(root.path(), &changed, |_, _| {
- Err(io::Error::new(
- io::ErrorKind::PermissionDenied,
- "simulated replacement failure",
- ))
- })
- .unwrap_err();
-
- assert!(error.contains("simulated replacement failure"));
- assert_eq!(fs::read(&destination).unwrap(), original_bytes);
- assert_eq!(
- read_project(root.path()).unwrap().config,
- without_derived_project_state(validate_and_normalize_config(original).unwrap())
- );
- assert_eq!(
- fs::read_dir(root.path())
- .unwrap()
- .filter_map(Result::ok)
- .filter(|entry| entry.path().is_file())
- .count(),
- 1
- );
-}
-
-#[test]
-fn new_project_uses_the_selected_empty_folder_itself() {
- let selected = tempfile::tempdir().unwrap();
- let expected_root = selected.path().canonicalize().unwrap();
-
- let created = create_project_at_with_references(selected.path(), &fixture(), &[]).unwrap();
-
- assert_eq!(
- PathBuf::from(created.folder_path).canonicalize().unwrap(),
- expected_root
- );
- assert!(selected.path().join(PROJECT_FILE_NAME).is_file());
- assert!(!selected
- .path()
- .join(safe_folder_name(&created.config.name))
- .exists());
-}
-
-#[test]
-fn new_project_rejects_a_nonempty_selected_folder_without_changing_it() {
- let selected = tempfile::tempdir().unwrap();
- let existing = selected.path().join("keep.txt");
- fs::write(&existing, b"user data").unwrap();
-
- let error =
- create_project_at_with_references(selected.path(), &fixture(), &[]).unwrap_err();
-
- assert!(error.contains("not empty"), "unexpected error: {error}");
- assert_eq!(fs::read(&existing).unwrap(), b"user data");
- assert!(!selected.path().join(PROJECT_FILE_NAME).exists());
-}
-
-#[test]
-fn project_mutation_rejects_broken_relational_ids() {
- let mut config = fixture();
- config.generation_jobs[0]
- .reference_ids
- .push("missing-reference".into());
- assert!(validate_and_normalize_config(config)
- .unwrap_err()
- .contains("unknown reference"));
-}
-
-#[test]
-fn reference_icon_files_are_256_square_jpegs_confined_to_the_project() {
- let root = tempfile::tempdir().unwrap();
- write_project(root.path(), &fixture()).unwrap();
- let rgba = vec![128; 768 * 768 * 4];
- let folder = root.path().to_str().unwrap();
- let relative = write_reference_icon_frame(folder, "icon-test", &rgba).unwrap();
- assert_eq!(relative, "references/icons/icon-test.jpg");
- let jpeg = fs::read(root.path().join(&relative)).unwrap();
- let mut expected = Vec::new();
- jpeg_encoder::Encoder::new(&mut expected, 95)
- .encode(&vec![128; 256 * 256 * 3], 256, 256, jpeg_encoder::ColorType::Rgb)
- .unwrap();
- assert_eq!(jpeg, expected);
- assert_eq!(&jpeg[..2], &[0xff, 0xd8]);
- assert_eq!(&jpeg[jpeg.len() - 2..], &[0xff, 0xd9]);
- let frame = jpeg.windows(2).position(|bytes| bytes == [0xff, 0xc0]).unwrap();
- assert_eq!(u16::from_be_bytes([jpeg[frame + 5], jpeg[frame + 6]]), 256);
- assert_eq!(u16::from_be_bytes([jpeg[frame + 7], jpeg[frame + 8]]), 256);
- assert!(write_reference_icon_frame(folder, "../escape", &rgba).is_err());
- assert!(write_reference_icon_frame(folder, "icon-invalid", &[0; 4]).is_err());
-}
-
-#[test]
-fn reference_categories_and_subcategories_survive_project_save() {
- let root = tempfile::tempdir().unwrap();
- for (category, subcategory) in [
- ("character", "Animation"),
- ("animal", "Pets"),
- ("product", "Technology"),
- ("location", "Urban"),
- ("style", "Cinematic"),
- ] {
- let mut config = fixture();
- let reference = &mut config.references[0];
- reference.intended_use = vec![category.into()];
- reference.subcategory = Some(subcategory.into());
- reference.icon_relative_path = Some("references/icons/example.jpg".into());
- reference.description.clear();
- reference.content = None;
- write_project(root.path(), &config).unwrap();
- let restored = read_project(root.path()).unwrap();
- let reference = &restored.config.references[0];
- assert_eq!(reference.intended_use, vec![category]);
- assert_eq!(reference.subcategory.as_deref(), Some(subcategory));
- assert_eq!(reference.icon_relative_path.as_deref(), Some("references/icons/example.jpg"));
- assert!(reference.description.is_empty());
- assert!(reference.content.is_none());
- }
-}
-
-#[test]
-fn initial_reference_images_are_copied_and_bound_to_the_first_draft() {
- let root = tempfile::tempdir().unwrap();
- let source = root.path().join("mood board.webp");
- fs::write(&source, b"fixture-image").unwrap();
- let config = fixture();
-
- let created =
- create_project_in_with_references(root.path(), &config, std::slice::from_ref(&source))
- .unwrap();
- let reference = created
- .config
- .references
- .iter()
- .find(|reference| reference.id == "ref-initial-1")
- .unwrap();
-
- assert_eq!(reference.kind, "image");
- assert_eq!(reference.intended_use, vec!["style"]);
- // The description must stay EMPTY. `compileMiniMaxH3Prompt` emits a
- // reference's description as the subject's traits in the prompt sent to
- // the paid model, so app-authored filing boilerplate here is shipped to
- // the model as if the user had written it about their own image
- // ("<Subject 1> is harbor-facade, shown in <Picture 1>. Visual
- // reference supplied with the initial project brief."). The app never
- // invents words and presents them as the user's description — the text
- // path documents the same rule at src/lib/project.ts:87.
- assert_eq!(
- reference.description, "",
- "an imported reference must carry no app-authored description"
- );
- assert!(created
- .config
- .generation_jobs
- .first()
- .unwrap()
- .reference_ids
- .contains(&reference.id));
- assert!(Path::new(&created.folder_path)
- .join(reference.relative_path.as_ref().unwrap())
- .is_file());
-}
#[test]
fn the_windows_verbatim_prefix_never_reaches_the_user() {
@@ -294,39 +86,6 @@ fn video_and_audio_are_recorded_where_they_are_and_images_are_copied() {
assert_eq!(copied, ["title card.png"]);
}
-#[test]
-fn a_video_reference_is_pointed_at_while_an_image_reference_is_copied() {
- let access = MediaAccess::default();
- let root = tempfile::tempdir().unwrap();
- let project = root.path().join("project");
- fs::create_dir(&project).unwrap();
- let video = root.path().join("reference cut.mov");
- fs::write(&video, b"video").unwrap();
- let image = root.path().join("harbor facade.png");
- fs::write(&image, b"\x89PNG\r\n\x1a\n").unwrap();
-
- let referenced = import_reference_file(&access, &video, &project).unwrap();
- assert_eq!(referenced.kind, "video");
- assert_eq!(referenced.relative_path, None);
- assert!(referenced.source_path.is_some());
- assert!(
- !project
- .join("references")
- .join("reference cut.mov")
- .exists(),
- "a video reference was copied into the project"
- );
-
- let copied = import_reference_file(&access, &image, &project).unwrap();
- assert_eq!(copied.kind, "image");
- assert_eq!(
- copied.relative_path.as_deref(),
- Some("references/harbor facade.png")
- );
- assert_eq!(copied.source_path, None);
- assert!(project.join("references/harbor facade.png").is_file());
-}
-
#[test]
fn external_media_is_readable_only_because_the_project_names_it() {
let access = MediaAccess::default();
@@ -403,9 +162,12 @@ fn a_clip_imported_a_moment_ago_previews_before_the_project_is_saved() {
// is still refused.
let sibling = root.path().join("never picked.mp4");
fs::write(&sibling, b"other rush").unwrap();
- assert!(
- external_media_bytes(&access, &project.to_string_lossy(), &sibling.to_string_lossy()).is_err()
- );
+ assert!(external_media_bytes(
+ &access,
+ &project.to_string_lossy(),
+ &sibling.to_string_lossy()
+ )
+ .is_err());
}
// S5: the window shipped with `"csp": null`, which is not a policy — it is
@@ -414,6 +176,7 @@ fn a_clip_imported_a_moment_ago_previews_before_the_project_is_saved() {
// attacker something (no inline or eval'd script, nothing off-origin) and
// stay open in the two directions media previews genuinely need: `blob:`
// URLs for imported footage and `data:` URIs for thumbnails.
+
#[test]
fn the_window_ships_a_policy_that_previews_still_work_under() {
let config: serde_json::Value =
@@ -471,6 +234,7 @@ fn the_window_ships_a_policy_that_previews_still_work_under() {
//
// Turning it off costs nothing the app uses: files come in through the
// Import button's native dialog, not by dropping them on the window.
+
#[test]
fn the_window_leaves_drag_and_drop_to_the_webview() {
let config: serde_json::Value =
@@ -487,3 +251,140 @@ fn the_window_leaves_drag_and_drop_to_the_webview() {
// Writes a minimal real project folder and returns it, so a test can say
// "a folder that holds a project" without the create ceremony.
+#[test]
+fn a_project_the_user_only_opened_reads_any_media_file_it_names() {
+ let access = MediaAccess::default();
+ let root = tempfile::tempdir().unwrap();
+ let pictures = root.path().join("Pictures");
+ fs::create_dir(&pictures).unwrap();
+ let private_photo = pictures.join("private.jpg");
+ fs::write(&private_photo, b"PRIVATE PHOTO BYTES").unwrap();
+ let diary = pictures.join("diary.txt");
+ fs::write(&diary, b"DIARY").unwrap();
+ let unnamed = pictures.join("holiday.jpg");
+ fs::write(&unnamed, b"ANOTHER PHOTO").unwrap();
+
+ // A project file the user did not write: a template a colleague sent,
+ // an unzipped folder. Nobody picked these paths in any dialog.
+ let mut config = created_fixture();
+ for (index, (id, file)) in [("named", &private_photo), ("crafted", &diary)]
+ .into_iter()
+ .enumerate()
+ {
+ config.assets.push(ProjectAsset {
+ id: format!("asset-{id}"),
+ kind: "image".into(),
+ name: format!("Shared {index}"),
+ relative_path: None,
+ source_path: Some(external_source_path(file).unwrap()),
+ mime_type: "image/jpeg".into(),
+ duration_ms: None,
+ width: None,
+ height: None,
+ has_audio: None,
+ created_at: config.created_at.clone(),
+ });
+ }
+ let shared = root.path().join("Shared project");
+ fs::create_dir(&shared).unwrap();
+ write_project(&shared, &config).unwrap();
+ let folder = shared.to_string_lossy().into_owned();
+
+ // The rule, stated plainly: the project names it, so it is served.
+ let named = config.assets[0].source_path.clone().unwrap();
+ assert_eq!(
+ external_media_bytes(&access, &folder, &named).unwrap(),
+ b"PRIVATE PHOTO BYTES",
+ "this is the documented perimeter, not a wish about it"
+ );
+
+ // And the two things that DO bound it. Media extensions only, checked
+ // on the canonical path — a project file cannot name credentials.
+ let crafted = config.assets[1].source_path.clone().unwrap();
+ assert!(external_media_bytes(&access, &folder, &crafted)
+ .unwrap_err()
+ .contains("not a media file"));
+ // And only what the project names: not the whole folder around it.
+ assert!(
+ external_media_bytes(&access, &folder, &unnamed.to_string_lossy())
+ .unwrap_err()
+ .contains("not one of the files this project points at")
+ );
+}
+
+// S2: a file picked while project A was open is not project B's to read.
+// The session list used to be process-global, so opening a colleague's
+// project after importing your own rushes handed their project file a
+// reader for your footage — no hand-editing required, the paths were
+// already in memory.
+
+#[test]
+fn one_project_s_picks_are_not_another_project_s_to_read() {
+ let access = MediaAccess::default();
+ let root = tempfile::tempdir().unwrap();
+ let rushes = root.path().join("Rushes");
+ fs::create_dir(&rushes).unwrap();
+ let footage = rushes.join("my footage.mp4");
+ fs::write(&footage, b"A's footage").unwrap();
+
+ let mine = project_folder_at(&root.path().join("Mine"));
+ let theirs = project_folder_at(&root.path().join("Theirs"));
+
+ // Imported into MY project, and not saved yet: only the session list
+ // knows about it.
+ let imported = import_media_file(&access, &footage, &mine).unwrap();
+ let source = imported.source_path.unwrap();
+ assert!(recorded_external_paths(&read_project(&mine).unwrap().config).is_empty());
+
+ assert_eq!(
+ external_media_bytes(&access, &mine.to_string_lossy(), &source).unwrap(),
+ b"A's footage",
+ "the project the clip was imported into must still preview it"
+ );
+ let error = external_media_bytes(&access, &theirs.to_string_lossy(), &source).unwrap_err();
+ assert!(
+ error.contains("not one of the files this project points at"),
+ "another project read a file picked for this one: {error}"
+ );
+}
+
+// S3: `read_project_file` confines the relative path against the folder it
+// is handed, and nothing used to check that the folder was a project. The
+// pair was the hole: every check passed while pointing at `.ssh`.
+
+#[test]
+fn reading_a_project_file_requires_the_folder_to_hold_a_project() {
+ let access = MediaAccess::default();
+ let root = tempfile::tempdir().unwrap();
+ let ssh = root.path().join(".ssh");
+ fs::create_dir(&ssh).unwrap();
+ fs::write(ssh.join("id_rsa"), b"BEGIN OPENSSH PRIVATE KEY").unwrap();
+
+ // `tauri::ipc::Response` is not `Debug`, so the error comes out by hand.
+ let read = |folder: &Path, relative: &str| {
+ read_project_file(folder.to_string_lossy().into_owned(), relative.into())
+ .map(|_| ())
+ .err()
+ };
+ let error = read(&ssh, "id_rsa").expect("a folder with no project was read");
+ assert!(
+ error.contains("does not hold a Slopus project"),
+ "unexpected error: {error}"
+ );
+ // Same shape for the external read, which takes the folder too.
+ assert!(external_media_bytes(
+ &access,
+ &ssh.to_string_lossy(),
+ &ssh.join("id_rsa").to_string_lossy()
+ )
+ .unwrap_err()
+ .contains("does not hold a Slopus project"));
+
+ // A real project still reads its own files.
+ let project = project_folder_at(&root.path().join("project"));
+ fs::create_dir_all(project.join("references")).unwrap();
+ fs::write(project.join("references/harbor.png"), b"\x89PNG\r\n\x1a\n").unwrap();
+ assert_eq!(read(&project, "references/harbor.png"), None);
+ // ...and still cannot climb out of itself.
+ assert!(read(&project, "../.ssh/id_rsa").is_some());
+}
diff --git a/src-tauri/src/tests/mod.rs b/src-tauri/src/tests/mod.rs
index 2d8244a..a21bf70 100644
--- a/src-tauri/src/tests/mod.rs
+++ b/src-tauri/src/tests/mod.rs
@@ -1,9 +1,12 @@
-use crate::project::{*, paths::*, storage::*, lifecycle::*, validation::*};
-use crate::media::{access::*, import::*, artifacts::*};
-use crate::commands::{media::*, artifacts::*};
+use crate::commands::{artifacts::*, media::*};
+use crate::media::{access::*, artifacts::*, import::*};
+use crate::project::{lifecycle::*, paths::*, storage::*, validation::*, *};
use crate::slopfab;
-use std::{env,fs,io,collections::BTreeMap,path::{Path,PathBuf}};
-
+use std::{
+ collections::BTreeMap,
+ env, fs, io,
+ path::{Path, PathBuf},
+};
pub(super) fn fixture() -> ProjectConfig {
serde_json::from_str(include_str!("../../../fixtures/project-v1-complete.json")).unwrap()
@@ -56,13 +59,16 @@ pub(super) fn scene_fixture() -> ProjectConfig {
// `Option` field missing `skip_serializing_if` is invisible here until
// someone remembers to add its name. The authority is the generated
// `fixtures/rust-serialized-*.json` written by
-// `serialized_wire_format_fixtures_are_regenerated_for_the_frontend`,
+// `serialized_wire_format_matches_frontend_fixtures`,
// which the frontend test suite parses with the real zod schema — a
// forgotten field fails there without anyone editing this array.
-const NON_NULLABLE_OPTIONAL_KEYS: [&str; 5] =
- ["clipId", "durationMs", "width", "height", "color"];
+const NON_NULLABLE_OPTIONAL_KEYS: [&str; 5] = ["clipId", "durationMs", "width", "height", "color"];
-pub(super) fn collect_forbidden_nulls(value: &serde_json::Value, path: &str, found: &mut Vec<String>) {
+pub(super) fn collect_forbidden_nulls(
+ value: &serde_json::Value,
+ path: &str,
+ found: &mut Vec<String>,
+) {
match value {
serde_json::Value::Object(fields) => {
for (key, child) in fields {
@@ -99,13 +105,25 @@ pub(super) fn object_of<'a>(
.unwrap_or_else(|| panic!("{path} is not a JSON object"))
}
-mod group_0;
-mod group_1;
-mod group_2;
-mod group_3;
-
fn project_folder_at(path: &Path) -> PathBuf {
fs::create_dir_all(path).unwrap();
write_project(path, &created_fixture()).unwrap();
path.to_path_buf()
}
+
+fn project_folder() -> tempfile::TempDir {
+ let folder = tempfile::tempdir().unwrap();
+ fs::write(
+ folder.path().join(PROJECT_FILE_NAME),
+ serde_json::to_vec(&created_fixture()).unwrap(),
+ )
+ .unwrap();
+ folder
+}
+
+mod artifacts;
+mod media_access;
+mod persistence;
+mod references;
+mod scenes;
+mod schema;
diff --git a/src-tauri/src/tests/persistence.rs b/src-tauri/src/tests/persistence.rs
new file mode 100644
index 0000000..b18cc6f
--- /dev/null
+++ b/src-tauri/src/tests/persistence.rs
@@ -0,0 +1,340 @@
+use super::*;
+
+#[test]
+fn legacy_project_defaults_to_video_and_persists_its_type() {
+ let root = tempfile::tempdir().unwrap();
+ let legacy = include_str!("../../../fixtures/project-v1-created.json");
+ assert!(serde_json::from_str::<serde_json::Value>(legacy)
+ .unwrap()
+ .get("generationType")
+ .is_none());
+ fs::write(root.path().join(PROJECT_FILE_NAME), legacy).unwrap();
+ let opened = read_project(root.path()).unwrap();
+ assert_eq!(opened.config.generation_type, GenerationType::Video);
+ write_project(root.path(), &opened.config).unwrap();
+ let saved: serde_json::Value =
+ serde_json::from_slice(&fs::read(root.path().join(PROJECT_FILE_NAME)).unwrap()).unwrap();
+ assert_eq!(saved["generationType"], "video");
+}
+
+#[test]
+fn generation_types_survive_create_save_and_reopen() {
+ for generation_type in ["video", "image", "3d", "music", "speech"] {
+ let root = tempfile::tempdir().unwrap();
+ let mut value = serde_json::to_value(created_fixture()).unwrap();
+ value["generationType"] = serde_json::json!(generation_type);
+ let config: ProjectConfig = serde_json::from_value(value).unwrap();
+ let created = create_project_in(root.path(), &config).unwrap();
+ let folder = Path::new(&created.folder_path);
+ let opened = read_project(folder).unwrap();
+ write_project(folder, &opened.config).unwrap();
+ let reopened = read_project(folder).unwrap();
+ assert_eq!(reopened.config.generation_type, config.generation_type);
+ assert_eq!(
+ serde_json::to_value(reopened.config).unwrap()["generationType"],
+ generation_type
+ );
+ }
+}
+
+#[test]
+fn invalid_explicit_generation_types_are_rejected() {
+ for generation_type in [
+ serde_json::Value::Null,
+ serde_json::json!(""),
+ serde_json::json!("unknown"),
+ serde_json::json!("Video"),
+ serde_json::json!(3),
+ ] {
+ let mut value = serde_json::to_value(created_fixture()).unwrap();
+ value["generationType"] = generation_type;
+ assert!(serde_json::from_value::<ProjectConfig>(value).is_err());
+ }
+}
+
+#[test]
+fn complete_project_create_open_save_reopen_is_lossless() {
+ let root = tempfile::tempdir().unwrap();
+ let expected = without_derived_project_state(validate_and_normalize_config(fixture()).unwrap());
+ let created = create_project_in(root.path(), &expected).unwrap();
+ assert_eq!(created.config, expected);
+
+ let project_folder = PathBuf::from(&created.folder_path);
+ let opened = read_project(&project_folder).unwrap();
+ assert_eq!(opened.config, expected);
+
+ let mut saved = opened.config.clone();
+ saved.updated_at = "2026-02-03T04:05:06.000Z".into();
+ write_project(&project_folder, &saved).unwrap();
+ assert_eq!(read_project(&project_folder).unwrap().config, saved);
+
+ let mut directories = Vec::new();
+ fn collect_directories(root: &Path, current: &Path, output: &mut Vec<String>) {
+ for entry in fs::read_dir(current).unwrap() {
+ let path = entry.unwrap().path();
+ if path.is_dir() {
+ output.push(
+ path.strip_prefix(root)
+ .unwrap()
+ .to_string_lossy()
+ .replace('\\', "/"),
+ );
+ collect_directories(root, &path, output);
+ }
+ }
+ }
+ collect_directories(&project_folder, &project_folder, &mut directories);
+ directories.sort();
+ assert_eq!(
+ directories,
+ [
+ "cache",
+ "exports",
+ "media",
+ "media/generated",
+ "media/imported",
+ "references",
+ "thumbnails",
+ ]
+ );
+ let files: Vec<_> = fs::read_dir(&project_folder)
+ .unwrap()
+ .filter_map(Result::ok)
+ .filter(|entry| entry.path().is_file())
+ .map(|entry| entry.file_name().to_string_lossy().into_owned())
+ .collect();
+ assert_eq!(files, [PROJECT_FILE_NAME]);
+}
+
+#[test]
+fn chroma_key_survives_save_and_reopen_and_validates_settings() {
+ let mut config = fixture();
+ config.timeline.tracks[0].clips[0].chroma_key = Some(ClipChromaKey {
+ color: "#12ABef".into(),
+ tolerance: 27.0,
+ });
+ let config = without_derived_project_state(validate_and_normalize_config(config).unwrap());
+ let root = tempfile::tempdir().unwrap();
+ let created = create_project_in(root.path(), &config).unwrap();
+ let folder = PathBuf::from(&created.folder_path);
+ write_project(&folder, &config).unwrap();
+ assert_eq!(read_project(&folder).unwrap().config, config);
+ let json = serde_json::to_value(&config).unwrap();
+ assert_eq!(
+ json["timeline"]["tracks"][0]["clips"][0]["chromaKey"]["color"],
+ "#12ABef"
+ );
+ for (color, tolerance) in [
+ ("green", 20.0),
+ ("#12345g", 20.0),
+ ("#00ff00", -1.0),
+ ("#00ff00", 101.0),
+ ("#00ff00", f64::NAN),
+ ] {
+ let mut invalid = config.clone();
+ invalid.timeline.tracks[0].clips[0].chroma_key = Some(ClipChromaKey {
+ color: color.into(),
+ tolerance,
+ });
+ assert!(validate_and_normalize_config(invalid)
+ .unwrap_err()
+ .contains("chroma key"));
+ }
+ let mut removed = config.clone();
+ removed.timeline.tracks[0].clips[0].chroma_key = None;
+ write_project(&folder, &removed).unwrap();
+ assert!(
+ read_project(&folder).unwrap().config.timeline.tracks[0].clips[0]
+ .chroma_key
+ .is_none()
+ );
+}
+
+#[test]
+fn deleting_a_project_removes_its_folder_and_every_file_inside_it() {
+ let parent = tempfile::tempdir().unwrap();
+ let project = project_folder_at(&parent.path().join("Disposable project"));
+ fs::create_dir_all(project.join("media/generated")).unwrap();
+ fs::write(project.join("media/generated/scene.mp4"), b"video").unwrap();
+ let id = read_project(&project).unwrap().config.id;
+
+ delete_project_folder(&project.to_string_lossy(), &id).unwrap();
+
+ assert!(!project.exists());
+ assert!(parent.path().is_dir());
+}
+
+#[test]
+fn deletion_refuses_a_different_project_identity_and_keeps_the_folder() {
+ let parent = tempfile::tempdir().unwrap();
+ let project = project_folder_at(&parent.path().join("Keep this project"));
+
+ let error =
+ delete_project_folder(&project.to_string_lossy(), "some-other-project").unwrap_err();
+
+ assert!(error.contains("not the project selected for deletion"));
+ assert!(project.is_dir());
+ assert!(project.join(PROJECT_FILE_NAME).is_file());
+}
+
+#[test]
+fn old_v1_documents_receive_empty_persistence_containers() {
+ let mut value = serde_json::to_value(fixture()).unwrap();
+ let object = value.as_object_mut().unwrap();
+ object.remove("references");
+ object.remove("generationJobs");
+ object.remove("agentConversation");
+ object.remove("providerSettings");
+ let config: ProjectConfig = serde_json::from_value(value).unwrap();
+ assert!(config.references.is_empty());
+ assert!(config.generation_jobs.is_empty());
+ assert!(config.agent_conversation.messages.is_empty());
+ assert!(config.provider_settings.is_empty());
+}
+
+#[test]
+fn replacement_failure_preserves_original_project_json() {
+ let root = tempfile::tempdir().unwrap();
+ let original = fixture();
+ write_project(root.path(), &original).unwrap();
+ let destination = root.path().join(PROJECT_FILE_NAME);
+ let original_bytes = fs::read(&destination).unwrap();
+
+ let mut changed = original.clone();
+ changed.name = "This must not replace the original".into();
+ let error = write_project_with_replacer(root.path(), &changed, |_, _| {
+ Err(io::Error::new(
+ io::ErrorKind::PermissionDenied,
+ "simulated replacement failure",
+ ))
+ })
+ .unwrap_err();
+
+ assert!(error.contains("simulated replacement failure"));
+ assert_eq!(fs::read(&destination).unwrap(), original_bytes);
+ assert_eq!(
+ read_project(root.path()).unwrap().config,
+ without_derived_project_state(validate_and_normalize_config(original).unwrap())
+ );
+ assert_eq!(
+ fs::read_dir(root.path())
+ .unwrap()
+ .filter_map(Result::ok)
+ .filter(|entry| entry.path().is_file())
+ .count(),
+ 1
+ );
+}
+
+#[test]
+fn new_project_uses_the_selected_empty_folder_itself() {
+ let selected = tempfile::tempdir().unwrap();
+ let expected_root = selected.path().canonicalize().unwrap();
+
+ let created = create_project_at_with_references(selected.path(), &fixture(), &[]).unwrap();
+
+ assert_eq!(
+ PathBuf::from(created.folder_path).canonicalize().unwrap(),
+ expected_root
+ );
+ assert!(selected.path().join(PROJECT_FILE_NAME).is_file());
+ assert!(!selected
+ .path()
+ .join(safe_folder_name(&created.config.name))
+ .exists());
+}
+
+#[test]
+fn new_project_rejects_a_nonempty_selected_folder_without_changing_it() {
+ let selected = tempfile::tempdir().unwrap();
+ let existing = selected.path().join("keep.txt");
+ fs::write(&existing, b"user data").unwrap();
+
+ let error = create_project_at_with_references(selected.path(), &fixture(), &[]).unwrap_err();
+
+ assert!(error.contains("not empty"), "unexpected error: {error}");
+ assert_eq!(fs::read(&existing).unwrap(), b"user data");
+ assert!(!selected.path().join(PROJECT_FILE_NAME).exists());
+}
+
+#[test]
+fn project_mutation_rejects_broken_relational_ids() {
+ let mut config = fixture();
+ config.generation_jobs[0]
+ .reference_ids
+ .push("missing-reference".into());
+ assert!(validate_and_normalize_config(config)
+ .unwrap_err()
+ .contains("unknown reference"));
+}
+
+#[test]
+fn a_project_file_only_yields_media_a_hand_edit_cannot_widen() {
+ let access = MediaAccess::default();
+ // Belt and braces for the direction the allow-list alone cannot cover:
+ // a HAND-EDITED project file naming something that is not media. The
+ // path is recorded, so the allow-list passes — the extension check is
+ // what refuses it.
+ let root = tempfile::tempdir().unwrap();
+ let secret = root.path().join("id_rsa");
+ fs::write(&secret, b"private key").unwrap();
+
+ let mut config = created_fixture();
+ config.assets.push(ProjectAsset {
+ id: "asset-crafted".into(),
+ kind: "video".into(),
+ name: "Not a clip".into(),
+ relative_path: None,
+ source_path: Some(external_source_path(&secret).unwrap()),
+ mime_type: "video/mp4".into(),
+ duration_ms: None,
+ width: None,
+ height: None,
+ has_audio: None,
+ created_at: config.created_at.clone(),
+ });
+ let created = create_project_in(root.path(), &config).unwrap();
+ let recorded = created.config.assets[0].source_path.clone().unwrap();
+ let error = external_media_bytes(&access, &created.folder_path, &recorded).unwrap_err();
+ assert!(
+ error.contains("not a media file"),
+ "unexpected error: {error}"
+ );
+}
+
+#[test]
+fn the_settings_file_is_slopus_json_and_the_older_names_still_open() {
+ assert_eq!(PROJECT_FILE_NAME, "slopus.json");
+ let root = tempfile::tempdir().unwrap();
+ let created = create_project_in(root.path(), &fixture()).unwrap();
+ let folder = PathBuf::from(&created.folder_path);
+ assert!(folder.join("slopus.json").is_file());
+
+ // Every older name still opens, one folder per name, because a project
+ // written by an earlier build must not become unopenable.
+ for legacy in LEGACY_PROJECT_FILE_NAMES {
+ let old = root.path().join(format!("old-{legacy}"));
+ fs::create_dir(&old).unwrap();
+ fs::copy(folder.join(PROJECT_FILE_NAME), old.join(legacy)).unwrap();
+ assert_eq!(
+ read_project(&old).unwrap().config,
+ created.config,
+ "a project stored as {legacy} failed to open"
+ );
+ // Saving migrates the name and leaves the old file where it is, so
+ // the build that wrote it can still read the project.
+ write_project(&old, &created.config).unwrap();
+ assert!(old.join(PROJECT_FILE_NAME).is_file());
+ assert!(old.join(legacy).is_file());
+ // The new name wins once both exist.
+ assert_eq!(project_file_in(&old), old.join(PROJECT_FILE_NAME));
+ }
+}
+
+#[test]
+fn blank_brief_is_a_valid_empty_project() {
+ let mut config = fixture();
+ config.brief.prompt.clear();
+ config.generation_jobs.clear();
+ assert!(validate_and_normalize_config(config).is_ok());
+}
diff --git a/src-tauri/src/tests/references.rs b/src-tauri/src/tests/references.rs
new file mode 100644
index 0000000..3584c37
--- /dev/null
+++ b/src-tauri/src/tests/references.rs
@@ -0,0 +1,291 @@
+use super::*;
+
+#[test]
+fn reference_icon_files_are_256_square_jpegs_confined_to_the_project() {
+ let root = tempfile::tempdir().unwrap();
+ write_project(root.path(), &fixture()).unwrap();
+ let rgba = vec![128; 768 * 768 * 4];
+ let folder = root.path().to_str().unwrap();
+ let relative = write_reference_icon_frame(folder, "icon-test", &rgba).unwrap();
+ assert_eq!(relative, "references/icons/icon-test.jpg");
+ let jpeg = fs::read(root.path().join(&relative)).unwrap();
+ let mut expected = Vec::new();
+ jpeg_encoder::Encoder::new(&mut expected, 95)
+ .encode(
+ &vec![128; 256 * 256 * 3],
+ 256,
+ 256,
+ jpeg_encoder::ColorType::Rgb,
+ )
+ .unwrap();
+ assert_eq!(jpeg, expected);
+ assert_eq!(&jpeg[..2], &[0xff, 0xd8]);
+ assert_eq!(&jpeg[jpeg.len() - 2..], &[0xff, 0xd9]);
+ let frame = jpeg
+ .windows(2)
+ .position(|bytes| bytes == [0xff, 0xc0])
+ .unwrap();
+ assert_eq!(u16::from_be_bytes([jpeg[frame + 5], jpeg[frame + 6]]), 256);
+ assert_eq!(u16::from_be_bytes([jpeg[frame + 7], jpeg[frame + 8]]), 256);
+ assert!(write_reference_icon_frame(folder, "../escape", &rgba).is_err());
+ assert!(write_reference_icon_frame(folder, "icon-invalid", &[0; 4]).is_err());
+}
+
+#[test]
+fn reference_categories_and_subcategories_survive_project_save() {
+ let root = tempfile::tempdir().unwrap();
+ for (category, subcategory) in [
+ ("character", "Animation"),
+ ("animal", "Pets"),
+ ("product", "Technology"),
+ ("location", "Urban"),
+ ("style", "Cinematic"),
+ ] {
+ let mut config = fixture();
+ let reference = &mut config.references[0];
+ reference.intended_use = vec![category.into()];
+ reference.subcategory = Some(subcategory.into());
+ reference.icon_relative_path = Some("references/icons/example.jpg".into());
+ reference.description.clear();
+ reference.content = None;
+ write_project(root.path(), &config).unwrap();
+ let restored = read_project(root.path()).unwrap();
+ let reference = &restored.config.references[0];
+ assert_eq!(reference.intended_use, vec![category]);
+ assert_eq!(reference.subcategory.as_deref(), Some(subcategory));
+ assert_eq!(
+ reference.icon_relative_path.as_deref(),
+ Some("references/icons/example.jpg")
+ );
+ assert!(reference.description.is_empty());
+ assert!(reference.content.is_none());
+ }
+}
+
+#[test]
+fn initial_reference_images_are_copied_and_bound_to_the_first_draft() {
+ let root = tempfile::tempdir().unwrap();
+ let source = root.path().join("mood board.webp");
+ fs::write(&source, b"fixture-image").unwrap();
+ let config = fixture();
+
+ let created =
+ create_project_in_with_references(root.path(), &config, std::slice::from_ref(&source))
+ .unwrap();
+ let reference = created
+ .config
+ .references
+ .iter()
+ .find(|reference| reference.id == "ref-initial-1")
+ .unwrap();
+
+ assert_eq!(reference.kind, "image");
+ assert_eq!(reference.intended_use, vec!["style"]);
+ // The description must stay EMPTY. `compileMiniMaxH3Prompt` emits a
+ // reference's description as the subject's traits in the prompt sent to
+ // the paid model, so app-authored filing boilerplate here is shipped to
+ // the model as if the user had written it about their own image
+ // ("<Subject 1> is harbor-facade, shown in <Picture 1>. Visual
+ // reference supplied with the initial project brief."). The app never
+ // invents words and presents them as the user's description — the text
+ // path documents the same rule at src/lib/project.ts:87.
+ assert_eq!(
+ reference.description, "",
+ "an imported reference must carry no app-authored description"
+ );
+ assert!(created
+ .config
+ .generation_jobs
+ .first()
+ .unwrap()
+ .reference_ids
+ .contains(&reference.id));
+ assert!(Path::new(&created.folder_path)
+ .join(reference.relative_path.as_ref().unwrap())
+ .is_file());
+}
+
+#[test]
+fn a_video_reference_is_pointed_at_while_an_image_reference_is_copied() {
+ let access = MediaAccess::default();
+ let root = tempfile::tempdir().unwrap();
+ let project = root.path().join("project");
+ fs::create_dir(&project).unwrap();
+ let video = root.path().join("reference cut.mov");
+ fs::write(&video, b"video").unwrap();
+ let image = root.path().join("harbor facade.png");
+ fs::write(&image, b"\x89PNG\r\n\x1a\n").unwrap();
+
+ let referenced = import_reference_file(&access, &video, &project).unwrap();
+ assert_eq!(referenced.kind, "video");
+ assert_eq!(referenced.relative_path, None);
+ assert!(referenced.source_path.is_some());
+ assert!(
+ !project
+ .join("references")
+ .join("reference cut.mov")
+ .exists(),
+ "a video reference was copied into the project"
+ );
+
+ let copied = import_reference_file(&access, &image, &project).unwrap();
+ assert_eq!(copied.kind, "image");
+ assert_eq!(
+ copied.relative_path.as_deref(),
+ Some("references/harbor facade.png")
+ );
+ assert_eq!(copied.source_path, None);
+ assert!(project.join("references/harbor facade.png").is_file());
+}
+
+#[test]
+fn blank_text_references_never_block_a_project_save() {
+ // The workspace creates an empty text reference the instant "New
+ // definition" is clicked, before the user has typed anything. Rejecting
+ // it here failed the whole save and blocked every unrelated edit in the
+ // project — a regression that shipped once already. A blank text
+ // reference must stay valid; do not tighten this without a UI change.
+ let mut config = fixture();
+ config.references.push(ReusableReference {
+ id: "reference-blank".into(),
+ kind: "text".into(),
+ name: "New definition".into(),
+ description: String::new(),
+ content: None,
+ relative_path: None,
+ source_path: None,
+ images: Vec::new(),
+ refmods: Vec::new(),
+ video: None,
+ intended_use: Vec::new(),
+ subcategory: None,
+ icon_relative_path: None,
+ created_at: "2026-01-01T00:07:00.000Z".into(),
+ });
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "a blank text reference must never block saving the project"
+ );
+}
+
+#[test]
+fn refmod_attachments_round_trip_and_validate_ranges_and_paths() {
+ let mut value = serde_json::to_value(fixture()).unwrap();
+ value["references"][0]["refmods"] = serde_json::json!([
+ { "id": "latent", "name": "Person", "sourcePath": "D:/person.safetensors", "strength": 0.7, "copies": 2 }
+ ]);
+ let config =
+ validate_and_normalize_config(serde_json::from_value(value.clone()).unwrap()).unwrap();
+ let root = tempfile::tempdir().unwrap();
+ let created = create_project_in(root.path(), &config).unwrap();
+ let folder = Path::new(&created.folder_path);
+ write_project(folder, &created.config).unwrap();
+ assert_eq!(
+ read_project(folder).unwrap().config.references[0].refmods,
+ config.references[0].refmods
+ );
+ for (key, invalid) in [
+ ("strength", serde_json::json!(-0.1)),
+ ("strength", serde_json::json!(1.1)),
+ ("copies", serde_json::json!(0)),
+ ("copies", serde_json::json!(11)),
+ ("sourcePath", serde_json::json!("../outside.safetensors")),
+ ("sourcePath", serde_json::Value::Null),
+ ] {
+ let mut broken = value.clone();
+ broken["references"][0]["refmods"][0][key] = invalid;
+ assert!(serde_json::from_value(broken)
+ .map_err(|error| error.to_string())
+ .and_then(validate_and_normalize_config)
+ .is_err());
+ }
+}
+
+#[test]
+fn unified_reference_import_copies_images_and_keeps_video_and_refmod_sources() {
+ let access = MediaAccess::default();
+ let root = tempfile::tempdir().unwrap();
+ let project = root.path().join("project");
+ fs::create_dir_all(&project).unwrap();
+ let paths = [
+ root.path().join("photo.png"),
+ root.path().join("motion.mp4"),
+ root.path().join("person.safetensors"),
+ ];
+ for path in &paths {
+ fs::write(path, b"source").unwrap();
+ }
+ let imported = import_reference_attachments(&access, &project, &paths).unwrap();
+ assert_eq!(
+ imported.iter().map(|file| file.kind).collect::<Vec<_>>(),
+ ["image", "video", "refmod"]
+ );
+ assert!(project
+ .join(imported[0].relative_path.as_ref().unwrap())
+ .is_file());
+ assert!(imported[2].relative_path.is_none());
+ assert_eq!(
+ imported[2].source_path.as_deref(),
+ Some(external_source_path(&paths[2]).unwrap().as_str())
+ );
+ assert!(paths.iter().all(|path| path.is_file()));
+ assert!(
+ import_reference_attachments(&access, &project, &[paths[1].clone(), paths[1].clone()])
+ .unwrap_err()
+ .contains("one video")
+ );
+ assert!(reference_attachment_kind(Path::new("script.exe")).is_err());
+}
+
+#[test]
+fn video_reference_clip_settings_survive_save_and_reopen() {
+ let mut config = fixture();
+ let reference = &mut config.references[0];
+ reference.kind = "video".into();
+ reference.relative_path = Some("media/reference.mp4".into());
+ reference.source_path = None;
+ reference.video = Some(ReferenceVideoOptions {
+ start_seconds: 3.5,
+ duration_seconds: 4.0,
+ include_audio: false,
+ });
+ let config = validate_and_normalize_config(config).unwrap();
+ let value = serde_json::to_value(&config).unwrap();
+ assert_eq!(value["references"][0]["video"]["startSeconds"], 3.5);
+ let reopened: ProjectConfig = serde_json::from_value(value).unwrap();
+ assert_eq!(reopened.references[0].video, config.references[0].video);
+ let mut invalid = reopened;
+ invalid.references[0]
+ .video
+ .as_mut()
+ .unwrap()
+ .duration_seconds = 16.0;
+ assert!(validate_and_normalize_config(invalid).is_err());
+}
+
+#[test]
+fn reference_images_are_attachments_and_derived_state_is_not_serialized() {
+ let mut config = fixture();
+ config.references[0].images = vec![
+ ReferenceImage {
+ id: "tone-front".into(),
+ name: "Front".into(),
+ relative_path: Some("references/front.png".into()),
+ source_path: None,
+ },
+ ReferenceImage {
+ id: "tone-side".into(),
+ name: "Side".into(),
+ relative_path: Some("references/side.png".into()),
+ source_path: None,
+ },
+ ];
+ let config = validate_and_normalize_config(config).unwrap();
+ let value = serde_json::to_value(&config).unwrap();
+ assert_eq!(
+ value["references"][0]["images"].as_array().unwrap().len(),
+ 2
+ );
+ assert!(value.get("agentConversation").is_none());
+ assert!(value["generationJobs"][0].get("compiledPrompt").is_none());
+}
diff --git a/src-tauri/src/tests/group_3.rs b/src-tauri/src/tests/scenes.rs
similarity index 59%
rename from src-tauri/src/tests/group_3.rs
rename to src-tauri/src/tests/scenes.rs
index dbb2ee7..c76c891 100644
--- a/src-tauri/src/tests/group_3.rs
+++ b/src-tauri/src/tests/scenes.rs
@@ -1,4 +1,48 @@
use super::*;
+
+#[test]
+fn scene_frame_settings_survive_save_and_reopen_and_validate_images() {
+ let mut config = fixture();
+ let image_id = config
+ .references
+ .iter()
+ .find(|reference| reference.kind == "image")
+ .unwrap()
+ .id
+ .clone();
+ config.generation_jobs[0].end_frame_reference_id = Some(image_id.clone());
+ config.generation_jobs[0].use_previous_scene_last_frame = Some(true);
+ let folder = tempfile::tempdir().unwrap();
+ write_project(folder.path(), &config).unwrap();
+ let restored = read_project(folder.path()).unwrap().config;
+ assert_eq!(
+ restored.generation_jobs[0]
+ .end_frame_reference_id
+ .as_deref(),
+ Some(image_id.as_str())
+ );
+ assert_eq!(
+ restored.generation_jobs[0].use_previous_scene_last_frame,
+ Some(true)
+ );
+ config.generation_jobs[0].end_frame_reference_id = Some("missing".into());
+ assert!(validate_and_normalize_config(config.clone())
+ .unwrap_err()
+ .contains("unknown end-frame"));
+ config.generation_jobs[0].end_frame_reference_id = Some(
+ config
+ .references
+ .iter()
+ .find(|reference| reference.kind == "text")
+ .unwrap()
+ .id
+ .clone(),
+ );
+ assert!(validate_and_normalize_config(config)
+ .unwrap_err()
+ .contains("is not an image"));
+}
+
#[test]
fn shot_tags_normalize_the_same_way_the_frontend_does() {
// The three steps `normalizeShotTagSelection` performs in
@@ -223,8 +267,7 @@ fn shot_speech_and_custom_languages_survive_the_project_round_trip() {
shot.speech = Some("行こう! Keep this punctuation.".into());
shot.speech_language = Some("Japanese".into());
- let normalized =
- validate_and_normalize_config(config).expect("documented H3 speech is valid");
+ let normalized = validate_and_normalize_config(config).expect("documented H3 speech is valid");
let shot = &normalized.generation_jobs[0].shots.as_ref().unwrap()[0];
assert_eq!(
shot.speech.as_deref(),
@@ -233,8 +276,7 @@ fn shot_speech_and_custom_languages_survive_the_project_round_trip() {
assert_eq!(shot.speech_language.as_deref(), Some("Japanese"));
let mut custom = scene_fixture();
- custom.generation_jobs[0].shots.as_mut().unwrap()[0].speech_language =
- Some("Klingon".into());
+ custom.generation_jobs[0].shots.as_mut().unwrap()[0].speech_language = Some("Klingon".into());
let normalized = validate_and_normalize_config(custom)
.expect("custom speech languages are not validator errors");
assert_eq!(
@@ -294,114 +336,6 @@ fn scene_generation_controls_match_the_frontend_boundaries() {
}
}
-#[test]
-fn validator_accepts_every_boundary_the_frontend_schema_allows() {
- for aspect_ratio in ["16:9", "9:16", "1:1", "4:5"] {
- let mut config = fixture();
- config.settings.aspect_ratio = aspect_ratio.into();
- config.brief.aspect_ratio = aspect_ratio.into();
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "rejected valid aspect ratio {aspect_ratio}"
- );
- }
- for resolution in [
- "416p", "544p", "640p", "768p", "1088p", "1344p", "720p", "1080p", "4k",
- ] {
- let mut config = fixture();
- config.settings.resolution = resolution.into();
- config.brief.resolution = resolution.into();
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "rejected valid resolution {resolution}"
- );
- }
- for frame_rate in [24u32, 25, 30, 60] {
- let mut config = fixture();
- config.settings.frame_rate = frame_rate;
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "rejected valid frame rate {frame_rate}"
- );
- }
- for background_color in ["#000000", "#FFFFFF", "#abcdef", "#ABCDEF", "#10131a"] {
- let mut config = fixture();
- config.settings.background_color = background_color.into();
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "rejected valid background color {background_color}"
- );
- }
- for seconds in [0u32, 1, 5, 60, 600] {
- let mut config = fixture();
- config.brief.target_duration_seconds = seconds;
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "rejected valid target duration {seconds}"
- );
- }
- for status in ["draft", "queued", "generating", "ready", "failed"] {
- let mut config = fixture();
- config.brief.status = status.into();
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "rejected valid brief status {status}"
- );
- }
- for kind in ["video", "audio", "image", "caption", "generated"] {
- let mut config = fixture();
- config.assets[0].kind = kind.into();
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "rejected valid asset kind {kind}"
- );
- }
- for kind in ["video", "audio", "caption"] {
- let mut config = fixture();
- config.timeline.tracks[0].kind = kind.into();
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "rejected valid track kind {kind}"
- );
- }
- for status in ["draft", "generated", "approved"] {
- let mut config = fixture();
- config.timeline.tracks[0].clips[0].status = status.into();
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "rejected valid clip status {status}"
- );
- }
- for intent in ["character", "animal", "product", "location", "style", "audio"] {
- let mut config = fixture();
- config.references[0].intended_use = vec![intent.into()];
- assert!(
- validate_and_normalize_config(config).is_ok(),
- "rejected valid reference intended use {intent}"
- );
- }
-
- let mut longest_name = fixture();
- longest_name.name = "n".repeat(120);
- assert!(
- validate_and_normalize_config(longest_name).is_ok(),
- "rejected a 120 character project name"
- );
-
- let mut sparse = fixture();
- sparse.assets[0].width = None;
- sparse.assets[0].height = None;
- sparse.assets[0].duration_ms = None;
- sparse.references[0].content = None;
- sparse.references[0].intended_use = Vec::new();
- sparse.generation_jobs[0].provider_id = None;
- sparse.generation_jobs[0].error = None;
- assert!(
- validate_and_normalize_config(sparse).is_ok(),
- "rejected a config whose optional fields are absent"
- );
-}
-
#[test]
fn timeline_flags_fall_back_to_the_frontend_defaults() {
let mut value = serde_json::to_value(fixture()).unwrap();
@@ -430,115 +364,3 @@ fn timeline_flags_fall_back_to_the_frontend_defaults() {
The webview names the scene, and the scene names the file. That is the
whole of the caller's influence over this path, and these pin it.
------------------------------------------------------------------- */
-
-fn project_folder() -> tempfile::TempDir {
- let folder = tempfile::tempdir().unwrap();
- fs::write(
- folder.path().join(PROJECT_FILE_NAME),
- serde_json::to_vec(&created_fixture()).unwrap(),
- )
- .unwrap();
- folder
-}
-
-#[test]
-fn a_rendered_scene_lands_in_the_project_under_its_own_id() {
- let folder = project_folder();
- let (destination, relative) =
- generated_video_destination(&folder.path().to_string_lossy(), "job-initial-brief")
- .unwrap();
- assert_eq!(relative, "media/generated/job-initial-brief.mp4");
- assert!(destination.ends_with("media/generated/job-initial-brief.mp4"));
- // The folder is made, so the write that follows has somewhere to go.
- assert!(destination.parent().unwrap().is_dir());
- // And it really is inside the project, not merely named as though it were.
- assert!(destination.starts_with(folder.path().canonicalize().unwrap()));
-}
-
-#[test]
-fn latent_archives_are_unique_and_confined_to_the_project() {
- let folder = project_folder();
- let root = folder.path().to_string_lossy();
- let destination = generated_latent_destination(&root, "work-one").unwrap();
- assert!(destination.ends_with("latents/work-one.safetensors"));
- fs::write(&destination, b"archive").unwrap();
- assert!(generated_latent_destination(&root, "work-one").is_err());
- assert!(generated_latent_destination(&root, "../escape").is_err());
- let mut request: slopfab::GenerationRequest = serde_json::from_value(serde_json::json!({
- "jobId": "next", "prompt": "Continue", "frames": 119, "steps": 4, "seed": 1,
- "canvasWidth": 736, "canvasHeight": 416,
- "continuationRelativePath": "latents/work-one.safetensors",
- "saveLatentsPath": "C:/outside.safetensors", "continuationPath": "C:/outside.safetensors",
- })).unwrap();
- assert!(request.save_latents_path.is_none());
- assert!(request.continuation_path.is_none());
- assert!(prepare_continuation_path(&mut request, None).is_err());
- prepare_continuation_path(&mut request, Some(&root)).unwrap();
- assert_eq!(request.continuation_path, Some(destination));
- for invalid in ["../outside.safetensors", "C:/outside.safetensors", "latents/missing.safetensors"] {
- request.continuation_relative_path = Some(invalid.into());
- assert!(prepare_continuation_path(&mut request, Some(&root)).is_err());
- }
- let mut config = created_fixture();
- config.generation_jobs[0].latent_relative_path = Some("latents/work-one.safetensors".into());
- assert!(validate_and_normalize_config(config.clone()).is_ok());
- config.generation_jobs[0].latent_relative_path = Some("../outside.safetensors".into());
- assert!(validate_and_normalize_config(config).is_err());
-}
-
-#[test]
-fn purging_timeline_thumbnails_removes_only_the_named_scene() {
- let folder = project_folder();
- let first = folder.path().join("thumbnails/timeline/job-first");
- let second = folder.path().join("thumbnails/timeline/job-second");
- fs::create_dir_all(&first).unwrap();
- fs::create_dir_all(&second).unwrap();
- fs::write(first.join("00000000.jpg"), b"first").unwrap();
- fs::write(second.join("00000000.jpg"), b"second").unwrap();
-
- purge_timeline_thumbnails(
- folder.path().to_string_lossy().into_owned(),
- "job-first".into(),
- )
- .unwrap();
-
- assert!(!first.exists());
- assert!(second.join("00000000.jpg").is_file());
-}
-
-#[test]
-fn a_scene_id_that_is_not_a_scene_id_is_refused_rather_than_scrubbed() {
- let folder = project_folder();
- let root = folder.path().to_string_lossy().into_owned();
- for hostile in [
- "../../etc/passwd",
- "..",
- ".",
- "job/../../escape",
- r"job\..\escape",
- "job:stream",
- "job.mp4",
- "",
- " ",
- &"j".repeat(65),
- ] {
- assert!(
- generated_video_destination(&root, hostile).is_err(),
- "'{hostile}' must not name a file"
- );
- }
- // A dot is refused too — nothing Slopus generates has one, and
- // allowing it is how a second extension gets in.
- assert!(generated_file_stem("job-01_A").is_ok());
- assert!(generated_file_stem("job.01").is_err());
-}
-
-#[test]
-fn a_folder_that_holds_no_project_gets_no_writer() {
- // The same rule every other command that takes a folderPath follows:
- // confining a name against an unchecked folder confines nothing.
- let empty = tempfile::tempdir().unwrap();
- assert!(generated_video_destination(&empty.path().to_string_lossy(), "job-01").is_err());
- assert!(generated_video_destination("", "job-01").is_err());
-}
-
diff --git a/src-tauri/src/tests/group_0.rs b/src-tauri/src/tests/schema.rs
similarity index 54%
rename from src-tauri/src/tests/group_0.rs
rename to src-tauri/src/tests/schema.rs
index 5f6af18..d4f557c 100644
--- a/src-tauri/src/tests/group_0.rs
+++ b/src-tauri/src/tests/schema.rs
@@ -1,4 +1,5 @@
use super::*;
+
#[test]
fn rust_never_emits_a_null_the_frontend_schema_refuses() {
// The cross-layer direction that went unchecked for nine rounds: Rust
@@ -31,23 +32,23 @@ fn rust_never_emits_a_null_the_frontend_schema_refuses() {
assert!(!json.contains("\"clipId\""), "clipId leaked into {json}");
}
-// Writes the REAL serialised output of `validate_and_normalize_config`
-// into `fixtures/rust-serialized-*.json`, which the frontend test suite
+// Checks the REAL serialised output of `validate_and_normalize_config`
+// against `fixtures/rust-serialized-*.json`, which the frontend test suite
// parses with its own zod schema. This is how the two-validator contract
// stops being hand-maintained: a field added to Rust as an `Option`
// without `skip_serializing_if` (or added to zod as a bare `.optional()`)
// changes these bytes and fails on the frontend side, with nobody having
// to remember to extend `NON_NULLABLE_OPTIONAL_KEYS`.
//
-// THESE FILES ARE GENERATED BY `cargo test` AND COMMITTED ON PURPOSE. If
-// `git status` is dirty after a test run, the wire format changed: re-run
-// the frontend schema tests against the new bytes before committing them.
+// Normal tests are read-only. Set SLOPUS_UPDATE_FIXTURES=1 to regenerate these
+// committed contracts deliberately, then run the frontend schema tests.
//
// The output is deterministic — every input is a checked-in fixture or is
// derived from one. The imported-reference case runs the real product code
// path inside a `tempfile::tempdir()`, but the temp path cannot leak into
// the JSON because references store project-relative paths only
// (`references/<file>`); the assertion below proves it per run.
+
#[test]
fn serialized_wire_format_matches_frontend_fixtures() {
fn serialize(config: &ProjectConfig) -> String {
@@ -62,11 +63,16 @@ fn serialized_wire_format_matches_frontend_fixtures() {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../fixtures")
.join(name);
- if std::env::var_os("SLOPUS_UPDATE_FIXTURES").is_some() {
+ if std::env::var("SLOPUS_UPDATE_FIXTURES").as_deref() == Ok("1") {
fs::write(&path, json).unwrap();
} else {
let expected = fs::read_to_string(&path).unwrap().replace("\r\n", "\n");
- assert_eq!(json, expected, "{} changed; run with SLOPUS_UPDATE_FIXTURES=1 to update intentionally", path.display());
+ assert_eq!(
+ json,
+ expected,
+ "{} changed; run with SLOPUS_UPDATE_FIXTURES=1 to update intentionally",
+ path.display()
+ );
}
}
@@ -384,170 +390,338 @@ fn every_date_field_is_checked_the_way_the_frontend_checks_it() {
}
#[test]
-fn legacy_project_defaults_to_video_and_persists_its_type() {
- let root = tempfile::tempdir().unwrap();
- let legacy = include_str!("../../../fixtures/project-v1-created.json");
- assert!(serde_json::from_str::<serde_json::Value>(legacy)
- .unwrap().get("generationType").is_none());
- fs::write(root.path().join(PROJECT_FILE_NAME), legacy).unwrap();
- let opened = read_project(root.path()).unwrap();
- assert_eq!(opened.config.generation_type, GenerationType::Video);
- write_project(root.path(), &opened.config).unwrap();
- let saved: serde_json::Value = serde_json::from_slice(
- &fs::read(root.path().join(PROJECT_FILE_NAME)).unwrap(),
- ).unwrap();
- assert_eq!(saved["generationType"], "video");
-}
+fn stored_paths_are_normalized_and_escaping_paths_are_rejected() {
+ let mut normalized = fixture();
+ normalized.assets[0].relative_path = Some(".\\media\\imported//macro.mp4".into());
+ assert_eq!(
+ validate_and_normalize_config(normalized).unwrap().assets[0]
+ .relative_path
+ .as_deref(),
+ Some("media/imported/macro.mp4")
+ );
-#[test]
-fn generation_types_survive_create_save_and_reopen() {
- for generation_type in ["video", "image", "3d", "music", "speech"] {
- let root = tempfile::tempdir().unwrap();
- let mut value = serde_json::to_value(created_fixture()).unwrap();
- value["generationType"] = serde_json::json!(generation_type);
- let config: ProjectConfig = serde_json::from_value(value).unwrap();
- let created = create_project_in(root.path(), &config).unwrap();
- let folder = Path::new(&created.folder_path);
- let opened = read_project(folder).unwrap();
- write_project(folder, &opened.config).unwrap();
- let reopened = read_project(folder).unwrap();
- assert_eq!(reopened.config.generation_type, config.generation_type);
- assert_eq!(serde_json::to_value(reopened.config).unwrap()["generationType"], generation_type);
+ for path in [
+ "/etc/passwd",
+ "\\Windows\\system.ini",
+ "C:\\Users\\creator\\clip.mp4",
+ "https://example.com/clip.mp4",
+ "media/../../outside.mp4",
+ "references/../outside.png",
+ ] {
+ let mut escaping = fixture();
+ escaping.assets[0].relative_path = Some(path.into());
+ assert!(
+ validate_and_normalize_config(escaping).is_err(),
+ "accepted escaping path {path}"
+ );
}
-}
-#[test]
-fn invalid_explicit_generation_types_are_rejected() {
- for generation_type in [
- serde_json::Value::Null, serde_json::json!(""), serde_json::json!("unknown"),
- serde_json::json!("Video"), serde_json::json!(3),
- ] {
- let mut value = serde_json::to_value(created_fixture()).unwrap();
- value["generationType"] = generation_type;
- assert!(serde_json::from_value::<ProjectConfig>(value).is_err());
+ let mut thumbnail = fixture();
+ thumbnail.thumbnail = Some("../thumbnail.webp".into());
+ let mut reference = fixture();
+ reference.references[1].relative_path = Some("../product.png".into());
+ let mut job = fixture();
+ job.generation_jobs[0].output_relative_path = Some("C:\\output.mp4".into());
+ for config in [thumbnail, reference, job] {
+ assert!(validate_and_normalize_config(config).is_err());
}
}
#[test]
-fn complete_project_create_open_save_reopen_is_lossless() {
- let root = tempfile::tempdir().unwrap();
- let expected =
- without_derived_project_state(validate_and_normalize_config(fixture()).unwrap());
- let created = create_project_in(root.path(), &expected).unwrap();
- assert_eq!(created.config, expected);
-
- let project_folder = PathBuf::from(&created.folder_path);
- let opened = read_project(&project_folder).unwrap();
- assert_eq!(opened.config, expected);
-
- let mut saved = opened.config.clone();
- saved.updated_at = "2026-02-03T04:05:06.000Z".into();
- write_project(&project_folder, &saved).unwrap();
- assert_eq!(read_project(&project_folder).unwrap().config, saved);
-
- let mut directories = Vec::new();
- fn collect_directories(root: &Path, current: &Path, output: &mut Vec<String>) {
- for entry in fs::read_dir(current).unwrap() {
- let path = entry.unwrap().path();
- if path.is_dir() {
- output.push(
- path.strip_prefix(root)
- .unwrap()
- .to_string_lossy()
- .replace('\\', "/"),
- );
- collect_directories(root, &path, output);
- }
- }
- }
- collect_directories(&project_folder, &project_folder, &mut directories);
- directories.sort();
+fn every_stored_location_is_one_place_and_only_one() {
+ let external = external_fixture();
+ let normalized = validate_and_normalize_config(external.clone()).unwrap();
assert_eq!(
- directories,
- [
- "cache",
- "exports",
- "media",
- "media/generated",
- "media/imported",
- "references",
- "thumbnails",
- ]
+ normalized.assets[0].source_path.as_deref(),
+ Some(r"D:\tmp\news\News broadcast\rush-01.mp4"),
+ "an external path is stored verbatim, not rewritten as a relative one"
);
- let files: Vec<_> = fs::read_dir(&project_folder)
- .unwrap()
- .filter_map(Result::ok)
- .filter(|entry| entry.path().is_file())
- .map(|entry| entry.file_name().to_string_lossy().into_owned())
- .collect();
- assert_eq!(files, [PROJECT_FILE_NAME]);
+ assert!(normalized.assets[0].relative_path.is_none());
+
+ // Both at once is not a location, and neither is neither.
+ let mut both = external_fixture();
+ both.assets[0].relative_path = Some("media/rush-01.mp4".into());
+ assert!(validate_and_normalize_config(both)
+ .unwrap_err()
+ .contains("cannot have both"));
+ let mut neither = external_fixture();
+ neither.assets[0].source_path = None;
+ assert!(validate_and_normalize_config(neither)
+ .unwrap_err()
+ .contains("must have either"));
+
+ // A Generator scene can be arranged before its render exists. It still
+ // has an asset id for timeline integrity, and gains its path when the
+ // generated file is saved.
+ let mut waiting_scene = external_fixture();
+ waiting_scene.assets[0].kind = "generated".into();
+ waiting_scene.assets[0].source_path = None;
+ assert!(validate_and_normalize_config(waiting_scene).is_ok());
+
+ // A "source path" that is not absolute resolves against nothing.
+ for path in [
+ "Footage\\clip.mp4",
+ "media/clip.mp4",
+ "..\\..\\clip.mp4",
+ "D:\\..\\clip.mp4",
+ "",
+ ] {
+ let mut relative = external_fixture();
+ relative.assets[0].source_path = Some(path.into());
+ assert!(
+ validate_and_normalize_config(relative).is_err(),
+ "accepted '{path}' as an absolute source path"
+ );
+ }
+ // Every absolute form is accepted on every platform: a project file
+ // written on Windows is still read on Linux and back.
+ for path in [
+ "D:\\Footage\\clip.mp4",
+ "D:/Footage/clip.mp4",
+ "/home/nn/clip.mp4",
+ "\\\\nas\\share\\clip.mp4",
+ ] {
+ let mut absolute = external_fixture();
+ absolute.assets[0].source_path = Some(path.into());
+ assert!(
+ validate_and_normalize_config(absolute).is_ok(),
+ "rejected the absolute path '{path}'"
+ );
+ }
+
+ // References follow the same rule, and a file-backed one still needs
+ // its file.
+ let mut both_on_reference = external_fixture();
+ both_on_reference.references[1].relative_path = Some("references/cut.mov".into());
+ assert!(validate_and_normalize_config(both_on_reference).is_err());
+ let mut nowhere = external_fixture();
+ nowhere.references[1].source_path = None;
+ assert!(validate_and_normalize_config(nowhere).is_err());
}
#[test]
-fn chroma_key_survives_save_and_reopen_and_validates_settings() {
- let mut config = fixture();
- config.timeline.tracks[0].clips[0].chroma_key = Some(ClipChromaKey {
- color: "#12ABef".into(),
- tolerance: 27.0,
- });
- let config = without_derived_project_state(validate_and_normalize_config(config).unwrap());
- let root = tempfile::tempdir().unwrap();
- let created = create_project_in(root.path(), &config).unwrap();
- let folder = PathBuf::from(&created.folder_path);
- write_project(&folder, &config).unwrap();
- assert_eq!(read_project(&folder).unwrap().config, config);
- let json = serde_json::to_value(&config).unwrap();
- assert_eq!(json["timeline"]["tracks"][0]["clips"][0]["chromaKey"]["color"], "#12ABef");
- for (color, tolerance) in [("green", 20.0), ("#12345g", 20.0), ("#00ff00", -1.0), ("#00ff00", 101.0), ("#00ff00", f64::NAN)] {
- let mut invalid = config.clone();
- invalid.timeline.tracks[0].clips[0].chroma_key = Some(ClipChromaKey { color: color.into(), tolerance });
- assert!(validate_and_normalize_config(invalid).unwrap_err().contains("chroma key"));
- }
- let mut removed = config.clone();
- removed.timeline.tracks[0].clips[0].chroma_key = None;
- write_project(&folder, &removed).unwrap();
- assert!(read_project(&folder).unwrap().config.timeline.tracks[0].clips[0].chroma_key.is_none());
+fn sanitizes_folder_names() {
+ assert_eq!(safe_folder_name(" Launch: Film? "), "Launch- Film-");
+ assert_eq!(safe_folder_name("..."), "Untitled video");
}
#[test]
-fn deleting_a_project_removes_its_folder_and_every_file_inside_it() {
- let parent = tempfile::tempdir().unwrap();
- let project = project_folder_at(&parent.path().join("Disposable project"));
- fs::create_dir_all(project.join("media/generated")).unwrap();
- fs::write(project.join("media/generated/scene.mp4"), b"video").unwrap();
- let id = read_project(&project).unwrap().config.id;
-
- delete_project_folder(&project.to_string_lossy(), &id).unwrap();
+fn validator_rejects_what_the_frontend_schema_rejects() {
+ // Configs arriving from the agent subprocess are written to disk before
+ // the frontend ever parses them, so anything zod refuses has to be
+ // refused here too or a project lands on disk that cannot be reopened.
+ fn rejects(case: &str, break_config: impl FnOnce(&mut ProjectConfig)) {
+ let mut config = fixture();
+ break_config(&mut config);
+ assert!(
+ validate_and_normalize_config(config).is_err(),
+ "accepted a config the frontend schema rejects: {case}"
+ );
+ }
- assert!(!project.exists());
- assert!(parent.path().is_dir());
+ rejects("name longer than 120 characters", |config| {
+ config.name = "n".repeat(200);
+ });
+ rejects("unsupported settings aspect ratio", |config| {
+ config.settings.aspect_ratio = "21:9".into();
+ });
+ rejects("unsupported settings resolution", |config| {
+ config.settings.resolution = "8k".into();
+ });
+ rejects("unsupported frame rate", |config| {
+ config.settings.frame_rate = 48;
+ });
+ rejects("named background color", |config| {
+ config.settings.background_color = "black".into();
+ });
+ rejects("shorthand background color", |config| {
+ config.settings.background_color = "#fff".into();
+ });
+ rejects("non-hex digit in background color", |config| {
+ config.settings.background_color = "#10131g".into();
+ });
+ rejects("unsupported brief status", |config| {
+ config.brief.status = "done".into();
+ });
+ rejects("target duration above 600 seconds", |config| {
+ config.brief.target_duration_seconds = 900;
+ });
+ rejects("unsupported brief aspect ratio", |config| {
+ config.brief.aspect_ratio = "21:9".into();
+ });
+ rejects("unsupported brief resolution", |config| {
+ config.brief.resolution = "8k".into();
+ });
+ rejects("unsupported asset kind", |config| {
+ config.assets[0].kind = "clip".into();
+ });
+ rejects("empty asset mime type", |config| {
+ config.assets[0].mime_type = String::new();
+ });
+ rejects("zero asset width", |config| {
+ config.assets[0].width = Some(0);
+ });
+ rejects("zero asset height", |config| {
+ config.assets[0].height = Some(0);
+ });
+ rejects("unsupported track kind", |config| {
+ config.timeline.tracks[0].kind = "text".into();
+ });
+ rejects("empty track name", |config| {
+ config.timeline.tracks[0].name = String::new();
+ });
+ rejects("empty clip label", |config| {
+ config.timeline.tracks[0].clips[0].label = String::new();
+ });
+ rejects("zero clip duration", |config| {
+ config.timeline.tracks[0].clips[0].duration_ms = 0;
+ });
+ rejects("unsupported clip status", |config| {
+ config.timeline.tracks[0].clips[0].status = "final".into();
+ });
+ rejects("empty reference content", |config| {
+ config.references[0].content = Some(String::new());
+ });
+ rejects("unsupported reference intended use", |config| {
+ config.references[0].intended_use = vec!["mood".into()];
+ });
+ rejects("empty generation job provider id", |config| {
+ config.generation_jobs[0].provider_id = Some(String::new());
+ });
+ rejects("empty generation job error", |config| {
+ config.generation_jobs[0].error = Some(String::new());
+ });
+ rejects("shot tag group id the frontend regex refuses", |config| {
+ config.generation_jobs[0].shot_tags = Some(BTreeMap::from([(
+ "Camera Movement".into(),
+ vec!["push-in".into()],
+ )]));
+ });
+ rejects("shot tag id the frontend regex refuses", |config| {
+ config.generation_jobs[0].shot_tags = Some(BTreeMap::from([(
+ "cameraMovement".into(),
+ vec!["Push In".into()],
+ )]));
+ });
+ rejects("empty shot tag id", |config| {
+ config.generation_jobs[0].shot_tags = Some(BTreeMap::from([(
+ "cameraMovement".into(),
+ vec![String::new()],
+ )]));
+ });
}
#[test]
-fn deletion_refuses_a_different_project_identity_and_keeps_the_folder() {
- let parent = tempfile::tempdir().unwrap();
- let project = project_folder_at(&parent.path().join("Keep this project"));
-
- let error =
- delete_project_folder(&project.to_string_lossy(), "some-other-project").unwrap_err();
+fn validator_accepts_every_boundary_the_frontend_schema_allows() {
+ for aspect_ratio in ["16:9", "9:16", "1:1", "4:5"] {
+ let mut config = fixture();
+ config.settings.aspect_ratio = aspect_ratio.into();
+ config.brief.aspect_ratio = aspect_ratio.into();
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected valid aspect ratio {aspect_ratio}"
+ );
+ }
+ for resolution in [
+ "416p", "544p", "640p", "768p", "1088p", "1344p", "720p", "1080p", "4k",
+ ] {
+ let mut config = fixture();
+ config.settings.resolution = resolution.into();
+ config.brief.resolution = resolution.into();
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected valid resolution {resolution}"
+ );
+ }
+ for frame_rate in [24u32, 25, 30, 60] {
+ let mut config = fixture();
+ config.settings.frame_rate = frame_rate;
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected valid frame rate {frame_rate}"
+ );
+ }
+ for background_color in ["#000000", "#FFFFFF", "#abcdef", "#ABCDEF", "#10131a"] {
+ let mut config = fixture();
+ config.settings.background_color = background_color.into();
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected valid background color {background_color}"
+ );
+ }
+ for seconds in [0u32, 1, 5, 60, 600] {
+ let mut config = fixture();
+ config.brief.target_duration_seconds = seconds;
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected valid target duration {seconds}"
+ );
+ }
+ for status in ["draft", "queued", "generating", "ready", "failed"] {
+ let mut config = fixture();
+ config.brief.status = status.into();
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected valid brief status {status}"
+ );
+ }
+ for kind in ["video", "audio", "image", "caption", "generated"] {
+ let mut config = fixture();
+ config.assets[0].kind = kind.into();
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected valid asset kind {kind}"
+ );
+ }
+ for kind in ["video", "audio", "caption"] {
+ let mut config = fixture();
+ config.timeline.tracks[0].kind = kind.into();
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected valid track kind {kind}"
+ );
+ }
+ for status in ["draft", "generated", "approved"] {
+ let mut config = fixture();
+ config.timeline.tracks[0].clips[0].status = status.into();
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected valid clip status {status}"
+ );
+ }
+ for intent in [
+ "character",
+ "animal",
+ "product",
+ "location",
+ "style",
+ "audio",
+ ] {
+ let mut config = fixture();
+ config.references[0].intended_use = vec![intent.into()];
+ assert!(
+ validate_and_normalize_config(config).is_ok(),
+ "rejected valid reference intended use {intent}"
+ );
+ }
- assert!(error.contains("not the project selected for deletion"));
- assert!(project.is_dir());
- assert!(project.join(PROJECT_FILE_NAME).is_file());
-}
+ let mut longest_name = fixture();
+ longest_name.name = "n".repeat(120);
+ assert!(
+ validate_and_normalize_config(longest_name).is_ok(),
+ "rejected a 120 character project name"
+ );
-#[test]
-fn old_v1_documents_receive_empty_persistence_containers() {
- let mut value = serde_json::to_value(fixture()).unwrap();
- let object = value.as_object_mut().unwrap();
- object.remove("references");
- object.remove("generationJobs");
- object.remove("agentConversation");
- object.remove("providerSettings");
- let config: ProjectConfig = serde_json::from_value(value).unwrap();
- assert!(config.references.is_empty());
- assert!(config.generation_jobs.is_empty());
- assert!(config.agent_conversation.messages.is_empty());
- assert!(config.provider_settings.is_empty());
+ let mut sparse = fixture();
+ sparse.assets[0].width = None;
+ sparse.assets[0].height = None;
+ sparse.assets[0].duration_ms = None;
+ sparse.references[0].content = None;
+ sparse.references[0].intended_use = Vec::new();
+ sparse.generation_jobs[0].provider_id = None;
+ sparse.generation_jobs[0].error = None;
+ assert!(
+ validate_and_normalize_config(sparse).is_ok(),
+ "rejected a config whose optional fields are absent"
+ );
}
-
diff --git a/src-tauri/src/window.rs b/src-tauri/src/window.rs
index 0ddfe6d..75adf5a 100644
--- a/src-tauri/src/window.rs
+++ b/src-tauri/src/window.rs
@@ -59,7 +59,11 @@ pub(crate) fn set_generation_active(state: tauri::State<'_, ExitGuard>, active:
}
#[tauri::command]
-pub(crate) fn answer_app_close(window: tauri::Window, state: tauri::State<'_, ExitGuard>, confirmed: bool) {
+pub(crate) fn answer_app_close(
+ window: tauri::Window,
+ state: tauri::State<'_, ExitGuard>,
+ confirmed: bool,
+) {
state.answered(confirmed);
if confirmed {
let _ = window.destroy();
@@ -86,7 +90,11 @@ pub(crate) const GROUND_DARK: tauri::window::Color = tauri::window::Color(0x08,
pub(crate) const GROUND_LIGHT: tauri::window::Color = tauri::window::Color(0xee, 0xf1, 0xf6, 0xff);
pub(crate) fn apply_theme(window: &tauri::WebviewWindow) {
- let ground = if matches!(window.theme(), Ok(tauri::Theme::Light)) { GROUND_LIGHT } else { GROUND_DARK };
+ let ground = if matches!(window.theme(), Ok(tauri::Theme::Light)) {
+ GROUND_LIGHT
+ } else {
+ GROUND_DARK
+ };
let _ = window.set_background_color(Some(ground));
}
#[cfg(test)]
diff --git a/src/App.tsx b/src/App.tsx
index f893c50..6e34772 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -93,7 +93,7 @@ function App() {
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 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. */
+ and answered. See the fenced block in src-tauri/src/window.rs. */
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);
diff --git a/src/lib/persistence.ts b/src/lib/persistence.ts
index 3d8a4f0..9e3b56f 100644
--- a/src/lib/persistence.ts
+++ b/src/lib/persistence.ts
@@ -204,7 +204,7 @@ export async function readProjectFileUrl(folderPath: string, relativePath: strin
* project folder, or at the absolute path the project recorded for it. The
* external read goes through its own command, which only serves paths the
* project itself names — see `read_external_media_file` in
- * src-tauri/src/lib.rs. Same revoke rule as `readProjectFileUrl`. */
+ * src-tauri/src/media/access.rs. Same revoke rule as `readProjectFileUrl`. */
export async function readMediaFileUrl(folderPath: string, item: StoredLocation, mimeType: string): Promise<string | null> {
if (!isTauri() || (!item.sourcePath && !item.relativePath)) return null;
return URL.createObjectURL(new Blob([await readMediaFileBytes(folderPath, item)], { type: mimeType }));
diff --git a/src/lib/project.test.ts b/src/lib/project.test.ts
index a6982cd..808ff09 100644
--- a/src/lib/project.test.ts
+++ b/src/lib/project.test.ts
@@ -724,7 +724,7 @@ describe("project schema", () => {
describe("the frame sizes a project can be", () => {
it("accepts exactly the ladder plus the names already on disk, and nothing else", () => {
- /* `is_supported_resolution` in src-tauri/src/lib.rs spells the same nine
+ /* `is_supported_resolution` in src-tauri/src/project/validation/values.rs spells the same nine
names. They have to agree in BOTH directions: Rust writes the settings
file before the frontend ever parses it, so a name Rust accepts and zod
refuses is saved and then fails to open (see CLAUDE.md). */
diff --git a/src/lib/project.ts b/src/lib/project.ts
index 058e2a8..ccc760e 100644
--- a/src/lib/project.ts
+++ b/src/lib/project.ts
@@ -3,7 +3,7 @@ import { normalizeShotTagSelection, shotTagClauses, SHOT_TAG_ID_PATTERN, type Sh
export const PROJECT_FILE_NAME = "slopus.json";
/** What the settings file used to be called, newest first. All are still
- * opened (`project_file_in` in src-tauri/src/lib.rs); only the current name is
+ * opened (`project_file_in` in src-tauri/src/project/); only the current name is
* 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;
@@ -77,7 +77,7 @@ export const projectRelativePathSchema = z.string().transform((value, context) =
* all three absolute forms are accepted on every platform, because a project
* file written on Windows is still parsed by tests (and by a reader) on Linux.
*
- * Mirrors `normalize_external_path` in src-tauri/src/lib.rs. The two must
+ * Mirrors `normalize_external_path` in src-tauri/src/project/. The two must
* agree in BOTH directions — Rust writes this file before zod ever sees it. */
export function normalizeExternalPath(value: string): string {
if (!value || value.includes("\0")) throw new Error("External media paths cannot be empty or contain null bytes.");
@@ -323,7 +323,7 @@ export const projectReferenceSchema = z.object({
term for instead of losing the user's choices on the next save.
Both layers validate SHAPE, not vocabulary, and they validate the same shape:
- `is_shot_tag_id` in src-tauri/src/lib.rs is this regex. Were only one side to
+ `is_shot_tag_id` in src-tauri/src/project/ is this regex. Were only one side to
know the taxonomy, the other would happily persist a tag it then refused to
read back. */
export const shotTagIdSchema = z.string().regex(SHOT_TAG_ID_PATTERN, "Shot tag ids start with a lowercase letter and carry only letters, digits, and hyphens.");
@@ -487,7 +487,7 @@ export const generationJobSchema = z.object({
its shots; everything written before scenes existed keeps them in `prompt`
and `creativeBrief`, which is why those two may not both be blank when
there are no shots to hold them. `validate_and_normalize_config` in
- src-tauri/src/lib.rs applies exactly this rule — the two layers have to
+ src-tauri/src/project/ applies exactly this rule — the two layers have to
refuse the same files or Rust writes one the UI then cannot open. */
if (job.shots && job.shots.length > 0) {
const ids = new Set<string>();
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index b90b028..e735896 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -9,7 +9,7 @@
* disk layout into a file the user is invited to move, copy, and share.
*
* The option names below are the contract with `Configuration::from_settings`
- * in src-tauri/src/slopfab.rs. Renaming one here without renaming it there
+ * in src-tauri/src/slopfab/config.rs. Renaming one here without renaming it there
* silently drops that path.
*/
import { DEFAULT_GENERATION_STEPS, MAX_GENERATION_STEPS, type ProjectConfig, type ProviderSetting } from "./project";
diff --git a/src/lib/shot-tags.test.ts b/src/lib/shot-tags.test.ts
index 4b30db9..1ca31ea 100644
--- a/src/lib/shot-tags.test.ts
+++ b/src/lib/shot-tags.test.ts
@@ -49,7 +49,7 @@ const macroPush: ShotTagSelection = {
describe("shot tag taxonomy", () => {
it("keeps every id in the shape both validators enforce, and keeps them unique", () => {
- // The ids are persisted, and `is_shot_tag_id` in src-tauri/src/lib.rs
+ // The ids are persisted, and `is_shot_tag_id` in src-tauri/src/project/validation/values.rs
// decides whether a file carrying them can be written back. A taxonomy
// entry that fails this regex is a shot the desktop app would refuse to
// save AFTER the user tagged it.
@@ -92,7 +92,7 @@ describe("shot tag taxonomy", () => {
it("normalizes exactly the way the Rust validator does", () => {
// Three steps, same order, same result — see normalize_shot_tags in
- // src-tauri/src/lib.rs. Drift here means the two layers write different
+ // src-tauri/src/project/validation/values.rs. Drift here means the two layers write different
// bytes for the same selection.
expect(normalizeShotTagSelection({ mood: [] })).toBeNull();
expect(normalizeShotTagSelection({ lighting: ["soft-light", "soft-light", "backlight"] }))
diff --git a/src/lib/shot-tags.ts b/src/lib/shot-tags.ts
index d1366b3..0d08e85 100644
--- a/src/lib/shot-tags.ts
+++ b/src/lib/shot-tags.ts
@@ -17,7 +17,7 @@ import h3ShotGroups from "../../shared/models/minimax-h3-shot-tags.json";
The ids are persisted in `pols.json`, so they are stable forever: rename a
`label` freely, never an `id`. Both validators constrain ids to
- `SHOT_TAG_ID_PATTERN` (src/lib/project.ts and src-tauri/src/lib.rs), so a new
+ `SHOT_TAG_ID_PATTERN` (src/lib/project.ts and src-tauri/src/project/validation/values.rs), so a new
id has to keep that shape.
--------------------------------------------------------------------------- */
@@ -70,7 +70,7 @@ export interface ShotTagGroup {
export type ShotTagSelection = Record<string, string[]>;
/** Ids both validators accept. Kept in lockstep with `is_shot_tag_id` in
- * src-tauri/src/lib.rs — a shape neither layer has to guess about. */
+ * src-tauri/src/project/validation/values.rs — a shape neither layer has to guess about. */
export const SHOT_TAG_ID_PATTERN = /^[a-z][a-zA-Z0-9-]*$/;
/** The persisted H3 vocabulary is shared with the Rust agent policy. */
@@ -116,7 +116,7 @@ export function countShotTags(selection: ShotTagSelection | null | undefined): n
* It deliberately does NOT drop ids this build doesn't recognise. A project
* written by a newer build would otherwise lose the user's choices the first
* time an older build re-saved it. `validate_and_normalize_config` in
- * src-tauri/src/lib.rs performs exactly these three steps, in this order, so
+ * src-tauri/src/project/validation/values.rs performs exactly these three steps, in this order, so
* the file is byte-identical whichever layer wrote it last. */
export function normalizeShotTagSelection(selection: ShotTagSelection | null | undefined): ShotTagSelection | null {
if (!selection) return null;
diff --git a/src/lib/theme.test.ts b/src/lib/theme.test.ts
index 2c833ac..f3667b6 100644
--- a/src/lib/theme.test.ts
+++ b/src/lib/theme.test.ts
@@ -193,7 +193,7 @@ describe("tokens.css", () => {
It stays the DARK ground on purpose. It is what a window is created with
before any of our code runs, and one static value cannot follow a
- three-state preference; src-tauri/src/lib.rs repaints it from the OS
+ three-state preference; src-tauri/src/window.rs repaints it from the OS
theme as soon as the app is up, and theme-boot.js corrects it again on
the webview's first frame. See the comment above GROUND_DARK for the one
case that still gets a wrong frame and why nothing here can fix it. */