From ac9bb359723e4ab37a7f6bdb94f6e3789b99cb61 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:58:03 -0500 Subject: [PATCH 01/11] fix: ask to save changes before a project is replaced or the window closes Open, New, Close Project, Open Recent, templates and the demo project now offer Save, Don't Save or Cancel when the project has unsaved changes, as the demo did already. Closing the desktop window and Quit ask the same before the engine stops. --- frontend/src/app/app.ts | 14 +++++--------- frontend/src/app/ctx.ts | 27 +++++++++++++++++++++++---- frontend/src/app/leave.ts | 29 +++++++++++++++++++++++++++++ frontend/src/ui/native-menu.ts | 2 +- src-tauri/capabilities/default.json | 2 +- 5 files changed, 59 insertions(+), 15 deletions(-) create mode 100644 frontend/src/app/leave.ts diff --git a/frontend/src/app/app.ts b/frontend/src/app/app.ts index de8da00..4f0ab39 100644 --- a/frontend/src/app/app.ts +++ b/frontend/src/app/app.ts @@ -19,8 +19,9 @@ import { TimelinePanel } from '../panels/timeline'; import { TrackerPanel } from '../panels/tracker'; import { editTarget, trackerOptions } from '../panels/tracker-controls'; import { ViewerPanel } from '../panels/viewer'; -import { askSaveChanges, Dialog } from '../ui/dialogs'; +import { Dialog } from '../ui/dialogs'; import { buildDemo, DEMO_NAMES, DEMOS, type DemoId } from './demos'; +import { guardWindowClose, quit } from './leave'; import { Dock, WORKSPACES } from '../ui/dock'; import { el, q, revealApp, setClass, setText } from '../ui/dom'; import { HomeScreen, HOME_PRESETS } from '../ui/home'; @@ -232,6 +233,7 @@ class App { ctx.ui.on('showPanel', (id) => this.showPanel(id)); ctx.ui.on('focusPanel', (id) => this.dock.focus(id)); ctx.start(); + guardWindowClose(ctx); this.formext.onChange = () => { this.extPanel?.render(); this.native?.schedule(0); @@ -595,7 +597,7 @@ class App { ctx.ui.emit('find', String(params.query ?? '')); return; case 'app.quit': - window.close(); + void quit(ctx); return; case 'playback.toggle': void ctx.playback.toggle(); @@ -675,13 +677,7 @@ class App { private async openDemo(id: DemoId): Promise { if (this.demoBusy || !DEMOS.some((dm) => dm.id === id)) return; - const st = ctx.store.state; - if (st?.dirty) { - const name = st.path ? st.path.split(/[\\/]/).pop() ?? 'Untitled Project' : 'Untitled Project'; - const choice = await askSaveChanges(name); - if (choice === 'cancel') return; - if (choice === 'save' && (await ctx.invoke('file.save')) === undefined) return; - } + if (!(await ctx.keepChanges())) return; this.demoBusy = true; toast(`Opening the ${DEMO_NAMES[id]} demo...`); try { diff --git a/frontend/src/app/ctx.ts b/frontend/src/app/ctx.ts index 8cbb20d..c521219 100644 --- a/frontend/src/app/ctx.ts +++ b/frontend/src/app/ctx.ts @@ -4,10 +4,13 @@ import { FrameStream } from '../engine/frames'; import { Playback } from '../engine/playback'; import { Store } from '../engine/store'; import type { CommandSpec, EffectSpec } from '../engine/types'; +import { askSaveChanges } from '../ui/dialogs'; import { pickFiles } from '../ui/file-dialog'; import { commandForm, prefill } from '../ui/forms'; import { toast } from '../ui/toast'; +const REPLACES_PROJECT = new Set(['file.open', 'file.newProject', 'file.closeProject', 'file.openRecent', 'file.openDemoProject', 'templates.create']); + export type ToolId = | 'selection' | 'hand' | 'zoom' | 'rotation' | 'orbit' | 'pan3d' | 'dolly' | 'panBehind' | 'rect' | 'rounded' | 'ellipse' | 'polygon' | 'star' @@ -140,7 +143,22 @@ export class Ctx { this.ui.emit('tool', t); } + async keepChanges(): Promise { + const st = this.store.state; + if (!st?.dirty) return true; + const name = st.path ? st.path.split(/[\\/]/).pop() ?? 'Untitled Project' : 'Untitled Project'; + const choice = await askSaveChanges(name); + if (choice === 'cancel') return false; + if (choice === 'save') return (await this.invoke('file.save')) !== undefined; + return true; + } + async run(command: string, params: Record = {}, quiet = false): Promise { + if (REPLACES_PROJECT.has(command) && !(await this.keepChanges())) return undefined; + return this.runChecked(command, params, quiet); + } + + private async runChecked(command: string, params: Record, quiet = false): Promise { try { return await this.client.exec(command, params); } catch (e) { @@ -160,6 +178,7 @@ export class Ctx { async invoke(command: string, params: Record | null = null): Promise { if (!command) return undefined; + if (REPLACES_PROJECT.has(command) && !(await this.keepChanges())) return undefined; const p: Record = { ...(params || {}) }; const empty = Object.keys(p).length === 0; const picker = PICKERS[command]; @@ -173,15 +192,15 @@ export class Ctx { if (importSpec) { const r = await commandForm(importSpec, { ...p, importAs: 'footage' }); if (!r) return undefined; - return this.run(command, { ...r.params, [picker.key]: p[picker.key] }); + return this.runChecked(command, { ...r.params, [picker.key]: p[picker.key] }); } - return this.run(command === 'file.save' ? 'file.saveAs' : command, p); + return this.runChecked(command === 'file.save' ? 'file.saveAs' : command, p); } const spec = this.specs.get(command); if (empty && spec && FORM_FIRST.has(command)) { const r = await commandForm(spec, prefill(command, this.store.state)); if (!r) return undefined; - return this.run(command, r.params); + return this.runChecked(command, r.params); } if (command === 'renderQueue.render' && p.wait === undefined) { p.wait = false; @@ -193,7 +212,7 @@ export class Ctx { const msg = e instanceof RpcFailure ? e.message : String(e); if (spec && /invalid parameters|missing|required|needs/i.test(msg) && spec.params && spec.params !== '{}') { const r = await commandForm(spec, { ...prefill(command, this.store.state), ...p }); - if (r) return this.run(command, r.params); + if (r) return this.runChecked(command, r.params); return undefined; } toast(msg, 'error'); diff --git a/frontend/src/app/leave.ts b/frontend/src/app/leave.ts new file mode 100644 index 0000000..a90d860 --- /dev/null +++ b/frontend/src/app/leave.ts @@ -0,0 +1,29 @@ +import type { Ctx } from './ctx'; + +const inDesktop = (): boolean => typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window; + +let leaving = false; + +export function guardWindowClose(ctx: Ctx): void { + if (!inDesktop()) return; + void import('@tauri-apps/api/window') + .then(({ getCurrentWindow }) => + getCurrentWindow().onCloseRequested(async (event) => { + if (leaving) return; + if (await ctx.keepChanges()) leaving = true; + else event.preventDefault(); + }), + ) + .catch((e) => console.warn('[formvfx] close guard unavailable', e)); +} + +export async function quit(ctx: Ctx): Promise { + if (!(await ctx.keepChanges())) return; + leaving = true; + if (!inDesktop()) { + window.close(); + return; + } + const { getCurrentWindow } = await import('@tauri-apps/api/window'); + await getCurrentWindow().destroy(); +} diff --git a/frontend/src/ui/native-menu.ts b/frontend/src/ui/native-menu.ts index 05a413f..1c31279 100644 --- a/frontend/src/ui/native-menu.ts +++ b/frontend/src/ui/native-menu.ts @@ -126,7 +126,7 @@ export class NativeMenus { await api.PredefinedMenuItem.new({ item: 'HideOthers' }), await api.PredefinedMenuItem.new({ item: 'ShowAll' }), await sep(), - await api.PredefinedMenuItem.new({ item: 'Quit' }), + await item(`Quit ${this.appName}`, 'Cmd+Q', true, undefined, () => void this.ctx.invoke('app.quit')), ] as never[], }), ]; diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index f2d4feb..fe2f5cb 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -6,5 +6,5 @@ "remote": { "urls": ["http://127.0.0.1:*"] }, - "permissions": ["core:default", "core:window:allow-start-dragging", "core:window:allow-toggle-maximize", "dialog:default", "allow-set-window-title", "allow-app-ready"] + "permissions": ["core:default", "core:window:allow-start-dragging", "core:window:allow-toggle-maximize", "core:window:allow-destroy", "dialog:default", "allow-set-window-title", "allow-app-ready"] } From 5c4039bfedfdd7e3cf3c8d72b4304ed7abe83293 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:15:46 -0500 Subject: [PATCH 02/11] fix: the project tool keeps unsaved changes unless told to discard them new, open, close and demo replace the project and clear its undo history, so they now refuse while it has unsaved changes unless discard is true. A default render output no longer replaces an earlier render of a composition with the same name. --- .../formvfx-harness/references/tools.md | 3 +- .../formvfx-harness/references/tools.md | 3 +- backend/app/agent/tools.py | 23 ++++++++++++-- backend/tests/test_f3_mcp.py | 31 +++++++++++++++++++ 4 files changed, 55 insertions(+), 5 deletions(-) diff --git a/.agents/skills/formvfx-harness/references/tools.md b/.agents/skills/formvfx-harness/references/tools.md index 0420f55..5a9fe87 100644 --- a/.agents/skills/formvfx-harness/references/tools.md +++ b/.agents/skills/formvfx-harness/references/tools.md @@ -217,10 +217,11 @@ Live Link: another app (formcut, an editor, a script) uses a composition as a li ## project -Project files: new, open (path), save (path for the first save), saveAs (path), close. formvfx projects are .fvxproj JSON; projects saved as .ecproj by earlier formvfx releases open as imports. +Project files: new, open (path), save (path for the first save), saveAs (path), close. formvfx projects are .fvxproj JSON; projects saved as .ecproj by earlier formvfx releases open as imports. new, open, close and demo replace the open project and clear its undo history, so they refuse while it has unsaved changes: save first, or pass discard: true only when the person agreed to lose them. - `action`: string (new | open | save | saveAs | close | demo); required - `path`: string +- `discard`: boolean; default false; new, open, close, demo: replace a project that has unsaved changes Note: replaces or removes. diff --git a/.claude/skills/formvfx-harness/references/tools.md b/.claude/skills/formvfx-harness/references/tools.md index 0420f55..5a9fe87 100644 --- a/.claude/skills/formvfx-harness/references/tools.md +++ b/.claude/skills/formvfx-harness/references/tools.md @@ -217,10 +217,11 @@ Live Link: another app (formcut, an editor, a script) uses a composition as a li ## project -Project files: new, open (path), save (path for the first save), saveAs (path), close. formvfx projects are .fvxproj JSON; projects saved as .ecproj by earlier formvfx releases open as imports. +Project files: new, open (path), save (path for the first save), saveAs (path), close. formvfx projects are .fvxproj JSON; projects saved as .ecproj by earlier formvfx releases open as imports. new, open, close and demo replace the open project and clear its undo history, so they refuse while it has unsaved changes: save first, or pass discard: true only when the person agreed to lose them. - `action`: string (new | open | save | saveAs | close | demo); required - `path`: string +- `discard`: boolean; default false; new, open, close, demo: replace a project that has unsaved changes Note: replaces or removes. diff --git a/backend/app/agent/tools.py b/backend/app/agent/tools.py index 9f71289..ed92e8d 100644 --- a/backend/app/agent/tools.py +++ b/backend/app/agent/tools.py @@ -2,6 +2,7 @@ import asyncio import base64 +import glob import json import struct import zlib @@ -52,6 +53,7 @@ } RENDER_WAIT_SECONDS = 600 +REPLACING_ACTIONS = ("new", "open", "close", "demo") RENDER_NEXT = "The render runs in the engine, independent of this call: call wait {timeout} until it is done, or execute renderQueue.list for progress and renderQueue.stop to cancel." PROMPTS = [{"name": "workflow", "title": "How to build in formvfx", "description": "The loop for compositions, layers, animation, effects, looking at the result and rendering.", "arguments": []}] @@ -109,8 +111,8 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = {"comp": _COMP, "format": {"type": "string", "default": "h264"}, "output": {"type": "string"}, "wait": {"type": "boolean", "default": True}}), _tool("dynamic_link", "Live Link: another app (formcut, an editor, a script) uses a composition as a live clip with no render. export writes a .fvxlink descriptor beside the saved project (or at path) naming the project, the comp and the frame and audio URLs; the editor fetches GET /api/link/frame.png?project=&comp=&time= and /api/link/audio with the x-formvfx-local: 1 header, so every saved change shows up on its next frame (the open project serves its unsaved state too). info reads a comp's size, rate and duration from any saved project file, and frame renders one of its frames, both without opening that project in the window. Links survive a moved or renamed project (found again by its project id or file name beside the .fvxlink, in the project's old folder or among recent projects) and a renumbered comp (found again by name). check reads a .fvxlink (path), reports whether it resolves, was relinked, or was written by a newer formvfx, and with write: true rewrites it to the new location; render renders the linked comp to a movie beside the project (Render and Replace for the editor); status lists the projects being served and the recent link requests.", {"action": {"type": "string", "enum": ["export", "info", "frame", "check", "render", "status"]}, "project": {"type": "string", "description": "absolute project path, .fvxproj or .ecproj (default the open project)"}, "comp": _COMP, "path": {"type": "string", "description": "export: where to write the .fvxlink; check and render: the .fvxlink to read"}, "write": {"type": "boolean", "default": False}, "format": {"type": "string", "enum": ["prores", "h264", "hevc", "webm"], "default": "prores"}, "output": {"type": "string"}, "time": _TIME, "max_size": {"type": "integer", "minimum": 64, "maximum": 2048, "default": 960}}, ["action"]), - _tool("project", "Project files: new, open (path), save (path for the first save), saveAs (path), close. formvfx projects are .fvxproj JSON; projects saved as .ecproj by earlier formvfx releases open as imports.", - {"action": {"type": "string", "enum": ["new", "open", "save", "saveAs", "close", "demo"]}, "path": {"type": "string"}}, ["action"], destructive=True), + _tool("project", "Project files: new, open (path), save (path for the first save), saveAs (path), close. formvfx projects are .fvxproj JSON; projects saved as .ecproj by earlier formvfx releases open as imports. new, open, close and demo replace the open project and clear its undo history, so they refuse while it has unsaved changes: save first, or pass discard: true only when the person agreed to lose them.", + {"action": {"type": "string", "enum": ["new", "open", "save", "saveAs", "close", "demo"]}, "path": {"type": "string"}, "discard": {"type": "boolean", "default": False, "description": "new, open, close, demo: replace a project that has unsaved changes"}}, ["action"], destructive=True), _tool("import_files", "Imports footage, images, audio, PSD, SVG, PDF, Lottie or 3D models (absolute paths) into the project; addToComp also places them in the active composition.", {"paths": {"type": "array", "items": {"type": "string"}, "minItems": 1}, "addToComp": {"type": "boolean", "default": False}}, ["paths"]), _tool("run_script", "Runs a JavaScript program against the project (app.project, items.addComp, CompItem, layers.addSolid/addText/addNull/addShape, layer.property('Transform').property('Position').setValueAtTime(t, v), effects through property('Effects').addProperty, File, app.settings, ScriptUI windows). The whole script is one undo step. Returns {ok, result, output (writeLn, alert and $.writeln), error: {message, line}}.", {"code": {"type": "string"}}, ["code"]), @@ -132,6 +134,17 @@ def text(value: Any) -> dict: return {"content": [{"type": "text", "text": body}]} +def _unused_render_path(folder: Path, stem: str, ext: str) -> Path: + def taken(name: str) -> bool: + return (folder / f"{name}.{ext}").exists() or any(folder.glob(f"{glob.escape(name)}_[0-9]*.{ext}")) + + name, n = stem, 1 + while taken(name): + n += 1 + name = f"{stem} {n}" + return folder / f"{name}.{ext}" + + def fail(message: str) -> dict: return {"content": [{"type": "text", "text": message}], "isError": True} @@ -419,7 +432,7 @@ async def _call(name: str, a: dict, source: str) -> dict: ci = await ex("comp.info", _comp_param(a), source) ext = {"h264": "mp4", "hevc": "mp4", "av1": "mp4", "prores": "mov", "webm": "webm", "gif": "gif", "png": "png", "jpeg": "jpg", "tiff": "tif", "exr": "exr", "wav": "wav", "aiff": "aif"}.get(fmt, "mp4") safe = "".join(ch if ch.isalnum() or ch in "-_ " else "_" for ch in str(ci.get("name") or "render")).strip() or "render" - output = str(ensure() / "renders" / f"{safe}.{ext}") + output = str(_unused_render_path(ensure() / "renders", safe, ext)) params["output"] = output added = await ex("renderQueue.add", params, source) started = await ex("renderQueue.render", {"wait": False}, source) @@ -434,6 +447,10 @@ async def _call(name: str, a: dict, source: str) -> dict: p = {"path": path} if path else {} if action in ("open", "saveAs") and not path: return fail(f"{action} needs an absolute path") + if action in REPLACING_ACTIONS and not a.get("discard"): + summary = await ex("project.summary", {}, source) + if summary.get("dirty"): + return fail(f"The open project has unsaved changes, and {action} would replace it with no undo. Save it first (project save), or pass discard: true if the person agreed to lose the changes.") return text({"result": await ex(cmd, p, source), "revision": host.revision}) if name == "import_files": p = {"paths": a.get("paths") or []} diff --git a/backend/tests/test_f3_mcp.py b/backend/tests/test_f3_mcp.py index 3dd0d19..99a27ad 100644 --- a/backend/tests/test_f3_mcp.py +++ b/backend/tests/test_f3_mcp.py @@ -128,3 +128,34 @@ def test_the_render_tool_renders_in_the_background_and_reports_the_output(client body = json.loads(result["content"][0]["text"]) assert body["result"]["results"][0]["ok"] is True, body assert len(list(tmp_path.glob("t_*.png"))) == 5 + + +def test_the_project_tool_keeps_unsaved_changes_unless_told_to_discard(client, tmp_path): + token = {TOKEN_HEADER: inapp_token()} + call = lambda name, args: client.post(MCP_PATH, json={"jsonrpc": "2.0", "id": 11, "method": "tools/call", "params": {"name": name, "arguments": args}}, headers=token).json()["result"] + saved = tmp_path / "kept.fvxproj" + assert not call("project", {"action": "new", "discard": True}).get("isError") + assert not call("project", {"action": "saveAs", "path": str(saved)}).get("isError") + assert not call("execute", {"command": "comp.new", "params": {"name": "Unsaved work"}}).get("isError") + for args in ({"action": "new"}, {"action": "close"}, {"action": "demo"}, {"action": "open", "path": str(saved)}): + refused = call("project", args) + assert refused.get("isError"), args + assert "unsaved changes" in refused["content"][0]["text"] + status = json.loads(call("status", {})["content"][0]["text"]) + assert "Unsaved work" in [c["name"] for c in status["project"]["compositions"]] + assert not call("project", {"action": "open", "path": str(saved), "discard": True}).get("isError") + status = json.loads(call("status", {})["content"][0]["text"]) + assert status["project"]["unsaved"] is False + assert "Unsaved work" not in [c["name"] for c in status["project"]["compositions"]] + + +def test_a_default_render_output_never_replaces_an_earlier_render(tmp_path): + from app.agent.tools import _unused_render_path + + assert _unused_render_path(tmp_path, "Main", "mp4") == tmp_path / "Main.mp4" + (tmp_path / "Main.mp4").write_bytes(b"earlier") + assert _unused_render_path(tmp_path, "Main", "mp4") == tmp_path / "Main 2.mp4" + (tmp_path / "Main 2.mp4").write_bytes(b"earlier") + assert _unused_render_path(tmp_path, "Main", "mp4") == tmp_path / "Main 3.mp4" + (tmp_path / "Seq_00001.png").write_bytes(b"frame") + assert _unused_render_path(tmp_path, "Seq", "png") == tmp_path / "Seq 2.png" From 99e8bd86fe8b8450dfbd8a85c65cb5613183ad8a Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:15:46 -0500 Subject: [PATCH 03/11] fix: render H.264 and HEVC with an encoder the installed FFmpeg has Movie renders pick libx264 or libx265 when present and otherwise a platform encoder (VideoToolbox, Media Foundation, OpenH264, NVENC, QSV, AMF), so the LGPL FFmpeg build renders the default format. Encoder names match whole words. A render never writes over footage the project uses. --- backend/tests/test_render.py | 12 +++++ native/fvx-core/src/engine/rq.rs | 92 ++++++++++++++++++++++++++++---- 2 files changed, 95 insertions(+), 9 deletions(-) diff --git a/backend/tests/test_render.py b/backend/tests/test_render.py index 86531fc..4fe559d 100644 --- a/backend/tests/test_render.py +++ b/backend/tests/test_render.py @@ -217,3 +217,15 @@ def test_a_background_render_keeps_its_results_for_polling(core, tmp_path): time.sleep(0.05) assert finished and finished[0]["ok"] is True, listing assert len(list(tmp_path.glob("f_*.png"))) == FRAMES + + +@needs_ffmpeg +def test_a_render_never_writes_over_footage_the_project_uses(core, tmp_path): + build(core) + source = tmp_path / "voice.wav" + queue(core, "wav", source) + before = source.read_bytes() + core.run("file.import", paths=[str(source)]) + result = queue(core, "wav", source) + assert source.read_bytes() == before + assert "footage this project uses" in json.dumps(result) diff --git a/native/fvx-core/src/engine/rq.rs b/native/fvx-core/src/engine/rq.rs index cc1d936..592d032 100644 --- a/native/fvx-core/src/engine/rq.rs +++ b/native/fvx-core/src/engine/rq.rs @@ -811,9 +811,28 @@ fn encoders() -> &'static String { E.get_or_init(|| Command::new(media::tool("ffmpeg")).args(["-hide_banner", "-encoders"]).output().map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default()) } +const H264_ENCODERS: [&str; 7] = ["libx264", "h264_videotoolbox", "h264_mf", "libopenh264", "h264_nvenc", "h264_qsv", "h264_amf"]; +const HEVC_ENCODERS: [&str; 6] = ["libx265", "hevc_videotoolbox", "hevc_mf", "hevc_nvenc", "hevc_qsv", "hevc_amf"]; +const AV1_ENCODERS: [&str; 3] = ["libsvtav1", "libaom-av1", "librav1e"]; + +fn first_listed(listing: &str, names: &[&'static str]) -> Option<&'static str> { + names.iter().copied().find(|n| listing.lines().any(|l| l.split_whitespace().nth(1) == Some(*n))) +} + fn av1_encoder() -> Option<&'static str> { - let e = encoders(); - ["libsvtav1", "libaom-av1", "librav1e"].into_iter().find(|n| e.contains(n)) + first_listed(encoders(), &AV1_ENCODERS) +} + +fn source_at(project: &Project, output: &str) -> Option { + let out = std::fs::canonicalize(output).ok()?; + project.items.iter().find_map(|it| match &it.kind { + ItemKind::Footage(f) if !f.path.is_empty() && std::fs::canonicalize(&f.path).ok().as_ref() == Some(&out) => Some(f.path.clone()), + _ => None, + }) +} + +fn bitrate_kbps(w: usize, h: usize, fps: f64, q: f64, bits_per_pixel: f64) -> u64 { + ((w * h) as f64 * fps.max(1.0) * bits_per_pixel * (0.35 + 0.65 * q) / 1000.0).round().max(500.0) as u64 } fn ext80(v: f64) -> [u8; 10] { @@ -1105,6 +1124,11 @@ fn open_writer(m: &OutputModule, path: String, r: &Renderer, comp: &Comp, comp_i _ => has_audio, }; let mono = m.audio_channels == "mono"; + if !is_seq(&m.format) + && let Some(src) = source_at(project, &path) + { + return Err(format!("{path} is footage this project uses ({src}); choose another output file")); + } if is_audio(&m.format) { let frames = ((span.1 - span.0) * m.sample_rate as f64) as usize; let pcm = audio::mix_comp(project, media, comp_id, span.0, frames, m.sample_rate); @@ -1162,13 +1186,20 @@ fn open_writer(m: &OutputModule, path: String, r: &Renderer, comp: &Comp, comp_i }; match m.format.as_str() { "h264" => { - cmd.args(["-vf", &pad, "-c:v", "libx264", "-preset", "medium"]); - rate(&mut cmd, 14.0, 32.0); + let enc = first_listed(encoders(), &H264_ENCODERS).ok_or("this FFmpeg has no H.264 encoder (libx264, h264_videotoolbox, h264_mf, libopenh264, h264_nvenc, h264_qsv or h264_amf)")?; + cmd.args(["-vf", &pad, "-c:v", enc]); + if enc == "libx264" { + cmd.args(["-preset", "medium"]); + rate(&mut cmd, 14.0, 32.0); + } else { + let kbps = if m.bitrate > 0 { m.bitrate as u64 } else { bitrate_kbps(w2, h2, fps, q, 0.15) }; + cmd.args(["-b:v", &format!("{kbps}k"), "-maxrate", &format!("{}k", kbps * 3 / 2), "-bufsize", &format!("{}k", kbps * 2)]); + } cmd.args(["-pix_fmt", "yuv420p", "-movflags", "+faststart"]); - if m.profile == "high" { + if m.profile == "high" && enc != "libopenh264" { cmd.args(["-profile:v", "high"]); } - if interlaced { + if interlaced && enc == "libx264" { cmd.args(["-flags", "+ildct+ilme"]); } if wr.wav.is_some() { @@ -1176,9 +1207,19 @@ fn open_writer(m: &OutputModule, path: String, r: &Renderer, comp: &Comp, comp_i } } "hevc" => { - cmd.args(["-vf", &pad, "-c:v", "libx265"]); - rate(&mut cmd, 16.0, 34.0); - cmd.args(["-pix_fmt", if deep { "yuv420p10le" } else { "yuv420p" }, "-tag:v", "hvc1"]); + let enc = first_listed(encoders(), &HEVC_ENCODERS).ok_or("this FFmpeg has no HEVC encoder (libx265, hevc_videotoolbox, hevc_mf, hevc_nvenc, hevc_qsv or hevc_amf)")?; + cmd.args(["-vf", &pad, "-c:v", enc]); + if enc == "libx265" { + rate(&mut cmd, 16.0, 34.0); + } else { + let kbps = if m.bitrate > 0 { m.bitrate as u64 } else { bitrate_kbps(w2, h2, fps, q, 0.1) }; + cmd.args(["-b:v", &format!("{kbps}k"), "-maxrate", &format!("{}k", kbps * 3 / 2), "-bufsize", &format!("{}k", kbps * 2)]); + } + let ten_bit = match enc { + "libx265" => "yuv420p10le", + _ => "p010le", + }; + cmd.args(["-pix_fmt", if deep { ten_bit } else { "yuv420p" }, "-tag:v", "hvc1"]); if wr.wav.is_some() { aac(&mut cmd); } @@ -1426,3 +1467,36 @@ fn write_log(it: &RenderItem, cname: &str, lines: &[String], err: Option<&str>) let safe: String = cname.chars().map(|c| if c.is_alphanumeric() || c == ' ' || c == '-' || c == '_' { c } else { '_' }).collect(); let _ = std::fs::write(dir.join(format!("{safe} Render Log.txt")), text); } + +#[cfg(test)] +mod encoder_tests { + use super::*; + + const LGPL_MAC: &str = " V....D h264_videotoolbox VideoToolbox H.264 Encoder (codec h264)\n V....D hevc_videotoolbox VideoToolbox H.265 Encoder (codec hevc)\n V....D libvpx-vp9 libvpx VP9 (codec vp9)\n A....D aac AAC (Advanced Audio Coding)\n"; + const FULL: &str = " V....D libx264 libx264 H.264 / AVC (codec h264)\n V....D libx264rgb libx264 H.264 RGB (codec h264)\n V....D h264_videotoolbox VideoToolbox H.264 Encoder (codec h264)\n V....D libx265 libx265 H.265 / HEVC (codec hevc)\n"; + + #[test] + fn h264_and_hevc_fall_back_to_an_encoder_the_ffmpeg_has() { + assert_eq!(first_listed(FULL, &H264_ENCODERS), Some("libx264")); + assert_eq!(first_listed(FULL, &HEVC_ENCODERS), Some("libx265")); + assert_eq!(first_listed(LGPL_MAC, &H264_ENCODERS), Some("h264_videotoolbox")); + assert_eq!(first_listed(LGPL_MAC, &HEVC_ENCODERS), Some("hevc_videotoolbox")); + assert_eq!(first_listed(LGPL_MAC, &AV1_ENCODERS), None); + assert_eq!(first_listed("", &H264_ENCODERS), None); + } + + #[test] + fn an_encoder_name_matches_only_as_a_whole_word() { + let listing = " V....D libx264rgb libx264 H.264 RGB (codec h264)\n"; + assert_eq!(first_listed(listing, &H264_ENCODERS), None); + } + + #[test] + fn the_bitrate_follows_size_rate_and_quality() { + let low = bitrate_kbps(1920, 1080, 30.0, 0.0, 0.15); + let high = bitrate_kbps(1920, 1080, 30.0, 1.0, 0.15); + assert!(low < high); + assert!(bitrate_kbps(16, 16, 1.0, 0.5, 0.15) >= 500); + assert!(bitrate_kbps(3840, 2160, 30.0, 0.8, 0.15) > bitrate_kbps(1920, 1080, 30.0, 0.8, 0.15)); + } +} From 9c5c3b002a364bd97fd01b82ab2e690a068355e3 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:15:46 -0500 Subject: [PATCH 04/11] fix: open footage in its default app on Windows without the command interpreter Edit Original starts explorer with the quoted path, so a file name with & or ^ stays one file name. --- native/fvx-core/src/engine/cmd/editing.rs | 28 ++++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/native/fvx-core/src/engine/cmd/editing.rs b/native/fvx-core/src/engine/cmd/editing.rs index 3bb3d87..c628549 100644 --- a/native/fvx-core/src/engine/cmd/editing.rs +++ b/native/fvx-core/src/engine/cmd/editing.rs @@ -928,17 +928,29 @@ pub fn edit_original(e: &mut Engine, p: &Json) -> Res { if std::env::var_os("FORMVFX_NO_REVEAL").is_some() || pb(p, "dryRun").unwrap_or(false) { return Ok(json!({"path": f, "opened": false})); } - let spawned = if cfg!(target_os = "macos") { - std::process::Command::new("open").arg(&f).spawn() - } else if cfg!(target_os = "windows") { - std::process::Command::new("cmd").args(["/C", "start", "", &f]).spawn() - } else { - std::process::Command::new("xdg-open").arg(&f).spawn() - }; - spawned.map_err(|x| format!("could not open {f}: {x}"))?; + open_in_default_app(&f).map_err(|x| format!("could not open {f}: {x}"))?; Ok(json!({"path": f, "opened": true})) } +#[cfg(target_os = "windows")] +fn open_in_default_app(f: &str) -> std::io::Result { + use std::os::windows::process::CommandExt; + if f.contains('"') || f.chars().any(char::is_control) { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "the file name has a character Windows cannot pass on")); + } + std::process::Command::new("explorer").raw_arg(format!("\"{f}\"")).spawn() +} + +#[cfg(target_os = "macos")] +fn open_in_default_app(f: &str) -> std::io::Result { + std::process::Command::new("open").arg(f).spawn() +} + +#[cfg(not(any(target_os = "windows", target_os = "macos")))] +fn open_in_default_app(f: &str) -> std::io::Result { + std::process::Command::new("xdg-open").arg(f).spawn() +} + fn work_area_edit(e: &mut Engine, p: &Json, extract: bool) -> Res { let (cid, ids) = e.layers_param(p)?; let c = e.project.comp(cid).ok_or("no composition")?; From 89f5be381192e22312d08f8dc54a09db9d2e0f06 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:15:46 -0500 Subject: [PATCH 05/11] fix: keep auto-save copies and recent projects apart between projects and engines Auto-save copies in a shared folder carry a tag from the project id, so same-named and untitled projects no longer number or prune each other's copies. Recent lists are re-read before each change and written in one step, and Live Link engines no longer add to them. --- backend/app/engine/link.py | 2 +- backend/tests/test_f6_project.py | 59 +++++++++++++++++++ native/fvx-core/src/engine/cmd/session.rs | 71 ++++++++++++++++------- native/fvx-core/src/py.rs | 7 ++- 4 files changed, 114 insertions(+), 25 deletions(-) diff --git a/backend/app/engine/link.py b/backend/app/engine/link.py index 3e87c5a..52609b6 100644 --- a/backend/app/engine/link.py +++ b/backend/app/engine/link.py @@ -108,7 +108,7 @@ def _run(self) -> None: engine = failed = None try: - engine = native.module().Engine() + engine = native.module().Engine(recent=False) except BaseException as exc: failed = exc while True: diff --git a/backend/tests/test_f6_project.py b/backend/tests/test_f6_project.py index 3194428..8fdddb2 100644 --- a/backend/tests/test_f6_project.py +++ b/backend/tests/test_f6_project.py @@ -1,4 +1,6 @@ import json +import os +from pathlib import Path import pytest @@ -84,3 +86,60 @@ def test_a_file_that_is_not_a_project_is_refused_and_changes_nothing(core, tmp_p bad.write_text("{ not json", encoding="utf-8") assert core.fails("file.open", path=str(bad)) assert canonical(core) == before + + +def test_auto_save_copies_of_same_named_projects_in_one_folder_stay_apart(core, tmp_path): + shared = tmp_path / "Auto-Save" + core.run("prefs.set", key="autoSave.folder", value=str(shared)) + core.run("prefs.set", key="autoSave.versions", value=2) + try: + copies = {} + for client in ("clientA", "clientB"): + core.run("file.newProject") + core.comp(f"Intro for {client}") + (tmp_path / client).mkdir() + core.run("file.saveAs", path=str(tmp_path / client / "intro.fvxproj")) + core.solid("Change") + core.run("file.autoSave") + core.run("file.autoSave") + copies[client] = core.run("file.recoveryInfo")["copies"] + assert len(copies[client]) == 2 + assert not set(copies["clientA"]) & set(copies["clientB"]) + for path in copies["clientA"] + copies["clientB"]: + assert Path(path).is_file() + core.run("file.newProject") + core.comp("Untitled one") + core.run("file.autoSave") + untitled = core.run("file.recoveryInfo")["copies"] + core.run("file.newProject") + core.comp("Untitled two") + core.run("file.autoSave") + assert not set(untitled) & set(core.run("file.recoveryInfo")["copies"]) + assert all(Path(path).is_file() for path in untitled) + finally: + core.run("prefs.set", key="autoSave.folder", value="") + core.run("prefs.set", key="autoSave.versions", value=5) + + +def recent_projects(): + store = Path(os.environ.get("FORMVFX_DATA") or Path(os.environ["HOME"]) / ".formvfx") / "recent.json" + return json.loads(store.read_text(encoding="utf-8"))["projects"] if store.is_file() else [] + + +def test_two_engines_keep_each_others_recent_projects_and_a_side_engine_adds_none(core, tmp_path): + import fvx_core + + paths = [] + for name in ("first", "second", "linked"): + core.run("file.newProject") + core.comp(name) + paths.append(str(tmp_path / f"{name}.fvxproj")) + core.run("file.saveAs", path=paths[-1]) + first, second = Core(), Core() + first.run("file.open", path=paths[0]) + second.run("file.open", path=paths[1]) + assert recent_projects()[:2] == [paths[1], paths[0]] + before = recent_projects() + side = fvx_core.Engine(recent=False) + side.execute("file.open", json.dumps({"path": paths[2]})) + assert recent_projects() == before diff --git a/native/fvx-core/src/engine/cmd/session.rs b/native/fvx-core/src/engine/cmd/session.rs index 0fe61dc..729d621 100644 --- a/native/fvx-core/src/engine/cmd/session.rs +++ b/native/fvx-core/src/engine/cmd/session.rs @@ -30,6 +30,7 @@ pub struct Session { pub last_effect: Option, pub effect_clip: Vec, pub param_shortcuts: Vec<(String, String, Json)>, + pub private: bool, } fn store() -> PathBuf { @@ -40,16 +41,33 @@ pub fn clock() -> f64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0) } +fn stored_lists() -> (Vec, Vec) { + let j: Json = std::fs::read_to_string(store()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Json::Null); + let list = |k: &str| -> Vec { j.get(k).and_then(Json::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).take(KEEP).collect()).unwrap_or_default() }; + (list("projects"), list("footage")) +} + impl Session { pub fn load() -> Session { - let j: Json = std::fs::read_to_string(store()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Json::Null); - let list = |k: &str| -> Vec { j.get(k).and_then(Json::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).take(KEEP).collect()).unwrap_or_default() }; - Session { recent_projects: list("projects"), recent_footage: list("footage"), ..Session::default() } + let (recent_projects, recent_footage) = stored_lists(); + Session { recent_projects, recent_footage, ..Session::default() } } - fn save(&self) { + fn change(&mut self, f: impl FnOnce(&mut Session)) { + if self.private { + f(self); + return; + } + (self.recent_projects, self.recent_footage) = stored_lists(); + f(self); let _ = std::fs::create_dir_all(data_dir()); - let _ = std::fs::write(store(), serde_json::to_string_pretty(&json!({"projects": self.recent_projects, "footage": self.recent_footage})).unwrap_or_default()); + let body = serde_json::to_string_pretty(&json!({"projects": self.recent_projects, "footage": self.recent_footage})).unwrap_or_default(); + static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = store().with_extension(format!("json.{}.{n}.tmp", std::process::id())); + if std::fs::write(&tmp, body).is_ok() && std::fs::rename(&tmp, store()).is_err() { + let _ = std::fs::remove_file(&tmp); + } } } @@ -60,16 +78,16 @@ fn push(list: &mut Vec, path: &str) { } pub fn note_project(e: &mut Engine, path: &str) { - push(&mut e.session.recent_projects, path); e.session.autosave.mark = clock(); - e.session.save(); + e.session.change(|s| push(&mut s.recent_projects, path)); } pub fn note_footage(e: &mut Engine, paths: &[String]) { - for p in paths.iter().rev() { - push(&mut e.session.recent_footage, p); - } - e.session.save(); + e.session.change(|s| { + for p in paths.iter().rev() { + push(&mut s.recent_footage, p); + } + }); } fn pick(list: &[String], p: &Json, what: &str) -> Result { @@ -83,8 +101,7 @@ fn pick(list: &[String], p: &Json, what: &str) -> Result { pub fn open_recent(e: &mut Engine, p: &Json) -> Res { let path = pick(&e.session.recent_projects, p, "projects")?; if !Path::new(&path).is_file() { - e.session.recent_projects.retain(|x| *x != path); - e.session.save(); + e.session.change(|s| s.recent_projects.retain(|x| *x != path)); return Err(format!("{path} is no longer there; it is taken off Open Recent")); } super::file::open(e, &json!({"path": path})) @@ -93,24 +110,27 @@ pub fn open_recent(e: &mut Engine, p: &Json) -> Res { pub fn import_recent(e: &mut Engine, p: &Json) -> Res { let path = pick(&e.session.recent_footage, p, "footage")?; if !Path::new(&path).exists() { - e.session.recent_footage.retain(|x| *x != path); - e.session.save(); + e.session.change(|s| s.recent_footage.retain(|x| *x != path)); return Err(format!("{path} is no longer there; it is taken off Import Recent Footage")); } super::file::import(e, &json!({"paths": [path]})) } pub fn clear_recent(e: &mut Engine, _: &Json) -> Res { - let n = e.session.recent_projects.len(); - e.session.recent_projects.clear(); - e.session.save(); + let mut n = 0; + e.session.change(|s| { + n = s.recent_projects.len(); + s.recent_projects.clear(); + }); Ok(json!({"cleared": n})) } pub fn clear_recent_footage(e: &mut Engine, _: &Json) -> Res { - let n = e.session.recent_footage.len(); - e.session.recent_footage.clear(); - e.session.save(); + let mut n = 0; + e.session.change(|s| { + n = s.recent_footage.len(); + s.recent_footage.clear(); + }); Ok(json!({"cleared": n})) } @@ -194,7 +214,14 @@ fn folder(e: &Engine) -> PathBuf { } fn stem(e: &Engine) -> String { - e.path.as_deref().and_then(|p| Path::new(p).file_stem()).and_then(|s| s.to_str()).unwrap_or("Untitled Project").to_string() + let name = e.path.as_deref().and_then(|p| Path::new(p).file_stem()).and_then(|s| s.to_str()).unwrap_or("Untitled Project"); + let custom = pref(e, "autoSave.folder").as_str().is_some_and(|s| !s.trim().is_empty()); + if !custom && e.path.is_some() { + return name.to_string(); + } + let key = if e.project.uid.is_empty() { e.path.as_deref().unwrap_or("") } else { e.project.uid.as_str() }; + let tag = key.bytes().fold(0x811c_9dc5_u32, |h, b| (h ^ b as u32).wrapping_mul(0x0100_0193)); + format!("{name} {tag:08x}") } fn versions(e: &Engine) -> Vec<(u64, PathBuf)> { diff --git a/native/fvx-core/src/py.rs b/native/fvx-core/src/py.rs index 16eb27e..902abc3 100644 --- a/native/fvx-core/src/py.rs +++ b/native/fvx-core/src/py.rs @@ -29,8 +29,11 @@ pub struct Engine { #[pymethods] impl Engine { #[new] - fn new() -> Self { - Engine { e: engine::Engine::new(), gesture: 0 } + #[pyo3(signature = (recent = true))] + fn new(recent: bool) -> Self { + let mut e = engine::Engine::new(); + e.session.private = !recent; + Engine { e, gesture: 0 } } fn execute(&mut self, py: Python<'_>, id: &str, params: &str) -> PyResult { From dd3521dbfed01e87bd5247016bcc02a544ba4e1f Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:15:46 -0500 Subject: [PATCH 06/11] fix: start Windows .cmd agent shims without the command interpreter An npm style shim is followed to the node script or program it starts. Any other .cmd or .bat refuses words cmd.exe would misread: control characters, percent signs, quote marks, and & | < > ^ ( ) ! in a word that is not quoted. Shared finder 1.0.2. --- backend/app/agent/agent_lookup.py | 57 ++++++++++++++++++++++++++-- backend/app/routers/terminal.py | 2 +- backend/tests/test_agent_programs.py | 54 ++++++++++++++++++++++++++ setup/agents.py | 2 +- 4 files changed, 109 insertions(+), 6 deletions(-) diff --git a/backend/app/agent/agent_lookup.py b/backend/app/agent/agent_lookup.py index ea34eba..f3b8896 100644 --- a/backend/app/agent/agent_lookup.py +++ b/backend/app/agent/agent_lookup.py @@ -24,9 +24,9 @@ import threading import time from dataclasses import dataclass, field -from pathlib import Path +from pathlib import Path, PureWindowsPath -VERSION = "1.0.1" +VERSION = "1.0.2" PROGRAMS: dict = { "claude": {"title": "Claude Code", "names": ("claude",), "setting": "claudeBin", "install": "curl -fsSL https://claude.ai/install.sh | bash", "install_windows": "irm https://claude.ai/install.ps1 | iex", @@ -359,13 +359,62 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +class UnsafeArgument(ValueError): + """A word that the Windows command interpreter would read as something other than one plain argument.""" + + +_SHIM_TARGET = re.compile(r'"%~?dp0%?\\?([^"%\r\n]+?\.(?:js|cjs|mjs|exe))"', re.I) +_CONTROL = re.compile(r"[\x00-\x1f\x7f]") +_CMD_SPECIAL = frozenset('&|<>^()!') + + +def shim_target(shim: str | os.PathLike, env: dict | None = None) -> list[str] | None: + """The program an npm style .cmd shim starts, as words to run without the command interpreter: the .exe it names, or + node (the one beside the shim, else node on PATH) and the script it names. None when the shim is of another kind.""" + env = os.environ if env is None else env + try: + with open(shim, encoding="utf-8", errors="replace") as f: + text = f.read(65536) + except OSError: + return None + found = [f for f in _SHIM_TARGET.findall(text) if PureWindowsPath(f).name.lower() != "node.exe"] + if not found: + return None + folder = Path(shim).parent + target = folder.joinpath(*PureWindowsPath(found[-1]).parts) + if not target.is_file(): + return None + if target.suffix.lower() == ".exe": + return [str(target)] + beside = folder / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH")) + return [node, str(target)] if node else None + + +def cmd_safe(words: list[str]) -> list[str]: + """Words for `cmd.exe /c`, refused when one has a control character (a newline among them), a percent sign or a quote + mark, or a command interpreter character in a word that will not be quoted (only a word with a space or a tab is).""" + for word in words: + quoted = word == "" or " " in word or "\t" in word + if _CONTROL.search(word) or "%" in word or '"' in word or (not quoted and _CMD_SPECIAL & set(word)): + raise UnsafeArgument("This text cannot be passed to the program through the Windows command interpreter (it has a line break, " + "a quote mark, a percent sign or one of & | < > ^ ( ) !). Install the program's own .exe, or leave those out.") + return words + + def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]: """How a program is started, the same for a tab, Chat and a check: through the person's login shell on macOS and Linux - (exec, so the process is the program), directly on Windows with the command interpreter in front of a .cmd or .bat.""" + (exec, so the process is the program), directly on Windows. A .cmd shim is followed to the program it starts; any other + .cmd or .bat goes through the command interpreter, which takes only words it cannot misread.""" words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words + if not words[0].lower().endswith((".cmd", ".bat")): + return words + direct = shim_target(words[0], env) if words[0].lower().endswith(".cmd") else None + if direct: + return [*direct, *words[1:]] + return [env.get("COMSPEC") or "cmd.exe", "/c", *cmd_safe(words)] shell = login_shell(env, platform) fish = Path(shell).name == "fish" return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] diff --git a/backend/app/routers/terminal.py b/backend/app/routers/terminal.py index b0b4a1c..3284e30 100644 --- a/backend/app/routers/terminal.py +++ b/backend/app/routers/terminal.py @@ -79,7 +79,7 @@ async def open_claude(request: Request) -> dict: try: session = await _off(terminals.open_claude, _base(request), str(body.get("prompt") or ""), str(body.get("resume") or ""), cols, rows) return session.describe() - except terminals.NotInstalled as e: + except (terminals.NotInstalled, ValueError) as e: raise HTTPException(400, str(e)) from e diff --git a/backend/tests/test_agent_programs.py b/backend/tests/test_agent_programs.py index 023443e..aa31b5b 100644 --- a/backend/tests/test_agent_programs.py +++ b/backend/tests/test_agent_programs.py @@ -98,3 +98,57 @@ def test_connecting_antigravity_writes_one_entry_and_keeps_the_rest(tmp_path, mo assert connect.install(["antigravity"])[1].endswith("has a server named formvfx that formvfx did not write; left alone") assert json.loads(cfg.read_text(encoding="utf-8"))["mcpServers"]["formvfx"] == {"command": "/elsewhere/tool", "args": ["serve"]} assert connect.install(["nope"]) == ["unknown client nope (claude, codex, cursor or antigravity)"] + + +NPM_SHIM = ( + '@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\n' + 'IF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\n' + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@scope\\agent\\{target}" %*\r\n' +) + + +def _shim(tmp_path, target): + from app.agent import agent_lookup + + folder = tmp_path / "npm" + script = folder.joinpath("node_modules", "@scope", "agent", *target.split("/")) + script.parent.mkdir(parents=True) + script.write_text("", encoding="utf-8") + (folder / "node.exe").write_bytes(b"") + shim = folder / "claude.cmd" + shim.write_text(NPM_SHIM.replace("{target}", target.replace("/", "\\")), encoding="utf-8") + return agent_lookup, folder, shim, script + + +def test_a_windows_npm_shim_runs_its_script_with_node_and_no_command_interpreter(tmp_path): + agent_lookup, folder, shim, script = _shim(tmp_path, "cli.js") + prompt = 'Fix the title\n\n[context: composition "a" & b %PATH%]' + argv = agent_lookup.start_argv([str(shim), "-p", prompt, "--verbose"], {"PATH": ""}, "win32") + assert argv == [str(folder / "node.exe"), str(script), "-p", prompt, "--verbose"] + + +def test_a_windows_npm_shim_for_a_program_runs_that_program(tmp_path): + agent_lookup, _folder, shim, exe = _shim(tmp_path, "bin/claude.exe") + assert agent_lookup.start_argv([str(shim), "--version"], {"PATH": ""}, "win32") == [str(exe), "--version"] + + +@pytest.mark.parametrize("word", ["two\nlines", "carriage\rreturn", "tab\tand\x7f", "50%", "%USERPROFILE%", 'say "hi"', "a&b", "x|y", "in Date: Sun, 29 Nov 2026 09:20:50 -0500 Subject: [PATCH 07/11] test: New Project asks before unsaved changes are replaced --- frontend/tests/window/test_window.py | 51 ++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/frontend/tests/window/test_window.py b/frontend/tests/window/test_window.py index b377943..d065880 100644 --- a/frontend/tests/window/test_window.py +++ b/frontend/tests/window/test_window.py @@ -1,3 +1,4 @@ +import contextlib import os import shutil import socket @@ -48,8 +49,8 @@ def free_port(): return s.getsockname()[1] -@pytest.fixture(scope="module") -def engine(): +@contextlib.contextmanager +def started_engine(): assert (DIST / "index.html").is_file(), f"build the window first: {DIST} has no index.html (npm run build)" port = free_port() sandbox = Path(tempfile.mkdtemp(prefix=f"{APP_ID}-window-")) @@ -82,6 +83,18 @@ def engine(): shutil.rmtree(sandbox, ignore_errors=True) +@pytest.fixture(scope="module") +def engine(): + with started_engine() as base: + yield base + + +@pytest.fixture +def own_engine(): + with started_engine() as base: + yield base + + def ignored(url): return any(part in url for part in IGNORED_REQUESTS) @@ -115,3 +128,37 @@ def test_window_loads_throttled_without_shift_errors_or_refusals(engine, path): assert not failed, f"failed requests: {failed}" assert not errors, f"console errors: {errors}" assert cls <= CLS_LIMIT, f"layout shift {cls}: {shifts}" + + + +def post(base, path, body, extra=None): + import json + + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), method="POST", headers={"x-formvfx-local": "1", "content-type": "application/json", **(extra or {})}) + with urllib.request.urlopen(req, timeout=30) as r: + return json.loads(r.read().decode("utf-8") or "null") + + +def test_new_project_asks_before_unsaved_changes_are_replaced(own_engine): + engine = own_engine + from playwright.sync_api import sync_playwright + + key = post(engine, "/api/window/key", {})["key"] + run = lambda command, params: post(engine, "/api/rpc", {"jsonrpc": "2.0", "id": 1, "method": "command.execute", "params": {"command": command, "params": params}}, {"x-formvfx-window-key": key})["result"] + with sync_playwright() as p: + browser = p.chromium.launch() + page = browser.new_page(viewport={"width": 1440, "height": 900}) + page.add_init_script(f"window.__FORMVFX_WINDOW_KEY = {key!r};") + page.goto(engine + "/", wait_until="load", timeout=120_000) + page.wait_for_load_state("networkidle", timeout=120_000) + run("comp.new", {"name": "Unsaved work"}) + page.wait_for_timeout(1000) + page.keyboard.press("Meta+Alt+N" if sys.platform == "darwin" else "Control+Alt+N") + dialog = page.locator(".cv-savechanges") + dialog.wait_for(state="visible", timeout=10_000) + dialog.get_by_role("button", name="Cancel").click() + page.wait_for_timeout(500) + summary = run("project.summary", {}) + browser.close() + assert summary["dirty"] is True + assert "Unsaved work" in [i["name"] for i in summary["items"]] From f53b42b9acc4cb8e0bc18c84b18a2c8eb10eeaf7 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 10:02:55 -0500 Subject: [PATCH 08/11] fix: treat every spelling of a Windows batch file alike and keep its quoting intact A .cmd or .bat named with another case, trailing dots or spaces, or a stream suffix goes through the same checks. When the program's own path needs quotes, cmd /c drops the outer quote marks, so then no word may need quotes or carry a command interpreter character. --- backend/app/agent/agent_lookup.py | 34 ++++++++++++++++++++++------ backend/tests/test_agent_programs.py | 23 +++++++++++++++++++ setup/agents.py | 2 +- 3 files changed, 51 insertions(+), 8 deletions(-) diff --git a/backend/app/agent/agent_lookup.py b/backend/app/agent/agent_lookup.py index f3b8896..73c5943 100644 --- a/backend/app/agent/agent_lookup.py +++ b/backend/app/agent/agent_lookup.py @@ -391,14 +391,34 @@ def shim_target(shim: str | os.PathLike, env: dict | None = None) -> list[str] | return [node, str(target)] if node else None +def _quoted(word: str) -> bool: + return word == "" or " " in word or "\t" in word + + +def _windows_name(program: str) -> str: + return str(program).lower().rstrip(" .").removesuffix("::$data").rstrip(" .") + + +def is_batch(program: str) -> bool: + """Whether Windows runs this file through the command interpreter: a .cmd or .bat, in any case, also with the trailing dots, + spaces or ::$DATA stream name that Windows drops from a file name.""" + return _windows_name(program).endswith((".cmd", ".bat")) + + def cmd_safe(words: list[str]) -> list[str]: """Words for `cmd.exe /c`, refused when one has a control character (a newline among them), a percent sign or a quote - mark, or a command interpreter character in a word that will not be quoted (only a word with a space or a tab is).""" - for word in words: - quoted = word == "" or " " in word or "\t" in word - if _CONTROL.search(word) or "%" in word or '"' in word or (not quoted and _CMD_SPECIAL & set(word)): + mark, or a command interpreter character in a word that will not be quoted (only a word with a space or a tab is). + When the program path itself is quoted and more quote marks follow, `cmd /c` drops the first and the last quote mark of + the line, so then no word may need quotes or carry a command interpreter character.""" + program_quoted = _quoted(words[0]) + for i, word in enumerate(words): + quoted = _quoted(word) + special = bool(_CMD_SPECIAL & set(word)) + if (_CONTROL.search(word) or "%" in word or '"' in word or (special and (program_quoted or not quoted)) + or (program_quoted and i and quoted)): raise UnsafeArgument("This text cannot be passed to the program through the Windows command interpreter (it has a line break, " - "a quote mark, a percent sign or one of & | < > ^ ( ) !). Install the program's own .exe, or leave those out.") + "a quote mark, a percent sign or one of & | < > ^ ( ) !, or the program's folder has a space). " + "Install the program's own .exe, or leave those out.") return words @@ -409,9 +429,9 @@ def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - if not words[0].lower().endswith((".cmd", ".bat")): + if not is_batch(words[0]): return words - direct = shim_target(words[0], env) if words[0].lower().endswith(".cmd") else None + direct = shim_target(words[0], env) if _windows_name(words[0]).endswith(".cmd") else None if direct: return [*direct, *words[1:]] return [env.get("COMSPEC") or "cmd.exe", "/c", *cmd_safe(words)] diff --git a/backend/tests/test_agent_programs.py b/backend/tests/test_agent_programs.py index aa31b5b..9fa5437 100644 --- a/backend/tests/test_agent_programs.py +++ b/backend/tests/test_agent_programs.py @@ -152,3 +152,26 @@ def test_the_windows_command_interpreter_still_takes_plain_and_quoted_words(tmp_ other = tmp_path / "custom.cmd" other.write_text("@echo off\r\nrun.exe %*\r\n", encoding="utf-8") assert agent_lookup.start_argv([str(other), "plain"], {"COMSPEC": "cmd.exe"}, "win32") == ["cmd.exe", "/c", str(other), "plain"] + + +@pytest.mark.parametrize("ending", [".CMD", ".bat.", ".cmd ", ".Bat::$DATA"]) +def test_every_spelling_of_a_batch_file_goes_through_the_same_checks(tmp_path, ending): + from app.agent import agent_lookup + + batch = tmp_path / "agent.bat" + batch.write_text("@echo off\r\n", encoding="utf-8") + with pytest.raises(agent_lookup.UnsafeArgument): + agent_lookup.start_argv([str(batch)[:-4] + ending, "-p", "a&b"], {"COMSPEC": "cmd.exe"}, "win32") + + +@pytest.mark.parametrize("word", ["fade in & out", "two words", "plain&joined"]) +def test_a_batch_file_in_a_folder_with_a_space_takes_only_words_that_need_no_quotes(tmp_path, word): + from app.agent import agent_lookup + + folder = tmp_path / "Program Files" + folder.mkdir() + batch = folder / "agent.bat" + batch.write_text("@echo off\r\n", encoding="utf-8") + with pytest.raises(agent_lookup.UnsafeArgument): + agent_lookup.start_argv([str(batch), "-p", word], {"COMSPEC": "cmd.exe"}, "win32") + assert agent_lookup.start_argv([str(batch), "--version"], {"COMSPEC": "cmd.exe"}, "win32") == ["cmd.exe", "/c", str(batch), "--version"] diff --git a/setup/agents.py b/setup/agents.py index 15333b6..2c53a84 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -33,7 +33,7 @@ DOCK = {"present": True, "positions": ["bottom", "right"], "tabs": ["chat", "terminal", "claude-code", "codex", "cursor", "antigravity"]} DOCK_FOLDER = ROOT / "frontend" / "src" / "dock" LOOKUP = ROOT / "backend" / "app" / "agent" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "db4c79e81046e040dd626e8b132169976e83faee194102db3bb5c29e3ec5e3bc"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "a706029f18c33a18de27220d80218ac40638ee13c563f92b00a2bc60a38e5db7"} ORDER = ["file", "edit", "project", "item", "footage", "comp", "layer", "prop", "keys", "anim", "time", "markers", "effect", "mask", "path", "paths", "shape", "text", "camera", "light", "material", "track", "warp", "roto", "paint", "puppet", "liquify", "contentFill", "face", "essential", "expr", "script", "scriptui", "render", "renderQueue", "playback", "view", "window", "editor", "scopes", "cache", "jobs", From 339c7dfa2148a1eb177e735ece0a34774a51fd8a Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 10:04:17 -0500 Subject: [PATCH 09/11] fix: execute and batch keep unsaved changes like the project tool Commands that replace the open project, run through execute or inside a batch, refuse while it has unsaved changes unless discard is true. --- .../formvfx-harness/references/tools.md | 6 ++-- .../formvfx-harness/references/tools.md | 6 ++-- backend/app/agent/tools.py | 31 ++++++++++++++----- backend/tests/test_f3_mcp.py | 10 ++++-- 4 files changed, 38 insertions(+), 15 deletions(-) diff --git a/.agents/skills/formvfx-harness/references/tools.md b/.agents/skills/formvfx-harness/references/tools.md index 5a9fe87..5da4376 100644 --- a/.agents/skills/formvfx-harness/references/tools.md +++ b/.agents/skills/formvfx-harness/references/tools.md @@ -37,10 +37,11 @@ Note: read-only. ## execute -Runs one formvfx command by id with its parameters (see describe_command) and returns its result. Undoable commands are one step in the person's History. +Runs one formvfx command by id with its parameters (see describe_command) and returns its result. Undoable commands are one step in the person's History. Commands that replace the open project (file.newProject, file.open, file.closeProject, file.openRecent, file.openDemoProject, templates.create) refuse while it has unsaved changes unless discard is true. - `command`: string; required - `params`: object; The command's parameters. +- `discard`: boolean; default false; replace an open project that has unsaved changes ## batch @@ -49,6 +50,7 @@ Runs several commands as one undo step. Each step is {command, params}; a string - `steps`: array; required - `label`: string - `atomic`: boolean; default true +- `discard`: boolean; default false; replace an open project that has unsaved changes ## get_comp @@ -221,7 +223,7 @@ Project files: new, open (path), save (path for the first save), saveAs (path), - `action`: string (new | open | save | saveAs | close | demo); required - `path`: string -- `discard`: boolean; default false; new, open, close, demo: replace a project that has unsaved changes +- `discard`: boolean; default false; replace an open project that has unsaved changes Note: replaces or removes. diff --git a/.claude/skills/formvfx-harness/references/tools.md b/.claude/skills/formvfx-harness/references/tools.md index 5a9fe87..5da4376 100644 --- a/.claude/skills/formvfx-harness/references/tools.md +++ b/.claude/skills/formvfx-harness/references/tools.md @@ -37,10 +37,11 @@ Note: read-only. ## execute -Runs one formvfx command by id with its parameters (see describe_command) and returns its result. Undoable commands are one step in the person's History. +Runs one formvfx command by id with its parameters (see describe_command) and returns its result. Undoable commands are one step in the person's History. Commands that replace the open project (file.newProject, file.open, file.closeProject, file.openRecent, file.openDemoProject, templates.create) refuse while it has unsaved changes unless discard is true. - `command`: string; required - `params`: object; The command's parameters. +- `discard`: boolean; default false; replace an open project that has unsaved changes ## batch @@ -49,6 +50,7 @@ Runs several commands as one undo step. Each step is {command, params}; a string - `steps`: array; required - `label`: string - `atomic`: boolean; default true +- `discard`: boolean; default false; replace an open project that has unsaved changes ## get_comp @@ -221,7 +223,7 @@ Project files: new, open (path), save (path for the first save), saveAs (path), - `action`: string (new | open | save | saveAs | close | demo); required - `path`: string -- `discard`: boolean; default false; new, open, close, demo: replace a project that has unsaved changes +- `discard`: boolean; default false; replace an open project that has unsaved changes Note: replaces or removes. diff --git a/backend/app/agent/tools.py b/backend/app/agent/tools.py index ed92e8d..3ec5cff 100644 --- a/backend/app/agent/tools.py +++ b/backend/app/agent/tools.py @@ -54,6 +54,7 @@ RENDER_WAIT_SECONDS = 600 REPLACING_ACTIONS = ("new", "open", "close", "demo") +REPLACING_COMMANDS = frozenset({"file.newProject", "file.open", "file.closeProject", "file.openRecent", "file.openDemoProject", "templates.create"}) RENDER_NEXT = "The render runs in the engine, independent of this call: call wait {timeout} until it is done, or execute renderQueue.list for progress and renderQueue.stop to cancel." PROMPTS = [{"name": "workflow", "title": "How to build in formvfx", "description": "The loop for compositions, layers, animation, effects, looking at the result and rendering.", "arguments": []}] @@ -71,16 +72,18 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = } +_DISCARD = {"type": "boolean", "default": False, "description": "replace an open project that has unsaved changes"} + TOOLS = [ _tool("status", "Start here. The open project (path, unsaved changes), the active composition (id, name, size, frame rate, duration, layer count, current time), the selection, background jobs, how many formvfx windows are watching, the engine and the extension it saves projects with, and the command and effect counts.", {}, read=True, idempotent=True), _tool("list_commands", "formvfx's commands (every menu item, button and drag is one): id, label, menu path, parameter summary, enabled now. Filter by text or namespace (layer, comp, keys, effect, mask, text, shape, camera, track, renderQueue, view, file...).", {"filter": {"type": "string"}, "namespace": {"type": "string"}, "enabledOnly": {"type": "boolean", "default": False}, "limit": {"type": "integer", "minimum": 1, "maximum": 1000, "default": 200}}, read=True, idempotent=True), _tool("describe_command", "One command in full: label, menu, parameter documentation and JSON Schema, whether it is undoable and enabled now.", {"command": {"type": "string"}}, ["command"], read=True, idempotent=True), - _tool("execute", "Runs one formvfx command by id with its parameters (see describe_command) and returns its result. Undoable commands are one step in the person's History.", - {"command": {"type": "string"}, "params": {"type": "object", "description": "The command's parameters.", "additionalProperties": True}}, ["command"]), + _tool("execute", "Runs one formvfx command by id with its parameters (see describe_command) and returns its result. Undoable commands are one step in the person's History. Commands that replace the open project (file.newProject, file.open, file.closeProject, file.openRecent, file.openDemoProject, templates.create) refuse while it has unsaved changes unless discard is true.", + {"command": {"type": "string"}, "params": {"type": "object", "description": "The command's parameters.", "additionalProperties": True}, "discard": _DISCARD}, ["command"]), _tool("batch", "Runs several commands as one undo step. Each step is {command, params}; a string \"$N.key\" in a later step's params is replaced by step N's result field, counting steps from 1, e.g. {\"layer\": \"$1.layer\"} is the layer the first step made. atomic (default true) undoes everything if one step fails.", {"steps": {"type": "array", "items": {"type": "object", "properties": {"command": {"type": "string"}, "params": {"type": "object", "additionalProperties": True}}, "required": ["command"]}, "minItems": 1, "maxItems": 500}, - "label": {"type": "string", "maxLength": 120}, "atomic": {"type": "boolean", "default": True}}, ["steps"]), + "label": {"type": "string", "maxLength": 120}, "atomic": {"type": "boolean", "default": True}, "discard": _DISCARD}, ["steps"]), _tool("get_comp", "A composition: size, frame rate, duration, work area, background, and its layers top to bottom (id, index, name, type, in and out points, start, stretch, switches, blend mode, parent, track matte). With flowchart, also the Flowchart graph: nodes (comps, footage, solids, layers, effects with their depth) and edges from each comp or layer to what it uses, nested comps followed.", {"comp": _COMP, "flowchart": {"type": "boolean", "default": False}}, read=True, idempotent=True), _tool("get_layer", "A layer's property tree: every property with its path (use it in set_property and set_keyframes), value at the time, keyframes and expression; masks, effects and text included.", {"layer": _LAYER, "comp": _COMP, "depth": {"type": "integer", "minimum": 1, "maximum": 32, "default": 16}, "time": _TIME}, ["layer"], read=True, idempotent=True), @@ -112,7 +115,7 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = _tool("dynamic_link", "Live Link: another app (formcut, an editor, a script) uses a composition as a live clip with no render. export writes a .fvxlink descriptor beside the saved project (or at path) naming the project, the comp and the frame and audio URLs; the editor fetches GET /api/link/frame.png?project=&comp=&time= and /api/link/audio with the x-formvfx-local: 1 header, so every saved change shows up on its next frame (the open project serves its unsaved state too). info reads a comp's size, rate and duration from any saved project file, and frame renders one of its frames, both without opening that project in the window. Links survive a moved or renamed project (found again by its project id or file name beside the .fvxlink, in the project's old folder or among recent projects) and a renumbered comp (found again by name). check reads a .fvxlink (path), reports whether it resolves, was relinked, or was written by a newer formvfx, and with write: true rewrites it to the new location; render renders the linked comp to a movie beside the project (Render and Replace for the editor); status lists the projects being served and the recent link requests.", {"action": {"type": "string", "enum": ["export", "info", "frame", "check", "render", "status"]}, "project": {"type": "string", "description": "absolute project path, .fvxproj or .ecproj (default the open project)"}, "comp": _COMP, "path": {"type": "string", "description": "export: where to write the .fvxlink; check and render: the .fvxlink to read"}, "write": {"type": "boolean", "default": False}, "format": {"type": "string", "enum": ["prores", "h264", "hevc", "webm"], "default": "prores"}, "output": {"type": "string"}, "time": _TIME, "max_size": {"type": "integer", "minimum": 64, "maximum": 2048, "default": 960}}, ["action"]), _tool("project", "Project files: new, open (path), save (path for the first save), saveAs (path), close. formvfx projects are .fvxproj JSON; projects saved as .ecproj by earlier formvfx releases open as imports. new, open, close and demo replace the open project and clear its undo history, so they refuse while it has unsaved changes: save first, or pass discard: true only when the person agreed to lose them.", - {"action": {"type": "string", "enum": ["new", "open", "save", "saveAs", "close", "demo"]}, "path": {"type": "string"}, "discard": {"type": "boolean", "default": False, "description": "new, open, close, demo: replace a project that has unsaved changes"}}, ["action"], destructive=True), + {"action": {"type": "string", "enum": ["new", "open", "save", "saveAs", "close", "demo"]}, "path": {"type": "string"}, "discard": _DISCARD}, ["action"], destructive=True), _tool("import_files", "Imports footage, images, audio, PSD, SVG, PDF, Lottie or 3D models (absolute paths) into the project; addToComp also places them in the active composition.", {"paths": {"type": "array", "items": {"type": "string"}, "minItems": 1}, "addToComp": {"type": "boolean", "default": False}}, ["paths"]), _tool("run_script", "Runs a JavaScript program against the project (app.project, items.addComp, CompItem, layers.addSolid/addText/addNull/addShape, layer.property('Transform').property('Position').setValueAtTime(t, v), effects through property('Effects').addProperty, File, app.settings, ScriptUI windows). The whole script is one undo step. Returns {ok, result, output (writeLn, alert and $.writeln), error: {message, line}}.", {"code": {"type": "string"}}, ["code"]), @@ -145,6 +148,15 @@ def taken(name: str) -> bool: return folder / f"{name}.{ext}" +async def _keeps_changes(what: str, a: dict, source: str) -> dict | None: + if a.get("discard") is True: + return None + summary = await ex("project.summary", {}, source) + if not summary.get("dirty"): + return None + return fail(f"The open project has unsaved changes, and {what} would replace it with no undo. Save it first (project save), or pass discard: true if the person agreed to lose the changes.") + + def fail(message: str) -> dict: return {"content": [{"type": "text", "text": message}], "isError": True} @@ -262,9 +274,14 @@ async def _call(name: str, a: dict, source: str) -> dict: if name == "describe_command": return text(await ex("command.describe", {"command": a.get("command")}, source)) if name == "execute": + if isinstance(a.get("command"), str) and a["command"] in REPLACING_COMMANDS and (refused := await _keeps_changes(str(a["command"]), a, source)): + return refused result = await ex(a.get("command", ""), a.get("params") or {}, source) return text({"result": result, "revision": host.revision}) if name == "batch": + replacing = [st.get("command") for st in a.get("steps") or [] if isinstance(st, dict) and isinstance(st.get("command"), str) and st["command"] in REPLACING_COMMANDS] + if replacing and (refused := await _keeps_changes(str(replacing[0]), a, source)): + return refused args = {"steps": a.get("steps") or [], "atomic": a.get("atomic", True)} if a.get("label"): args["label"] = a["label"] @@ -447,10 +464,8 @@ async def _call(name: str, a: dict, source: str) -> dict: p = {"path": path} if path else {} if action in ("open", "saveAs") and not path: return fail(f"{action} needs an absolute path") - if action in REPLACING_ACTIONS and not a.get("discard"): - summary = await ex("project.summary", {}, source) - if summary.get("dirty"): - return fail(f"The open project has unsaved changes, and {action} would replace it with no undo. Save it first (project save), or pass discard: true if the person agreed to lose the changes.") + if action in REPLACING_ACTIONS and (refused := await _keeps_changes(action, a, source)): + return refused return text({"result": await ex(cmd, p, source), "revision": host.revision}) if name == "import_files": p = {"paths": a.get("paths") or []} diff --git a/backend/tests/test_f3_mcp.py b/backend/tests/test_f3_mcp.py index 99a27ad..701926d 100644 --- a/backend/tests/test_f3_mcp.py +++ b/backend/tests/test_f3_mcp.py @@ -137,9 +137,13 @@ def test_the_project_tool_keeps_unsaved_changes_unless_told_to_discard(client, t assert not call("project", {"action": "new", "discard": True}).get("isError") assert not call("project", {"action": "saveAs", "path": str(saved)}).get("isError") assert not call("execute", {"command": "comp.new", "params": {"name": "Unsaved work"}}).get("isError") - for args in ({"action": "new"}, {"action": "close"}, {"action": "demo"}, {"action": "open", "path": str(saved)}): - refused = call("project", args) - assert refused.get("isError"), args + attempts = [("project", args) for args in ({"action": "new"}, {"action": "close"}, {"action": "demo"}, {"action": "open", "path": str(saved)})] + attempts += [("execute", {"command": "file.newProject"}), ("execute", {"command": "file.open", "params": {"path": str(saved)}}), + ("execute", {"command": "file.openRecent", "params": {"index": 0}}), ("execute", {"command": "file.closeProject", "discard": "yes"}), + ("batch", {"steps": [{"command": "comp.new", "params": {}}, {"command": "file.newProject"}]})] + for name, args in attempts: + refused = call(name, args) + assert refused.get("isError"), (name, args) assert "unsaved changes" in refused["content"][0]["text"] status = json.loads(call("status", {})["content"][0]["text"]) assert "Unsaved work" in [c["name"] for c in status["project"]["compositions"]] From 63b7271499e63b3d4392ff66cbc05dc61a8d6e94 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 10:09:10 -0500 Subject: [PATCH 10/11] fix: compare render outputs with footage by file identity and keep Edit Original to media A render output is matched against every footage, sequence frame and proxy file the project uses by device and inode (by the resolved path, ignoring case, on Windows), so a link, a case change or a .. step finds the same file. Image sequence frames are checked as they are written. Edit Original declines program and script files. --- backend/tests/test_render.py | 22 ++++++++- native/fvx-core/src/engine/cmd/editing.rs | 29 ++++++++++++ native/fvx-core/src/engine/rq.rs | 58 ++++++++++++++++++----- 3 files changed, 96 insertions(+), 13 deletions(-) diff --git a/backend/tests/test_render.py b/backend/tests/test_render.py index 4fe559d..72a1d07 100644 --- a/backend/tests/test_render.py +++ b/backend/tests/test_render.py @@ -226,6 +226,24 @@ def test_a_render_never_writes_over_footage_the_project_uses(core, tmp_path): queue(core, "wav", source) before = source.read_bytes() core.run("file.import", paths=[str(source)]) - result = queue(core, "wav", source) - assert source.read_bytes() == before + alias = tmp_path / "alias.wav" + alias.symlink_to(source) + spellings = [source, alias, tmp_path / "sub" / ".." / "voice.wav"] + if (tmp_path / "VOICE.wav").exists(): + spellings.append(tmp_path / "VOICE.wav") + for output in spellings: + result = queue(core, "wav", output) + assert source.read_bytes() == before, output + assert "footage this project uses" in json.dumps(result), output + + +@needs_ffmpeg +def test_an_image_sequence_render_never_writes_over_frames_the_project_uses(core, tmp_path): + build(core) + queue(core, "png", tmp_path / "plate_[#####].png") + frame = tmp_path / "plate_00002.png" + before = frame.read_bytes() + core.run("file.import", paths=[str(frame)]) + result = queue(core, "png", tmp_path / "plate_[#####].png") + assert frame.read_bytes() == before assert "footage this project uses" in json.dumps(result) diff --git a/native/fvx-core/src/engine/cmd/editing.rs b/native/fvx-core/src/engine/cmd/editing.rs index c628549..9dfcbe6 100644 --- a/native/fvx-core/src/engine/cmd/editing.rs +++ b/native/fvx-core/src/engine/cmd/editing.rs @@ -925,6 +925,9 @@ pub fn edit_original(e: &mut Engine, p: &Json) -> Res { if !Path::new(&f).exists() { return Err(format!("{f} is missing")); } + if runs_as_program(&f) { + return Err(format!("{f} is a program or script, not media; open it yourself if you mean to run it")); + } if std::env::var_os("FORMVFX_NO_REVEAL").is_some() || pb(p, "dryRun").unwrap_or(false) { return Ok(json!({"path": f, "opened": false})); } @@ -932,6 +935,17 @@ pub fn edit_original(e: &mut Engine, p: &Json) -> Res { Ok(json!({"path": f, "opened": true})) } +const PROGRAM_ENDINGS: [&str; 26] = [ + "exe", "com", "bat", "cmd", "scr", "pif", "cpl", "msi", "msc", "ps1", "vbs", "vbe", "js", "jse", "wsf", "wsh", "hta", "lnk", "url", "reg", "jar", "app", "command", "tool", "sh", "workflow", +]; + +fn runs_as_program(f: &str) -> bool { + let lower = f.to_ascii_lowercase(); + let name = lower.trim_end_matches([' ', '.']); + let name = name.strip_suffix("::$data").unwrap_or(name).trim_end_matches([' ', '.']); + Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| PROGRAM_ENDINGS.contains(&e)) +} + #[cfg(target_os = "windows")] fn open_in_default_app(f: &str) -> std::io::Result { use std::os::windows::process::CommandExt; @@ -1709,3 +1723,18 @@ pub fn scene_edit_detection(e: &mut Engine, p: &Json) -> Res { Ok(apply) }) } + +#[cfg(test)] +mod edit_original_tests { + use super::runs_as_program; + + #[test] + fn programs_and_scripts_are_not_opened_as_media() { + for f in ["C:\\clips\\run.cmd", "C:\\clips\\RUN.BAT", "C:\\clips\\tool.exe.", "C:\\clips\\tool.exe ", "C:\\clips\\x.ps1::$DATA", "/clips/Thing.app", "/clips/go.command"] { + assert!(runs_as_program(f), "{f}"); + } + for f in ["C:\\clips\\Tom&Jerry.mp4", "/clips/voice.wav", "/clips/plate.exr", "/clips/anim.json", "/clips/noext"] { + assert!(!runs_as_program(f), "{f}"); + } + } +} diff --git a/native/fvx-core/src/engine/rq.rs b/native/fvx-core/src/engine/rq.rs index 592d032..31beb15 100644 --- a/native/fvx-core/src/engine/rq.rs +++ b/native/fvx-core/src/engine/rq.rs @@ -823,12 +823,42 @@ fn av1_encoder() -> Option<&'static str> { first_listed(encoders(), &AV1_ENCODERS) } -fn source_at(project: &Project, output: &str) -> Option { - let out = std::fs::canonicalize(output).ok()?; - project.items.iter().find_map(|it| match &it.kind { - ItemKind::Footage(f) if !f.path.is_empty() && std::fs::canonicalize(&f.path).ok().as_ref() == Some(&out) => Some(f.path.clone()), - _ => None, - }) +fn file_id(path: &Path) -> Option { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let m = std::fs::metadata(path).ok()?; + Some(format!("{}:{}", m.dev(), m.ino())) + } + #[cfg(not(unix))] + { + std::fs::canonicalize(path).ok().map(|c| c.to_string_lossy().to_lowercase()) + } +} + +fn used_files(project: &Project) -> Vec<(String, String)> { + let mut out = vec![]; + for it in &project.items { + let ItemKind::Footage(f) = &it.kind else { continue }; + let proxy = it.proxy.as_ref().map(|p| &p.footage); + for f in std::iter::once(f).chain(proxy) { + for p in std::iter::once(&f.path).chain(f.sequence.iter()).filter(|p| !p.is_empty()) { + if let Some(id) = file_id(Path::new(p)) { + out.push((id, p.clone())); + } + } + } + } + out +} + +fn source_at(used: &[(String, String)], output: &str) -> Option { + let id = file_id(Path::new(output))?; + used.iter().find(|(u, _)| *u == id).map(|(_, p)| p.clone()) +} + +fn overwrites_source(path: &str, src: &str) -> String { + format!("{path} is footage this project uses ({src}); choose another output file") } fn bitrate_kbps(w: usize, h: usize, fps: f64, q: f64, bits_per_pixel: f64) -> u64 { @@ -974,6 +1004,7 @@ struct Writer { sink: Sink, skip_existing: bool, wav: Option, + used: Vec<(String, String)>, } impl Writer { @@ -1036,6 +1067,10 @@ impl Writer { if let Some(dir) = t { path = Path::new(dir).join(Path::new(&path).file_name().unwrap_or_default()).to_string_lossy().to_string(); } + if let Some(src) = source_at(&self.used, &path) { + last = overwrites_source(&path, &src); + continue; + } let r = write_still(&self.m, &shown, &path, premul); match r { Ok(()) => return Ok(()), @@ -1116,7 +1151,8 @@ fn open_writer(m: &OutputModule, path: String, r: &Renderer, comp: &Comp, comp_i if let Some(dir) = Path::new(&path).parent() { let _ = std::fs::create_dir_all(dir); } - let mut wr = Writer { m: m.clone(), path: path.clone(), proc, bg, sink: Sink::Seq, skip_existing, wav: None }; + let used = used_files(project); + let mut wr = Writer { m: m.clone(), path: path.clone(), proc, bg, sink: Sink::Seq, skip_existing, wav: None, used: vec![] }; let has_audio = audio::comp_has_audio(project, comp_id); let wants_audio = match m.audio.as_str() { "off" => false, @@ -1124,10 +1160,10 @@ fn open_writer(m: &OutputModule, path: String, r: &Renderer, comp: &Comp, comp_i _ => has_audio, }; let mono = m.audio_channels == "mono"; - if !is_seq(&m.format) - && let Some(src) = source_at(project, &path) - { - return Err(format!("{path} is footage this project uses ({src}); choose another output file")); + if is_seq(&m.format) { + wr.used = used; + } else if let Some(src) = source_at(&used, &path) { + return Err(overwrites_source(&path, &src)); } if is_audio(&m.format) { let frames = ((span.1 - span.0) * m.sample_rate as f64) as usize; From 674e0db80f79674f8b487cefbca612e1c92460d2 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:55:50 -0500 Subject: [PATCH 11/11] fix: refuse command interpreter characters in every Windows batch file argument When a .cmd or .bat still has to start through cmd.exe, any argument with & | < > ^ ( ) ! % a quote mark or a control character is refused, with or without spaces, and the message points to standard input or a file for long text. The program path takes ( ) only when quoted. npm style shims keep starting their script or program directly. --- backend/app/agent/agent_lookup.py | 32 ++++++++++++-------- backend/tests/test_agent_programs.py | 45 ++++++++++++++++++++++++---- setup/agents.py | 2 +- 3 files changed, 59 insertions(+), 20 deletions(-) diff --git a/backend/app/agent/agent_lookup.py b/backend/app/agent/agent_lookup.py index 73c5943..e23fc88 100644 --- a/backend/app/agent/agent_lookup.py +++ b/backend/app/agent/agent_lookup.py @@ -366,6 +366,7 @@ class UnsafeArgument(ValueError): _SHIM_TARGET = re.compile(r'"%~?dp0%?\\?([^"%\r\n]+?\.(?:js|cjs|mjs|exe))"', re.I) _CONTROL = re.compile(r"[\x00-\x1f\x7f]") _CMD_SPECIAL = frozenset('&|<>^()!') +_CMD_TEXT = _CMD_SPECIAL | frozenset('%"') def shim_target(shim: str | os.PathLike, env: dict | None = None) -> list[str] | None: @@ -406,19 +407,24 @@ def is_batch(program: str) -> bool: def cmd_safe(words: list[str]) -> list[str]: - """Words for `cmd.exe /c`, refused when one has a control character (a newline among them), a percent sign or a quote - mark, or a command interpreter character in a word that will not be quoted (only a word with a space or a tab is). - When the program path itself is quoted and more quote marks follow, `cmd /c` drops the first and the last quote mark of - the line, so then no word may need quotes or carry a command interpreter character.""" - program_quoted = _quoted(words[0]) - for i, word in enumerate(words): - quoted = _quoted(word) - special = bool(_CMD_SPECIAL & set(word)) - if (_CONTROL.search(word) or "%" in word or '"' in word or (special and (program_quoted or not quoted)) - or (program_quoted and i and quoted)): - raise UnsafeArgument("This text cannot be passed to the program through the Windows command interpreter (it has a line break, " - "a quote mark, a percent sign or one of & | < > ^ ( ) !, or the program's folder has a space). " - "Install the program's own .exe, or leave those out.") + """Words for `cmd.exe /c`. The batch file reads its arguments again (%*), and the command interpreter acts on + & | < > ^ ( ) ! % and quote marks even inside quotes, so any argument with one of them, or with a control character, + is refused whether or not it has a space. The program path may hold ( ) only when it is quoted (it has a space), and + then no argument may need quotes either, because `cmd /c` drops the first and the last quote mark of such a line.""" + program = words[0] + program_quoted = _quoted(program) + allowed = frozenset("()") if program_quoted else frozenset() + if _CONTROL.search(program) or set(program) & (_CMD_SPECIAL - allowed) or "%" in program or '"' in program: + raise UnsafeArgument("This program cannot be started through the Windows command interpreter from its folder (the path " + "has a control character, a quote mark, a percent sign or one of & | < > ^ ( ) !). " + "Install the program's own .exe, or move it to a plain folder.") + for word in words[1:]: + if _CONTROL.search(word) or set(word) & _CMD_TEXT or (program_quoted and _quoted(word)): + raise UnsafeArgument("This text cannot be passed to the program through the Windows command interpreter (it has a " + "line break or other control character, a quote mark, a percent sign or one of & | < > ^ ( ) !, " + "or the program's folder has a space and the text needs quotes). Pass long text through standard " + "input or a file if the program takes it that way, install the program's own .exe, or leave " + "those characters out.") return words diff --git a/backend/tests/test_agent_programs.py b/backend/tests/test_agent_programs.py index 9fa5437..e8e4691 100644 --- a/backend/tests/test_agent_programs.py +++ b/backend/tests/test_agent_programs.py @@ -132,28 +132,61 @@ def test_a_windows_npm_shim_for_a_program_runs_that_program(tmp_path): assert agent_lookup.start_argv([str(shim), "--version"], {"PATH": ""}, "win32") == [str(exe), "--version"] -@pytest.mark.parametrize("word", ["two\nlines", "carriage\rreturn", "tab\tand\x7f", "50%", "%USERPROFILE%", 'say "hi"', "a&b", "x|y", "inin", "up^", "(group)", "bang!"] + + +@pytest.mark.parametrize("word", CMD_REFUSED + [f"fade in {c} out" for c in "&|<>^()!%\""]) def test_the_windows_command_interpreter_gets_no_word_it_could_misread(tmp_path, word): from app.agent import agent_lookup batch = tmp_path / "agent.bat" batch.write_text("@echo off\r\n", encoding="utf-8") - with pytest.raises(agent_lookup.UnsafeArgument): + with pytest.raises(agent_lookup.UnsafeArgument, match="standard input or a file"): agent_lookup.start_argv([str(batch), "-p", word], {"COMSPEC": "cmd.exe"}, "win32") -def test_the_windows_command_interpreter_still_takes_plain_and_quoted_words(tmp_path): +def test_the_windows_command_interpreter_still_takes_plain_words(tmp_path): from app.agent import agent_lookup batch = tmp_path / "agent.bat" batch.write_text("@echo off\r\n", encoding="utf-8") - words = [str(batch), "-p", "fade in & out", "--flag", "", "C:/Program Files (x86)/x"] + words = [str(batch), "-p", "fade in and out", "--flag", "", "C:/Projects/title one.fvxproj"] assert agent_lookup.start_argv(words, {"COMSPEC": "cmd.exe"}, "win32") == ["cmd.exe", "/c", *words] other = tmp_path / "custom.cmd" other.write_text("@echo off\r\nrun.exe %*\r\n", encoding="utf-8") assert agent_lookup.start_argv([str(other), "plain"], {"COMSPEC": "cmd.exe"}, "win32") == ["cmd.exe", "/c", str(other), "plain"] +def test_a_cmd_file_that_is_not_an_npm_shim_still_gets_the_strict_checks(tmp_path): + from app.agent import agent_lookup + + other = tmp_path / "custom.cmd" + other.write_text("@echo off\r\nrun.exe %*\r\n", encoding="utf-8") + with pytest.raises(agent_lookup.UnsafeArgument): + agent_lookup.start_argv([str(other), "-p", "a & b"], {"COMSPEC": "cmd.exe"}, "win32") + + +def test_an_npm_shim_with_a_missing_script_falls_back_to_the_strict_checks(tmp_path): + agent_lookup, _folder, shim, script = _shim(tmp_path, "cli.js") + script.unlink() + with pytest.raises(agent_lookup.UnsafeArgument): + agent_lookup.start_argv([str(shim), "-p", "50%"], {"COMSPEC": "cmd.exe", "PATH": ""}, "win32") + assert agent_lookup.start_argv([str(shim), "--version"], {"COMSPEC": "cmd.exe", "PATH": ""}, "win32") == ["cmd.exe", "/c", str(shim), "--version"] + + +@pytest.mark.parametrize("folder", ["a&b", "up^", "bang!", "50%", "par(en)"]) +def test_a_batch_file_in_a_folder_the_command_interpreter_could_misread_is_refused(tmp_path, folder): + from app.agent import agent_lookup + + place = tmp_path / folder + place.mkdir() + batch = place / "agent.bat" + batch.write_text("@echo off\r\n", encoding="utf-8") + with pytest.raises(agent_lookup.UnsafeArgument): + agent_lookup.start_argv([str(batch), "--version"], {"COMSPEC": "cmd.exe"}, "win32") + + @pytest.mark.parametrize("ending", [".CMD", ".bat.", ".cmd ", ".Bat::$DATA"]) def test_every_spelling_of_a_batch_file_goes_through_the_same_checks(tmp_path, ending): from app.agent import agent_lookup @@ -164,11 +197,11 @@ def test_every_spelling_of_a_batch_file_goes_through_the_same_checks(tmp_path, e agent_lookup.start_argv([str(batch)[:-4] + ending, "-p", "a&b"], {"COMSPEC": "cmd.exe"}, "win32") -@pytest.mark.parametrize("word", ["fade in & out", "two words", "plain&joined"]) +@pytest.mark.parametrize("word", ["fade in & out", "two words", "plain&joined", ""]) def test_a_batch_file_in_a_folder_with_a_space_takes_only_words_that_need_no_quotes(tmp_path, word): from app.agent import agent_lookup - folder = tmp_path / "Program Files" + folder = tmp_path / "Program Files (x86)" folder.mkdir() batch = folder / "agent.bat" batch.write_text("@echo off\r\n", encoding="utf-8") diff --git a/setup/agents.py b/setup/agents.py index 2c53a84..06b7cda 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -33,7 +33,7 @@ DOCK = {"present": True, "positions": ["bottom", "right"], "tabs": ["chat", "terminal", "claude-code", "codex", "cursor", "antigravity"]} DOCK_FOLDER = ROOT / "frontend" / "src" / "dock" LOOKUP = ROOT / "backend" / "app" / "agent" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "a706029f18c33a18de27220d80218ac40638ee13c563f92b00a2bc60a38e5db7"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "3abb72b7c8d6e99b1e9be46979364cddfcaec79457e95a7599989567f4aba437"} ORDER = ["file", "edit", "project", "item", "footage", "comp", "layer", "prop", "keys", "anim", "time", "markers", "effect", "mask", "path", "paths", "shape", "text", "camera", "light", "material", "track", "warp", "roto", "paint", "puppet", "liquify", "contentFill", "face", "essential", "expr", "script", "scriptui", "render", "renderQueue", "playback", "view", "window", "editor", "scopes", "cache", "jobs",