Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ jobs:
shell: bash
env:
FORMCUT_NO_WARM: "1"
FORMCUT_DATA_DIR: ${{ runner.temp }}/formcut-bench-data
run: |
cd backend
python -c "from app.bench import _demo_project" 2>/dev/null || true
Expand All @@ -188,6 +189,8 @@ jobs:
# cannot read the heredoc.
- name: the engine imports and its routes mount once
shell: bash
env:
FORMCUT_DATA_DIR: ${{ runner.temp }}/formcut-routes-data
run: |
python - <<'PY'
import sys, collections
Expand Down
6 changes: 6 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

Reasoning behind engine changes, newest first.

## Unreleased · the suite's data folder on Windows is checked against the person's data folder (`tests/test_stand_in_home.py`)

- **What was there.** `test_the_data_folder_read_at_import_is_the_suites_own_and_not_under_the_persons_home` asserted that the suite's data folder is not anywhere under the person's home. On Windows the system temporary folder is `%LOCALAPPDATA%\Temp`, inside the home, so the folder `tempfile.mkdtemp` makes there always failed it (CI: `C:\Users\runneradmin\AppData\Local\Temp\formcut-tests-...`).
- **The change.** The whole-home check stays where the temporary folder is outside the home (macOS, Linux). Everywhere the data folder must not be the person's own formcut data folder, worked out as `paths.data_root` would from the variables as they were before the stand-in home (`conftest._HOME_BEFORE`): `~/Library/Application Support/formcut`, `%LOCALAPPDATA%\formcut`, or `$XDG_DATA_HOME/formcut`.
- **Seen.** The file passes on Linux; the Windows paths from the failed run checked by hand: the home check is skipped, the data-folder check passes, and a folder inside `%LOCALAPPDATA%\formcut` would fail it. Not run on Windows.

## 2.20.2 · the MCP tools give the clip ids that per-clip edits need (`app/agent_mcp.py`)

- **What was there.** `formcut_edit` takes a clip id for its per-clip operations (crossfade, trim, move, remove), but no tool gave one: `formcut_add_clip` answered with the clip's name and place, and `formcut_get_project` listed clips by label. An agent could place clips and then not change them.
Expand Down
51 changes: 48 additions & 3 deletions backend/app/agent_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from __future__ import annotations

import errno
import os
import re
import shutil
Expand All @@ -26,7 +27,7 @@
from dataclasses import dataclass, field
from pathlib import Path

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",
Expand Down Expand Up @@ -359,13 +360,57 @@ def _quote(word: str, fish: bool) -> str:
return "'" + word.replace("'", "'\"'\"'") + "'"


_SHIM_TARGET = re.compile(r'"%~?dp0%?\\?([^"%]+)"\s+%\*')
_CMD_NEVER = re.compile(r'[\x00-\x1f\x7f&|<>^()!%"]')


def shim_target(shim: str | os.PathLike, env: dict | None = None) -> list[str] | None:
"""What a package manager's .cmd shim runs (the program, or node and its script), read from the shim, so it can be
started directly instead of through the command interpreter; None when the shim says nothing this can follow."""
shim = Path(shim)
try:
text = shim.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
found = _SHIM_TARGET.findall(text)
if not found:
return None
target = shim.parent / found[-1].strip().replace("\\", os.sep).lstrip(os.sep)
kind = target.suffix.lower()
if not target.is_file() or kind not in (".exe", ".js", ".cjs", ".mjs"):
return None
if kind == ".exe":
return [str(target)]
beside = shim.parent / "node.exe"
node = str(beside) if beside.is_file() else shutil.which("node", path=(env or os.environ).get("PATH"))
return [node, str(target)] if node else None


def cmd_words(words: list[str]) -> list[str]:
"""Words for the command interpreter's /c line. A .cmd file reads its arguments again through %*, and the interpreter
acts on & | < > ^ ( ) ! % and quotes even inside quotes, so any word holding one of them, or a control character, is
refused whether or not it has spaces. Long or free text belongs on the program's standard input or in a file."""
for word in words:
if _CMD_NEVER.search(word):
raise OSError(errno.EINVAL, "an argument holds a character the Windows command interpreter would act on "
"(& | < > ^ ( ) ! % \" or a control character), so it cannot be passed on the command line; "
"pass long text through standard input or a file if the program supports it")
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 or .bat runs what it points at directly when it is
a package manager's shim, else through the command interpreter with only words it passes on as text."""
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().rstrip(". ").endswith((".cmd", ".bat")):
return words
direct = shim_target(words[0], env)
if direct:
return [*direct, *words[1:]]
return [env.get("COMSPEC") or "cmd.exe", "/c", *cmd_words(words)]
shell = login_shell(env, platform)
fish = Path(shell).name == "fish"
return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)]
Expand Down
4 changes: 3 additions & 1 deletion backend/app/automation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1073,7 +1073,9 @@ async def http_rpc_read(request: Request):

@router.websocket("/ws")
async def websocket_rpc(socket: WebSocket):
if socket.client and socket.client.host not in ("127.0.0.1", "::1", "testclient"):
from . import security

if not socket.client or not security.loopback(socket.client.host):
await socket.close(code=1008)
return
await socket.accept()
Expand Down
17 changes: 14 additions & 3 deletions backend/app/project_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ def open_file(path: Path) -> dict:
project = document["project"]
if not project.get("id"):
raise HTTPException(400, f"{path.name} holds no project id")
if not isinstance(project["id"], str) or not store.safe_id(project["id"]):
raise HTTPException(400, f"{path.name} holds a project id formcut cannot keep")
existing = store.get_project(project["id"])
project = {**project, "revision": int(existing.get("revision", 0)) if existing else 0}
saved = store._save_project(project) # the file is the word on it; the file itself is not written back yet
Expand Down Expand Up @@ -185,14 +187,23 @@ def collect(project_id: str, folder: Path, report=lambda *_: None, cancelled=lam
"""Collect Files, as After Effects does: <folder>/<title>/<title>.fmc with a copy of every file its clips use in
Footage/ beside it, the .fmc pointing at those copies (by path and relative to it), so the folder can be moved,
zipped or handed over whole. The project itself stays kept where it was; the collected .fmc is a copy of it.
Two files of the same name are told apart (a number added); a file missing now is listed, not copied."""
Two files of the same name are told apart (a number added), and so is a folder of that name already there, which is
never written into; a file missing now is listed, not copied."""
project = store.get_project(project_id)
if project is None:
raise HTTPException(404, "project not found")
title = "".join(ch for ch in str(project.get("title") or "Untitled") if ch not in '/\\:*?"<>|').strip() or "Untitled"
root = Path(folder).expanduser() / title
parent = Path(folder).expanduser()
parent.mkdir(parents=True, exist_ok=True)
root, number = parent / title, 2
while True:
try:
root.mkdir()
break
except FileExistsError:
root, number = parent / f"{title} {number}", number + 1
footage = root / "Footage"
footage.mkdir(parents=True, exist_ok=True)
footage.mkdir()
where = root / f"{title}{SUFFIX}"
table = media_table(project, where)
used: set[str] = set()
Expand Down
16 changes: 9 additions & 7 deletions backend/app/projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,8 @@ def _ensure_cover(record: dict) -> None:
Four cards showing the same film icon tell a person nothing, which is what
the home screen looked like while covers were only made on request.
"""
project_id = str(record.get("id") or "")
path = COVERS / f"{project_id}.jpg"
if not project_id or path.is_file():
path = store.id_path(COVERS, record.get("id"), ".jpg")
if path is None or path.is_file():
return
document = record.get("document") or {}
if not document.get("timelines"):
Expand Down Expand Up @@ -119,8 +118,8 @@ def project_summaries() -> list[dict]:

@router.get("/{project_id}/cover")
def project_cover(project_id: str):
path = COVERS / f"{project_id}.jpg"
if not path.is_file():
path = store.id_path(COVERS, project_id, ".jpg")
if path is None or not path.is_file():
raise HTTPException(status_code=404, detail="no cover")
return FileResponse(path, media_type="image/jpeg")

Expand All @@ -133,14 +132,17 @@ def set_project_cover(project_id: str, body: dict) -> None:
from .render_api import FrameRenderer
from .render_document import validate_document

document = validate_document(body.get("project") or {})
COVERS.mkdir(parents=True, exist_ok=True)
path = store.id_path(COVERS, project_id, ".jpg")
if path is None:
raise HTTPException(status_code=400, detail="bad project id")
document = validate_document(body.get("project") or {})
renderer = FrameRenderer(document, 480)
try:
pixels = renderer.frame(max(0.0, float(body.get("time") or 0)))
finally:
renderer.close()
Image.fromarray(pixels[:, :, :3]).save(COVERS / f"{project_id}.jpg", quality=80)
Image.fromarray(pixels[:, :, :3]).save(path, quality=80)


@router.patch("/{project_id}", status_code=200)
Expand Down
4 changes: 2 additions & 2 deletions backend/app/recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@

router = APIRouter(prefix="/api/recovery", tags=["recovery"])
RECOVERY_DIR = DATA_DIR / "recovery"
_KEY = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
_KEY = re.compile(r"[A-Za-z0-9_-]{1,64}")


def _path(key: str):
if not _KEY.match(key):
if not isinstance(key, str) or not _KEY.fullmatch(key):
raise HTTPException(status_code=400, detail="bad key")
return RECOVERY_DIR / f"{key}.json"

Expand Down
2 changes: 1 addition & 1 deletion backend/app/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


def loopback(value: str) -> bool:
if value in ("localhost", "testclient", "testserver"):
if value == "localhost":
return True
try:
return ipaddress.ip_address(value).is_loopback
Expand Down
34 changes: 30 additions & 4 deletions backend/app/store.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import contextlib
import json
import re
import threading
import time
from pathlib import Path

from .durable import read_json, set_aside, write_json
from .paths import DATA_DIR
Expand All @@ -15,6 +17,27 @@
_record_texts: dict[str, str] = {}


_PLAIN_ID = re.compile(r"[A-Za-z0-9_-]{1,64}")
_DEVICE_NAMES = re.compile(r"(?i)(con|prn|aux|nul|com[0-9]|lpt[0-9])")


def safe_id(project_id) -> bool:
"""An id of the kind formcut issues (letters, digits, - and _, as a uuid's hex is), so it names one file of its own
inside formcut's folders on every system: no separator, drive, dot or device name."""
return type(project_id) is str and bool(_PLAIN_ID.fullmatch(project_id)) and not _DEVICE_NAMES.fullmatch(project_id)


def id_path(folder: Path, project_id, suffix: str) -> Path | None:
"""The file kept for a project id in folder, or None when the id is not a plain one or the file is not in folder."""
if not safe_id(project_id):
return None
path = Path(folder) / f"{project_id}{suffix}"
try:
return path if path.resolve().parent == Path(folder).resolve() else None
except (OSError, RuntimeError):
return None


def _read() -> list[dict]:
"""projects.json; when it is missing or damaged, the projects' own records (the latest word on each, a deleted
project's gone with it), else its backup (one save behind), else none."""
Expand Down Expand Up @@ -43,12 +66,13 @@ def _write(projects: list[dict]) -> None:
write_json(PROJECTS_FILE, projects)
RECORDS_DIR.mkdir(parents=True, exist_ok=True)
for project in projects:
project_id = str(project.get("id") or "")
if not project_id or "/" in project_id or "\\" in project_id or project_id.startswith("."):
project_id = project.get("id")
record = id_path(RECORDS_DIR, project_id, ".json")
if record is None:
continue
text = json.dumps(project)
if _record_texts.get(project_id) != text:
write_json(RECORDS_DIR / f"{project_id}.json", project, indent=None, keep_backup=False)
write_json(record, project, indent=None, keep_backup=False)
_record_texts[project_id] = text


Expand Down Expand Up @@ -110,6 +134,8 @@ def delete_project(project_id: str) -> bool:
if len(remaining) == len(projects):
return False
_write(remaining)
(RECORDS_DIR / f"{project_id}.json").unlink(missing_ok=True) # deleted: not to be rebuilt
record = id_path(RECORDS_DIR, project_id, ".json")
if record is not None:
record.unlink(missing_ok=True) # deleted: not to be rebuilt
_record_texts.pop(project_id, None)
return True
5 changes: 3 additions & 2 deletions frontend/src/ui/settings-popout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import { t } from "../i18n";
import { localizeElement, text } from "../i18n/text";
import { icon } from "./icons";
import { escapeHtml } from "./safe-text";
import type { ProjectEngine } from "../engine/project";
import type { MediaBin } from "../engine/media";
import { ACCENTS, PROFILES, apply, read, setAccent, setTheme } from "./appearance";
Expand Down Expand Up @@ -446,7 +447,7 @@ export function installSettingsPopout(engine: ProjectEngine, bin: MediaBin, open
const row = document.createElement("div");
row.className = "panel-row";
const last = session.operations.at(-1)?.method ?? "";
row.innerHTML = `<span>${session.name}${session.agent ? ` · ${session.agent}` : ""}</span><span>${session.operations.length} ${t("conn.calls")}${last ? ` · ${last}` : ""}</span>`;
row.innerHTML = `<span>${escapeHtml(String(session.name))}${session.agent ? ` · ${escapeHtml(String(session.agent))}` : ""}</span><span>${session.operations.length} ${t("conn.calls")}${last ? ` · ${escapeHtml(String(last))}` : ""}</span>`;
sessionList.append(row);
}
} catch {
Expand All @@ -467,7 +468,7 @@ export function installSettingsPopout(engine: ProjectEngine, bin: MediaBin, open
const row = document.createElement("div");
row.className = "panel-row";
const percent = Math.round(job.progress * 100);
row.innerHTML = `<span>${job.kind} · ${t("conn.status." + job.status) || job.status}${job.status === "running" ? ` ${percent}%` : ""}</span>`;
row.innerHTML = `<span>${escapeHtml(String(job.kind))} · ${escapeHtml(String(t("conn.status." + job.status) || job.status))}${job.status === "running" ? ` ${percent}%` : ""}</span>`;
if (job.status === "running") {
const stop = document.createElement("button");
stop.className = "tool-chip";
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/ui/start-screen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ export function buildStartScreen(engine: ProjectEngine, bin: MediaBin): HTMLElem
fresh.className = "restore-bar";
fresh.dataset.ref = "restore";
fresh.dataset.key = newest.key;
fresh.innerHTML = `<span>${t("save.recover")}: ${newest.title || t("start.new")}</span><button class="tool-chip is-primary" data-restore="${newest.key}">${t("save.restore")}</button><button class="tool-chip" data-discard="${newest.key}">${t("save.discard")}</button>`;
fresh.innerHTML = `<span>${t("save.recover")}: ${escapeHtml(String(newest.title || t("start.new")))}</span><button class="tool-chip is-primary" data-restore="${newest.key}">${t("save.restore")}</button><button class="tool-chip" data-discard="${newest.key}">${t("save.discard")}</button>`;
fresh.querySelector("[data-restore]")!.addEventListener("click", () => void (async () => {
if (await restoreJournal(engine, newest.key)) {
void clearJournal(newest.key);
Expand Down
6 changes: 6 additions & 0 deletions frontend/tests/window/test_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@
"FORMCUT_FFMPEG_AUTO": "0",
"FORMCUT_MODELS_AUTO": "0",
"USERPROFILE": "{home}",
"LOCALAPPDATA": "{home}/AppData/Local",
"APPDATA": "{home}/AppData/Roaming",
"XDG_DATA_HOME": "{home}/.local/share",
"XDG_CONFIG_HOME": "{home}/.config",
"XDG_CACHE_HOME": "{home}/.cache",
"XDG_STATE_HOME": "{home}/.local/state",
}
CLEAR_ENV_PREFIX = "FORMCUT_"
DIST = REPO / "frontend" / "dist"
Expand Down
1 change: 1 addition & 0 deletions setup/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ def dock_problems(folder: Path = DOCK_DIR) -> list[str]:
LOOKUP_HASHES = {
"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3",
"1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51",
"1.0.2": "c3e2a64f16a4f592b28d091bbe7bdceaf07d027738324e8ac6b44c905c5bea7e",
}


Expand Down
3 changes: 3 additions & 0 deletions setup/golden_frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
import sys
from pathlib import Path

import scratch_home

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "backend"))

Expand Down Expand Up @@ -206,6 +208,7 @@ def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--update", action="store_true", help="write the current output as the golden")
args = parser.parse_args()
scratch_home.use("formcut-golden-")

current = render_all()

Expand Down
3 changes: 3 additions & 0 deletions setup/output_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import time
from pathlib import Path

import scratch_home

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "backend"))

Expand Down Expand Up @@ -199,6 +201,7 @@ def rpc_checks() -> None:


def main() -> int:
scratch_home.use("formcut-output-checks-")
export_checks()
rpc_checks()
print()
Expand Down
Loading
Loading