Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Import media, drag it onto the timeline, and stop lying about providers

Bittid674dbc7e906
diff --git a/fixtures/project-v1-created.json b/fixtures/project-v1-created.json
index b12a193..a45b9ed 100644
--- a/fixtures/project-v1-created.json
+++ b/fixtures/project-v1-created.json
@@ -21,6 +21,14 @@
"assets": [],
"timeline": {
"tracks": [
+ {
+ "id": "track-overlay",
+ "kind": "video",
+ "name": "Overlays",
+ "locked": false,
+ "muted": false,
+ "clips": []
+ },
{
"id": "track-story",
"kind": "video",
diff --git a/fixtures/rust-serialized-created.json b/fixtures/rust-serialized-created.json
index 32390e0..54847ce 100644
--- a/fixtures/rust-serialized-created.json
+++ b/fixtures/rust-serialized-created.json
@@ -21,6 +21,14 @@
"assets": [],
"timeline": {
"tracks": [
+ {
+ "id": "track-overlay",
+ "kind": "video",
+ "name": "Overlays",
+ "locked": false,
+ "muted": false,
+ "clips": []
+ },
{
"id": "track-story",
"kind": "video",
diff --git a/fixtures/rust-serialized-initial-reference.json b/fixtures/rust-serialized-initial-reference.json
index c26c9f3..c07c730 100644
--- a/fixtures/rust-serialized-initial-reference.json
+++ b/fixtures/rust-serialized-initial-reference.json
@@ -21,6 +21,14 @@
"assets": [],
"timeline": {
"tracks": [
+ {
+ "id": "track-overlay",
+ "kind": "video",
+ "name": "Overlays",
+ "locked": false,
+ "muted": false,
+ "clips": []
+ },
{
"id": "track-story",
"kind": "video",
diff --git a/package.cmd b/package.cmd
index 9f2bc3a..658e9d0 100644
--- a/package.cmd
+++ b/package.cmd
@@ -126,12 +126,13 @@ copy /Y "%RELEASE_EXE%" "%OUTPUT_DIR%\PolStudio.exe" >nul || goto :fail
set "VIDFAB_BUNDLED=no"
if exist "%VIDFAB_DIR%\vidfab_c.dll" (
- mkdir "%OUTPUT_DIR%\vidfab-runtime" || goto :fail
- rem vidfab_c.dll is loaded with LOAD_WITH_ALTERED_SEARCH_PATH, so its
- rem dependencies must sit in the same folder as it.
- copy /Y "%VIDFAB_DIR%\vidfab_c.dll" "%OUTPUT_DIR%\vidfab-runtime\" >nul || goto :fail
- if exist "%VIDFAB_DIR%\vidfab_core.dll" copy /Y "%VIDFAB_DIR%\vidfab_core.dll" "%OUTPUT_DIR%\vidfab-runtime\" >nul
- if exist "%VIDFAB_DIR%\vidfab_cuda.dll" copy /Y "%VIDFAB_DIR%\vidfab_cuda.dll" "%OUTPUT_DIR%\vidfab-runtime\" >nul
+ rem Beside PolStudio.exe, not in a subfolder. That is where the app looks,
+ rem so there is nothing left for anyone to configure - and vidfab_c.dll is
+ rem loaded with LOAD_WITH_ALTERED_SEARCH_PATH, so its dependencies have to
+ rem sit in the same folder as it anyway.
+ copy /Y "%VIDFAB_DIR%\vidfab_c.dll" "%OUTPUT_DIR%\" >nul || goto :fail
+ if exist "%VIDFAB_DIR%\vidfab_core.dll" copy /Y "%VIDFAB_DIR%\vidfab_core.dll" "%OUTPUT_DIR%\" >nul
+ if exist "%VIDFAB_DIR%\vidfab_cuda.dll" copy /Y "%VIDFAB_DIR%\vidfab_cuda.dll" "%OUTPUT_DIR%\" >nul
set "VIDFAB_BUNDLED=yes"
echo Runtime: vidfab DLLs included.
) else (
@@ -176,10 +177,9 @@ exit /b 0
>>"%~1" echo.
>>"%~1" echo GENERATION RUNTIME
if /I "%VIDFAB_BUNDLED%"=="yes" (
- >>"%~1" echo The vidfab DLLs are in vidfab-runtime\ next to this file. The app does
- >>"%~1" echo NOT find them there on its own yet: point it at
- >>"%~1" echo vidfab-runtime\vidfab_c.dll in the provider settings, or it will
- >>"%~1" echo report the generator as unavailable.
+ >>"%~1" echo The vidfab DLLs sit beside PolStudio.exe. The app loads them from
+ >>"%~1" echo there on its own - there is nothing to configure. Keep them next to
+ >>"%~1" echo the executable if you move this folder.
) else (
>>"%~1" echo Not included in this build. The app runs and saves projects, and
>>"%~1" echo reports the generator as unavailable.
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 0bc54b7..94a3678 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -220,6 +220,18 @@ struct ImportedReferenceImage {
mime_type: String,
}
+/// One file copied into the project's `media/` folder. Deliberately carries no
+/// duration or dimensions: PolStudio has no decoder yet, and a made-up number
+/// here would be indistinguishable from a measured one everywhere downstream.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ImportedMediaFile {
+ kind: &'static str,
+ name: String,
+ relative_path: String,
+ mime_type: String,
+}
+
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct PendingReferenceImage {
@@ -711,7 +723,7 @@ fn read_project(folder: &Path) -> Result<ProjectRecord, String> {
.map_err(|error| format!("Project config is not valid: {error}"))?;
let config = validate_and_normalize_config(config)?;
Ok(ProjectRecord {
- folder_path: canonical_folder.to_string_lossy().into_owned(),
+ folder_path: display_path(&canonical_folder),
config,
})
}
@@ -809,6 +821,19 @@ fn atomic_replace(temporary: &Path, destination: &Path) -> io::Result<()> {
}
}
+/// `Path::canonicalize` returns a Windows *verbatim* path — `\?\D:\tmp\news`.
+/// That prefix is an OS-level escape hatch, not something to show anybody, and
+/// it was being rendered verbatim under every project in the library. Strip it
+/// for the path that leaves this process. Every command re-canonicalizes what
+/// it is given, so the stripped form is still a valid round trip.
+fn display_path(path: &Path) -> String {
+ let text = path.to_string_lossy().into_owned();
+ if let Some(rest) = text.strip_prefix(r"\?\UNC\") {
+ return format!(r"\{rest}");
+ }
+ text.strip_prefix(r"\?\").unwrap_or(&text).to_string()
+}
+
fn safe_folder_name(name: &str) -> String {
let mut value: String = name
.chars()
@@ -950,6 +975,122 @@ fn choose_reference_image(
copy_reference_image(&source, &project_folder).map(Some)
}
+/// Extensions PolStudio will copy into a project, and what each one is.
+/// Anything not listed is refused rather than imported as an unknown blob.
+fn media_kind_and_mime(extension: &str) -> Option<(&'static str, &'static str)> {
+ Some(match extension {
+ "mp4" | "m4v" => ("video", "video/mp4"),
+ "mov" => ("video", "video/quicktime"),
+ "webm" => ("video", "video/webm"),
+ "mkv" => ("video", "video/x-matroska"),
+ "mp3" => ("audio", "audio/mpeg"),
+ "m4a" | "aac" => ("audio", "audio/mp4"),
+ "wav" => ("audio", "audio/wav"),
+ "flac" => ("audio", "audio/flac"),
+ "ogg" | "oga" => ("audio", "audio/ogg"),
+ "png" => ("image", "image/png"),
+ "jpg" | "jpeg" => ("image", "image/jpeg"),
+ "webp" => ("image", "image/webp"),
+ "gif" => ("image", "image/gif"),
+ _ => return None,
+ })
+}
+
+const MEDIA_EXTENSIONS: &[&str] = &[
+ "mp4", "m4v", "mov", "webm", "mkv", "mp3", "m4a", "aac", "wav", "flac", "ogg", "oga", "png",
+ "jpg", "jpeg", "webp", "gif",
+];
+
+fn copy_media_file(source: &Path, project_folder: &Path) -> Result<ImportedMediaFile, String> {
+ if !source.is_file() {
+ return Err(format!("{} does not exist.", source.to_string_lossy()));
+ }
+ let extension = source
+ .extension()
+ .and_then(|value| value.to_str())
+ .map(str::to_ascii_lowercase)
+ .ok_or_else(|| "The selected file needs a file extension.".to_string())?;
+ let (kind, mime_type) = media_kind_and_mime(&extension)
+ .ok_or_else(|| format!("PolStudio cannot import .{extension} files yet."))?;
+ let media_folder = project_folder.join("media");
+ fs::create_dir_all(&media_folder)
+ .map_err(|error| format!("Could not prepare media folder: {error}"))?;
+ let display_name = source
+ .file_stem()
+ .and_then(|value| value.to_str())
+ .unwrap_or("Imported media");
+ let base_name = safe_folder_name(display_name);
+ let mut file_name = format!("{base_name}.{extension}");
+ let mut destination = media_folder.join(&file_name);
+ let mut suffix = 2;
+ // Never overwrite: two different files with the same name are two files.
+ while destination.exists() {
+ file_name = format!("{base_name}-{suffix}.{extension}");
+ destination = media_folder.join(&file_name);
+ suffix += 1;
+ }
+ fs::copy(source, &destination)
+ .map_err(|error| format!("Could not copy {display_name} into this project: {error}"))?;
+ Ok(ImportedMediaFile {
+ kind,
+ name: display_name.to_string(),
+ relative_path: format!("media/{file_name}"),
+ mime_type: mime_type.into(),
+ })
+}
+
+/// Hands the webview the bytes of one file inside a project, so it can show a
+/// reference image the user imported. Confined to the project folder: the
+/// relative path goes through the same normaliser every stored path does, and
+/// the result is checked to still sit under the canonical root, so a crafted
+/// `..` in a hand-edited pols.json cannot read the rest of the disk.
+#[tauri::command]
+fn read_project_file(folder_path: String, relative_path: String) -> Result<tauri::ipc::Response, String> {
+ let root = PathBuf::from(folder_path)
+ .canonicalize()
+ .map_err(|error| format!("Could not resolve project folder: {error}"))?;
+ let relative = normalize_project_path(&relative_path)?;
+ let target = root
+ .join(&relative)
+ .canonicalize()
+ .map_err(|error| format!("Could not resolve {relative}: {error}"))?;
+ if !target.starts_with(&root) || !target.is_file() {
+ return Err(format!("{relative} is not a file inside this project."));
+ }
+ let bytes = fs::read(&target).map_err(|error| format!("Could not read {relative}: {error}"))?;
+ Ok(tauri::ipc::Response::new(bytes))
+}
+
+/// Copies the chosen files into the project so the folder stays portable — the
+/// same rule references already follow. An empty list means the user cancelled.
+#[tauri::command]
+fn import_media_files(
+ app: AppHandle,
+ folder_path: String,
+) -> Result<Vec<ImportedMediaFile>, String> {
+ let project_folder = PathBuf::from(folder_path)
+ .canonicalize()
+ .map_err(|error| format!("Could not resolve project folder: {error}"))?;
+ let selected = app
+ .dialog()
+ .file()
+ .set_title("Import media into this project")
+ .add_filter("Media", MEDIA_EXTENSIONS)
+ .blocking_pick_files();
+ let Some(selected) = selected else {
+ return Ok(Vec::new());
+ };
+ selected
+ .into_iter()
+ .map(|path| {
+ let source = path
+ .into_path()
+ .map_err(|error| format!("Could not access the selected file: {error}"))?;
+ copy_media_file(&source, &project_folder)
+ })
+ .collect()
+}
+
#[tauri::command]
fn create_project(
app: AppHandle,
@@ -1100,13 +1241,25 @@ fn choose_engine_path(
Ok(Some(path.to_string_lossy().into_owned()))
}
+/// What is installed on this computer: the two agent CLIs and the video engine.
+///
+/// Async on purpose — this launches two CLIs (up to 7s each) and loads the
+/// engine DLL. Run inline on the main thread it froze the window for as long
+/// as that took, which is what it was doing.
+///
+/// Takes provider settings rather than a whole project: what is installed here
+/// is a property of the machine, so the frontend probes it ONCE at startup and
+/// every project shares the answer.
#[tauri::command]
-fn runtime_status(config: ProjectConfig) -> Result<RuntimeStatus, String> {
- let config = validate_and_normalize_config(config)?;
- Ok(RuntimeStatus {
- providers: agent::provider_statuses(&config.provider_settings),
- vidfab: vidfab::status(&config.provider_settings),
+async fn runtime_status(
+ settings: BTreeMap<String, ProviderSetting>,
+) -> Result<RuntimeStatus, String> {
+ tauri::async_runtime::spawn_blocking(move || RuntimeStatus {
+ providers: agent::provider_statuses(&settings),
+ vidfab: vidfab::status(&settings),
})
+ .await
+ .map_err(|error| format!("Could not probe this computer: {error}"))
}
#[tauri::command]
@@ -1164,6 +1317,8 @@ pub fn run() {
choose_project_folder,
choose_initial_reference_images,
choose_reference_image,
+ import_media_files,
+ read_project_file,
create_project,
save_project,
runtime_status,
diff --git a/src-tauri/src/vidfab.rs b/src-tauri/src/vidfab.rs
index 6a30c1c..d9e1995 100644
--- a/src-tauri/src/vidfab.rs
+++ b/src-tauri/src/vidfab.rs
@@ -15,7 +15,26 @@ use std::{
};
use tauri::{AppHandle, Emitter};
-pub const DEFAULT_DLL_PATH: &str = r"D:\Projects\vidfab\build-shared\Release\vidfab_c.dll";
+const DLL_FILE_NAME: &str = "vidfab_c.dll";
+/// Where the packaged build puts the runtime while it is being developed. Used
+/// only when the DLL is NOT beside the executable, so a `cargo run` out of the
+/// source tree still finds it.
+const DEVELOPMENT_DLL_PATH: &str = r"D:\Projects\vidfab\build-shared\Release\vidfab_c.dll";
+
+/// The runtime ships beside PolStudio.exe and is loaded from there — there is
+/// no path for anyone to configure and no way for one to go stale. vidfab_c.dll
+/// is loaded with LOAD_WITH_ALTERED_SEARCH_PATH, so its own dependencies sit in
+/// that folder too, which is the same reason a subfolder never bought anything.
+pub fn default_dll_path() -> PathBuf {
+ if let Some(beside_exe) = std::env::current_exe()
+ .ok()
+ .and_then(|exe| exe.parent().map(|dir| dir.join(DLL_FILE_NAME)))
+ .filter(|path| path.is_file())
+ {
+ return beside_exe;
+ }
+ DEVELOPMENT_DLL_PATH.into()
+}
const EXPECTED_CAPI_MAJOR: u32 = 1;
const NOT_READY: i32 = -7;
const CANCELLED: i32 = -8;
@@ -217,7 +236,10 @@ impl Configuration {
})
};
Self {
- dll_path: option("dllPath").unwrap_or_else(|| DEFAULT_DLL_PATH.into()),
+ // `dllPath` is no longer written by the app and has no settings UI.
+ // It is still READ so a project or a test that carries one keeps
+ // working; with none, the runtime is found beside the executable.
+ dll_path: option("dllPath").unwrap_or_else(default_dll_path),
models: [
(0, "transformer", option("transformer")),
(1, "textEncoder", option("textEncoder")),
@@ -864,9 +886,12 @@ mod tests {
assert_eq!(packed >> 24, EXPECTED_CAPI_MAJOR);
}
+ /// Under `cargo test` the executable is a test harness in target/debug, so
+ /// this resolves to the development path — which is exactly the build this
+ /// test is here to check.
#[test]
fn installed_development_dll_reports_a_compatible_api_when_present() {
- if Path::new(DEFAULT_DLL_PATH).is_file() {
+ if default_dll_path().is_file() {
let runtime = status(&BTreeMap::new());
assert_ne!(runtime.state, "runtimeMissing", "{}", runtime.detail);
assert_ne!(runtime.state, "incompatible", "{}", runtime.detail);
diff --git a/src/App.tsx b/src/App.tsx
index 854a336..2dccd27 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -7,6 +7,7 @@ import { PromptComposer } from "./components/PromptComposer";
import { SettingsView } from "./components/SettingsView";
import { chooseAndOpenProject, createProject, listRecentProjects, saveProject } from "./lib/persistence";
import type { CreateProjectInput, ProjectRecord } from "./lib/project";
+import { getRuntimeStatus, type RuntimeStatus } from "./lib/runtime";
interface LibraryError {
/** What failed, in the user’s terms. */
@@ -35,6 +36,11 @@ function App() {
const [settingsOpen, setSettingsOpen] = useState(false);
const [settingsRevision, setSettingsRevision] = useState(0);
const closeSettings = () => { setSettingsOpen(false); setSettingsRevision((value) => value + 1); };
+ /* What is installed on this computer. Probed ONCE here rather than every
+ time a project opens: it launches two agent CLIs and loads the engine DLL,
+ which is seconds of work, and the answer is the same for every project.
+ Null means the probe has not landed yet — never "nothing is installed". */
+ const [runtime, setRuntime] = useState<RuntimeStatus | null>(null);
const searchInput = useRef<HTMLInputElement>(null);
useEffect(() => {
@@ -54,6 +60,20 @@ function App() {
.finally(() => setLoading(false));
}, []);
+ useEffect(() => {
+ // Re-probed when the settings overlay closes, because that is where the
+ // engine paths get fixed.
+ let live = true;
+ setRuntime(null);
+ void getRuntimeStatus()
+ .then((status) => { if (live) setRuntime(status); })
+ .catch((reason: unknown) => {
+ if (!live) return;
+ setError({ title: "Couldn’t check what’s installed on this computer", detail: describe(reason) });
+ });
+ return () => { live = false; };
+ }, [settingsRevision]);
+
useEffect(() => {
const focusSearch = (event: KeyboardEvent) => {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {
@@ -106,14 +126,14 @@ function App() {
paths it holds are what makes generation work at all, and finding out they
are wrong happens inside a project, not in the library. */
const settingsLauncher = (
- <button className="settings-launcher" type="button" onClick={() => setSettingsOpen(true)} title="Settings">
- <Settings size={18} aria-hidden="true" /> <span>Settings</span>
+ <button className="settings-launcher" type="button" onClick={() => setSettingsOpen(true)} title="Settings" aria-label="Settings">
+ <Settings size={22} aria-hidden="true" />
</button>
);
if (activeProject) {
return <>
- <ProjectWorkspace project={activeProject} initialView={activeProjectInitialView} settingsRevision={settingsRevision} onBack={() => setActiveProject(null)} onSave={async (project) => {
+ <ProjectWorkspace project={activeProject} initialView={activeProjectInitialView} runtime={runtime} onBack={() => setActiveProject(null)} onSave={async (project) => {
const saved = await saveProject(project);
setActiveProject(saved);
setProjects((current) => [saved, ...current.filter((item) => item.config.id !== saved.config.id)]);
diff --git a/src/components/ProjectWorkspace.test.ts b/src/components/ProjectWorkspace.test.ts
index 4d99008..a43fd74 100644
--- a/src/components/ProjectWorkspace.test.ts
+++ b/src/components/ProjectWorkspace.test.ts
@@ -86,7 +86,7 @@ describe("project workspace timecode", () => {
const firstTrackWithClip = config.timeline.tracks.find((track) => track.clips.length > 0)!;
const locked = { ...config, timeline: { tracks: config.timeline.tracks.map((track) => track.id === firstTrackWithClip.id ? { ...track, locked: true } : track) } };
const onChange = vi.fn();
- const { container } = render(createElement(TimelineView, { config: locked, onChange, onOpenGenerator: () => undefined }));
+ const { container } = render(createElement(TimelineView, { config: locked, folderPath: "C:\Locked Project", onChange, onOpenGenerator: () => undefined }));
const timeline = container.querySelector(".timeline-view")!;
fireEvent.keyDown(timeline, { key: "Delete" });
expect(onChange).not.toHaveBeenCalled();
@@ -145,7 +145,7 @@ describe("project workspace timecode", () => {
it("disables Split while the playhead sits outside the selected clip", () => {
const config = parseProjectConfig(completeFixture);
- const { container } = render(createElement(TimelineView, { config, onChange: () => undefined, onOpenGenerator: () => undefined }));
+ const { container } = render(createElement(TimelineView, { config, folderPath: "C:\Timeline Project", onChange: () => undefined, onOpenGenerator: () => undefined }));
const split = () => screen.getByRole("button", { name: "Split" }) as HTMLButtonElement;
// The playhead starts at the head of the first clip, where splitSelected
// returns early — so the button must not look live.
@@ -208,7 +208,7 @@ describe("project workspace timecode", () => {
it("says why Duplicate and Delete are unavailable, not just that they are", () => {
const config = createProjectConfig({ name: "Ceramic lamp", prompt: "A quiet product film", aspectRatio: "16:9", resolution: "1080p", targetDurationSeconds: 30 });
- render(createElement(TimelineView, { config, onChange: () => undefined, onOpenGenerator: () => undefined }));
+ render(createElement(TimelineView, { config, folderPath: "C:\Timeline Project", onChange: () => undefined, onOpenGenerator: () => undefined }));
for (const label of ["Duplicate", "Delete"]) {
const button = screen.getByRole("button", { name: label }) as HTMLButtonElement;
expect(button.disabled).toBe(true);
diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsx
index a67bb11..9f085ff 100644
--- a/src/components/ProjectWorkspace.tsx
+++ b/src/components/ProjectWorkspace.tsx
@@ -1,7 +1,7 @@
import { ArrowLeft, BookOpen, Download, Film, Save, Sparkles } from "lucide-react";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import type { ProjectConfig, ProjectRecord } from "../lib/project";
-import { getRuntimeStatus, type RuntimeStatus } from "../lib/runtime";
+import { CHECKING_PROVIDERS, type RuntimeStatus } from "../lib/runtime";
import { AgentDock } from "./workspace/AgentDock";
import { GeneratorView } from "./workspace/GeneratorView";
import { ReferencesView } from "./workspace/ReferencesView";
@@ -17,13 +17,12 @@ export function formatDurationTimecode(totalSeconds: number): string {
return [hours, minutes, remainder].map((value) => String(value).padStart(2, "0")).join(":");
}
-export function ProjectWorkspace({ project, initialView = "timeline", settingsRevision = 0, onBack, onSave }: {
+export function ProjectWorkspace({ project, initialView = "timeline", runtime = null, onBack, onSave }: {
project: ProjectRecord;
initialView?: ProjectView;
- /** Bumped when the settings overlay closes, so edits to this machine's
- * engine paths reach an already-open project instead of waiting for a
- * reopen. */
- settingsRevision?: number;
+ /** What is installed on this computer, probed once at startup by App. Null
+ * while that probe is still in flight — not "nothing is installed". */
+ runtime?: RuntimeStatus | null;
onBack: () => void;
onSave: (project: ProjectRecord) => Promise<void>;
}) {
@@ -36,14 +35,6 @@ export function ProjectWorkspace({ project, initialView = "timeline", settingsRe
const [saving, setSaving] = useState(false);
const [dirty, setDirty] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
- const [runtime, setRuntime] = useState<RuntimeStatus | null>(null);
-
- useEffect(() => {
- void getRuntimeStatus(config).then(setRuntime).catch(() => setRuntime(null));
- // Reprobe when the project's own provider settings change, and when the
- // machine's engine paths have just been edited.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [config.providerSettings, settingsRevision]);
const changeConfig = (next: ProjectConfig) => {
setConfig(next);
@@ -97,17 +88,14 @@ export function ProjectWorkspace({ project, initialView = "timeline", settingsRe
</header>
<div className={`project-content project-content--${view}`}>
- {view === "timeline" && <TimelineView config={config} onChange={changeConfig} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}
+ {view === "timeline" && <TimelineView config={config} folderPath={project.folderPath} onChange={changeConfig} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}
{view === "generator" && <GeneratorView config={config} folderPath={project.folderPath} runtime={runtime?.vidfab ?? null} onChange={changeConfig} selectedJobId={selectedGenerationJobId} onOpenTimeline={() => setView("timeline")} draftPrompt={generatorPrompt} onDraftPromptChange={setGeneratorPrompt} />}
{view === "references" && <ReferencesView config={config} folderPath={project.folderPath} onChange={changeConfig} />}
</div>
<footer className="project-agent-row"><AgentDock
context={view === "timeline" ? "the edit" : view === "generator" ? "this generation queue" : "project references"}
record={{ ...project, config }}
- providers={runtime?.providers ?? [
- { id: "claude", label: "Claude Code", state: "unavailable", executable: null, version: null, detail: "Checking provider…" },
- { id: "codex", label: "Codex", state: "unavailable", executable: null, version: null, detail: "Checking provider…" },
- ]}
+ providers={runtime?.providers ?? CHECKING_PROVIDERS}
/* Routed through the same save() as the Save button. Clearing `dirty`
up front reported a saved project even when the write then failed,
and swallowed the reason; save() clears only on success and surfaces
diff --git a/src/components/PromptComposer.tsx b/src/components/PromptComposer.tsx
index 3d6f6a5..0e2f7e7 100644
--- a/src/components/PromptComposer.tsx
+++ b/src/components/PromptComposer.tsx
@@ -44,6 +44,7 @@ const modifierKey =
typeof navigator !== "undefined" && /Mac|iPhone|iPad/i.test(navigator.userAgent) ? "⌘" : "Ctrl";
export function PromptComposer({ busy, onCreate }: PromptComposerProps) {
+ const [open, setOpen] = useState(false);
const [prompt, setPrompt] = useState("");
const [aspectRatio, setAspectRatio] = useState<AspectRatio>("16:9");
const [resolution, setResolution] = useState<Resolution>("1080p");
@@ -76,15 +77,18 @@ export function PromptComposer({ busy, onCreate }: PromptComposerProps) {
setPrompt(ideaPrompt);
};
- /* The description box is the first thing you use, so start in it — saving a
- click on the headline flow. Runs once, and only while focus is still on the
- document body, so it never yanks focus off a field the user already picked
- (Ctrl+K search included). */
+ /* Focus the box when the section is opened — that click is a statement of
+ intent, so landing in the field saves a second one. It used to fire on
+ mount, which is wrong now that the section starts closed: there would be
+ nothing to focus. Focus still moves only from the summary that was just
+ activated or from nowhere, so it never yanks focus off a field the user
+ already picked (Ctrl+K search included). */
useEffect(() => {
+ if (!open) return;
const active = document.activeElement;
- if (active && active !== document.body) return;
+ if (active && active !== document.body && !(active instanceof HTMLElement && active.tagName === "SUMMARY")) return;
promptInput.current?.focus({ preventScroll: true });
- }, []);
+ }, [open]);
const addReferenceImages = async () => {
setReferenceError(null);
@@ -109,12 +113,17 @@ export function PromptComposer({ busy, onCreate }: PromptComposerProps) {
};
return (
- <section className="composer-shell" aria-labelledby="create-heading">
- <div className="composer-shell__glow" />
- <div className="composer-heading">
+ /* Collapsed by default. The library's job on open is to show you your
+ projects; starting a new one is deliberate, so it asks for one click
+ rather than taking the top of the page every time. <details> carries the
+ open/closed state and the keyboard behaviour natively. */
+ <details className="composer-shell" open={open} onToggle={(event) => setOpen(event.currentTarget.open)}>
+ <summary className="composer-heading">
<span className="eyebrow"><Sparkles size={14} /> New project</span>
<h2 id="create-heading">What do you want to make?</h2>
- </div>
+ <ChevronDown className="composer-heading__chevron" size={20} aria-hidden="true" />
+ </summary>
+ <div className="composer-shell__glow" />
<div className="composer">
<div className="composer__input-row">
@@ -204,6 +213,6 @@ export function PromptComposer({ busy, onCreate }: PromptComposerProps) {
<Undo2 size={15} /> Undo — put my words back
</button>}
</div>
- </section>
+ </details>
);
}
diff --git a/src/components/SettingsView.tsx b/src/components/SettingsView.tsx
index da3f79e..3785c08 100644
--- a/src/components/SettingsView.tsx
+++ b/src/components/SettingsView.tsx
@@ -10,12 +10,9 @@ import {
type PathState = "unset" | "checking" | "found" | "missing";
-/* The backend reports the DLL separately from the five model paths, so one
- lookup answers "is this path actually there?" for either kind. */
function pathState(field: EnginePathField, value: string, status: VidfabStatus | null): PathState {
if (!value.trim()) return "unset";
if (!status) return "checking";
- if (field.id === "dllPath") return status.state === "runtimeMissing" ? "missing" : "found";
const model: ModelStatus | undefined = status.models.find((item) => item.id === field.id);
if (!model) return "checking";
/* `available` is a file test on the Rust side, so a tokenizer FOLDER reads
@@ -94,8 +91,9 @@ export function SettingsView({ onClose }: { onClose: () => void }) {
</header>
<p className="settings-view__lead">
- PolStudio needs the engine library and its model files to render a shot. These paths belong to
- this computer, not to a project — they are remembered here and used by every project you open.
+ PolStudio needs the model files to render a shot. Where they live is a property of this
+ computer, not of a project, so the paths are remembered here and used by every project you
+ open. The engine itself ships with the app and needs no setting.
</p>
<div className={`settings-status settings-status--${status?.state ?? "checking"}`} role="status">
@@ -104,7 +102,7 @@ export function SettingsView({ onClose }: { onClose: () => void }) {
</div>
<section className="settings-section" aria-labelledby="paths-heading">
- <h2 id="paths-heading">Engine and model paths</h2>
+ <h2 id="paths-heading">Model weights</h2>
{ENGINE_PATH_FIELDS.map((field) => {
const value = settings[field.id];
const state = pathState(field, value, status);
@@ -159,7 +157,7 @@ const engineHeadline = (status: VidfabStatus | null, desktop: boolean) => {
switch (status.state) {
case "ready": return "Engine ready";
case "modelsMissing": return "Model files missing";
- case "runtimeMissing": return "Engine not found";
+ case "runtimeMissing": return "Engine missing from this install";
case "incompatible": return "Engine version not supported";
case "demo": return "Browser preview";
}
@@ -167,7 +165,8 @@ const engineHeadline = (status: VidfabStatus | null, desktop: boolean) => {
const engineDetail = (status: VidfabStatus | null, desktop: boolean, missing: number) => {
if (!desktop) return "Paths are saved here, but only the desktop app can check them or render with them.";
- if (!status) return "Looking for the engine library and the model files.";
+ if (!status) return "Looking for the engine and the model files.";
+ if (status.state === "runtimeMissing") return `${status.detail} vidfab_c.dll should sit next to PolStudio.exe.`;
if (status.state === "ready") return "Everything PolStudio needs to render a shot is in place.";
if (missing > 0) return `${status.detail} ${missing === 1 ? "One path" : `${missing} paths`} still need setting below.`;
return status.detail;
diff --git a/src/components/workspace/AgentDock.tsx b/src/components/workspace/AgentDock.tsx
index e65390b..089fc05 100644
--- a/src/components/workspace/AgentDock.tsx
+++ b/src/components/workspace/AgentDock.tsx
@@ -90,7 +90,7 @@ export function AgentDock({ context, record, providers, onRecord }: {
);
}
-const providerStateLabel = (state: ProviderStatus["state"]) => state === "ready" ? "Ready" : state === "notInstalled" ? "Not installed" : state === "authRequired" ? "Sign in required" : state === "disabled" ? "Disabled" : "Unavailable";
+const providerStateLabel = (state: ProviderStatus["state"]) => state === "checking" ? "Checking…" : state === "ready" ? "Ready" : state === "notInstalled" ? "Not installed" : state === "authRequired" ? "Sign in required" : state === "disabled" ? "Disabled" : "Unavailable";
/* Only states with a genuine user action get a next step — never invent one. */
const providerNextStep = ({ state, label }: ProviderStatus): string => {
@@ -101,6 +101,7 @@ const providerNextStep = ({ state, label }: ProviderStatus): string => {
return `Sign in to ${label} in your terminal, then reopen this project.`;
case "disabled":
return `${label} is switched off for this project.`;
+ case "checking":
case "ready":
case "unavailable":
return "";
diff --git a/src/components/workspace/ReferenceImage.tsx b/src/components/workspace/ReferenceImage.tsx
new file mode 100644
index 0000000..4063527
--- /dev/null
+++ b/src/components/workspace/ReferenceImage.tsx
@@ -0,0 +1,66 @@
+import { Image as ImageIcon, TriangleAlert } from "lucide-react";
+import { useEffect, useState } from "react";
+import { readProjectFileUrl } from "../../lib/persistence";
+
+/* Reference images live in the project folder, which the webview cannot reach
+ * directly — so the bytes come back through a Tauri command and become a blob
+ * URL here. The URL is revoked on unmount and on every path change; without
+ * that, browsing a library of references pins each one in memory for the life
+ * of the window.
+ *
+ * The extension is the only thing available to type the blob: nothing has
+ * decoded the file. Getting it wrong costs a broken <img>, which is exactly
+ * what `failed` renders. */
+const mimeFor = (relativePath: string) => {
+ const extension = relativePath.split(".").pop()?.toLowerCase();
+ switch (extension) {
+ case "png": return "image/png";
+ case "webp": return "image/webp";
+ case "gif": return "image/gif";
+ default: return "image/jpeg";
+ }
+};
+
+export function ReferenceImage({ folderPath, relativePath, alt, className = "" }: {
+ folderPath: string;
+ relativePath: string;
+ alt: string;
+ className?: string;
+}) {
+ const [url, setUrl] = useState<string | null>(null);
+ const [failed, setFailed] = useState(false);
+
+ useEffect(() => {
+ let current: string | null = null;
+ let live = true;
+ setFailed(false);
+ setUrl(null);
+ void readProjectFileUrl(folderPath, relativePath, mimeFor(relativePath))
+ .then((value) => {
+ // Unmounted (or moved to another reference) while the read was in
+ // flight: revoke immediately, because nothing else ever will.
+ if (!live) {
+ if (value) URL.revokeObjectURL(value);
+ return;
+ }
+ current = value;
+ setUrl(value);
+ if (!value) setFailed(true);
+ })
+ .catch(() => { if (live) setFailed(true); });
+ return () => {
+ live = false;
+ if (current) URL.revokeObjectURL(current);
+ };
+ }, [folderPath, relativePath]);
+
+ if (url) {
+ return <img className={className} src={url} alt={alt} loading="lazy" onError={() => setFailed(true)} />;
+ }
+ /* Two different states, said plainly rather than with one ambiguous
+ placeholder: still loading, or the file is not where the project says. */
+ return <span className={`reference-image-fallback ${className}`.trim()} role="img" aria-label={failed ? `${alt} — file missing` : `${alt} — loading`}>
+ {failed ? <TriangleAlert size={22} aria-hidden="true" /> : <ImageIcon size={22} aria-hidden="true" />}
+ <em>{failed ? "File not found" : "Loading…"}</em>
+ </span>;
+}
diff --git a/src/components/workspace/ReferencesView.tsx b/src/components/workspace/ReferencesView.tsx
index 0882905..eae4bde 100644
--- a/src/components/workspace/ReferencesView.tsx
+++ b/src/components/workspace/ReferencesView.tsx
@@ -3,6 +3,7 @@ import { invoke } from "@tauri-apps/api/core";
import { useMemo, useState } from "react";
import { isReferenceDescribed, type ProjectConfig, type ProjectReference } from "../../lib/project";
import { isTauri } from "../../lib/persistence";
+import { ReferenceImage } from "./ReferenceImage";
type ReferenceUse = ProjectReference["intendedUse"][number];
@@ -82,7 +83,11 @@ export function ReferencesView({ config, folderPath, onChange }: { config: Proje
<div className="reference-library__toolbar"><span>{config.references.length === 1 ? "1 reference" : `${config.references.length} references`}</span></div>
<div className="reference-grid">
{config.references.map((ref) => <button key={ref.id} className={selectedId === ref.id ? "selected" : ""} onClick={() => setSelectedId(ref.id)}>
- {ref.kind === "image" ? <span className="reference-art"><Image size={26} /><em>Image file</em></span> : <span className="reference-copy-art"><FileText size={26} /><em>Text definition</em></span>}
+ {ref.kind === "image" && ref.relativePath
+ ? <span className="reference-art reference-art--photo"><ReferenceImage folderPath={folderPath} relativePath={ref.relativePath} alt={ref.name} /></span>
+ : ref.kind === "image"
+ ? <span className="reference-art"><Image size={26} /><em>Image file</em></span>
+ : <span className="reference-copy-art"><FileText size={26} /><em>Text definition</em></span>}
<span className="reference-card__body"><span><b>{ref.name}</b><small>{ref.kind === "text" ? "Text definition" : ref.relativePath}</small></span>{isReferenceDescribed(ref)
? <p>{ref.description}</p>
: <p className="reference-card__incomplete">{ref.kind === "image"
@@ -102,7 +107,12 @@ export function ReferencesView({ config, folderPath, onChange }: { config: Proje
<aside className="reference-inspector">
<div className="panel-chrome"><h2>Reference details</h2>{selected && <button onClick={remove} aria-label="Delete reference" title="Delete this reference"><Trash2 size={16} /></button>}</div>
{selected ? <>
- <div className={`reference-detail-art reference-detail-art--${selected.kind}`}><span>{selected.kind === "image" ? <Image size={30} /> : <Users size={30} />}</span><em>{selected.kind === "image" ? selected.relativePath : "Reusable text definition"}</em></div>
+ <div className={`reference-detail-art reference-detail-art--${selected.kind}${selected.kind === "image" && selected.relativePath ? " reference-detail-art--photo" : ""}`}>
+ {selected.kind === "image" && selected.relativePath
+ ? <ReferenceImage folderPath={folderPath} relativePath={selected.relativePath} alt={selected.name} />
+ : <span>{selected.kind === "image" ? <Image size={30} /> : <Users size={30} />}</span>}
+ <em>{selected.kind === "image" ? selected.relativePath : "Reusable text definition"}</em>
+ </div>
<div className="reference-fields">
<label><span>Name</span><input value={selected.name} onChange={(event) => update(selected.id, { name: event.target.value || "Untitled reference" })} /></label>
<label><span>Definition</span><textarea value={selected.description} placeholder="Describe what should stay consistent — the traits, materials, colours, or wardrobe PolStudio should preserve across shots." onChange={(event) => update(selected.id, { description: event.target.value, content: event.target.value || null })} /></label>
diff --git a/src/components/workspace/TimelineView.tsx b/src/components/workspace/TimelineView.tsx
index 49fb49e..a9a9ab4 100644
--- a/src/components/workspace/TimelineView.tsx
+++ b/src/components/workspace/TimelineView.tsx
@@ -4,10 +4,19 @@ import {
Volume2, VolumeX,
} from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
-import type { ProjectConfig, TimelineClip } from "../../lib/project";
+import { importMediaFiles, isTauri } from "../../lib/persistence";
+import type { ProjectAsset, ProjectConfig, TimelineClip } from "../../lib/project";
const MIN_DURATION = 10_000;
const NOT_YET = "Not available yet. This control doesn’t change your project.";
+/* What a dropped media file is worth on the timeline until PolStudio can read
+ its real length. Imported assets carry no duration — nothing has decoded
+ them — so the clip starts at a stated default and the inspector's Lasts
+ field is editable so the user can set the truth. */
+const DROPPED_CLIP_MS = 5_000;
+/* The drag payload is the asset id. A custom type keeps files dragged in from
+ the desktop, and text dragged from anywhere else, out of the drop handler. */
+const ASSET_DRAG_TYPE = "application/x-polstudio-asset";
/* The canvas used to be a hard-coded 34s — the seeded fixture's exact length —
so a 60-second project still got a 34-second ruler. Derive it from the real
@@ -35,13 +44,24 @@ const timecode = (ms: number) => {
return `00:${String(Math.floor(seconds / 60)).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}:${String(frames).padStart(2, "0")}`;
};
-export function TimelineView({ config, onChange, onOpenGenerator }: { config: ProjectConfig; onChange: (next: ProjectConfig) => void; onOpenGenerator: (jobId?: string) => void }) {
+export function TimelineView({ config, folderPath, onChange, onOpenGenerator }: { config: ProjectConfig; folderPath: string; onChange: (next: ProjectConfig) => void; onOpenGenerator: (jobId?: string) => void }) {
const firstClip = config.timeline.tracks.flatMap((track) => track.clips)[0];
const [selectedId, setSelectedId] = useState(firstClip?.id ?? "");
const [playhead, setPlayhead] = useState(firstClip?.startMs ?? 0);
const [playing, setPlaying] = useState(false);
const [panelTab, setPanelTab] = useState<"scenes" | "media">("scenes");
const timelineGrid = useRef<HTMLDivElement>(null);
+ const [importing, setImporting] = useState(false);
+ const [importError, setImportError] = useState<string | null>(null);
+ /* Which track the pointer is currently over with a compatible asset, so the
+ lane can light up. A drop target the user cannot see is a drop target the
+ user will not find. */
+ const [dropTrackId, setDropTrackId] = useState<string | null>(null);
+ /* The asset currently under the pointer. Browsers withhold dataTransfer's
+ payload until the drop event, so a dragover handler cannot read the id it
+ is being offered — it can only see the TYPE. Remembering what dragstart
+ put there is the only way to know whether this lane can take it. */
+ const [draggedAsset, setDraggedAsset] = useState<ProjectAsset | undefined>(undefined);
const tracks = config.timeline.tracks;
const selected = useMemo(() => tracks.flatMap((track) => track.clips).find((clip) => clip.id === selectedId), [tracks, selectedId]);
const selectedTrack = tracks.find((track) => track.id === selected?.trackId);
@@ -125,6 +145,65 @@ export function TimelineView({ config, onChange, onOpenGenerator }: { config: Pr
const deleteBlockedBy = !selected
? "Select a clip to delete it"
: !selectedTrack || selectedTrack.locked ? "This clip’s track is locked" : null;
+ const importMedia = async () => {
+ setImportError(null);
+ setImporting(true);
+ try {
+ const imported = await importMediaFiles(folderPath);
+ if (imported.length === 0) return;
+ const now = new Date().toISOString();
+ const assets: ProjectAsset[] = imported.map((file) => ({
+ id: `asset-${crypto.randomUUID()}`,
+ kind: file.kind,
+ name: file.name,
+ relativePath: file.relativePath,
+ mimeType: file.mimeType,
+ // Genuinely unknown until something decodes the file. Left null rather
+ // than filled with a plausible number.
+ durationMs: null,
+ width: null,
+ height: null,
+ createdAt: now,
+ }));
+ onChange({ ...config, assets: [...config.assets, ...assets] });
+ setPanelTab("media");
+ } catch (reason) {
+ setImportError(reason instanceof Error ? reason.message : String(reason));
+ } finally {
+ setImporting(false);
+ }
+ };
+
+ /* A video or image belongs on a video track and a sound on an audio track;
+ dropping either on the other would make a clip nothing can ever play. */
+ const acceptsAsset = (track: ProjectConfig["timeline"]["tracks"][number], asset: ProjectAsset | undefined) => {
+ if (!asset || track.locked) return false;
+ return track.kind === "audio" ? asset.kind === "audio" : asset.kind !== "audio";
+ };
+
+ const assetById = (id: string) => config.assets.find((asset) => asset.id === id);
+
+ const dropAsset = (trackId: string, assetId: string, ratio: number) => {
+ const track = tracks.find((item) => item.id === trackId);
+ const asset = assetById(assetId);
+ if (!track || !acceptsAsset(track, asset) || !asset) return;
+ // Clamp so a drop near the right edge still lands a whole clip on the ruler.
+ const startMs = Math.round(Math.max(0, Math.min(duration - DROPPED_CLIP_MS, ratio * duration)));
+ const clip: TimelineClip = {
+ id: `clip-${crypto.randomUUID()}`,
+ assetId: asset.id,
+ trackId: track.id,
+ startMs,
+ durationMs: asset.durationMs && asset.durationMs > 0 ? asset.durationMs : DROPPED_CLIP_MS,
+ sourceStartMs: 0,
+ label: asset.name,
+ color: null,
+ status: "approved",
+ };
+ updateTracks(tracks.map((item) => item.id === track.id ? { ...item, clips: [...item.clips, clip] } : item));
+ setSelectedId(clip.id);
+ };
+
const addScene = () => {
// A new project already carries an unstarted draft made from the user's own
// words, so open that rather than stacking a near-identical second shot.
@@ -157,22 +236,44 @@ export function TimelineView({ config, onChange, onOpenGenerator }: { config: Pr
<span><b>{clip.label.replace(/^\d+ · /, "")}</b><small>{clip.status === "generated" ? "Needs review" : "In timeline"}</small></span>
</button>
))}
- {sceneClips.length === 0 && <p className="panel-hint">No scenes yet. Use the button below to open your shot in the Generator — scenes appear here once they land on the timeline.</p>}
<button className="scene-add" onClick={addScene}><Plus size={18} /> Add or generate a scene</button>
</div>
) : (
<div className="media-grid">
- {config.assets.map((asset) => <button key={asset.id}><span className="media-thumb">{asset.kind === "audio" ? <Music2 size={22} /> : asset.kind === "image" ? <ImageIcon size={22} /> : <Video size={22} />}</span><b>{asset.name}</b><small>{asset.kind} · {asset.durationMs ? `${(asset.durationMs / 1000).toFixed(1)}s` : "still"}</small></button>)}
- {config.assets.length === 0 && <p className="panel-hint">No media in this project yet. PolStudio can’t save generated shots as files yet, so nothing lands here.</p>}
- <button className="media-import" disabled title="Importing your own files isn’t available yet. Generate a scene instead.">
- <Upload size={20} /><b>Import media</b><small>Not available yet</small>
+ {/* Draggable onto the timeline. `draggable` on a <button> is the
+ whole mechanism — the button still clicks and still takes
+ focus, so keyboard users are not shut out of selecting it. */}
+ {config.assets.map((asset) => <button
+ key={asset.id}
+ draggable
+ onDragStart={(event) => {
+ event.dataTransfer.setData(ASSET_DRAG_TYPE, asset.id);
+ event.dataTransfer.effectAllowed = "copy";
+ setDraggedAsset(asset);
+ }}
+ onDragEnd={() => { setDraggedAsset(undefined); setDropTrackId(null); }}
+ title={`${asset.name} — drag onto a ${asset.kind === "audio" ? "sound" : "video"} track below`}
+ >
+ <span className="media-thumb">{asset.kind === "audio" ? <Music2 size={22} /> : asset.kind === "image" ? <ImageIcon size={22} /> : <Video size={22} />}</span>
+ <b>{asset.name}</b>
+ {/* Duration is only claimed when something actually measured it. */}
+ <small>{asset.kind}{asset.durationMs ? ` · ${(asset.durationMs / 1000).toFixed(1)}s` : ""}</small>
+ </button>)}
+ <button
+ className="media-import"
+ onClick={() => void importMedia()}
+ disabled={importing || !isTauri()}
+ title={isTauri() ? "Copy video, sound, or image files into this project" : "Importing files is available in the desktop app"}
+ >
+ <Upload size={20} /><b>{importing ? "Importing…" : "Import media"}</b><small>Video, sound, or images</small>
</button>
+ {importError && <p className="panel-hint panel-hint--error" role="alert">{importError}</p>}
</div>
)}
</aside>
<main className="program-panel">
- <div className="panel-chrome"><h2><i className="live-dot" /> Program monitor</h2></div>
+ <h2 className="sr-only">Program monitor</h2>
<div className="program-canvas">
{hasVisualOutput ? (
<div className="program-empty program-empty--footage">
@@ -252,7 +353,31 @@ export function TimelineView({ config, onChange, onOpenGenerator }: { config: Pr
<div className="time-ruler" onPointerDown={(event) => { const rect = event.currentTarget.getBoundingClientRect(); setPlayhead(Math.round(Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)) * duration)); }}>
{ticks.map((second) => <span key={second} style={{ left: `${second * 1000 / duration * 100}%` }}><i />{rulerLabel(second)}</span>)}
</div>
- {tracks.map((track) => <TrackRow key={track.id} track={track} duration={duration} selectedId={selectedId} onSelect={setSelectedId} onToggle={toggleTrack} />)}
+ {tracks.map((track) => <TrackRow
+ key={track.id}
+ track={track}
+ duration={duration}
+ selectedId={selectedId}
+ dropActive={dropTrackId === track.id}
+ onSelect={setSelectedId}
+ onToggle={toggleTrack}
+ onDragOverLane={(event) => {
+ if (!event.dataTransfer.types.includes(ASSET_DRAG_TYPE)) return;
+ if (!acceptsAsset(track, draggedAsset)) return;
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ setDropTrackId(track.id);
+ }}
+ onDragLeaveLane={() => setDropTrackId((current) => current === track.id ? null : current)}
+ onDropLane={(event) => {
+ event.preventDefault();
+ setDropTrackId(null);
+ const assetId = event.dataTransfer.getData(ASSET_DRAG_TYPE);
+ if (!assetId) return;
+ const rect = event.currentTarget.getBoundingClientRect();
+ dropAsset(track.id, assetId, (event.clientX - rect.left) / rect.width);
+ }}
+ />)}
<div className="timeline-playhead" style={{ left: `calc(var(--track-column) + (100% - var(--track-column)) * ${playhead / duration})` }}><span /><i /></div>
</div>
</section>
@@ -260,7 +385,17 @@ export function TimelineView({ config, onChange, onOpenGenerator }: { config: Pr
);
}
-function TrackRow({ track, duration, selectedId, onSelect, onToggle }: { track: ProjectConfig["timeline"]["tracks"][number]; duration: number; selectedId: string; onSelect: (id: string) => void; onToggle: (id: string, key: "muted" | "locked") => void }) {
+function TrackRow({ track, duration, selectedId, dropActive, onSelect, onToggle, onDragOverLane, onDragLeaveLane, onDropLane }: {
+ track: ProjectConfig["timeline"]["tracks"][number];
+ duration: number;
+ selectedId: string;
+ dropActive: boolean;
+ onSelect: (id: string) => void;
+ onToggle: (id: string, key: "muted" | "locked") => void;
+ onDragOverLane: (event: React.DragEvent<HTMLDivElement>) => void;
+ onDragLeaveLane: () => void;
+ onDropLane: (event: React.DragEvent<HTMLDivElement>) => void;
+}) {
return <>
<div className="track-head">
<span className={`track-kind track-kind--${track.kind}`}>{track.kind === "audio" ? <Music2 size={16} /> : <Video size={16} />}</span>
@@ -268,7 +403,12 @@ function TrackRow({ track, duration, selectedId, onSelect, onToggle }: { track:
<button className={track.muted ? "active" : ""} onClick={() => onToggle(track.id, "muted")} aria-label={`${track.muted ? "Unmute" : "Mute"} ${track.name}`} title={`${track.muted ? "Unmute" : "Mute"} ${track.name}`}>{track.muted ? <VolumeX size={16} /> : <Volume2 size={16} />}</button>
<button className={track.locked ? "active" : ""} onClick={() => onToggle(track.id, "locked")} aria-label={`${track.locked ? "Unlock" : "Lock"} ${track.name}`} title={`${track.locked ? "Unlock" : "Lock"} ${track.name}`}>{track.locked ? <Lock size={16} /> : <LockOpen size={16} />}</button>
</div>
- <div className={`track-lane ${track.muted ? "muted" : ""}`}>
+ <div
+ className={`track-lane ${track.muted ? "muted" : ""} ${dropActive ? "track-lane--drop" : ""}`}
+ onDragOver={onDragOverLane}
+ onDragLeave={onDragLeaveLane}
+ onDrop={onDropLane}
+ >
{track.clips.map((clip) => <button key={clip.id} className={`timeline-clip timeline-clip--${track.kind} ${selectedId === clip.id ? "selected" : ""}`} style={{ left: `${clip.startMs / duration * 100}%`, width: `${clip.durationMs / duration * 100}%`, "--clip-color": clip.color } as React.CSSProperties} onClick={() => onSelect(clip.id)} title={`${clip.label} · ${(clip.durationMs / 1000).toFixed(1)} seconds`}><span className="clip-text"><b>{clip.label}</b><small>{track.kind === "audio" ? "▂▅▃▆▂▃▇▅▂▆▃▅▂" : `${(clip.durationMs / 1000).toFixed(1)}s · ${clip.status}`}</small></span></button>)}
</div>
</>;
diff --git a/src/lib/persistence.ts b/src/lib/persistence.ts
index 350023e..923eaf0 100644
--- a/src/lib/persistence.ts
+++ b/src/lib/persistence.ts
@@ -146,6 +146,34 @@ export async function chooseInitialReferenceImages(): Promise<PendingReferenceIm
return invoke<PendingReferenceImage[]>("choose_initial_reference_images");
}
+/** A file the user picked, already copied into the project's `media/` folder.
+ * No duration or dimensions: PolStudio has no decoder yet, and a guessed
+ * number would be indistinguishable from a measured one downstream. */
+export interface ImportedMediaFile {
+ kind: "video" | "audio" | "image";
+ name: string;
+ relativePath: string;
+ mimeType: string;
+}
+
+/** Opens the picker and copies what was chosen into the project. Returns an
+ * empty list when the user cancels — and in the browser, where there is no
+ * project folder to copy into. */
+export async function importMediaFiles(folderPath: string): Promise<ImportedMediaFile[]> {
+ if (!isTauri()) return [];
+ return invoke<ImportedMediaFile[]>("import_media_files", { folderPath });
+}
+
+/** The bytes of one file inside a project folder, as a blob URL the webview
+ * can point an <img> at. Null in the browser, where there is no folder to
+ * read from. CALLERS MUST revokeObjectURL when done — a leaked blob URL pins
+ * the whole image in memory for the life of the document. */
+export async function readProjectFileUrl(folderPath: string, relativePath: string, mimeType: string): Promise<string | null> {
+ if (!isTauri()) return null;
+ const bytes = await invoke<ArrayBuffer>("read_project_file", { folderPath, relativePath });
+ return URL.createObjectURL(new Blob([bytes], { type: mimeType }));
+}
+
export async function createProject(input: CreateProjectInput): Promise<ProjectRecord | null> {
const config = createProjectConfig(input);
if (isTauri()) {
diff --git a/src/lib/project.test.ts b/src/lib/project.test.ts
index 5bd2d08..2bb02ab 100644
--- a/src/lib/project.test.ts
+++ b/src/lib/project.test.ts
@@ -51,7 +51,9 @@ describe("project schema", () => {
});
expect(parseProjectConfig(project)).toEqual(project);
expect(project.schemaVersion).toBe(1);
- expect(project.timeline.tracks.map((track) => track.name)).toEqual(["Story", "Voice-over", "Music"]);
+ // Two video layers: an overlay or title card has to be able to sit above
+ // the story track without displacing the shot underneath it.
+ expect(project.timeline.tracks.map((track) => track.name)).toEqual(["Overlays", "Story", "Voice-over", "Music"]);
expect(project.timeline.tracks.every((track) => track.clips.length === 0)).toBe(true);
expect(project.references).toEqual([]);
expect(project.generationJobs).toHaveLength(1);
diff --git a/src/lib/project.ts b/src/lib/project.ts
index 73ed6e6..c136048 100644
--- a/src/lib/project.ts
+++ b/src/lib/project.ts
@@ -449,7 +449,11 @@ export function createProjectConfig(input: CreateProjectInput): ProjectConfig {
aspectRatio: input.aspectRatio, resolution: input.resolution,
},
assets: [],
+ /* Two video layers, not one: an overlay, a title card, or a cutaway has
+ to sit ABOVE the story track, and with a single layer the only way to
+ get one there was to displace the shot underneath it. */
timeline: { tracks: [
+ { id: "track-overlay", kind: "video", name: "Overlays", locked: false, muted: false, clips: [] },
{ id: "track-story", kind: "video", name: "Story", locked: false, muted: false, clips: [] },
{ id: "track-voice-over", kind: "audio", name: "Voice-over", locked: false, muted: false, clips: [] },
{ id: "track-music", kind: "audio", name: "Music", locked: false, muted: false, clips: [] },
diff --git a/src/lib/runtime.test.ts b/src/lib/runtime.test.ts
index 632c8b5..e2438fc 100644
--- a/src/lib/runtime.test.ts
+++ b/src/lib/runtime.test.ts
@@ -20,7 +20,7 @@ describe("deterministic browser runtime", () => {
it("reports explicit demo status and a plan-only generation boundary", async () => {
const record = project();
- const status = await getRuntimeStatus(record.config);
+ const status = await getRuntimeStatus();
expect(status.vidfab.state).toBe("demo");
const plan = await resolveVidfabPlan({
jobId: "job-plan", prompt: "three field prompt", frames: 180, steps: 50,
diff --git a/src/lib/runtime.ts b/src/lib/runtime.ts
index d0c5b6d..acd4402 100644
--- a/src/lib/runtime.ts
+++ b/src/lib/runtime.ts
@@ -7,7 +7,11 @@ export type ProviderId = "claude" | "codex";
export interface ProviderStatus {
id: ProviderId;
label: string;
- state: "ready" | "disabled" | "notInstalled" | "authRequired" | "unavailable";
+ /* "checking" is FRONTEND-ONLY and never comes back from Rust: it is what the
+ dock shows while the probe is in flight. It used to borrow "unavailable"
+ for that, so a slow or failed probe left every provider reading
+ "Unavailable" — including a Claude Code that was installed and working. */
+ state: "checking" | "ready" | "disabled" | "notInstalled" | "authRequired" | "unavailable";
executable: string | null;
version: string | null;
detail: string;
@@ -68,10 +72,21 @@ const DEMO_STATUS: RuntimeStatus = {
/* Every vidfab command is handed the project config with THIS machine's engine
paths merged in (see lib/settings.ts). The merged copy is passed straight to
the command and dropped; it is never the config that gets saved. */
-export async function getRuntimeStatus(config: ProjectConfig): Promise<RuntimeStatus> {
- return isTauri() ? invoke<RuntimeStatus>("runtime_status", { config: withEngineSettings(config) }) : DEMO_STATUS;
+
+/** What is installed on this computer. Takes no project: the agent CLIs and
+ * the video engine belong to the machine, so the app probes this ONCE at
+ * startup and every project shares the answer. */
+export async function getRuntimeStatus(): Promise<RuntimeStatus> {
+ if (!isTauri()) return DEMO_STATUS;
+ return invoke<RuntimeStatus>("runtime_status", { settings: { vidfab: engineProviderSetting(loadEngineSettings()) } });
}
+/** The placeholder every caller shows until the startup probe lands. */
+export const CHECKING_PROVIDERS: ProviderStatus[] = [
+ { id: "claude", label: "Claude Code", state: "checking", executable: null, version: null, detail: "Looking for Claude Code on this computer…" },
+ { id: "codex", label: "Codex", state: "checking", executable: null, version: null, detail: "Looking for Codex on this computer…" },
+];
+
/** Probes the engine paths on their own, with no project in hand — what the
* settings screen shows. */
export async function getEngineStatus(): Promise<VidfabStatus> {
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index df4997a..225734a 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -16,7 +16,7 @@ import type { ProjectConfig, ProviderSetting } from "./project";
// Type-only: erased at build time, so this does not close a cycle with runtime.ts.
import type { ProviderId } from "./runtime";
-export type EnginePathId = "dllPath" | "transformer" | "textEncoder" | "tokenizer" | "videoVae" | "audioVae";
+export type EnginePathId = "transformer" | "textEncoder" | "tokenizer" | "videoVae" | "audioVae";
export interface EnginePathField {
id: EnginePathId;
@@ -31,8 +31,11 @@ export interface EnginePathField {
required: boolean;
}
+/* No entry for the engine library itself: it ships beside PolStudio.exe and is
+ loaded from there, so there was never a path worth asking anyone for — only
+ one that could be set wrong. Weights are different: they are large, they are
+ downloaded separately, and they live wherever the user put them. */
export const ENGINE_PATH_FIELDS: EnginePathField[] = [
- { id: "dllPath", label: "Video engine (vidfab_c.dll)", hint: "The engine library PolStudio loads to render shots.", directory: false, extensions: ["dll"], required: true },
{ id: "transformer", label: "Transformer weights", hint: "The main model that turns your description into moving pictures.", directory: false, extensions: ["safetensors", "gguf", "bin"], required: true },
{ id: "textEncoder", label: "Text encoder weights", hint: "Reads your prompt so the transformer can act on it.", directory: false, extensions: ["safetensors", "gguf", "bin"], required: true },
{ id: "tokenizer", label: "Tokenizer", hint: "Splits your prompt into pieces the text encoder understands. Usually a folder.", directory: true, extensions: [], required: false },
@@ -43,7 +46,7 @@ export const ENGINE_PATH_FIELDS: EnginePathField[] = [
export type EngineSettings = Record<EnginePathId, string>;
export const EMPTY_ENGINE_SETTINGS: EngineSettings = {
- dllPath: "", transformer: "", textEncoder: "", tokenizer: "", videoVae: "", audioVae: "",
+ transformer: "", textEncoder: "", tokenizer: "", videoVae: "", audioVae: "",
};
const ENGINE_KEY = "polstudio.engine-paths.v1";
diff --git a/src/main.tsx b/src/main.tsx
index 0808d9e..1c754d5 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -3,9 +3,19 @@ import ReactDOM from "react-dom/client";
import App from "./App";
import "./styles/index.css";
+/* PolStudio is an application window, not a web page. The browser's own
+ context menu offers Back, Reload, View source and Inspect — none of which
+ mean anything here, and Reload throws away unsaved project edits. Text
+ fields keep theirs: cut/copy/paste/undo are real editing commands, and
+ taking them away would cost the user more than the menu is worth. */
+document.addEventListener("contextmenu", (event) => {
+ const target = event.target as HTMLElement | null;
+ if (target?.closest("input, textarea, [contenteditable='true']")) return;
+ event.preventDefault();
+});
+
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
-
diff --git a/src/styles/base.css b/src/styles/base.css
index b3122d7..d114de6 100644
--- a/src/styles/base.css
+++ b/src/styles/base.css
@@ -83,6 +83,21 @@ select {
color: var(--text-primary);
}
+/* The dropdown list a <select> opens is painted by the platform, not by this
+ stylesheet, and it takes its colours from the select itself. A select with a
+ transparent background got a white menu with grey text on Windows. Both
+ sides are now stated outright, and color-scheme tells the platform which
+ scrollbars and highlight to use inside it. */
+select {
+ color-scheme: dark;
+ background-color: var(--panel-2);
+}
+
+option {
+ color: var(--text-primary);
+ background-color: var(--panel-2);
+}
+
::placeholder {
color: var(--text-faint);
opacity: 1;
diff --git a/src/styles/library.css b/src/styles/library.css
index 3b13d31..729c829 100644
--- a/src/styles/library.css
+++ b/src/styles/library.css
@@ -29,6 +29,17 @@
margin-left: auto;
}
+/* With the rail gone this is the app's only identity mark, so it is sized to
+ read as one rather than as a leftover sidebar badge. Scaled from the
+ transform origin so the artwork's internal proportions are untouched. */
+.library__topbar .brand {
+ height: auto;
+ transform: scale(1.35);
+ transform-origin: left center;
+ /* transform does not affect layout, so the row is told the real width. */
+ margin-right: calc(var(--space-5) + 42px);
+}
+
.library__content {
width: min(var(--content-max), calc(100% - var(--space-9)));
margin: 0 auto;
@@ -67,6 +78,40 @@
.composer-heading {
position: relative;
+ z-index: 1;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ align-items: center;
+ gap: var(--space-3);
+ cursor: pointer;
+ list-style: none;
+}
+
+/* Both engines' default disclosure triangles, replaced by the chevron below. */
+.composer-heading::-webkit-details-marker {
+ display: none;
+}
+
+.composer-heading__chevron {
+ grid-row: 1 / 3;
+ grid-column: 2;
+ flex: 0 0 auto;
+ color: var(--text-muted);
+ transition: transform 0.18s ease;
+}
+
+.composer-shell[open] .composer-heading__chevron {
+ transform: rotate(180deg);
+}
+
+/* Closed, the shell is a single control-height row; the padding that frames a
+ full composer would leave it looking like an empty card. */
+.composer-shell:not([open]) {
+ padding: var(--space-4) var(--space-5);
+}
+
+.composer-shell:not([open]) .composer-heading h2 {
+ margin-bottom: 0;
}
.composer-heading h2 {
diff --git a/src/styles/references.css b/src/styles/references.css
index 00cee64..dad3131 100644
--- a/src/styles/references.css
+++ b/src/styles/references.css
@@ -168,6 +168,50 @@
text-align: center;
}
+/* --- Real reference artwork -------------------------------------------------
+ The picture the user imported, read out of the project folder and shown at
+ the two places that used to display a striped placeholder plate: the library
+ card and the detail pane. `contain` on the card so a portrait and a landscape
+ reference stay comparable; `cover` would crop the subject out of one of them.
+ The striped plate stays as the backdrop, so a transparent PNG still reads. */
+
+.reference-art--photo {
+ padding: 0;
+}
+
+.reference-art--photo img {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+}
+
+.reference-detail-art--photo img {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ /* Clear of the path caption pinned along the bottom. */
+ padding: var(--space-2) var(--space-2) var(--space-7);
+}
+
+/* Loading, or the file is not where the project says it is. Two states, said
+ plainly, rather than one placeholder that could mean either. */
+.reference-image-fallback {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-2);
+ width: 100%;
+ height: 100%;
+ color: var(--text-muted);
+}
+
+.reference-image-fallback em {
+ font-size: var(--text-xs);
+ font-style: normal;
+ line-height: var(--leading-snug);
+}
+
.reference-card__body {
min-width: 0;
display: block;
diff --git a/src/styles/shell.css b/src/styles/shell.css
index e75a003..9813eb7 100644
--- a/src/styles/shell.css
+++ b/src/styles/shell.css
@@ -144,24 +144,24 @@
wrong happens inside a project. It sits above the agent dock, which is why
the dock reserves room for it (see .agent-dock-wrap in workspace.css). */
+/* The gear alone — the word "Settings" told nobody anything the icon did not.
+ Round and a step larger than a normal icon button so it reads as its own
+ thing floating over the corner rather than as part of the row behind it. */
.settings-launcher {
position: fixed;
z-index: 40;
left: var(--space-4);
bottom: var(--space-4);
- min-height: var(--control-sm);
- display: inline-flex;
- align-items: center;
- gap: var(--space-2);
- padding: 0 var(--space-3);
+ width: 44px;
+ height: 44px;
+ display: grid;
+ place-items: center;
+ padding: 0;
border: 1px solid var(--line-strong);
- border-radius: var(--radius-pill);
+ border-radius: 50%;
color: var(--text-muted);
background: rgba(13, 16, 22, 0.92);
backdrop-filter: blur(12px);
- font-size: var(--text-sm);
- font-weight: var(--weight-semibold);
- line-height: var(--leading-snug);
box-shadow: var(--shadow-sm);
transition: 0.16s ease;
}
@@ -401,13 +401,4 @@
align-items: flex-start;
}
- /* The launcher shares the bottom edge with the agent dock on small windows,
- so it drops to the mark alone rather than stacking on top of it. */
- .settings-launcher span {
- display: none;
- }
-
- .settings-launcher {
- padding: 0 var(--space-2);
- }
}
diff --git a/src/styles/timeline.css b/src/styles/timeline.css
index 901bcd0..4b9375b 100644
--- a/src/styles/timeline.css
+++ b/src/styles/timeline.css
@@ -321,8 +321,14 @@
);
}
-/* Import is not wired up yet, so the tile is visibly disabled rather than
- pretending to be a drop target. */
+.media-grid button[draggable="true"] {
+ cursor: grab;
+}
+
+.media-grid button[draggable="true"]:active {
+ cursor: grabbing;
+}
+
.media-grid .media-import {
min-height: 120px;
display: flex;
@@ -333,8 +339,21 @@
color: var(--text-muted);
border-style: dashed;
background: none;
- opacity: 0.65;
- cursor: not-allowed;
+}
+
+.media-grid .media-import:hover:not(:disabled) {
+ color: var(--text-primary);
+ border-color: var(--accent-bright);
+ background: var(--accent-soft);
+}
+
+/* Only in the browser preview, where there is no project folder to copy into. */
+.media-grid .media-import:disabled {
+ opacity: 0.6;
+}
+
+.panel-hint--error {
+ color: var(--danger);
}
.media-import b,
@@ -349,7 +368,11 @@
min-width: 0;
min-height: 0;
display: grid;
- grid-template-rows: var(--control-lg) minmax(0, 1fr) 64px;
+ /* Two rows, not three: the "Program monitor" header is gone (its heading
+ survives for screen readers as .sr-only, which takes no space), and the
+ transport under the video is 44px rather than 64. Every pixel freed here
+ goes to the picture. */
+ grid-template-rows: minmax(0, 1fr) 44px;
background: var(--bg);
}
@@ -417,7 +440,7 @@
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: var(--space-3);
- padding: 0 var(--space-4);
+ padding: 0 var(--space-3);
border-top: 1px solid var(--line);
background: var(--panel);
}
@@ -430,12 +453,12 @@
.monitor-transport > div {
display: flex;
align-items: center;
- gap: var(--space-2);
+ gap: var(--space-1);
}
.monitor-transport button {
- width: var(--control-sm);
- height: var(--control-sm);
+ width: 32px;
+ height: 32px;
display: grid;
place-items: center;
padding: 0;
@@ -451,8 +474,8 @@
}
.monitor-transport .play-button {
- width: var(--control-md);
- height: var(--control-md);
+ width: var(--control-sm);
+ height: var(--control-sm);
color: #fff;
background: var(--accent);
}
@@ -888,6 +911,15 @@
opacity: 0.46;
}
+/* Lit while a compatible media file is held over this lane. A drop target the
+ user cannot see is a drop target the user will not find — and lanes that
+ refuse the file (a sound over a video track, or a locked track) stay dark,
+ so the highlight IS the answer to "can this go here?". */
+.track-lane--drop {
+ background-color: rgba(60, 105, 239, 0.14);
+ box-shadow: inset 0 0 0 1px var(--accent-bright);
+}
+
/* --- Clips ----------------------------------------------------------------- */
.timeline-clip {