diff --git a/.agents/skills/formencoder-harness/references/commands.md b/.agents/skills/formencoder-harness/references/commands.md index 3168ddd..67abce3 100644 --- a/.agents/skills/formencoder-harness/references/commands.md +++ b/.agents/skills/formencoder-harness/references/commands.md @@ -2,11 +2,11 @@ Generated from the formencoder engine by `./formencoder agents sync`; do not edit by hand. -96 commands in 24 namespaces. Every menu item and button in formencoder is one of these. Run one over MCP with its own tool (the `MCP` name on each line, in the full profile) or `execute {command, params}` (every profile), several as one undo step with `batch`, or from a shell as `./formencoder ID --name value` (`--help` after the id lists the flags). `describe_command ID` returns the JSON Schema. In the summaries `?` marks an optional parameter and `a|b` lists the accepted values. `refs` takes output ids, item ids, `#n` (the nth queue item), `selected` or `all`. Unknown parameters are refused with the schema in the message. +94 commands in 23 namespaces. Every menu item and button in formencoder is one of these. Run one over MCP with its own tool (the `MCP` name on each line, in the full profile) or `execute {command, params}` (every profile), several as one undo step with `batch`, or from a shell as `./formencoder ID --name value` (`--help` after the id lists the flags). `describe_command ID` returns the JSON Schema. In the summaries `?` marks an optional parameter and `a|b` lists the accepted values. `refs` takes output ids, item ids, `#n` (the nth queue item), `selected` or `all`. Unknown parameters are refused with the schema in the message. ## Contents -`queue` (26) `encode` (5) `preset` (11) `format` (3) `watch` (9) `ingest` (1) `proxy` (1) `analyze` (1) `media` (3) `captions` (4) `lut` (2) `family` (2) `publish` (1) `log` (2) `prefs` (5) `edit` (2) `history` (1) `ui` (4) `app` (2) `settings` (1) `metadata` (3) `plugin` (3) `shortcuts` (3) `tools` (1) +`queue` (26) `encode` (5) `preset` (11) `format` (3) `watch` (9) `ingest` (1) `proxy` (1) `analyze` (1) `media` (3) `captions` (4) `lut` (2) `family` (1) `log` (2) `prefs` (5) `edit` (2) `history` (1) `ui` (4) `app` (2) `settings` (1) `metadata` (3) `plugin` (3) `shortcuts` (3) `tools` (1) ## queue @@ -68,8 +68,9 @@ Generated from the formencoder engine by `./formencoder agents sync`; do not edi Joins clips, in the order given, into one source with one output; sizes and rates follow the first clip. - `queue.select` Select · Edit · query · MCP `queue_select` `{items?: array, outputs?: array}` -- `queue.save` Save Queue · File · Cmd+S · query · MCP `queue_save` - `{path?: string}` +- `queue.save` Save Queue · File · Cmd+S · MCP `queue_save` + `{path?: string, overwrite?: boolean}` + Saves the queue, to path when given. An existing file at path is replaced only with overwrite: true. - `queue.open` Open Queue · File · undoable, destructive · MCP `queue_open` `{path: string, append?: boolean}` @@ -195,14 +196,6 @@ Generated from the formencoder engine by `./formencoder agents sync`; do not edi - `family.queue` Queue Family Source · File · undoable · MCP `family_queue` `{spec: object, preset?: string, format?: h264|hevc|av1|webm|quicktime|prores|prores_mxf|dnxhr_mxf|mxf_op1a|jpeg2000_mxf|as10|as11|..., settings?: object, folder?: string, outputs?: array, start?: boolean}` Queues a source described by the family bridge (family.add finds it in the app and calls this). -- `family.resolved` Family Media Ready · File · query · MCP `family_resolved` - `{output: string, media?: object, error?: string}` - The service hands a waiting output the media the family app produced. - -## publish - -- `publish.result` Publish Result · Publish · MCP `publish_result` - `{output: string, results: array}` ## log diff --git a/.agents/skills/formencoder-harness/references/tools.md b/.agents/skills/formencoder-harness/references/tools.md index 3106f21..9ef43b4 100644 --- a/.agents/skills/formencoder-harness/references/tools.md +++ b/.agents/skills/formencoder-harness/references/tools.md @@ -330,7 +330,7 @@ How to encode with formencoder through these tools. ### queue -Refs: an output id (o...), an item id (i...), '#n' for the nth item (its outputs), 'selected' or 'all'. queue.addSource {paths, preset|format|settings|outputs, folder, stitch, frameRate (image sequence), start}. queue.addOutput {item, preset} adds another output to a source. queue.duplicate, queue.remove, queue.clearDone, queue.reorder {item, to}, queue.skip {refs, skip}, queue.resetStatus {refs} (encode again). queue.setRange {refs, mode: entire|inout|custom, in, out} in source seconds. queue.interpret {item, frameRate, pixelAspect, fieldOrder, alpha, rotation}. queue.stitch {paths} joins clips into one output. queue.save {path} and queue.open {path} keep a queue as .fequeue. Status values: ready, preparing, encoding, paused, done, failed, stopped, skipped. +Refs: an output id (o...), an item id (i...), '#n' for the nth item (its outputs), 'selected' or 'all'. queue.addSource {paths, preset|format|settings|outputs, folder, stitch, frameRate (image sequence), start}. queue.addOutput {item, preset} adds another output to a source. queue.duplicate, queue.remove, queue.clearDone, queue.reorder {item, to}, queue.skip {refs, skip}, queue.resetStatus {refs} (encode again). queue.setRange {refs, mode: entire|inout|custom, in, out} in source seconds. queue.interpret {item, frameRate, pixelAspect, fieldOrder, alpha, rotation}. queue.stitch {paths} joins clips into one output. queue.save {path, overwrite} and queue.open {path} keep a queue as .fequeue (an existing file is replaced only with overwrite: true). Status values: ready, preparing, encoding, paused, done, failed, stopped, skipped. ### settings diff --git a/.agents/skills/formencoder-harness/sub-skills/queue-and-presets/SUB-SKILL.md b/.agents/skills/formencoder-harness/sub-skills/queue-and-presets/SUB-SKILL.md index d3f62e8..9284109 100644 --- a/.agents/skills/formencoder-harness/sub-skills/queue-and-presets/SUB-SKILL.md +++ b/.agents/skills/formencoder-harness/sub-skills/queue-and-presets/SUB-SKILL.md @@ -34,7 +34,7 @@ A source added without a preset gets the `defaultPreset` preference (Match Sourc - `queue {action: resetStatus, refs}` returns done, failed or stopped outputs to ready, to encode again after a fix. - `queue {action: reorder, item, to}` moves an item (1-based). `clearDone` removes finished items; `remove {refs}` removes outputs, or whole items when an item id is named. - The `parallel` and `maxParallel` preferences decide how many outputs of one source encode at once. -- `execute queue.save {path}` writes the queue as `.fequeue`; `execute queue.open {path, append}` brings one back. +- `execute queue.save {path, overwrite}` writes the queue as `.fequeue` (an existing file is replaced only with `overwrite: true`, which asks the person); `execute queue.open {path, append}` brings one back. ## Presets diff --git a/.claude/skills/formencoder-harness/references/commands.md b/.claude/skills/formencoder-harness/references/commands.md index 3168ddd..67abce3 100644 --- a/.claude/skills/formencoder-harness/references/commands.md +++ b/.claude/skills/formencoder-harness/references/commands.md @@ -2,11 +2,11 @@ Generated from the formencoder engine by `./formencoder agents sync`; do not edit by hand. -96 commands in 24 namespaces. Every menu item and button in formencoder is one of these. Run one over MCP with its own tool (the `MCP` name on each line, in the full profile) or `execute {command, params}` (every profile), several as one undo step with `batch`, or from a shell as `./formencoder ID --name value` (`--help` after the id lists the flags). `describe_command ID` returns the JSON Schema. In the summaries `?` marks an optional parameter and `a|b` lists the accepted values. `refs` takes output ids, item ids, `#n` (the nth queue item), `selected` or `all`. Unknown parameters are refused with the schema in the message. +94 commands in 23 namespaces. Every menu item and button in formencoder is one of these. Run one over MCP with its own tool (the `MCP` name on each line, in the full profile) or `execute {command, params}` (every profile), several as one undo step with `batch`, or from a shell as `./formencoder ID --name value` (`--help` after the id lists the flags). `describe_command ID` returns the JSON Schema. In the summaries `?` marks an optional parameter and `a|b` lists the accepted values. `refs` takes output ids, item ids, `#n` (the nth queue item), `selected` or `all`. Unknown parameters are refused with the schema in the message. ## Contents -`queue` (26) `encode` (5) `preset` (11) `format` (3) `watch` (9) `ingest` (1) `proxy` (1) `analyze` (1) `media` (3) `captions` (4) `lut` (2) `family` (2) `publish` (1) `log` (2) `prefs` (5) `edit` (2) `history` (1) `ui` (4) `app` (2) `settings` (1) `metadata` (3) `plugin` (3) `shortcuts` (3) `tools` (1) +`queue` (26) `encode` (5) `preset` (11) `format` (3) `watch` (9) `ingest` (1) `proxy` (1) `analyze` (1) `media` (3) `captions` (4) `lut` (2) `family` (1) `log` (2) `prefs` (5) `edit` (2) `history` (1) `ui` (4) `app` (2) `settings` (1) `metadata` (3) `plugin` (3) `shortcuts` (3) `tools` (1) ## queue @@ -68,8 +68,9 @@ Generated from the formencoder engine by `./formencoder agents sync`; do not edi Joins clips, in the order given, into one source with one output; sizes and rates follow the first clip. - `queue.select` Select · Edit · query · MCP `queue_select` `{items?: array, outputs?: array}` -- `queue.save` Save Queue · File · Cmd+S · query · MCP `queue_save` - `{path?: string}` +- `queue.save` Save Queue · File · Cmd+S · MCP `queue_save` + `{path?: string, overwrite?: boolean}` + Saves the queue, to path when given. An existing file at path is replaced only with overwrite: true. - `queue.open` Open Queue · File · undoable, destructive · MCP `queue_open` `{path: string, append?: boolean}` @@ -195,14 +196,6 @@ Generated from the formencoder engine by `./formencoder agents sync`; do not edi - `family.queue` Queue Family Source · File · undoable · MCP `family_queue` `{spec: object, preset?: string, format?: h264|hevc|av1|webm|quicktime|prores|prores_mxf|dnxhr_mxf|mxf_op1a|jpeg2000_mxf|as10|as11|..., settings?: object, folder?: string, outputs?: array, start?: boolean}` Queues a source described by the family bridge (family.add finds it in the app and calls this). -- `family.resolved` Family Media Ready · File · query · MCP `family_resolved` - `{output: string, media?: object, error?: string}` - The service hands a waiting output the media the family app produced. - -## publish - -- `publish.result` Publish Result · Publish · MCP `publish_result` - `{output: string, results: array}` ## log diff --git a/.claude/skills/formencoder-harness/references/tools.md b/.claude/skills/formencoder-harness/references/tools.md index 3106f21..9ef43b4 100644 --- a/.claude/skills/formencoder-harness/references/tools.md +++ b/.claude/skills/formencoder-harness/references/tools.md @@ -330,7 +330,7 @@ How to encode with formencoder through these tools. ### queue -Refs: an output id (o...), an item id (i...), '#n' for the nth item (its outputs), 'selected' or 'all'. queue.addSource {paths, preset|format|settings|outputs, folder, stitch, frameRate (image sequence), start}. queue.addOutput {item, preset} adds another output to a source. queue.duplicate, queue.remove, queue.clearDone, queue.reorder {item, to}, queue.skip {refs, skip}, queue.resetStatus {refs} (encode again). queue.setRange {refs, mode: entire|inout|custom, in, out} in source seconds. queue.interpret {item, frameRate, pixelAspect, fieldOrder, alpha, rotation}. queue.stitch {paths} joins clips into one output. queue.save {path} and queue.open {path} keep a queue as .fequeue. Status values: ready, preparing, encoding, paused, done, failed, stopped, skipped. +Refs: an output id (o...), an item id (i...), '#n' for the nth item (its outputs), 'selected' or 'all'. queue.addSource {paths, preset|format|settings|outputs, folder, stitch, frameRate (image sequence), start}. queue.addOutput {item, preset} adds another output to a source. queue.duplicate, queue.remove, queue.clearDone, queue.reorder {item, to}, queue.skip {refs, skip}, queue.resetStatus {refs} (encode again). queue.setRange {refs, mode: entire|inout|custom, in, out} in source seconds. queue.interpret {item, frameRate, pixelAspect, fieldOrder, alpha, rotation}. queue.stitch {paths} joins clips into one output. queue.save {path, overwrite} and queue.open {path} keep a queue as .fequeue (an existing file is replaced only with overwrite: true). Status values: ready, preparing, encoding, paused, done, failed, stopped, skipped. ### settings diff --git a/.claude/skills/formencoder-harness/sub-skills/queue-and-presets/SUB-SKILL.md b/.claude/skills/formencoder-harness/sub-skills/queue-and-presets/SUB-SKILL.md index d3f62e8..9284109 100644 --- a/.claude/skills/formencoder-harness/sub-skills/queue-and-presets/SUB-SKILL.md +++ b/.claude/skills/formencoder-harness/sub-skills/queue-and-presets/SUB-SKILL.md @@ -34,7 +34,7 @@ A source added without a preset gets the `defaultPreset` preference (Match Sourc - `queue {action: resetStatus, refs}` returns done, failed or stopped outputs to ready, to encode again after a fix. - `queue {action: reorder, item, to}` moves an item (1-based). `clearDone` removes finished items; `remove {refs}` removes outputs, or whole items when an item id is named. - The `parallel` and `maxParallel` preferences decide how many outputs of one source encode at once. -- `execute queue.save {path}` writes the queue as `.fequeue`; `execute queue.open {path, append}` brings one back. +- `execute queue.save {path, overwrite}` writes the queue as `.fequeue` (an existing file is replaced only with `overwrite: true`, which asks the person); `execute queue.open {path, append}` brings one back. ## Presets diff --git a/agents/manifest.json b/agents/manifest.json index 4e8c656..681756d 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -118,8 +118,6 @@ "tools_list", "prefs_clean_cache", "family_queue", - "family_resolved", - "publish_result", "edit_undo", "edit_redo", "history_list", @@ -150,7 +148,6 @@ "queue_get_settings", "settings_apply", "queue_select", - "queue_save", "encode_status", "encode_report", "encode_estimate", @@ -177,7 +174,6 @@ "plugin_result", "shortcuts_list", "tools_list", - "family_resolved", "history_list", "ui_panel", "ui_workspace", @@ -222,6 +218,7 @@ "queue_stop_current", "queue_auto_encode_watch", "queue_stitch", + "queue_save", "queue_open", "preset_create", "preset_update", @@ -255,7 +252,6 @@ "shortcuts_reset", "prefs_clean_cache", "family_queue", - "publish_result", "edit_undo", "edit_redo" ], diff --git a/backend/app/agent/approvals.py b/backend/app/agent/approvals.py index 6d04c4f..eb1c509 100644 --- a/backend/app/agent/approvals.py +++ b/backend/app/agent/approvals.py @@ -4,6 +4,7 @@ import itertools import json import os +import re import time from collections import deque from pathlib import Path @@ -16,6 +17,8 @@ WAIT = 120.0 _ids = itertools.count(1) _destructive: dict[str, str] = {} +_queries: set[str] = set() +PRESET_MAKERS = ("preset.create", "preset.update", "preset.duplicate", "preset.alias", "preset.import") pending: dict[int, tuple[dict, Callable[[], Awaitable[Any]], asyncio.Future]] = {} decided: deque = deque(maxlen=200) activity: deque = deque(maxlen=300) @@ -85,6 +88,8 @@ async def _load_registry() -> None: for r in rows: if (r.get("annotations") or {}).get("destructiveHint"): _destructive[r["id"]] = r.get("label") or r["id"] + if r.get("query"): + _queries.add(r["id"]) def _settings_in(params: dict) -> list[dict]: @@ -98,6 +103,56 @@ def _settings_in(params: dict) -> list[dict]: return found +def _unread(what: str, exc: Any = None) -> str: + detail = f" ({_shown(exc)[:160]})" if exc else "" + return f"{what} could not be read{detail}, so it may publish" + + +async def _engine_query(command: str, params: dict) -> Any: + return json.loads(await host.call(lambda e: e.execute(command, json.dumps(params), "engine"))) + + +async def _preset_settings(params: dict) -> tuple[list[dict], list[str]]: + """The settings of every preset the params name. A preset that cannot be read is a reason to ask (fail closed).""" + names = [params.get("preset")] + [o.get("preset") for o in params.get("outputs") or [] if isinstance(o, dict)] + found: list[dict] = [] + why: list[str] = [] + for name in sorted({n for n in names if isinstance(n, str) and n}): + try: + row = await _engine_query("preset.get", {"preset": name}) + except Exception as exc: + why.append(_unread(f"the preset {_shown(name)}", exc)) + continue + if isinstance(row, dict) and isinstance(row.get("settings"), dict): + found.append(row["settings"]) + else: + why.append(_unread(f"the preset {_shown(name)}")) + return found, why + + +async def _resolved_reasons(command: str, params: dict) -> list[str]: + """Whether the preset a preset command leaves publishes, as the engine works it out (preset.resolve, run only by the engine + service): an import reads the file the way preset.import reads it, an update applies its patch, a create from an output takes + that output's settings. The engine answers with a publish summary only, never the settings or the file.""" + try: + row = await _engine_query("preset.resolve", {"command": command, "params": params}) + except Exception as exc: + return [_unread("the preset settings", exc)] + if not isinstance(row, dict) or not isinstance(row.get("publishes"), bool) or not isinstance(row.get("destinations"), list): + return [_unread("the preset settings")] + kinds = {str(k) for k in row["destinations"]} + out = [f"it sends the encoded file to {k}" for k in sorted(kinds & UPLOADS)] + if "folder" in kinds: + out.append("it copies the encoded file into a folder") + if row.get("deletesLocal") is not False: + out.append("it deletes the local file after publishing") + return out + + +def _shown(value: Any) -> str: + return re.sub(r"[\x00-\x1f\x7f]", "?", str(value)) + + def _publish_reasons(settings: dict) -> list[str]: out = [] dests = settings.get("publish") @@ -109,6 +164,8 @@ def _publish_reasons(settings: dict) -> list[str]: kind = str(d.get("type") or "") if kind in UPLOADS: out.append(f"it sends the encoded file to {kind}") + if kind == "folder": + out.append(f"it copies the encoded file into {_shown(d.get('path') or 'a folder')}") if d.get("deleteLocal"): out.append("it deletes the local file after publishing") return out @@ -119,12 +176,20 @@ async def reasons(command: str, params: dict) -> list[str]: why: list[str] = [] if command in _destructive: why.append(f"{_destructive[command].rstrip('.')} deletes, clears or replaces something") - for s in _settings_in(params): - why += _publish_reasons(s) + if command not in _queries: + named, unread = await _preset_settings(params) + found = _settings_in(params) + named + why += unread + if command in PRESET_MAKERS: + why += await _resolved_reasons(command, params) + for s in found: + why += _publish_reasons(s) if command == "queue.setOutput" and isinstance(params.get("path"), str) and params["path"]: target = Path(os.path.expanduser(params["path"])) if target.exists(): - why.append(f"it would overwrite {target}") + why.append(f"it would overwrite {_shown(target)}") + if command == "queue.save" and params.get("overwrite") is True: + why.append(f"it may overwrite {_shown(params.get('path') or 'a saved queue')}") if command in ("watch.setOutput", "watch.addOutput") and params.get("folder") not in (None, ""): why.append("it changes where a watch folder writes its files") if command == "watch.chain": @@ -132,17 +197,31 @@ async def reasons(command: str, params: dict) -> list[str]: return sorted(set(why)) -async def guard(client: str, label: str, why: list[str], params: Any, run: Callable[[], Awaitable[Any]]) -> Any: - if not why: - return await run() - if full_faith(): - return await run() +def _register(client: str, label: str, why: list[str], params: Any, run: Callable[[], Awaitable[Any]]) -> tuple[dict, asyncio.Future]: rid = next(_ids) request = {"id": rid, "client": client, "action": label, "params": _short(params, 600), "why": why, "created": time.time(), "status": "pending", "summary": f"{client} asks to run {label}: {'; '.join(why)}"} fut: asyncio.Future = asyncio.get_running_loop().create_future() pending[rid] = (request, run, fut) _changed() + return request, fut + + +async def ask_later(client: str, label: str, why: list[str], params: Any, run: Callable[[], Awaitable[Any]]) -> dict: + """For a caller that cannot wait (a webhook): run now when nothing needs asking or full faith is on, otherwise leave the + request in the Agent Connect panel, where approving it runs it, and answer at once with its id.""" + if not why or full_faith(): + return {"result": await run()} + request, _fut = _register(client, label, why, params, run) + return {"pendingApproval": request["id"], "why": why, "summary": request["summary"]} + + +async def guard(client: str, label: str, why: list[str], params: Any, run: Callable[[], Awaitable[Any]]) -> Any: + if not why: + return await run() + if full_faith(): + return await run() + request, fut = _register(client, label, why, params, run) if not host.bus.windows(): raise Pending(request) try: diff --git a/backend/app/agent/connect.py b/backend/app/agent/connect.py index 7eec374..8f51a71 100644 --- a/backend/app/agent/connect.py +++ b/backend/app/agent/connect.py @@ -45,6 +45,19 @@ def _copy_skill(to: Path, dry: bool, said: list) -> None: shutil.copytree(skill, to) +def _add_claude(claude: str, cmd: str, args: list, line: str, dry: bool, said: list) -> None: + env = agent_programs.child_env(claude, base=dict(os.environ)) + have = agent_lookup.run([claude, "mcp", "get", NAME], env, 60) + if have.returncode == 0 and cmd in have.stdout and "--profile" in have.stdout: + said.append(f" MCP server {NAME} already set (user scope)") + return + said.append(f" claude mcp add --scope user {NAME} -- {line}") + if not dry: + if have.returncode == 0: + agent_lookup.run([claude, "mcp", "remove", NAME, "--scope", "user"], env, 60) + agent_lookup.run([claude, "mcp", "add", "--scope", "user", NAME, "--", cmd, *args], env, 60).check_returncode() + + def install_claude(home: Path, dry: bool, said: list) -> None: said.append("Claude Code:") cmd = launch() @@ -53,16 +66,10 @@ def install_claude(home: Path, dry: bool, said: list) -> None: found = agent_programs.usable("claude") claude = found.path if found.state == "runs" else None if claude: - env = agent_programs.child_env(claude, base=dict(os.environ)) - have = agent_lookup.run([claude, "mcp", "get", NAME], env, 60) - if have.returncode == 0 and cmd in have.stdout and "--profile" in have.stdout: - said.append(f" MCP server {NAME} already set (user scope)") - else: - said.append(f" claude mcp add --scope user {NAME} -- {line}") - if not dry: - if have.returncode == 0: - agent_lookup.run([claude, "mcp", "remove", NAME, "--scope", "user"], env, 60) - agent_lookup.run([claude, "mcp", "add", "--scope", "user", NAME, "--", cmd, *args], env, 60).check_returncode() + try: + _add_claude(claude, cmd, args, line, dry, said) + except agent_lookup.Refused as exc: + said.append(f" {exc} Run it yourself: claude mcp add --scope user {NAME} -- {line}") else: said.append(f" {agent_programs.said(found)} Once it starts, run: claude mcp add --scope user {NAME} -- {line}") _copy_skill(home / ".claude" / "skills" / SKILL, dry, said) diff --git a/backend/app/agent/tools.py b/backend/app/agent/tools.py index bbc3939..e664c8b 100644 --- a/backend/app/agent/tools.py +++ b/backend/app/agent/tools.py @@ -47,7 +47,7 @@ GUIDES = { "index": "Topics: workflow, queue, settings, video, audio, effects, captions, metadata, publish, watch, ingest, family, presets, ui. Call guide {topic}.", "workflow": WORKFLOW, - "queue": "Refs: an output id (o...), an item id (i...), '#n' for the nth item (its outputs), 'selected' or 'all'. queue.addSource {paths, preset|format|settings|outputs, folder, stitch, frameRate (image sequence), start}. queue.addOutput {item, preset} adds another output to a source. queue.duplicate, queue.remove, queue.clearDone, queue.reorder {item, to}, queue.skip {refs, skip}, queue.resetStatus {refs} (encode again). queue.setRange {refs, mode: entire|inout|custom, in, out} in source seconds. queue.interpret {item, frameRate, pixelAspect, fieldOrder, alpha, rotation}. queue.stitch {paths} joins clips into one output. queue.save {path} and queue.open {path} keep a queue as .fequeue. Status values: ready, preparing, encoding, paused, done, failed, stopped, skipped.", + "queue": "Refs: an output id (o...), an item id (i...), '#n' for the nth item (its outputs), 'selected' or 'all'. queue.addSource {paths, preset|format|settings|outputs, folder, stitch, frameRate (image sequence), start}. queue.addOutput {item, preset} adds another output to a source. queue.duplicate, queue.remove, queue.clearDone, queue.reorder {item, to}, queue.skip {refs, skip}, queue.resetStatus {refs} (encode again). queue.setRange {refs, mode: entire|inout|custom, in, out} in source seconds. queue.interpret {item, frameRate, pixelAspect, fieldOrder, alpha, rotation}. queue.stitch {paths} joins clips into one output. queue.save {path, overwrite} and queue.open {path} keep a queue as .fequeue (an existing file is replaced only with overwrite: true). Status values: ready, preparing, encoding, paused, done, failed, stopped, skipped.", "settings": "Settings object: format, outputName (tokens {source} {preset} {format} {date} {time} {width} {height} {fps} {index}), exportVideo, exportAudio, video{...}, audio{...}, multiplexer{container, fastStart}, range{mode,in,out}, crop{left,top,right,bottom}, rotation (0, 90, 180, 270), scaling (fit, fitBlack, fill, stretch, matchWidth), timeInterpolation (sampling, blending, opticalFlow), maxRenderQuality, maxDepth, startTimecode, alphaOnly, maxFileSize (MB), effects{...}, captions{...}, metadata{...}, publish[...]. Switching format keeps range, crop, scaling, effects, captions, metadata and publish. formats {format} lists every field with its options and showIf condition.", "video": "video: codec, matchSource (width, height and rate from the source), width, height, frameRate (null = source), fieldOrder (progressive, tff, bff, source), pixelAspect, profile, level, bitDepth (8, 10, 12), chroma (420, 422, 444), rateControl (vbr1, vbr2, cbr, quality), targetBitrate and maxBitrate in Mb/s, quality 0 to 100, keyframeDistance (frames), hardware (auto, on, off), colorSpace (rec709, rec2020, rec2100pq, rec2100hlg, rec601...), hdr10 with maxCLL and maxFALL, alpha, sequence (image sequences), startNumber, loop (GIF). H.264 and HEVC use the hardware encoder when one works (formats {format} shows which); vbr2 needs a software encoder.", "audio": "audio: codec (aac, pcm, mp3, opus, flac, ac3...), sampleRate, channels (mono, stereo, 5.1, 7.1, source, discrete), bitrate (kb/s), bitDepth (16, 24, 32), float. Loudness is an effect: effects.loudness {enabled, standard: ebu-r128|atsc-a85|itu-bs1770|custom, target LUFS, truePeak dBTP, lra, mode twopass, report (XML beside the file), limiter {enabled, lookahead ms, release ms}}.", @@ -514,6 +514,8 @@ def _commands_of(name: str, args: dict) -> list[tuple[str, dict]]: return [("queue.setSettings", {"settings": args["settings"]})] if name == "encode": return [("queue.addSource", args)] + if name == "family" and args.get("action") in ("add", "addLink", "linkFormcut"): + return [("family.queue", args)] return [] diff --git a/backend/app/engine/family.py b/backend/app/engine/family.py index 50453a0..892b0e8 100644 --- a/backend/app/engine/family.py +++ b/backend/app/engine/family.py @@ -4,6 +4,7 @@ import os import shlex import shutil +import socket import subprocess import sys import time @@ -82,6 +83,8 @@ def locate(app: str) -> dict: candidates.append(("engine.json", url.rstrip("/"))) except (OSError, ValueError): continue + if app in _started_urls and _started.get(app) is not None and _started[app].poll() is None: + candidates.append(("started here", _started_urls[app])) candidates.append(("default port", f"http://127.0.0.1:{spec['port']}")) for how, url in candidates: health = _health(url, spec["header"]) @@ -95,6 +98,13 @@ def discover() -> list[dict]: _started: dict[str, subprocess.Popen] = {} +_started_urls: dict[str, str] = {} + + +def _free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] def engine_command(app: str) -> list[str] | None: @@ -125,7 +135,10 @@ def start_headless(app: str, wait: float = 90.0) -> dict: if not cmd: raise ValueError(f"{app} is not running and its engine was not found (looked for {app}-engine on the PATH and in the usual install folders; {app.upper()}_ENGINE names it)") log = config.sub("logs") / f"{app}-engine.log" - env = {**os.environ, f"{app.upper()}_PORT": "0"} + port = 0 if APPS[app]["records"] else _free_port() + env = {**os.environ, f"{app.upper()}_PORT": str(port)} + if port: + _started_urls[app] = f"http://127.0.0.1:{port}" flags = 0x08000000 if os.name == "nt" else 0 with open(log, "ab") as out: proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT, env=env, creationflags=flags, start_new_session=os.name != "nt") @@ -137,8 +150,13 @@ def start_headless(app: str, wait: float = 90.0) -> dict: where["started"] = True return where if proc.poll() is not None: + _started.pop(app, None) + _started_urls.pop(app, None) raise ValueError(f"{app}'s engine exited ({proc.returncode}); see {log}") time.sleep(0.5) + proc.terminate() + _started.pop(app, None) + _started_urls.pop(app, None) raise ValueError(f"{app}'s engine did not answer within {int(wait)} s; see {log}") @@ -147,6 +165,7 @@ def stop_started() -> None: if proc.poll() is None: proc.terminate() _started.clear() + _started_urls.clear() def _need(app: str) -> dict: diff --git a/backend/app/engine/publish.py b/backend/app/engine/publish.py index aef10bd..543f0d0 100644 --- a/backend/app/engine/publish.py +++ b/backend/app/engine/publish.py @@ -280,6 +280,41 @@ def _webhook(dest: dict, files: list[str], context: dict) -> list[str]: return [f"webhook {r.status}"] +def _increment_names() -> bool: + try: + from .host import host + + prefs = json.loads(host.call_sync(lambda e: e.execute("prefs.get", "{}", "engine"), timeout=10)).get("prefs") or {} + except BaseException: + return True + return prefs.get("incrementNames", True) is not False + + +def _free_name(path: Path) -> Path: + for i in range(1, 10000): + candidate = path.with_name(f"{path.stem}_{i}{path.suffix}") + if not os.path.lexists(candidate): + return candidate + raise ValueError(f"no free file name beside {path}") + + +def _folder(dest: dict, files: list[str]) -> list[str]: + raw = str(dest.get("path") or "").strip() + if not raw: + raise ValueError("the folder destination needs a path") + target = Path(raw).expanduser() + target.mkdir(parents=True, exist_ok=True) + increment = _increment_names() + done = [] + for f in files: + out = target / Path(f).name + if os.path.lexists(out) and increment: + out = _free_name(out) + shutil.copy2(f, out) + done.append(str(out)) + return done + + def run(destinations: list[dict], files: list[str], context: dict) -> list[dict]: results = [] for dest in destinations or []: @@ -288,15 +323,7 @@ def run(destinations: list[dict], files: list[str], context: dict) -> list[dict] kind = dest.get("type") try: if kind == "folder": - target = Path(dest.get("path") or "").expanduser() - if not str(target): - raise ValueError("the folder destination needs a path") - target.mkdir(parents=True, exist_ok=True) - done = [] - for f in files: - shutil.copy2(f, target / Path(f).name) - done.append(str(target / Path(f).name)) - results.append({"type": kind, "ok": True, "sent": done}) + results.append({"type": kind, "ok": True, "sent": _folder(dest, files)}) elif kind == "ftp": results.append({"type": kind, "ok": True, "sent": _ftp(dest, files)}) elif kind == "s3": diff --git a/backend/app/engine/rpc.py b/backend/app/engine/rpc.py index e5045ba..1b8c246 100644 --- a/backend/app/engine/rpc.py +++ b/backend/app/engine/rpc.py @@ -38,6 +38,13 @@ def query_ids() -> set[str]: return _query_ids +def caller_source(name: Any, fallback: str) -> str: + text = str(name or "")[:60].strip() + if not text or text.lower() in WINDOW_SOURCES: + return fallback + return text + + def window_only(command: Any, params: Any, source: str) -> None: if source in WINDOW_SOURCES or command != "prefs.set" or not isinstance(params, dict) or not isinstance(params.get("values"), dict): return @@ -128,6 +135,22 @@ async def family_add(p: dict, source: str) -> Any: return await execute("family.queue", {"spec": spec, **{k: p[k] for k in _QUEUE_KEYS if k in p}}, source) +async def _preset_id(name: Any) -> str | None: + """The id of the preset a name, alias or id stands for, so a stored link keeps pointing at that preset; an unknown + preset is refused.""" + if name in (None, ""): + return None + if not isinstance(name, str): + raise RpcError("preset is the id or name of a preset (preset.list shows them)", -32602) + try: + row = await execute("preset.get", {"preset": name}, "engine") + except RpcError as exc: + raise RpcError(f"no preset {name!r} to link: {exc}", -32602) from None + if not isinstance(row, dict) or not isinstance(row.get("id"), str) or not row["id"]: + raise RpcError(f"no preset {name!r} to link", -32602) + return row["id"] + + async def fetch_ffmpeg() -> dict: from .. import ffmpeg_fetch @@ -255,7 +278,7 @@ async def dispatch(method: str, params: Any, source: str = "ui") -> Any: if method == "family.linkFormcut": from . import links - return await _bridge(links.link_formcut, p.get("preset"), p.get("folder"), bool(p.get("start", True))) + return await _bridge(links.link_formcut, await _preset_id(p.get("preset")), p.get("folder"), bool(p.get("start", True))) if method == "family.unlinkFormcut": from . import links diff --git a/backend/app/routers/hooks.py b/backend/app/routers/hooks.py index d89213c..2070ed3 100644 --- a/backend/app/routers/hooks.py +++ b/backend/app/routers/hooks.py @@ -4,6 +4,7 @@ from fastapi import APIRouter, HTTPException, Request +from ..agent import approvals from ..engine import links from ..engine import rpc as engine_rpc from ..engine.host import host @@ -46,10 +47,17 @@ async def formcut_hook(request: Request) -> dict: params["preset"] = got["preset"] if got.get("folder"): params["folder"] = got["folder"] + why = await approvals.reasons("queue.addSource", params) try: - added = await engine_rpc.execute("queue.addSource", params, "formcut") + asked = await approvals.ask_later("formcut", "queue.addSource", why, params, lambda: engine_rpc.execute("queue.addSource", params, "formcut")) except engine_rpc.RpcError as exc: raise HTTPException(422, f"formencoder could not queue {got['path']}: {exc}") from None - host.bus.publish({"type": "toast", "text": f"formcut sent {got['path'].rsplit('/', 1)[-1]}", "kind": "ok"}) - got["queued"] = added + name = got["path"].rsplit("/", 1)[-1] + if "pendingApproval" in asked: + host.bus.publish({"type": "toast", "text": f"formcut sent {name}; it waits for your approval in Agent Connect", "kind": "info"}) + got["pendingApproval"] = asked["pendingApproval"] + got["why"] = asked["why"] + return got + host.bus.publish({"type": "toast", "text": f"formcut sent {name}", "kind": "ok"}) + got["queued"] = asked["result"] return got diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index 7c84d17..decb764 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -5,6 +5,7 @@ from .. import __version__ from ..agent import consent, tools from ..core.security import local_origin +from ..engine.rpc import caller_source router = APIRouter(tags=["mcp"]) VERSIONS = ["2026-07-28", "2025-11-25", "2025-06-18", "2025-03-26"] @@ -40,8 +41,7 @@ async def mcp(request: Request) -> Response: modern = version == "2026-07-28" server = {"name": "formencoder", "version": __version__} client = request.headers.get("x-formencoder-source") or "mcp:" + str((params.get("clientInfo") or {}).get("name") or request.headers.get("user-agent", "agent").split("/")[0]) - if client.strip().lower() == "ui": - client = "mcp:agent" + client = caller_source(client, "mcp:agent") token = request.headers.get("x-formencoder-agent-token") profile = request.query_params.get("profile") or request.headers.get("x-formencoder-mcp-profile") caps = {"tools": {}, "prompts": {}, "resources": {}} diff --git a/backend/app/routers/rpc.py b/backend/app/routers/rpc.py index 71ea6a7..41a66f0 100644 --- a/backend/app/routers/rpc.py +++ b/backend/app/routers/rpc.py @@ -7,6 +7,7 @@ from ..engine import rpc router = APIRouter(tags=["rpc"]) +QUEUEING = ("family.add", "family.addLink", "family.linkFormcut") def _label(message) -> str: @@ -29,6 +30,8 @@ async def _reasons(message) -> list[str]: p = message.get("params") or {} if message.get("method") == "command.execute": return await approvals.reasons(str(p.get("command") or ""), p.get("params") or {}) + if message.get("method") in QUEUEING: + return await approvals.reasons("family.queue", p) if message.get("method") == "command.batch": out = [] for s in p.get("steps") or []: @@ -44,9 +47,7 @@ async def call(request: Request) -> Response: message = json.loads(await request.body()) except ValueError: return Response(json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}), media_type="application/json", status_code=400) - source = request.headers.get("x-formencoder-source", "cli")[:60] or "cli" - if source.strip().lower() == "ui": - source = "cli" + source = rpc.caller_source(request.headers.get("x-formencoder-source"), "cli") rid = message.get("id") if isinstance(message, dict) else None denied = await consent.gate_for(request, source, request.headers.get("x-formencoder-agent-token"), mutating=consent.mutating_rpc(message), what=f"run {_label(message)}"[:120]) if denied: diff --git a/backend/app/routers/terminal.py b/backend/app/routers/terminal.py index e72faeb..37d148a 100644 --- a/backend/app/routers/terminal.py +++ b/backend/app/routers/terminal.py @@ -395,7 +395,10 @@ async def open_tab(request: Request) -> dict: if found.state != "runs": raise HTTPException(404, {"code": "not_installed", "message": finder.said(found), "install": PROGRAMS[kind]["install"]}) path = found.path - argv = agent_lookup.start_argv([path, *(["--resume", resume] if resume else []), *((["--", prompt] if prompt.startswith("-") else [prompt]) if prompt else [])]) + try: + argv = agent_lookup.start_argv([path, *(["--resume", resume] if resume else []), *((["--", prompt] if prompt.startswith("-") else [prompt]) if prompt else [])]) + except agent_lookup.Refused as exc: + raise HTTPException(422, {"code": "refused", "message": str(exc)}) from None title = body.get("title") if isinstance(body.get("title"), str) else None cwd = body.get("cwd") if isinstance(body.get("cwd"), str) and kind != "antigravity" else None try: diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index ea34eba..6669908 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -26,7 +26,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", @@ -45,6 +45,10 @@ MARK = "__FORM_AGENT_LOOKUP__" HOW = {"setting": "your setting", "override": "the development override", "path": "the engine's PATH", "folder": "a known install folder", "shell": "your shell's PATH"} RETRY_SECONDS = 60.0 +BATCH_ENDINGS = (".cmd", ".bat") +SHIM_TARGET = re.compile(r'"%~?dp0%?\\([^"%\r\n]+)"\s+%\*', re.IGNORECASE) +SHIM_SCRIPTS = (".js", ".cjs", ".mjs") +INTERPRETER_REFUSED = re.compile(r'[&|<>^()!%"\x00-\x1f\x7f]') _lock = threading.RLock() _shell: dict = {} @@ -359,13 +363,75 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +class Refused(ValueError): + """A start this file will not make: the words cannot be handed to the command interpreter as plain text.""" + + +def batch(path: str | os.PathLike) -> bool: + """Whether Windows runs this file through the command interpreter (.cmd or .bat, trailing dots and spaces ignored).""" + return str(path).rstrip(". ").lower().endswith(BATCH_ENDINGS) + + +def _node(folder: Path, env: dict) -> str | None: + beside = folder / "node.exe" + if beside.is_file(): + return str(beside) + for part in env.get("PATH", "").split(os.pathsep): + found = Path(part) / "node.exe" if part else None + if found is not None and found.is_file(): + return str(found) + return None + + +def shim_target(path: str | os.PathLike, env: dict | None = None) -> list[str] | None: + """The words that run what an npm style .cmd shim starts, without the command interpreter: the .exe it names, or + node.exe (beside the shim, else on PATH) and the script. None when the file is not such a shim or its target is missing.""" + shim = Path(path) + try: + text = shim.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + said = SHIM_TARGET.findall(text) + if not said: + return None + target = shim.parent.joinpath(*[part for part in said[-1].replace("/", "\\").split("\\") if part]) + if not target.is_file(): + return None + ending = target.suffix.lower() + if ending == ".exe": + return [str(target)] + if ending not in SHIM_SCRIPTS: + return None + node = _node(shim.parent, os.environ if env is None else env) + return [node, str(target)] if node else None + + +def interpreter_words(words: list[str]) -> list[str]: + """The words, when the command interpreter reads every one of them as plain text. A .cmd or .bat reads its arguments + again through %*, and the interpreter acts on & | < > ^ ( ) ! % and double quotes even inside quotes, so a word holding + any of them, or a control character, is refused whether or not it holds a space.""" + for word in words: + if INTERPRETER_REFUSED.search(word): + raise Refused("A program started through the Windows command interpreter (a .cmd or .bat) cannot take text holding " + "& | < > ^ ( ) ! % \" or a control character. Pass long or free text through standard input or a file " + "if the program reads one, or start its .exe or node script directly.") + 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. An npm style .cmd shim is followed to the program it starts + and that runs directly; any other .cmd or .bat runs under the command interpreter (AutoRun off), its words checked + first by interpreter_words, which raises Refused.""" 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 batch(words[0]): + return words + direct = shim_target(words[0], env) + if direct: + return [*direct, *words[1:]] + return [env.get("COMSPEC") or "cmd.exe", "/d", "/c", *interpreter_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)] @@ -414,8 +480,8 @@ def check(found: Found, env: dict | None = None, timeout: float = 15.0, fresh: b kept = ("broken", None, _last_line(out.stderr) or _last_line(out.stdout) or f"it ended with code {out.returncode}", time.monotonic()) except subprocess.TimeoutExpired: kept = ("broken", None, f"it gave no answer to --version in {timeout:g} seconds", time.monotonic()) - except OSError as exc: - kept = ("broken", None, exc.strerror or str(exc), time.monotonic()) + except (OSError, Refused) as exc: + kept = ("broken", None, getattr(exc, "strerror", None) or str(exc), time.monotonic()) with _lock: _checked[key] = kept found.state, found.version, found.error = kept[0], kept[1], kept[2] diff --git a/backend/tests/test_agent_approvals.py b/backend/tests/test_agent_approvals.py new file mode 100644 index 0000000..31a4f21 --- /dev/null +++ b/backend/tests/test_agent_approvals.py @@ -0,0 +1,365 @@ +import asyncio +import json + +import pytest + +from conftest import LOCAL_HEADER, make_clip, set_policy + +WAITS = -32004 + + +@pytest.fixture +def allowed(monkeypatch): + from app.agent import approvals, consent + + set_policy("ask") + monkeypatch.setattr(consent, "_session", {"cli"}) + monkeypatch.setattr(approvals, "full_faith", lambda: False) + yield + approvals.pending.clear() + set_policy("ask") + + +def rpc(client, method, params): + return client.post("/api/rpc", json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, headers={LOCAL_HEADER: "1", "x-formencoder-source": "cli"}).json() + + +def waits(out): + return (out.get("error") or {}).get("code") == WAITS + + +@pytest.mark.parametrize("method", ["family.add", "family.addLink"]) +def test_family_items_that_publish_wait_for_the_person(client, allowed, method): + settings = {"format": "h264", "publish": [{"type": "webhook", "url": "https://example.com/hook"}]} + out = rpc(client, method, {"app": "formcut", "id": "p1", "path": "x.fvxlink", "settings": settings, "start": True}) + assert waits(out), out + + +def test_the_family_tool_counts_as_queueing(): + from app.agent import tools + + assert tools._commands_of("family", {"action": "add", "app": "formcut", "settings": {}}) == [("family.queue", {"action": "add", "app": "formcut", "settings": {}})] + assert tools._commands_of("family", {"action": "discover"}) == [] + + +def test_a_folder_destination_waits_for_the_person(client, allowed, tmp_path): + settings = {"publish": [{"type": "folder", "path": str(tmp_path / "deliveries")}]} + out = rpc(client, "command.execute", {"command": "queue.addSource", "params": {"paths": [str(tmp_path / "a.mov")], "settings": settings}}) + assert waits(out), out + + +def test_a_preset_that_publishes_waits_for_the_person(client, allowed, tmp_path): + from app.engine import rpc as engine_rpc + + settings = {"format": "h264", "publish": [{"type": "webhook", "url": "https://example.com/hook"}]} + made = asyncio.run(engine_rpc.execute("preset.create", {"name": "Sends Off", "settings": settings}, "test")) + preset = made["preset"] + try: + out = rpc(client, "command.execute", {"command": "queue.addSource", "params": {"paths": [str(tmp_path / "a.mov")], "preset": preset}}) + assert waits(out), out + finally: + asyncio.run(engine_rpc.execute("preset.delete", {"preset": preset}, "test")) + + +def test_saving_the_queue_over_a_file_is_refused_without_overwrite(client, allowed, tmp_path): + saved = tmp_path / "show.fequeue" + saved.write_text("{}", encoding="utf-8") + out = rpc(client, "command.execute", {"command": "queue.save", "params": {"path": str(tmp_path / "show")}}) + assert not waits(out) and "overwrite" in out["error"]["message"], out + assert saved.read_text(encoding="utf-8") == "{}" + + +def test_saving_the_queue_with_overwrite_waits_for_the_person(client, allowed, tmp_path): + saved = tmp_path / "show.fequeue" + saved.write_text("{}", encoding="utf-8") + out = rpc(client, "command.execute", {"command": "queue.save", "params": {"path": str(saved), "overwrite": True}}) + assert waits(out), out + assert saved.read_text(encoding="utf-8") == "{}" + + +def test_the_engine_replaces_a_saved_queue_only_with_overwrite(tmp_path): + from app.engine import rpc as engine_rpc + + saved = tmp_path / "show.fequeue" + saved.write_text("{}", encoding="utf-8") + with pytest.raises(engine_rpc.RpcError, match="overwrite"): + asyncio.run(engine_rpc.execute("queue.save", {"path": str(saved)}, "ui")) + assert saved.read_text(encoding="utf-8") == "{}" + asyncio.run(engine_rpc.execute("queue.save", {"path": str(saved), "overwrite": True}, "ui")) + assert json.loads(saved.read_text(encoding="utf-8"))["format"] == "formencoder.queue/1" + + +def test_saving_the_queue_is_a_change_not_a_query(): + import fe_core + + rows = {r["id"]: r for r in json.loads(fe_core.Engine().command_list(None, False))} + assert rows["queue.save"]["query"] is False + + +def test_a_folder_destination_keeps_a_file_of_the_same_name(tmp_path): + from app.engine import publish + + made = tmp_path / "out" / "clip.mp4" + made.parent.mkdir() + made.write_bytes(b"new") + target = tmp_path / "deliveries" + target.mkdir() + (target / "clip.mp4").write_bytes(b"old") + results = publish.run([{"type": "folder", "path": str(target)}], [str(made)], {}) + assert results[0]["ok"], results + assert (target / "clip.mp4").read_bytes() == b"old" + assert (target / "clip_1.mp4").read_bytes() == b"new" + + +def test_a_folder_destination_with_no_path_is_refused(tmp_path, monkeypatch): + from app.engine import publish + + made = tmp_path / "out" / "clip.mp4" + made.parent.mkdir() + made.write_bytes(b"new") + monkeypatch.chdir(tmp_path) + results = publish.run([{"type": "folder", "path": " "}], [str(made)], {}) + assert not results[0]["ok"] and "needs a path" in results[0]["error"] + assert not (tmp_path / "clip.mp4").exists() + + +def test_importing_a_preset_file_that_publishes_waits_for_the_person(client, allowed, tmp_path): + preset = tmp_path / "Sends Off.fepreset" + preset.write_text(json.dumps({"name": "Sends Off", "settings": {"format": "h264", "publish": [{"type": "webhook", "url": "https://example.com/hook"}]}}), encoding="utf-8") + steps = [{"command": "preset.import", "params": {"path": str(preset)}}, {"command": "queue.addSource", "params": {"paths": [str(tmp_path / "a.mov")], "preset": "Sends Off"}}] + out = rpc(client, "command.batch", {"steps": steps}) + assert waits(out), out + + +def test_a_folder_path_is_shown_on_one_line(client, allowed, tmp_path): + settings = {"publish": [{"type": "folder", "path": str(tmp_path / "a\nb")}]} + out = rpc(client, "command.execute", {"command": "queue.addSource", "params": {"paths": [str(tmp_path / "a.mov")], "settings": settings}}) + assert waits(out), out + assert "\n" not in out["error"]["message"] + + +def test_a_folder_destination_keeps_a_link_of_the_same_name(tmp_path): + from app.engine import publish + + made = tmp_path / "out" / "clip.mp4" + made.parent.mkdir() + made.write_bytes(b"new") + target = tmp_path / "deliveries" + target.mkdir() + elsewhere = tmp_path / "elsewhere.mp4" + (target / "clip.mp4").symlink_to(elsewhere) + results = publish.run([{"type": "folder", "path": str(target)}], [str(made)], {}) + assert results[0]["ok"], results + assert not elsewhere.exists() + assert (target / "clip_1.mp4").read_bytes() == b"new" + + +PUBLISHING = {"format": "h264", "publish": [{"type": "webhook", "url": "https://example.com/hook"}]} + + +@pytest.fixture +def sends_off(): + from app.engine import rpc as engine_rpc + + made = asyncio.run(engine_rpc.execute("preset.create", {"name": "Sends Off", "settings": PUBLISHING}, "test")) + yield made["preset"] + asyncio.run(engine_rpc.execute("preset.delete", {"preset": made["preset"]}, "test")) + + +def test_a_preset_that_cannot_be_read_waits_for_the_person(client, allowed, tmp_path): + out = rpc(client, "command.execute", {"command": "queue.addSource", "params": {"paths": [str(tmp_path / "a.mov")], "preset": "user/not-a-preset-anywhere"}}) + assert waits(out), out + assert "could not be read" in out["error"]["message"] + + +@pytest.mark.parametrize("command,extra", [("preset.duplicate", {"name": "Copy"}), ("preset.alias", {"alias": "Short"}), ("preset.update", {"name": "Renamed"})]) +def test_naming_or_copying_a_preset_that_publishes_waits_for_the_person(client, allowed, sends_off, command, extra): + out = rpc(client, "command.execute", {"command": command, "params": {"preset": sends_off, **extra}}) + assert waits(out), out + + +def test_an_update_is_checked_on_the_settings_it_leaves(client, allowed): + from app.agent import approvals + from app.engine import rpc as engine_rpc + + made = asyncio.run(engine_rpc.execute("preset.create", {"name": "Quiet", "settings": {"format": "h264"}}, "test")) + params = {"preset": made["preset"], "settings": {"publish": [{"type": "youtube"}]}} + try: + row = asyncio.run(engine_rpc.execute("preset.resolve", {"command": "preset.update", "params": params}, "engine")) + assert row == {"publishes": True, "destinations": ["youtube"], "deletesLocal": False} + assert "it sends the encoded file to youtube" in asyncio.run(approvals.reasons("preset.update", params)) + assert asyncio.run(approvals.reasons("preset.update", {"preset": made["preset"], "name": "Still Quiet"})) == [] + finally: + asyncio.run(engine_rpc.execute("preset.delete", {"preset": made["preset"]}, "test")) + + +def test_a_preset_made_from_an_output_that_publishes_waits_for_the_person(client, allowed, tmp_path): + from app.engine import rpc as engine_rpc + + clip = tmp_path / "a.mp4" + make_clip(clip, seconds=1) + added = asyncio.run(engine_rpc.execute("queue.addSource", {"paths": [str(clip)], "settings": PUBLISHING}, "ui")) + state = asyncio.run(engine_rpc.state()) + output = next(o["id"] for it in state["items"] for o in it["outputs"] if it["path"] == str(clip)) + try: + out = rpc(client, "command.execute", {"command": "preset.create", "params": {"name": "From Output", "fromOutput": output}}) + assert waits(out), out + finally: + asyncio.run(engine_rpc.execute("queue.remove", {"refs": [it["id"] for it in state["items"] if it["path"] == str(clip)]}, "ui")) + assert added is not None + + +@pytest.mark.parametrize("body", [None, "not json {", "[1, 2]"]) +def test_a_preset_file_that_cannot_be_read_waits_for_the_person(client, allowed, tmp_path, body): + preset = tmp_path / "broken.fepreset" + if body is not None: + preset.write_text(body, encoding="utf-8") + out = rpc(client, "command.execute", {"command": "preset.import", "params": {"path": str(preset)}}) + assert waits(out), out + assert "could not be read" in out["error"]["message"] + + +def test_an_imported_preset_is_read_the_way_the_engine_reads_it(tmp_path, monkeypatch): + from app.engine import rpc as engine_rpc + + monkeypatch.setenv("HOME", str(tmp_path)) + (tmp_path / "Sends.fepreset").write_text(json.dumps({"name": "Sends", "settings": PUBLISHING}), encoding="utf-8") + row = asyncio.run(engine_rpc.execute("preset.resolve", {"command": "preset.import", "params": {"path": "~/Sends.fepreset"}}, "engine")) + assert row == {"publishes": True, "destinations": ["webhook"], "deletesLocal": False} + + +def test_resolving_preset_settings_returns_only_the_publish_summary(tmp_path): + from app.engine import rpc as engine_rpc + + marker = "settings-text-that-stays-in-the-file" + settings = {"format": "h264", "comments": marker, "publish": [{"type": "folder", "path": str(tmp_path / marker), "deleteLocal": True}, {"type": marker}]} + (tmp_path / "Folder.fepreset").write_text(json.dumps({"name": marker, "settings": settings}), encoding="utf-8") + row = asyncio.run(engine_rpc.execute("preset.resolve", {"command": "preset.import", "params": {"path": str(tmp_path / "Folder.fepreset")}}, "engine")) + assert row == {"publishes": True, "destinations": ["folder", "other"], "deletesLocal": True} + assert marker not in json.dumps(row) + quiet = tmp_path / "Quiet.fepreset" + quiet.write_text(json.dumps({"settings": {"format": "h264"}}), encoding="utf-8") + row = asyncio.run(engine_rpc.execute("preset.resolve", {"command": "preset.import", "params": {"path": str(quiet)}}, "engine")) + assert row == {"publishes": False, "destinations": [], "deletesLocal": False} + + +def test_a_file_that_is_not_a_preset_is_not_echoed_back(tmp_path): + from app.agent import approvals + from app.engine import rpc as engine_rpc + + marker = "plain-text-that-stays-in-the-file" + other = tmp_path / "notes.txt" + other.write_text(marker + " {", encoding="utf-8") + with pytest.raises(engine_rpc.RpcError) as raised: + asyncio.run(engine_rpc.execute("preset.resolve", {"command": "preset.import", "params": {"path": str(other)}}, "engine")) + assert marker not in str(raised.value) and str(other) not in str(raised.value) + missing = tmp_path / "missing.fepreset" + with pytest.raises(engine_rpc.RpcError) as raised: + asyncio.run(engine_rpc.execute("preset.resolve", {"command": "preset.import", "params": {"path": str(missing)}}, "engine")) + assert str(missing) not in str(raised.value) + why = asyncio.run(approvals.reasons("preset.import", {"path": str(other)})) + assert any("could not be read" in w for w in why) and not any(marker in w for w in why) + + +@pytest.mark.parametrize("source", ["agent", "mcp:agent", "cli", "ui", "test", "desktop"]) +def test_only_the_engine_resolves_preset_settings(tmp_path, source): + from app.engine import rpc as engine_rpc + + (tmp_path / "Sends.fepreset").write_text(json.dumps({"settings": PUBLISHING}), encoding="utf-8") + call = {"command": "preset.import", "params": {"path": str(tmp_path / "Sends.fepreset")}} + with pytest.raises(engine_rpc.RpcError) as raised: + asyncio.run(engine_rpc.execute("preset.resolve", call, source)) + assert "webhook" not in str(raised.value) + with pytest.raises(engine_rpc.RpcError): + asyncio.run(engine_rpc.batch([{"command": "preset.resolve", "params": call}], None, False, source)) + + +def test_an_outside_caller_cannot_resolve_preset_settings(client, allowed, tmp_path): + (tmp_path / "Sends.fepreset").write_text(json.dumps({"settings": PUBLISHING}), encoding="utf-8") + call = {"command": "preset.import", "params": {"path": str(tmp_path / "Sends.fepreset")}} + for method, params in (("command.execute", {"command": "preset.resolve", "params": call}), ("command.batch", {"steps": [{"command": "preset.resolve", "params": call}], "atomic": False})): + out = rpc(client, method, params) + assert "error" in out and not waits(out), out + assert "webhook" not in json.dumps(out) + out = client.post("/api/rpc", json={"jsonrpc": "2.0", "id": 1, "method": "command.execute", "params": {"command": "preset.resolve", "params": call}}, + headers={LOCAL_HEADER: "1", "x-formencoder-source": "engine"}).json() + assert "error" in out and "webhook" not in json.dumps(out), out + + +SERVICE_ONLY = {"preset.resolve": "preset_resolve", "family.resolved": "family_resolved", "publish.result": "publish_result"} +SERVICE_CALLS = [("family.resolved", {"output": "o-none", "error": "x"}), ("publish.result", {"output": "o-none", "results": [{"ok": True}]})] + + +@pytest.mark.parametrize("command,params", SERVICE_CALLS) +@pytest.mark.parametrize("source", ["agent", "mcp:agent", "cli", "ui", "test", "desktop"]) +def test_only_the_engine_hands_back_service_answers(command, params, source): + from app.engine import rpc as engine_rpc + + with pytest.raises(engine_rpc.RpcError) as raised: + asyncio.run(engine_rpc.execute(command, params, source)) + assert "internal to the engine" in str(raised.value) + with pytest.raises(engine_rpc.RpcError): + asyncio.run(engine_rpc.batch([{"command": command, "params": params}], None, False, source)) + + +@pytest.mark.parametrize("command,params", SERVICE_CALLS) +def test_an_outside_caller_cannot_hand_back_service_answers(client, allowed, command, params): + for method, body in (("command.execute", {"command": command, "params": params}), ("command.batch", {"steps": [{"command": command, "params": params}], "atomic": False})): + for source in ("cli", "engine"): + out = client.post("/api/rpc", json={"jsonrpc": "2.0", "id": 1, "method": method, "params": body}, headers={LOCAL_HEADER: "1", "x-formencoder-source": source}).json() + assert "error" in out and not waits(out), out + assert "internal to the engine" in out["error"]["message"], out + + +def test_engine_service_commands_are_not_offered_to_agents(): + import fe_core + + from conftest import REPO, tool_catalogue + + engine = fe_core.Engine() + listed = {r["id"] for r in json.loads(engine.command_list(None, False))} + tools = {t["name"] for t in tool_catalogue()} + manifest = json.loads((REPO / "agents" / "manifest.json").read_text(encoding="utf-8")) + docs = [doc.read_text(encoding="utf-8") for doc in (REPO / ".claude" / "skills" / "formencoder-harness" / "references").glob("*.md")] + for command, tool in SERVICE_ONLY.items(): + assert command not in listed and not engine.is_command(command), command + with pytest.raises(ValueError): + engine.describe(command) + assert tool not in tools, tool + assert not any(tool in v for v in manifest["mcp"].values() if isinstance(v, list)), tool + assert not any(f"`{command}`" in d for d in docs), command + + +def test_a_formcut_link_keeps_the_preset_id_and_refuses_an_unknown_preset(): + from app.engine import rpc as engine_rpc + + row = asyncio.run(engine_rpc.execute("preset.get", {"preset": "system/youtube-1080p"}, "test")) + assert asyncio.run(engine_rpc._preset_id(row["name"])) == row["id"] + assert asyncio.run(engine_rpc._preset_id("")) is None + with pytest.raises(engine_rpc.RpcError, match="no preset"): + asyncio.run(engine_rpc.dispatch("family.linkFormcut", {"preset": "user/not-a-preset-anywhere"}, "ui")) + + +def test_a_formcut_export_for_a_preset_that_publishes_waits_for_the_person(client, allowed, sends_off): + import hashlib + import hmac + import time + + from app.agent import approvals + from app.engine import links + + kept = links.read() + links._write({**kept, "formcut": {"hook": "h1", "secret": "s3cret", "formcutUrl": "http://127.0.0.1:1", "preset": sends_off, "folder": "", "start": True, "received": 0, "last": None}}) + data = b"exported" + payload = json.dumps({"event": "export.finished", "export": {"name": "cut.mp4", "sha256": hashlib.sha256(data).hexdigest()}}) + stamp = str(int(time.time())) + signature = "sha256=" + hmac.new(b"s3cret", stamp.encode() + b"." + payload.encode(), hashlib.sha256).hexdigest() + try: + r = client.post("/api/family/hooks/formcut", data={"payload": payload}, files={"file": ("cut.mp4", data, "video/mp4")}, + headers={"x-formcut-timestamp": stamp, "x-formcut-signature": signature}) + got = r.json() + assert r.status_code == 200, got + assert got.get("pendingApproval") in approvals.pending, got + assert "queued" not in got + finally: + links._write(kept) diff --git a/backend/tests/test_agent_start.py b/backend/tests/test_agent_start.py new file mode 100644 index 0000000..5c959f3 --- /dev/null +++ b/backend/tests/test_agent_start.py @@ -0,0 +1,108 @@ +"""How an agent program is started on Windows, tested through the argv builder with a made-up folder and environment, so it +runs on any system.""" + +import os + +import pytest + +from app.services import agent_lookup + +WIN = "win32" +MODERN_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\\tool\\cli.js" %*\r\n' +) +OLD_SHIM = '@IF EXIST "%~dp0\\node.exe" (\r\n "%~dp0\\node.exe" "%~dp0\\node_modules\\tool\\bin\\tool.js" %*\r\n) ELSE (\r\n node "%~dp0\\node_modules\\tool\\bin\\tool.js" %*\r\n)\r\n' +EXE_SHIM = '@ECHO off\r\n"%~dp0\\node_modules\\tool\\bin\\tool.exe" %*\r\n' +REFUSED = list('&|<>^()!%"') + ["\n", "\r", "\t", "\x00", "\x1b", "\x7f"] + + +def _file(path, text=""): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path + + +def _env(tmp_path, **more): + return {"COMSPEC": r"C:\Windows\System32\cmd.exe", "PATH": str(tmp_path / "empty"), **more} + + +def test_a_modern_npm_shim_runs_its_script_with_the_node_beside_it(tmp_path): + shim = _file(tmp_path / "npm" / "tool.cmd", MODERN_SHIM) + node = _file(tmp_path / "npm" / "node.exe") + script = _file(tmp_path / "npm" / "node_modules" / "@scope" / "tool" / "cli.js") + argv = agent_lookup.start_argv([str(shim), "--print", "a & b | c"], _env(tmp_path), WIN) + assert argv == [str(node), str(script), "--print", "a & b | c"] + + +def test_an_older_npm_shim_runs_its_script_with_node_from_path(tmp_path): + shim = _file(tmp_path / "npm" / "tool.CMD", OLD_SHIM) + script = _file(tmp_path / "npm" / "node_modules" / "tool" / "bin" / "tool.js") + node = _file(tmp_path / "nodejs" / "node.exe") + env = _env(tmp_path, PATH=os.pathsep.join([str(tmp_path / "empty"), str(tmp_path / "nodejs")])) + assert agent_lookup.start_argv([str(shim), "100%"], env, WIN) == [str(node), str(script), "100%"] + + +def test_a_shim_that_names_an_exe_runs_the_exe(tmp_path): + shim = _file(tmp_path / "npm" / "tool.cmd", EXE_SHIM) + exe = _file(tmp_path / "npm" / "node_modules" / "tool" / "bin" / "tool.exe") + assert agent_lookup.start_argv([str(shim), "(x)"], _env(tmp_path), WIN) == [str(exe), "(x)"] + + +def test_a_shim_whose_script_is_missing_falls_back_to_the_interpreter(tmp_path): + shim = _file(tmp_path / "npm" / "tool.cmd", MODERN_SHIM) + _file(tmp_path / "npm" / "node.exe") + env = _env(tmp_path) + assert agent_lookup.start_argv([str(shim), "--version"], env, WIN) == [env["COMSPEC"], "/d", "/c", str(shim), "--version"] + + +def test_a_shim_with_no_node_falls_back_to_the_interpreter(tmp_path): + shim = _file(tmp_path / "npm" / "tool.cmd", MODERN_SHIM) + _file(tmp_path / "npm" / "node_modules" / "@scope" / "tool" / "cli.js") + assert agent_lookup.start_argv([str(shim), "x"], _env(tmp_path), WIN)[:3] == [r"C:\Windows\System32\cmd.exe", "/d", "/c"] + + +def test_plain_words_and_spaces_pass_the_interpreter(tmp_path): + bat = _file(tmp_path / "my tools" / "agent.bat", "@echo off\r\nrem not a shim\r\n") + env = _env(tmp_path) + words = [str(bat), "--resume", "fix the build please", r"C:\work\clip one.mov"] + assert agent_lookup.start_argv(words, env, WIN) == [env["COMSPEC"], "/d", "/c", *words] + + +@pytest.mark.parametrize("char", REFUSED) +@pytest.mark.parametrize("spaced", [False, True]) +def test_an_interpreter_argument_with_a_special_character_is_refused(tmp_path, char, spaced): + bat = _file(tmp_path / "bin" / "agent.cmd", "@echo off\r\n") + word = f"say {char} this" if spaced else f"say{char}this" + with pytest.raises(agent_lookup.Refused, match="standard input or a file"): + agent_lookup.start_argv([str(bat), word], _env(tmp_path), WIN) + + +@pytest.mark.parametrize("char", list("&()!%")) +def test_an_interpreter_program_path_with_a_special_character_is_refused(tmp_path, char): + bat = _file(tmp_path / f"odd{char}dir" / "agent.bat", "@echo off\r\n") + with pytest.raises(agent_lookup.Refused): + agent_lookup.start_argv([str(bat), "--version"], _env(tmp_path), WIN) + + +def test_a_trailing_dot_still_counts_as_a_batch_file(tmp_path): + bat = _file(tmp_path / "bin" / "agent.cmd", "@echo off\r\n") + with pytest.raises(agent_lookup.Refused): + agent_lookup.start_argv([str(bat) + ".", "a&b"], _env(tmp_path), WIN) + + +def test_an_exe_takes_any_argument_directly(tmp_path): + exe = _file(tmp_path / "bin" / "agent.exe") + words = [str(exe), 'a & b | "c" %PATH% ^ (d) !e!\nf'] + assert agent_lookup.start_argv(words, _env(tmp_path), WIN) == words + + +def test_a_refused_start_is_reported_as_not_starting(tmp_path): + bat = _file(tmp_path / "odd&dir" / "agent.cmd", "@echo off\r\n") + agent_lookup.forget() + found = agent_lookup.Found("claude", "Claude Code", path=str(bat), how="path", state="found") + checked = agent_lookup.check(found, _env(tmp_path), fresh=True, platform=WIN) + assert checked.state == "broken" + assert "command interpreter" in checked.error + agent_lookup.forget() diff --git a/backend/tests/test_cache_folder.py b/backend/tests/test_cache_folder.py new file mode 100644 index 0000000..d39be20 --- /dev/null +++ b/backend/tests/test_cache_folder.py @@ -0,0 +1,24 @@ +from pathlib import Path + + +def test_cleaning_a_chosen_cache_folder_keeps_the_other_files_in_it(driver, tmp_path): + d = driver() + chosen = tmp_path / "media" + chosen.mkdir() + mine = chosen / "holiday.mov" + mine.write_bytes(b"x" * 4096) + d.run("prefs.set", values={"cacheFolder": str(chosen)}) + folder = Path(d.run("prefs.cacheInfo")["folder"]) + assert folder != chosen and chosen in folder.parents + (folder / "preview").mkdir(parents=True, exist_ok=True) + (folder / "preview" / "frame.png").write_bytes(b"y" * 4096) + out = d.run("prefs.cleanCache", all=True) + assert out["removed"] == 1 and out["files"] == 0 + assert mine.read_bytes() == b"x" * 4096 + + +def test_a_folder_already_named_for_the_cache_is_used_as_it_is(driver, tmp_path): + d = driver() + chosen = tmp_path / "Formencoder Cache" + d.run("prefs.set", values={"cacheFolder": str(chosen)}) + assert Path(d.run("prefs.cacheInfo")["folder"]) == chosen diff --git a/backend/tests/test_family_headless.py b/backend/tests/test_family_headless.py new file mode 100644 index 0000000..9c69d6d --- /dev/null +++ b/backend/tests/test_family_headless.py @@ -0,0 +1,52 @@ +import sys +import textwrap + +import pytest + + +def test_a_headless_app_without_an_engine_record_is_found_where_it_was_started(tmp_path, monkeypatch): + from app.engine import family + + server = tmp_path / "fake_formwav.py" + server.write_text(textwrap.dedent(""" + import json, os + from http.server import BaseHTTPRequestHandler, HTTPServer + + class Health(BaseHTTPRequestHandler): + def do_GET(self): + body = json.dumps({"status": "ok", "version": "test"}).encode() + self.send_response(200) + self.send_header("content-type", "application/json") + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + HTTPServer(("127.0.0.1", int(os.environ.get("FORMWAV_PORT") or 0)), Health).serve_forever() + """), encoding="utf-8") + monkeypatch.setenv("FORMWAV_ENGINE", f'"{sys.executable}" "{server}"') + monkeypatch.delenv("FORMWAV_URL", raising=False) + try: + where = family.start_headless("formwav", wait=30) + assert where["running"] and where["started"] + assert where["url"] != "http://127.0.0.1:8060" + assert family.locate("formwav")["url"] == where["url"] + finally: + family.stop_started() + + +def test_a_headless_app_that_exits_is_not_looked_for_where_it_was_started(tmp_path, monkeypatch): + from app.engine import family + + server = tmp_path / "quits.py" + server.write_text("raise SystemExit(3)\n", encoding="utf-8") + monkeypatch.setenv("FORMWAV_ENGINE", f'"{sys.executable}" "{server}"') + monkeypatch.delenv("FORMWAV_URL", raising=False) + try: + with pytest.raises(ValueError, match="exited"): + family.start_headless("formwav", wait=30) + assert "formwav" not in family._started_urls + assert "formwav" not in family._started + finally: + family.stop_started() diff --git a/backend/tests/test_window_prefs.py b/backend/tests/test_window_prefs.py index 8b31a54..a711454 100644 --- a/backend/tests/test_window_prefs.py +++ b/backend/tests/test_window_prefs.py @@ -27,11 +27,20 @@ def test_agents_cannot_change_window_only_preferences(client, allowed, values): assert MESSAGE in batch["error"]["message"] -def test_a_source_naming_itself_ui_is_still_an_agent(client, allowed): - out = rpc(client, "command.execute", {"command": "prefs.set", "params": {"values": {"incrementNames": False}}}, source="ui") +@pytest.mark.parametrize("name", ["ui", "engine", "desktop", " Desktop "]) +def test_a_source_naming_itself_after_the_app_is_still_an_agent(client, allowed, name): + out = rpc(client, "command.execute", {"command": "prefs.set", "params": {"values": {"incrementNames": False}}}, source=name) assert MESSAGE in out["error"]["message"] +@pytest.mark.parametrize("name", ["ui", "engine", "desktop"]) +def test_an_mcp_client_naming_itself_after_the_app_is_still_an_agent(client, name): + from app.engine import rpc as engine_rpc + + assert engine_rpc.caller_source(name, "mcp:agent") == "mcp:agent" + assert engine_rpc.caller_source("mcp:claude", "mcp:agent") == "mcp:claude" + + def test_agents_can_still_change_other_preferences(client, allowed): out = rpc(client, "command.execute", {"command": "prefs.set", "params": {"values": {"chime": True}}}) assert out["result"]["prefs"]["chime"] is True diff --git a/frontend/src/app/ctx.ts b/frontend/src/app/ctx.ts index f24f335..77c4a7f 100644 --- a/frontend/src/app/ctx.ts +++ b/frontend/src/app/ctx.ts @@ -23,6 +23,8 @@ interface Picker { ext?: string[]; name?: string; title?: string; + /** A boolean param set to true once the person picks a path here, as the save dialog is their consent to replace it. */ + overwrite?: string; } export const MEDIA = ['mp4', 'mov', 'm4v', 'mkv', 'webm', 'avi', 'mxf', 'mts', 'm2ts', 'ts', 'mpg', 'mpeg', 'm2v', 'vob', 'wmv', 'flv', '3gp', 'dv', 'ogv', 'y4m', 'png', 'jpg', 'jpeg', 'tif', 'tiff', 'bmp', 'tga', 'dpx', 'exr', 'webp', 'gif', 'jp2', 'psd', 'wav', 'aif', 'aiff', 'mp3', 'aac', 'm4a', 'flac', 'ogg', 'opus', 'wma', 'ac3', 'eac3', 'caf', 'bwf', 'fvxlink']; @@ -35,7 +37,7 @@ const PICKERS: Record = { 'watch.add': [{ key: 'folder', mode: 'folder', title: 'Add Watch Folder' }], 'preset.import': [{ key: 'path', mode: 'open', ext: ['fepreset', 'json', 'epr'], title: 'Import Preset' }], 'preset.export': [{ key: 'path', mode: 'save', ext: ['fepreset'], name: 'Preset.fepreset', title: 'Export Preset' }], - 'queue.save': [{ key: 'path', mode: 'save', ext: ['fequeue'], name: 'Queue.fequeue', title: 'Save Queue' }], + 'queue.save': [{ key: 'path', mode: 'save', ext: ['fequeue'], name: 'Queue.fequeue', title: 'Save Queue', overwrite: 'overwrite' }], 'queue.open': [{ key: 'path', mode: 'open', ext: ['fequeue', 'json'], title: 'Open Queue' }], 'lut.install': [{ key: 'path', mode: 'open', ext: ['cube', '3dl'], title: 'Install LUT' }], 'captions.read': [{ key: 'path', mode: 'open', ext: CAPTIONS, title: 'Read Captions' }], @@ -142,6 +144,7 @@ export class Ctx { const got = await pickFiles({ title: label, mode: picker.mode, multiple: picker.multiple, extensions: picker.ext, defaultName: picker.name }); if (!got || !got.length) return undefined; p[picker.key] = picker.multiple ? got : got[0]; + if (picker.overwrite) p[picker.overwrite] = true; } const spec = this.specs.get(command); const missing = (spec?.schema?.required ?? []).filter((k) => p[k] === undefined); diff --git a/frontend/src/ui/menubar.ts b/frontend/src/ui/menubar.ts index dced239..fc177e2 100644 --- a/frontend/src/ui/menubar.ts +++ b/frontend/src/ui/menubar.ts @@ -15,7 +15,7 @@ export interface MenuExtras { const ORDER = ['File', 'Edit', 'Queue', 'Preset', 'Watch', 'Effects', 'Extensions', 'Window', 'Help']; const HIDDEN = new Set([ - 'family.resolved', 'publish.result', 'queue.select', 'family.queue', 'settings.apply', 'ui.toast', 'ui.panel', 'ui.workspace', + 'queue.select', 'family.queue', 'settings.apply', 'ui.toast', 'ui.panel', 'ui.workspace', 'ui.exportSettings', 'queue.getSettings', 'history.list', 'queue.list', 'encode.status', 'preset.list', 'watch.list', 'media.browse', 'media.roots', 'format.list', 'format.describe', 'app.status', 'queue.setFormat', 'watch.setOutput', 'watch.removeOutput', 'watch.setActive', 'watch.remove', 'watch.addOutput', 'queue.reorder', 'preset.get', 'preset.update', 'preset.delete', 'preset.alias', 'log.clear', diff --git a/native/fencoder-commands/src/commands.rs b/native/fencoder-commands/src/commands.rs index 4b68f0a..9365374 100644 --- a/native/fencoder-commands/src/commands.rs +++ b/native/fencoder-commands/src/commands.rs @@ -194,7 +194,7 @@ pub fn all() -> &'static Vec { c("queue.stitch", "Stitch Clips Together", "File", p!("paths" => paths_s(), "preset" => preset_s(), "format" => format_s(), "settings" => ob(), "folder" => st(), "start" => bo()), &["paths"], true, false, "", "Joins clips, in the order given, into one source with one output; sizes and rates follow the first clip.", stitch), c("queue.select", "Select", "Edit", p!("items" => ids(), "outputs" => ids()), &[], false, true, "", "", select), - c("queue.save", "Save Queue", "File", p!("path" => st()), &[], false, true, "Cmd+S", "", save_queue), + c("queue.save", "Save Queue", "File", p!("path" => st(), "overwrite" => bo()), &[], false, false, "Cmd+S", "Saves the queue, to path when given. An existing file at path is replaced only with overwrite: true.", save_queue), c("queue.open", "Open Queue...", "File", p!("path" => st(), "append" => bo()), &["path"], true, false, "", "", open_queue), c("encode.status", "Encoding", "Window", p!(), &[], false, true, "Cmd+2", "The outputs being encoded now with progress, speed and time remaining.", encode_status), c("encode.report", "Output Report", "Queue", p!("outputs" => ids()), &[], false, true, "", "Final status, file, sidecars, loudness, publish results and errors of outputs.", outputs_report), @@ -265,8 +265,6 @@ pub fn all() -> &'static Vec { "Removes the oldest cache files until the cache is under its limit (all: everything not in use by a running encode).", cache_clean), c("family.queue", "Queue Family Source", "File", p!("spec" => ob(), "preset" => preset_s(), "format" => format_s(), "settings" => ob(), "folder" => st(), "outputs" => objs(), "start" => bo()), &["spec"], true, false, "", "Queues a source described by the family bridge (family.add finds it in the app and calls this).", family_queue), - c("family.resolved", "Family Media Ready", "File", p!("output" => st(), "media" => ob(), "error" => st()), &["output"], false, true, "", "The service hands a waiting output the media the family app produced.", family_resolved), - c("publish.result", "Publish Result", "Publish", p!("output" => st(), "results" => json!({"type": "array"})), &["output", "results"], false, false, "", "", publish_result), c("edit.undo", "Undo", "Edit", p!(), &[], false, false, "Cmd+Z", "", undo), c("edit.redo", "Redo", "Edit", p!(), &[], false, false, "Cmd+Shift+Z", "", redo), c("history.list", "History", "Edit", p!(), &[], false, true, "", "", history), @@ -280,6 +278,37 @@ pub fn all() -> &'static Vec { }) } +/// The source the engine service uses for its own calls; callers from outside can never claim it (rpc.caller_source). +pub const ENGINE_SOURCE: &str = "engine"; + +/// Commands only the engine service itself runs: never listed, described, put in a menu or offered as a tool. +fn internal() -> &'static Vec { + static C: OnceLock> = OnceLock::new(); + C.get_or_init(|| { + vec![Cmd { id: "preset.resolve", label: "Preset Publish Summary", menu: "", params: p!("command" => en(PRESET_MAKERS), "params" => ob()), required: &["command"], undoable: false, query: true, shortcut: "", + doc: "Whether the preset a preset command leaves would publish, and to which kinds of destination, worked out without changing anything.", run: preset_resolve }, + Cmd { id: "family.resolved", label: "Family Media Ready", menu: "", params: p!("output" => st(), "media" => ob(), "error" => st()), required: &["output"], undoable: false, query: true, shortcut: "", + doc: "The service hands a waiting output the media the family app produced.", run: family_resolved }, + Cmd { id: "publish.result", label: "Publish Result", menu: "", params: p!("output" => st(), "results" => json!({"type": "array"})), required: &["output", "results"], undoable: false, query: false, shortcut: "", + doc: "The service reports what publishing an output did.", run: publish_result }] + }) +} + +pub const PRESET_MAKERS: &[&str] = &["preset.create", "preset.update", "preset.duplicate", "preset.alias", "preset.import"]; + +pub fn is_internal(id: &str) -> bool { + internal().iter().any(|c| c.id == id) +} + +/// A command as `source` may run it: the public commands for every caller, the internal ones for the engine service only. +pub fn get_as(id: &str, source: &str) -> Res<&'static Cmd> { + match internal().iter().find(|c| c.id == id) { + Some(c) if source == ENGINE_SOURCE => Ok(c), + Some(_) => Err(format!("{id} is internal to the engine and is not available to callers")), + None => get(id), + } +} + pub fn get(id: &str) -> Res<&'static Cmd> { all().iter().find(|c| c.id == id).ok_or_else(|| { let ns = id.split('.').next().unwrap_or(""); diff --git a/native/fencoder-commands/src/commands/preset_cmds.rs b/native/fencoder-commands/src/commands/preset_cmds.rs index 185faa7..7284325 100644 --- a/native/fencoder-commands/src/commands/preset_cmds.rs +++ b/native/fencoder-commands/src/commands/preset_cmds.rs @@ -67,6 +67,67 @@ pub(super) fn preset_import(_: &mut Engine, p: &Value) -> Res { Ok(json!({"preset": m["id"], "name": m["name"], "notes": m["notes"]})) } +/// Destination kinds a publish summary names; anything else is reported as "other". +const DESTINATION_KINDS: &[&str] = &["facebook", "family", "folder", "ftp", "plugin", "s3", "vimeo", "webhook", "youtube"]; + +/// Whether the preset a preset command would leave publishes, and to which kinds of destination, worked out without writing +/// anything: preset.create (settings or fromOutput), preset.update (the patch applied), preset.duplicate, preset.alias and +/// preset.import (the file read as preset.import reads it). Only the engine service runs it (commands::get_as), for its approval +/// check, and it answers with that summary alone: never the settings themselves, and never what a file that is not a preset holds. +pub(super) fn preset_resolve(e: &mut Engine, p: &Value) -> Res { + let q = &p["params"]; + let key = s(q, "preset").unwrap_or(""); + let found = match s(p, "command").unwrap_or("") { + "preset.create" => match s(q, "fromOutput") { + Some(oid) => { + let pos = e.output_ref(&json!(oid))?; + e.items()[pos.0]["outputs"][pos.1]["settings"].clone() + } + None => q["settings"].clone(), + }, + "preset.update" => { + let pr = presets::require(key)?; + if q["settings"].is_object() { settings::apply_patch(&pr["settings"], &q["settings"])? } else { pr["settings"].clone() } + } + "preset.duplicate" | "preset.alias" => presets::require(key)?["settings"].clone(), + "preset.import" => { + let unread = |_| "the file could not be read as a preset".to_string(); + let read = presets::read_import(s(q, "path").unwrap_or("")).map_err(unread)?; + return Ok(publish_summary(&settings::normalize(&read["settings"]).map_err(unread)?)); + } + other => return Err(format!("preset.resolve covers {}, not {other:?}", PRESET_MAKERS.join(", "))), + }; + if !found.is_object() { + return Err("pass settings or fromOutput".into()); + } + Ok(publish_summary(&settings::normalize(&found)?)) +} + +fn publish_summary(settings: &Value) -> Value { + let mut kinds: Vec<&str> = Vec::new(); + let mut deletes_local = false; + for d in settings["publish"].as_array().into_iter().flatten().filter(|d| d.is_object()) { + let kind = DESTINATION_KINDS.iter().copied().find(|k| d["type"].as_str() == Some(*k)).unwrap_or("other"); + if !kinds.contains(&kind) { + kinds.push(kind); + } + deletes_local |= truthy(&d["deleteLocal"]); + } + kinds.sort_unstable(); + json!({"publishes": !kinds.is_empty(), "destinations": kinds, "deletesLocal": deletes_local}) +} + +fn truthy(v: &Value) -> bool { + match v { + Value::Null => false, + Value::Bool(b) => *b, + Value::Number(n) => n.as_f64() != Some(0.0), + Value::String(s) => !s.is_empty(), + Value::Array(a) => !a.is_empty(), + Value::Object(o) => !o.is_empty(), + } +} + pub(super) fn preset_export(_: &mut Engine, p: &Value) -> Res { presets::export(s(p, "preset").unwrap_or(""), s(p, "path").unwrap_or("")) } diff --git a/native/fencoder-commands/src/commands/queue_cmds.rs b/native/fencoder-commands/src/commands/queue_cmds.rs index abd892e..0596517 100644 --- a/native/fencoder-commands/src/commands/queue_cmds.rs +++ b/native/fencoder-commands/src/commands/queue_cmds.rs @@ -378,6 +378,9 @@ pub(super) fn save_queue(e: &mut Engine, p: &Value) -> Res { if target.extension().map(|x| x != "fequeue").unwrap_or(true) { target.set_extension("fequeue"); } + if target.exists() && !bv(p, "overwrite", false) { + return Err(format!("{} already exists; pass overwrite: true to replace it", target.to_string_lossy())); + } fs::write(&target, serde_json::to_string_pretty(&json!({"format": "formencoder.queue/1", "doc": e.doc})).unwrap_or_default()).map_err(|x| x.to_string())?; return Ok(json!({"path": target.to_string_lossy()})); } diff --git a/native/fencoder-commands/src/execute.rs b/native/fencoder-commands/src/execute.rs index 602c394..a3a2a38 100644 --- a/native/fencoder-commands/src/execute.rs +++ b/native/fencoder-commands/src/execute.rs @@ -11,7 +11,7 @@ pub trait Execute { impl Execute for Engine { fn execute(&mut self, id: &str, params: Value, source: &str) -> Res { - let cmd = commands::get(id)?; + let cmd = commands::get_as(id, source)?; let params = commands::check(cmd, params)?; if source == "ui" { self.last_interaction = now(); @@ -59,12 +59,17 @@ impl Execute for Engine { } fn batch(&mut self, steps: &[Value], label: Option<&str>, atomic: bool, source: &str) -> Res { + for step in steps { + if let Some(cid) = step["command"].as_str().filter(|c| commands::is_internal(c)) { + commands::get_as(cid, source)?; + } + } let before = self.doc.clone(); let mut results: Vec = Vec::new(); for (n, step) in steps.iter().enumerate() { let cid = step["command"].as_str().unwrap_or(""); let params = resolve_refs(&step["params"], &results); - let outcome = commands::get(cid).and_then(|c| commands::check(c, if params.is_null() { json!({}) } else { params }).and_then(|p| (c.run)(self, &p))); + let outcome = commands::get_as(cid, source).and_then(|c| commands::check(c, if params.is_null() { json!({}) } else { params }).and_then(|p| (c.run)(self, &p))); match outcome { Ok(v) => results.push(v), Err(e) => { @@ -114,3 +119,118 @@ fn resolve_refs(v: &Value, results: &[Value]) -> Value { other => other.clone(), } } + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + use std::sync::OnceLock; + + use serde_json::{Value, json}; + + use super::Execute; + use crate::commands; + use crate::engine::Engine; + + const MARKER: &str = "text-that-stays-in-the-file"; + + fn scratch() -> &'static PathBuf { + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| { + let dir = std::env::temp_dir().join(format!("fencoder-commands-test-{}", std::process::id())); + std::fs::create_dir_all(dir.join("home")).unwrap(); + // SAFETY: set once, before any engine in this test binary reads the environment. + unsafe { + std::env::set_var("HOME", dir.join("home")); + std::env::set_var("FORMENCODER_DATA_DIR", dir.join("data")); + std::env::set_var("FORMENCODER_FFMPEG_AUTO", "0"); + } + dir + }) + } + + fn preset_file(name: &str, settings: Value) -> String { + let path = scratch().join(name); + std::fs::write(&path, json!({"name": MARKER, "settings": settings}).to_string()).unwrap(); + path.to_string_lossy().into_owned() + } + + fn import_call(path: &str) -> Value { + json!({"command": "preset.import", "params": {"path": path}}) + } + + #[test] + fn preset_resolution_is_refused_to_every_caller_but_the_engine() { + let path = preset_file("sends.fepreset", json!({"format": "h264", "publish": [{"type": "webhook", "url": "https://example.com/hook"}]})); + let mut e = Engine::new(); + for source in ["agent", "mcp:agent", "cli", "ui", "desktop", "test", ""] { + let refused = e.execute("preset.resolve", import_call(&path), source).unwrap_err(); + assert!(!refused.contains("webhook") && !refused.contains(MARKER), "{source}: {refused}"); + let batch = e.batch(&[json!({"command": "preset.resolve", "params": import_call(&path)})], None, false, source); + assert!(batch.is_err(), "{source}: {batch:?}"); + } + assert!(e.execute("preset.resolve", import_call(&path), "engine").is_ok()); + } + + const SERVICE_ONLY: &[&str] = &["preset.resolve", "family.resolved", "publish.result"]; + + #[test] + fn service_answers_are_refused_to_every_caller_but_the_engine() { + let _ = scratch(); + let mut e = Engine::new(); + let calls = [("family.resolved", json!({"output": "o-none", "error": "x"})), ("publish.result", json!({"output": "o-none", "results": [{"ok": true}]}))]; + for (id, params) in calls { + for source in ["agent", "mcp:agent", "cli", "ui", "desktop", "test", ""] { + let refused = e.execute(id, params.clone(), source).unwrap_err(); + assert!(refused.contains("internal to the engine"), "{id} {source}: {refused}"); + assert!(e.batch(&[json!({"command": id, "params": params.clone()})], None, false, source).is_err(), "{id} {source}"); + } + assert!(e.runtime.get("o-none").is_none(), "{id} changed the engine for an outside caller"); + } + assert!(e.execute("publish.result", json!({"output": "o-none", "results": [{"ok": true}]}), "engine").is_ok()); + assert!(e.execute("family.resolved", json!({"output": "o-none", "error": "x"}), "engine").unwrap_err().contains("not waiting")); + } + + #[test] + fn service_answers_are_not_listed_or_described() { + let rows = commands::listing(None, true); + let menus = commands::menus().to_string(); + for id in SERVICE_ONLY { + assert!(commands::get(id).is_err() && commands::is_internal(id), "{id}"); + assert!(!rows.iter().any(|r| r["id"] == *id || r["mcpName"] == id.replace('.', "_")), "{id}"); + assert!(!menus.contains(id), "{id}"); + } + } + + #[test] + fn preset_resolution_is_not_listed_or_described() { + assert!(commands::get("preset.resolve").is_err()); + assert!(!commands::listing(None, true).iter().any(|r| r["id"] == "preset.resolve" || r["mcpName"] == "preset_resolve")); + assert!(!commands::listing(Some("resolve"), false).iter().any(|r| r["id"] == "preset.resolve")); + assert!(!commands::menus().to_string().contains("preset.resolve")); + } + + #[test] + fn preset_resolution_returns_the_publish_summary_only() { + let folder = scratch().join(MARKER).to_string_lossy().into_owned(); + let path = preset_file("folder.fepreset", json!({"format": "h264", "comments": MARKER, "publish": [{"type": "folder", "path": folder, "deleteLocal": true}, {"type": "youtube"}, {"type": MARKER}]})); + let mut e = Engine::new(); + let row = e.execute("preset.resolve", import_call(&path), "engine").unwrap(); + assert_eq!(row, json!({"publishes": true, "destinations": ["folder", "other", "youtube"], "deletesLocal": true})); + assert!(!row.to_string().contains(MARKER)); + let quiet = preset_file("quiet.fepreset", json!({"format": "h264"})); + assert_eq!(e.execute("preset.resolve", import_call(&quiet), "engine").unwrap(), json!({"publishes": false, "destinations": [], "deletesLocal": false})); + } + + #[test] + fn a_file_that_is_not_a_preset_is_not_echoed_back() { + let path = scratch().join("notes.txt"); + std::fs::write(&path, format!("{MARKER} {{")).unwrap(); + let path = path.to_string_lossy().into_owned(); + let mut e = Engine::new(); + let refused = e.execute("preset.resolve", import_call(&path), "engine").unwrap_err(); + assert!(!refused.contains(MARKER) && !refused.contains(&path), "{refused}"); + let missing = scratch().join("missing.fepreset").to_string_lossy().into_owned(); + let refused = e.execute("preset.resolve", import_call(&missing), "engine").unwrap_err(); + assert!(!refused.contains(&missing), "{refused}"); + } +} diff --git a/native/fencoder-core/src/paths.rs b/native/fencoder-core/src/paths.rs index 844d50c..51ff5fa 100644 --- a/native/fencoder-core/src/paths.rs +++ b/native/fencoder-core/src/paths.rs @@ -15,9 +15,15 @@ pub fn data_dir() -> PathBuf { root } +pub const CUSTOM_CACHE: &str = "Formencoder Cache"; + pub fn cache_dir() -> PathBuf { let custom = crate::prefs::load()["cacheFolder"].as_str().map(|s| s.trim().to_string()).unwrap_or_default(); - let p = if custom.is_empty() { data_dir().join("cache") } else { PathBuf::from(expand(&custom)) }; + let p = match PathBuf::from(expand(&custom)) { + _ if custom.is_empty() => data_dir().join("cache"), + chosen if chosen.file_name().is_some_and(|n| n == CUSTOM_CACHE) => chosen, + chosen => chosen.join(CUSTOM_CACHE), + }; let _ = fs::create_dir_all(&p); p } diff --git a/native/fencoder-core/src/prefs.rs b/native/fencoder-core/src/prefs.rs index 4ed6844..06035ba 100644 --- a/native/fencoder-core/src/prefs.rs +++ b/native/fencoder-core/src/prefs.rs @@ -44,7 +44,7 @@ pub fn descriptions() -> Value { "defaultPreset": "Preset given to sources added without one", "logFolder": "Folder for the encoding and error logs (empty: the data folder's logs)", "hwDecode": "Decode sources on the GPU when it can (auto, off)", - "cacheFolder": "Media cache folder for previews, thumbnails, plans and work files (empty: the data folder's cache)", + "cacheFolder": "Folder that holds the media cache for previews, thumbnails, plans and work files, in a Formencoder Cache folder of its own that trimming keeps to (empty: the data folder's cache)", "cacheLimitGB": "Largest size the media cache may grow to before the oldest files are removed", "memoryReserveGB": "Memory to leave for other applications: no further parallel encode starts while less than this is free", "openh264": "Use Cisco's OpenH264 for software H.264 when it is downloaded (off: formencoder never loads it)", diff --git a/native/fencoder-plan/src/presets.rs b/native/fencoder-plan/src/presets.rs index 6eea7b3..11d2563 100644 --- a/native/fencoder-plan/src/presets.rs +++ b/native/fencoder-plan/src/presets.rs @@ -411,19 +411,33 @@ pub fn export(key: &str, path: &str) -> Res { Ok(json!({"path": out.to_string_lossy()})) } -pub fn import_file(path: &str, group: Option<&str>) -> Res { +/// What a preset file holds, read the one way import_file reads it: name, settings, group, comment and notes (notes only for .epr). +/// Nothing is written; the approval check reads a file through this before preset.import makes the preset. +pub fn read_import(path: &str) -> Res { let src = PathBuf::from(paths::expand(path)); let text = fs::read_to_string(&src).map_err(|e| format!("cannot read {path}: {e}"))?; let stem = src.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "Imported".into()); if src.extension().map(|e| e.to_string_lossy().to_lowercase() == "epr").unwrap_or(false) || text.trim_start().starts_with('<') { let (name, settings, notes) = parse_epr(&text, &stem)?; - let mut made = create(&name, &settings, Some(group.unwrap_or("Imported")), &format!("Imported from {}. {notes}", src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()))?; - made["notes"] = json!(notes); - return Ok(made); + let comment = format!("Imported from {}. {notes}", src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()); + return Ok(json!({"name": name, "settings": settings, "group": Value::Null, "comment": comment, "notes": notes})); } let data: Value = serde_json::from_str(&text).map_err(|e| format!("not a preset file: {e}"))?; let settings = if data.get("settings").is_some() { data["settings"].clone() } else { data.clone() }; - create(data["name"].as_str().unwrap_or(&stem), &settings, Some(group.or(data["group"].as_str()).unwrap_or("Imported")), data["comment"].as_str().unwrap_or("")) + if !settings.is_object() { + return Err("not a preset file: its settings are not an object".into()); + } + Ok(json!({"name": data["name"].as_str().unwrap_or(&stem), "settings": settings, "group": data["group"].clone(), "comment": data["comment"].as_str().unwrap_or(""), "notes": Value::Null})) +} + +pub fn import_file(path: &str, group: Option<&str>) -> Res { + let read = read_import(path)?; + let group = group.or(read["group"].as_str()).unwrap_or("Imported"); + let mut made = create(read["name"].as_str().unwrap_or("Imported"), &read["settings"], Some(group), read["comment"].as_str().unwrap_or(""))?; + if !read["notes"].is_null() { + made["notes"] = read["notes"].clone(); + } + Ok(made) } const EPR_FORMATS: &[(&str, &str)] = &[ diff --git a/setup/agents.py b/setup/agents.py index 3166b32..04184b8 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -32,7 +32,7 @@ DOCK_FOLDER = ROOT / "frontend" / "src" / "dock" DOCK_IMPORT = re.compile(r"""(?:from|import)\s*\(?\s*['"]([^'"]+)['"]""") LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "8d026ab2907b5c998f423d467017d215cd043dbdd6e880bbe2b7bbccf05f2fae"} ORDER = ["queue", "encode", "preset", "format", "watch", "ingest", "proxy", "analyze", "media", "captions", "lut", "family", "publish", "log", "prefs", "edit", "history", "ui", "app", "settings"] HEAD = "Generated from the formencoder engine by `./formencoder agents sync`; do not edit by hand."