From a9ffe9ec0f56ad1dd65d269900268a4cedd41ed1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 19:24:29 -0500 Subject: [PATCH 01/30] fix(agents): only the formencoder window can change things, answer prompts or drive its terminal The engine makes a key at start and, in one place (WindowKeyGuard in main.py), refuses every request that is not GET, HEAD or OPTIONS unless it carries x-formencoder-window-key or its path is on a named open list: /mcp (outside agents and the stdio bridge, through consent), the development bootstrap /api/window/key, /api/rpc (the command line, which already goes through consent and approvals) and /api/family/hooks/formcut (formcut's engine, which signs each request). The desktop shell starts the sidecar with FORMENCODER_WINDOW_KEY_STDOUT=1; the engine prints "formencoder-window-key: [key]", flushed, before its address, and the shell sets window.__FORMENCODER_WINDOW_KEY for the engine's own origin only. From source, POST /api/window/key answers once, then 409. The page takes the key once, sends it on every write through LOCAL_HEADERS and api(), and opens the live and terminal sockets with a one-time ticket from POST /api/window/ticket. A live socket without a ticket is an observer with no rights and is not counted as a window; the terminal socket without one is closed. agents.approvals joins agents.decide and agents.fullFaith as window only, and a terminal's output needs the key. The in-app agent token is now one per terminal the window opens, only in that shell's environment, replaced on restart and revoked on close; terminals agents open get none. The Allow Always list and full faith are sealed with an HMAC whose key lives in the system keychain (keyring, loaded lazily); a hand edit that loosens them is ignored and reported as sealBroken, and without a keychain the stored values stand. keyring is added to the requirements, the freeze scripts and NOTICE.md. Checked by running before the tests: a sweep of the OpenAPI write operations with no key went from 15 answered of 15 to 4 of 17 (the open list); the sidecar entry printed the key line before the address and answered the bootstrap with 404; the bootstrap answered once then 409; sockets with and without tickets, MCP and the command line under ask, allow and deny, and the seal with stand-in keyring backends behaved as described in backend/HASHOUT_LOG.md; the page against the Vite dev server in headless Chrome booted, took the key and wrote. Then tests/test_window_key.py and tests/test_seal.py; conftest's client sends the key and a new bare client does not. tsc --noEmit passes. The desktop shell change (src-tauri/src/main.rs) was checked against the tauri 2.12.2 builder signature and parsed with rustfmt, not compiled. --- NOTICE.md | 2 + SECURITY.md | 6 ++ backend/HASHOUT_LOG.md | 14 +++ backend/app/agent/approvals.py | 20 +++-- backend/app/agent/consent.py | 46 ++++++++-- backend/app/core/seal.py | 67 +++++++++++++++ backend/app/core/window_key.py | 72 ++++++++++++++++ backend/app/engine/rpc.py | 4 +- backend/app/main.py | 2 + backend/app/routers/live.py | 9 +- backend/app/routers/system.py | 21 ++++- backend/app/routers/terminal.py | 32 ++++--- backend/formencoder_engine.py | 3 + backend/requirements.txt | 1 + backend/requirements_macos.txt | 1 + backend/tests/conftest.py | 20 ++++- backend/tests/test_seal.py | 102 ++++++++++++++++++++++ backend/tests/test_window_key.py | 138 ++++++++++++++++++++++++++++++ frontend/HASHOUT_LOG.md | 9 ++ frontend/src/engine/client.ts | 22 ++++- frontend/src/engine/window-key.ts | 28 ++++++ frontend/src/panels/terminal.ts | 7 +- setup/freeze_backend | 2 +- setup/freeze_backend.bat | 2 +- src-tauri/src/main.rs | 23 ++++- 25 files changed, 611 insertions(+), 42 deletions(-) create mode 100644 backend/app/core/seal.py create mode 100644 backend/app/core/window_key.py create mode 100644 backend/tests/test_seal.py create mode 100644 backend/tests/test_window_key.py create mode 100644 frontend/src/engine/window-key.ts diff --git a/NOTICE.md b/NOTICE.md index ee7c458..97c8de6 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -26,6 +26,8 @@ formencoder is licensed under the Apache License 2.0 (`LICENSE`). It includes or | anyio 4.15.1, idna 3.20, click 8.5.0, h11 0.16.0, httptools 0.9.0, uvloop 0.23.0, watchfiles 1.3.0, websockets 17.3, python-dotenv 1.2.4, PyYAML 6.0.3 (the `uvicorn[standard]` extras and FastAPI's other requirements, frozen into the engine sidecar where PyInstaller finds them imported) | HTTP and socket serving, async I/O, configuration | MIT (anyio, h11, httptools, uvloop, watchfiles, PyYAML); BSD-3-Clause (idna, click, websockets, python-dotenv); uvloop's wheel carries both MIT and Apache-2.0 texts (its License field says MIT) | | CPython runtime (3.12 in the release toolchain), embedded by PyInstaller in the `--onefile` engine sidecar | runs the engine service | PSF-2.0 | | pywinpty (Windows only) | the terminal on Windows | MIT | +| keyring 25.7.0, jaraco.classes, jaraco.context, jaraco.functools, more-itertools, jeepney (Linux) | keeps the key that seals the agent access choices in the system keychain, frozen into the engine sidecar | MIT | +| SecretStorage (Linux), pywin32-ctypes (Windows), cryptography, cffi and pycparser (Linux, through SecretStorage) | keychain access for keyring | BSD-3-Clause (SecretStorage, pywin32-ctypes, pycparser), Apache-2.0 OR BSD-3-Clause (cryptography), MIT (cffi) | | PyInstaller (build only) | freezing the engine sidecar | GPL-2.0 with the bootloader exception, which permits distributing the frozen program under its own licence | | pytest 9.1.1 (with iniconfig, packaging, pluggy, pygments) and httpx 0.28.1 | runs `backend/tests` in CI (`backend/requirements-test.txt`); never installed in the app | MIT (pytest, iniconfig, pluggy), Apache-2.0 OR BSD-2-Clause (packaging), BSD-2-Clause (pygments), BSD-3-Clause (httpx) | | Playwright 1.63.0 (Python) and its Chromium | runs the window smoke in `frontend/tests/window` in CI; never installed in the app | Apache-2.0 | diff --git a/SECURITY.md b/SECURITY.md index d6e8ddc..cfa3100 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -30,6 +30,12 @@ something outside it could get in: - **Agents and the terminal**: getting an agent's consequential action (deleting, overwriting, publishing, typing into a terminal) to run without the person's approval, or getting past the first-change consent. +- **The window key**: every change through the engine, answering a consent or + approval prompt, and the window's terminal need a key that only the FormEncoder + window holds; outside agents come in through MCP or the command line and are + asked. In the desktop app the shell hands the key to its own window. Run from + source (`./formencoder boot`), the engine gives the key once to the first page + that asks, which is weaker by nature: open the page before anything else does. - **Publish credentials** (FTP, S3, YouTube, Vimeo, Facebook and webhook secrets): anything that leaks them. - **Webhooks**: forging or replaying a signed export notification from formcut, or a diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 4e570a6..62aaaa6 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -202,3 +202,17 @@ Refers to `formencoder_engine.py` `serve` · kind: fix · logged: v0.8.4 · 2026 - `sock.listen()` now follows `bind`. A connection made before uvicorn is serving waits in the socket's backlog and is answered once it is, instead of being refused. uvicorn calls `listen` again on the socket it is given, which is harmless. The line, the port and the discovery record are unchanged. - Checked: the mechanism on its own, outside the repo: a script that binds, announces, waits 0.6 s and then runs uvicorn on the socket, with a client that connects at the announcement. Without `listen` the client is refused at once; with it the request returns 200 after 0.64 s. Not run: a rebuilt desktop app with this change. +## The window key: only the formencoder window changes things, answers prompts or drives its terminal (unreleased, after 0.8.4) + +Refers to `core/window_key.py`, `core/seal.py`, `main.py`, `routers/system.py`, `routers/live.py`, `routers/terminal.py`, `agent/consent.py`, `agent/approvals.py`, `engine/rpc.py` `dispatch`, `formencoder_engine.py` `serve` · kind: fix · logged: unreleased · 2026-11-19 + +- The engine makes a key at start (`secrets.token_urlsafe(32)`, memory only, compared with `hmac.compare_digest`). `WindowKeyGuard`, added once in `main.py` inside CORS and `LocalOnly`, refuses every request whose method is not GET, HEAD or OPTIONS with 403 `Only the formencoder window can do this` unless it carries `x-formencoder-window-key`, or its path is on `window_key.OPEN`. The `LocalOnly` Host, Origin and `x-formencoder-local` checks stay as they were; the key is an added layer. +- The open list and its callers: `/mcp` (outside agents and the stdio bridge, through consent), `/api/window/key` (the development bootstrap), `/api/rpc` (the command line, `app/agent/client.py`, used by `./formencoder ID ...`, `setup/fe.py` and the workspace shim; it already goes through `consent.gate` and `approvals.guard`, and a caller naming itself `ui` becomes `cli`), and `/api/family/hooks/formcut` (formcut's engine, which signs each request with the link secret instead). +- How the window gets the key. Packaged: the shell starts the sidecar with `FORMENCODER_WINDOW_KEY_STDOUT=1`; `serve` then prints `formencoder-window-key: [key]`, flushed, before the `Uvicorn running on` line, and the shell hands it to the page as `window.__FORMENCODER_WINDOW_KEY` for the engine's own origin only. From source: with the variable unset, `POST /api/window/key` answers the key once per launch, then 409, and `/api/system` reports `secondWindowClaim`; with it set, the route answers 404. The from-source mode is weaker by nature: the first page (or program) to ask gets the key. +- Sockets. A browser cannot set headers on a WebSocket, so the window asks `POST /api/window/ticket` (key required) for a one-time ticket that lives 30 seconds and opens `/api/live?kind=ui&ticket=...` and `/api/terminal/ws?...&ticket=...` with it. A live socket without a valid ticket joins the bus as an observer: it gets the hello and broadcasts, is not counted by `bus.windows()` (so it receives no consent or approval prompt and does not make consent think a window is open), and every request it sends is answered with the refusal; `reply` is ignored. The terminal socket without a valid ticket is closed with 4403 before it opens. `GET /api/terminal/sessions/{id}/output` also needs the key, because a shell's output can hold anything. +- `agents.approvals` (pending approval ids) is now refused to every source but `ui`, like `agents.decide` and `agents.fullFaith`; only the window called it. +- The in-app agent token. `consent.TOKEN` was one token for the whole run, put into every terminal's environment. Now `consent.issue()` makes one per terminal the window opens (the panel's socket or `POST /api/terminal/sessions`, both key-holding), it goes only into that shell's environment (never on a command line), is replaced when the shell restarts and revoked when the terminal closes. A terminal an agent opens with `terminal_open` gets none, and an inherited `FORMENCODER_AGENT_TOKEN` is removed from every shell's environment. The panel's shell is where the person starts Claude Code, Codex and Cursor with the buttons, so that shell keeps the token by design. The agents a terminal can launch are fixed in `AGENTS`; no setting names the program. +- The stored agent choices are sealed: the Allow Always list (`agents.json`) and full faith (`approvals.json`). `core/seal.py` keeps a random 32-byte key in the system keychain (`keyring`, service `FormEncoder`, account `settings-seal`, made on first use; imported lazily inside a try so a missing package or backend only makes the seal unavailable) and writes `seal`, an HMAC-SHA256 over the file's label and values. Only the window writes these files (a consent reply on the window's socket, full faith from the window). On read: seal right, values stand; seal missing or wrong while a value is loosened (a client allowed, full faith on), the engine acts as if nothing were allowed and full faith were off, and `/api/agents/status` and `/api/agents/consent` report `sealBroken: true`; no keychain, values stand and `seal` reads `unavailable`. The first launch after this change reads an earlier Allow Always list or full faith as unsealed and asks again. The `FORMENCODER_AGENTS` policy is an environment variable, not a stored file, and is not sealed. +- `keyring==25.7.0` is in `requirements.txt` and `requirements_macos.txt`, `setup/freeze_backend(.bat)` collect its submodules, and `NOTICE.md` has rows for it and its dependencies. +- Checked by running, before the tests were written: a sweep of `app.openapi()` write operations with no key went from 15 answered of 15 to 4 answered of 17 (exactly the open list; the two new routes are the bootstrap and the ticket). The sidecar entry with the variable set printed the key line first and the address second and answered the bootstrap with 404. From source: the bootstrap answered 200 then 409; the window socket with a ticket answered `ui.state` and `agents.approvals`; the same ticket again, and a socket without one, were refused for `agents.fullFaith`, `agents.decide` and `command.execute` and counted as 0 windows; the terminal socket was refused without a ticket and opened with one, its shell holding a token. MCP and the command line gave the same answers as before under `ask` (no window: refused; window allows: runs), `allow` and `deny`. The seal with an in-memory keyring backend: window writes read `ok`, a client added by hand and full faith set by hand read `broken` and are ignored, a keychain that raises reads `unavailable` and the values stand. The page against the Vite dev server in headless Chrome: see `frontend/HASHOUT_LOG.md`. Then `tests/test_window_key.py` and `tests/test_seal.py`; `conftest.py`'s `client` now sends the key, a new `bare` client does not, and `inapp_token()` issues a token. + diff --git a/backend/app/agent/approvals.py b/backend/app/agent/approvals.py index 620c2e4..6d04c4f 100644 --- a/backend/app/agent/approvals.py +++ b/backend/app/agent/approvals.py @@ -9,7 +9,7 @@ from pathlib import Path from typing import Any, Awaitable, Callable -from ..core import config +from ..core import config, seal from ..engine.host import host UPLOADS = {"ftp", "s3", "webhook", "youtube", "vimeo", "facebook", "plugin"} @@ -35,15 +35,25 @@ def _store() -> Path: return config.data_dir() / "approvals.json" -def full_faith() -> bool: +def _stored() -> dict: try: - return bool(json.loads(_store().read_text(encoding="utf-8")).get("fullFaith")) + found = json.loads(_store().read_text(encoding="utf-8")) except (OSError, ValueError): - return False + return {} + return found if isinstance(found, dict) else {} + + +def seal_state() -> str: + stored = _stored() + return seal.read("approvals", stored, bool(stored.get("fullFaith"))) + + +def full_faith() -> bool: + return bool(_stored().get("fullFaith")) and seal_state() != "broken" def set_full_faith(on: bool) -> dict: - _store().write_text(json.dumps({"fullFaith": bool(on)}, indent=2), encoding="utf-8") + _store().write_text(json.dumps(seal.sign("approvals", {"fullFaith": bool(on)}), indent=2), encoding="utf-8") note("ui", "agents.fullFaith", {"on": bool(on)}, True, 0) _changed() return state() diff --git a/backend/app/agent/consent.py b/backend/app/agent/consent.py index 436a445..e89d973 100644 --- a/backend/app/agent/consent.py +++ b/backend/app/agent/consent.py @@ -4,29 +4,58 @@ import secrets import time -from ..core import config +from ..core import config, seal from ..engine.host import host -TOKEN = secrets.token_urlsafe(24) +TOKENS: set[str] = set() _session: set[str] = set() _declined: dict[str, float] = {} _READ_RPC = {"command.list", "command.describe", "ui.state", "menu.bar", "frame.png", "encode.wait", "engine.info", "activity.list", "family.discover", "family.sources", "publish.destinations", "agents.approvals", "extensions.list"} +def issue() -> str: + token = secrets.token_urlsafe(32) + TOKENS.add(token) + return token + + +def revoke(token: str | None) -> None: + if token: + TOKENS.discard(token) + + +def inapp(token: str | None) -> bool: + return bool(token) and any(secrets.compare_digest(token, t) for t in list(TOKENS)) + + def _store(): return config.data_dir() / "agents.json" -def _always() -> set[str]: +def _stored() -> dict: try: - return set(json.loads(_store().read_text(encoding="utf-8")).get("allowed", [])) + found = json.loads(_store().read_text(encoding="utf-8")) except (OSError, ValueError): + return {} + return found if isinstance(found, dict) else {} + + +def seal_state() -> str: + stored = _stored() + return seal.read("agents", stored, bool(stored.get("allowed"))) + + +def _always() -> set[str]: + stored = _stored() + if seal.read("agents", stored, bool(stored.get("allowed"))) == "broken": return set() + allowed = stored.get("allowed", []) + return {str(a) for a in allowed} if isinstance(allowed, list) else set() def _remember(client: str) -> None: allowed = _always() | {client} - _store().write_text(json.dumps({"allowed": sorted(allowed)}, indent=2), encoding="utf-8") + _store().write_text(json.dumps(seal.sign("agents", {"allowed": sorted(allowed)}), indent=2), encoding="utf-8") def forget_all() -> None: @@ -61,11 +90,14 @@ def client_key(source: str) -> str: def state() -> dict: - return {"policy": config.agents_policy(), "session": sorted(_session), "always": sorted(_always())} + from . import approvals + + seals = seal.summary([seal_state(), approvals.seal_state()]) + return {"policy": config.agents_policy(), "session": sorted(_session), "always": sorted(_always()), "seal": seals, "sealBroken": seals == "broken"} async def gate(source: str, token: str | None, mutating: bool, detail: str = "") -> str | None: - if token and secrets.compare_digest(token, TOKEN): + if inapp(token): return None policy = config.agents_policy() if policy == "allow" or not mutating: diff --git a/backend/app/core/seal.py b/backend/app/core/seal.py new file mode 100644 index 0000000..fb05751 --- /dev/null +++ b/backend/app/core/seal.py @@ -0,0 +1,67 @@ +import hashlib +import hmac +import json +import secrets + +SERVICE = "FormEncoder" +ACCOUNT = "settings-seal" +FIELD = "seal" +_CACHE: dict = {"tried": False, "available": False, "key": None} + + +def reset() -> None: + _CACHE.update(tried=False, available=False, key=None) + + +def _load(create: bool) -> bytes | None: + if _CACHE["tried"] and (_CACHE["key"] is not None or not _CACHE["available"] or not create): + return _CACHE["key"] + _CACHE["tried"] = True + try: + import keyring + + stored = keyring.get_password(SERVICE, ACCOUNT) + if not stored and create: + keyring.set_password(SERVICE, ACCOUNT, secrets.token_hex(32)) + stored = keyring.get_password(SERVICE, ACCOUNT) + key = bytes.fromhex(stored) if stored else None + except Exception: + _CACHE.update(available=False, key=None) + return None + _CACHE.update(available=True, key=key) + return key + + +def available() -> bool: + _load(False) + return _CACHE["available"] + + +def digest(label: str, values: dict, key: bytes) -> str: + body = json.dumps({"label": label, "values": {k: v for k, v in values.items() if k != FIELD}}, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return hmac.new(key, body.encode("utf-8"), hashlib.sha256).hexdigest() + + +def read(label: str, stored: dict, loosened: bool) -> str: + key = _load(False) + if not _CACHE["available"]: + return "unavailable" + mark = stored.get(FIELD) + if key is not None and isinstance(mark, str) and hmac.compare_digest(mark, digest(label, stored, key)): + return "ok" + return "broken" if loosened else "unsealed" + + +def sign(label: str, values: dict) -> dict: + clean = {k: v for k, v in values.items() if k != FIELD} + key = _load(True) + if key is None: + return clean + return {**clean, FIELD: digest(label, clean, key)} + + +def summary(states: list[str]) -> str: + for state in ("broken", "unavailable", "unsealed"): + if state in states: + return state + return "ok" diff --git a/backend/app/core/window_key.py b/backend/app/core/window_key.py new file mode 100644 index 0000000..68c80e3 --- /dev/null +++ b/backend/app/core/window_key.py @@ -0,0 +1,72 @@ +import hmac +import json +import os +import secrets +import time + +from fastapi import HTTPException, Request + +HEADER = "x-formencoder-window-key" +STDOUT_ENV = "FORMENCODER_WINDOW_KEY_STDOUT" +LINE = "formencoder-window-key: " +REFUSED = "Only the formencoder window can do this" +TICKET_LIFE = 30.0 +READS = ("GET", "HEAD", "OPTIONS") +OPEN = ("/mcp", "/api/window/key", "/api/rpc", "/api/family/hooks/formcut") +KEY = secrets.token_urlsafe(32) +STATE = {"claimed": False, "secondClaim": False} +TICKETS: dict[str, float] = {} + + +def stdout_mode() -> bool: + return os.environ.get(STDOUT_ENV) == "1" + + +def valid(value) -> bool: + return isinstance(value, str) and bool(value) and hmac.compare_digest(value.encode("utf-8"), KEY.encode("utf-8")) + + +def require(request: Request) -> None: + if not valid(request.headers.get(HEADER)): + raise HTTPException(403, REFUSED) + + +def claim() -> str | None: + if STATE["claimed"]: + STATE["secondClaim"] = True + return None + STATE["claimed"] = True + return KEY + + +def ticket() -> str: + now = time.monotonic() + for old in [t for t, at in TICKETS.items() if now - at > TICKET_LIFE]: + TICKETS.pop(old, None) + value = secrets.token_urlsafe(24) + TICKETS[value] = now + return value + + +def spend(value) -> bool: + if not isinstance(value, str) or not value: + return False + at = TICKETS.pop(value, None) + return at is not None and time.monotonic() - at <= TICKET_LIFE + + +class WindowKeyGuard: + def __init__(self, app) -> None: + self.app = app + + async def __call__(self, scope, receive, send) -> None: + if scope["type"] != "http" or scope.get("method") in READS or str(scope.get("path", "")) in OPEN: + await self.app(scope, receive, send) + return + given = next((v.decode("latin-1") for k, v in scope.get("headers", []) if k.decode("latin-1").lower() == HEADER), None) + if valid(given): + await self.app(scope, receive, send) + return + body = json.dumps({"detail": REFUSED}).encode("utf-8") + await send({"type": "http.response.start", "status": 403, "headers": [(b"content-type", b"application/json"), (b"content-length", str(len(body)).encode())]}) + await send({"type": "http.response.body", "body": body}) diff --git a/backend/app/engine/rpc.py b/backend/app/engine/rpc.py index 09e2f97..d663ea1 100644 --- a/backend/app/engine/rpc.py +++ b/backend/app/engine/rpc.py @@ -170,10 +170,10 @@ async def dispatch(method: str, params: Any, source: str = "ui") -> Any: if method in ("agents.approvals", "agents.decide", "agents.fullFaith"): from ..agent import approvals - if method == "agents.approvals": - return approvals.state() if source != "ui": raise RpcError("Only the person, in the formencoder window, can approve agents' actions or change full faith.", -32003) + if method == "agents.approvals": + return approvals.state() if method == "agents.decide": try: return await approvals.decide(int(p.get("id") or 0), bool(p.get("allow"))) diff --git a/backend/app/main.py b/backend/app/main.py index 4645ddd..bdf6e3e 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -11,6 +11,7 @@ from .agent import workspace from .core import config, discovery from .core.security import LocalOnly +from .core.window_key import WindowKeyGuard from .engine import rpc as engine_rpc from .engine.host import host from .routers import agents, extensions, files, hooks, live, mcp, rpc, system, terminal @@ -64,6 +65,7 @@ async def lifespan(app: FastAPI): app = FastAPI(title="formencoder engine", version=__version__, lifespan=lifespan) +app.add_middleware(WindowKeyGuard) app.add_middleware(CORSMiddleware, allow_origins=config.cors_origins(), allow_credentials=False, allow_methods=["*"], allow_headers=["*"], expose_headers=["x-formencoder-preview"]) app.add_middleware(LocalOnly) for r in ROUTERS: diff --git a/backend/app/routers/live.py b/backend/app/routers/live.py index 6cecb44..85d9699 100644 --- a/backend/app/routers/live.py +++ b/backend/app/routers/live.py @@ -5,6 +5,7 @@ from fastapi import APIRouter, WebSocket, WebSocketDisconnect from .. import __version__ +from ..core import window_key from ..engine import rpc from ..engine.host import host @@ -15,8 +16,8 @@ @router.websocket("/api/live") async def live(socket: WebSocket) -> None: await socket.accept() - kind = socket.query_params.get("kind", "ui") - client = host.bus.join("ui" if kind == "ui" else "watch", socket.query_params.get("name", "")) + window = socket.query_params.get("kind", "ui") == "ui" and window_key.spend(socket.query_params.get("ticket")) + client = host.bus.join("ui" if window else "watch", socket.query_params.get("name", "")) async def pump() -> None: while True: @@ -44,6 +45,10 @@ async def slow(message: dict) -> None: continue if not isinstance(message, dict): continue + if not window: + if message.get("id") is not None: + put({"jsonrpc": "2.0", "id": message.get("id"), "error": {"code": -32003, "message": window_key.REFUSED}}) + continue if message.get("method") == "reply": params = message.get("params") or {} host.bus.answer(int(params.get("requestId") or 0), params.get("value") or {}) diff --git a/backend/app/routers/system.py b/backend/app/routers/system.py index 0504d4f..c42cba9 100644 --- a/backend/app/routers/system.py +++ b/backend/app/routers/system.py @@ -1,10 +1,10 @@ import os import platform -from fastapi import APIRouter +from fastapi import APIRouter, HTTPException, Request from .. import __version__, native -from ..core import config +from ..core import config, window_key from ..engine.host import host router = APIRouter(tags=["system"]) @@ -21,6 +21,22 @@ def version() -> dict: return {"version": __version__, "core": core if ok else None} +@router.post("/api/window/key") +def claim_window_key() -> dict: + if window_key.stdout_mode(): + raise HTTPException(404, "Not Found") + key = window_key.claim() + if key is None: + raise HTTPException(409, "Another window already holds this engine's window key; use that window, or restart formencoder") + return {"key": key} + + +@router.post("/api/window/ticket") +def window_ticket(request: Request) -> dict: + window_key.require(request) + return {"ticket": window_key.ticket()} + + @router.get("/api/system") def system() -> dict: return { @@ -38,4 +54,5 @@ def system() -> dict: "running": host.running, "windows": len(host.bus.windows()), "agentsPolicy": config.agents_policy(), + "secondWindowClaim": window_key.STATE["secondClaim"], } diff --git a/backend/app/routers/terminal.py b/backend/app/routers/terminal.py index ae9a396..3ce5c59 100644 --- a/backend/app/routers/terminal.py +++ b/backend/app/routers/terminal.py @@ -12,18 +12,20 @@ from fastapi import APIRouter, HTTPException, Request, WebSocket, WebSocketDisconnect from ..agent import consent, workspace -from ..core import config +from ..core import config, window_key router = APIRouter(prefix="/api/terminal", tags=["terminal"]) POSIX = os.name == "posix" AGENTS = {"claude": "claude", "codex": "codex", "cursor": "cursor-agent"} -def _environment(base_url: str) -> dict: +def _environment(base_url: str, token: str | None) -> dict: ws = workspace.ensure() env = dict(os.environ) env["FORMENCODER_URL"] = base_url - env["FORMENCODER_AGENT_TOKEN"] = consent.TOKEN + env.pop("FORMENCODER_AGENT_TOKEN", None) + if token: + env["FORMENCODER_AGENT_TOKEN"] = token env["FORMENCODER_AGENT_NAME"] = "terminal" env["FORMENCODER_WORKSPACE"] = str(ws) env["PATH"] = str(ws / "bin") + os.pathsep + env.get("PATH", "") @@ -153,8 +155,10 @@ def status() -> dict: class Term: - def __init__(self, tid: str, title: str, cwd: str, cols: int, rows: int, base: str, owned: bool) -> None: + def __init__(self, tid: str, title: str, cwd: str, cols: int, rows: int, base: str, owned: bool, trusted: bool = False) -> None: self.id, self.title, self.cwd, self.base, self.owned = tid, title, cwd, base, owned + self.trusted = trusted + self.token: str | None = None self.opener = "ui" self.created = time.time() self.buffer = "" @@ -167,7 +171,9 @@ def __init__(self, tid: str, title: str, cwd: str, cols: int, rows: int, base: s def _start(self, cols: int, rows: int) -> None: self.exited = False - self.session = Session(cols, rows, _environment(self.base), self.cwd) + consent.revoke(self.token) + self.token = consent.issue() if self.trusted else None + self.session = Session(cols, rows, _environment(self.base, self.token), self.cwd) session = self.session def pump() -> None: @@ -223,6 +229,8 @@ def close(self) -> None: if self.session: self.session.close() self.exited = True + consent.revoke(self.token) + self.token = None def row(self) -> dict: return {"id": self.id, "title": self.title, "cwd": self.cwd, "created": self.created, "exited": self.exited, "owned": self.owned, "offset": self.offset, "opener": self.opener} @@ -241,11 +249,11 @@ def changed(self) -> None: def listing(self) -> list[dict]: return [t.row() for t in self.terms.values() if not t.owned] - def open(self, title: str | None, cwd: str | None, cols: int, rows: int, base: str, owned: bool = False, run: str | None = None) -> Term: + def open(self, title: str | None, cwd: str | None, cols: int, rows: int, base: str, owned: bool = False, run: str | None = None, trusted: bool = False) -> Term: self._n += 1 tid = f"t{self._n}" place = cwd or str(workspace.ensure()) - term = Term(tid, title or f"Terminal {self._n}", place, cols, rows, base, owned) + term = Term(tid, title or f"Terminal {self._n}", place, cols, rows, base, owned, trusted) self.terms[tid] = term if run: term.write(run + "\r") @@ -287,7 +295,7 @@ async def open_session(request: Request) -> dict: body = await request.json() if (await request.body()) else {} launch = body.get("launch") run = AGENTS.get(launch) if launch in AGENTS else None - term = hub.open(body.get("title"), body.get("cwd"), int(body.get("cols") or 100), int(body.get("rows") or 30), _base(request.headers.get("host")), run=run) + term = hub.open(body.get("title"), body.get("cwd"), int(body.get("cols") or 100), int(body.get("rows") or 30), _base(request.headers.get("host")), run=run, trusted=True) return term.row() @@ -303,7 +311,8 @@ async def session_input(tid: str, request: Request) -> dict: @router.get("/sessions/{tid}/output") -def session_output(tid: str, since: int | None = None) -> dict: +def session_output(tid: str, request: Request, since: int | None = None) -> dict: + window_key.require(request) try: text, offset = hub.get(tid).read(since) except KeyError as exc: @@ -342,6 +351,9 @@ def session_close(tid: str) -> dict: @router.websocket("/ws") async def terminal(socket: WebSocket) -> None: + if not window_key.spend(socket.query_params.get("ticket")): + await socket.close(code=4403) + return await socket.accept() try: cols = int(socket.query_params.get("cols", "100")) @@ -355,7 +367,7 @@ async def terminal(socket: WebSocket) -> None: term.session.resize(cols, rows) else: base = _base(socket.headers.get("host"), socket.query_params.get("engine")) - term = hub.open(None, socket.query_params.get("cwd"), cols, rows, base, owned=True) + term = hub.open(None, socket.query_params.get("cwd"), cols, rows, base, owned=True, trusted=True) queue: asyncio.Queue = asyncio.Queue(maxsize=4000) replay, _ = term.read(None) if replay and attach: diff --git a/backend/formencoder_engine.py b/backend/formencoder_engine.py index 372595f..6d2fc35 100644 --- a/backend/formencoder_engine.py +++ b/backend/formencoder_engine.py @@ -87,7 +87,10 @@ def serve(headless: bool) -> None: from app import __version__ from app.core import discovery from app.main import app + from app.core import window_key + if window_key.stdout_mode(): + print(window_key.LINE + window_key.KEY, flush=True) print(f"Uvicorn running on http://127.0.0.1:{port}", flush=True) discovery.publish(f"http://127.0.0.1:{port}", __version__) server = uvicorn.Server(uvicorn.Config(app, log_level="warning")) diff --git a/backend/requirements.txt b/backend/requirements.txt index dafdd0c..bd170dd 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,5 +1,6 @@ fastapi==0.142.3 uvicorn[standard]==0.54.0 python-multipart==0.0.32 +keyring==25.7.0 maturin==1.15.0 pywinpty==3.0.5; sys_platform == "win32" diff --git a/backend/requirements_macos.txt b/backend/requirements_macos.txt index 177859b..d259226 100644 --- a/backend/requirements_macos.txt +++ b/backend/requirements_macos.txt @@ -1,4 +1,5 @@ fastapi==0.142.3 uvicorn[standard]==0.54.0 python-multipart==0.0.32 +keyring==25.7.0 maturin==1.15.0 diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 173fb39..683e3c8 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -66,7 +66,16 @@ def set_policy(mode): def inapp_token(): - return importlib.import_module("app.agent.consent").TOKEN + return importlib.import_module("app.agent.consent").issue() + + +def window_headers(): + key = importlib.import_module("app.core.window_key") + return {key.HEADER: key.KEY} + + +def window_ticket(): + return importlib.import_module("app.core.window_key").ticket() _SANDBOX = Path(tempfile.mkdtemp(prefix=f"{APP_ID}-tests-")) @@ -103,10 +112,17 @@ def app(): def client(app): from fastapi.testclient import TestClient - with TestClient(app, base_url=own_origin()) as c: + with TestClient(app, base_url=own_origin(), headers=window_headers()) as c: yield c +@pytest.fixture(scope="session") +def bare(client, app): + from fastapi.testclient import TestClient + + return TestClient(app, base_url=own_origin()) + + @pytest.fixture(scope="session") def repo_versions(): found = {} diff --git a/backend/tests/test_seal.py b/backend/tests/test_seal.py new file mode 100644 index 0000000..e38a3d0 --- /dev/null +++ b/backend/tests/test_seal.py @@ -0,0 +1,102 @@ +import json + +import pytest + +keyring = pytest.importorskip("keyring") +from keyring.backend import KeyringBackend + + +class Memory(KeyringBackend): + priority = 1 + + def __init__(self): + super().__init__() + self.store = {} + + def get_password(self, service, username): + return self.store.get((service, username)) + + def set_password(self, service, username, password): + self.store[(service, username)] = password + + def delete_password(self, service, username): + self.store.pop((service, username), None) + + +class Missing(KeyringBackend): + priority = 1 + + def get_password(self, service, username): + raise RuntimeError("no keychain") + + def set_password(self, service, username, password): + raise RuntimeError("no keychain") + + def delete_password(self, service, username): + raise RuntimeError("no keychain") + + +@pytest.fixture +def sealed(tmp_path, monkeypatch): + from app.core import seal + + monkeypatch.setenv("FORMENCODER_DATA_DIR", str(tmp_path)) + before = keyring.get_keyring() + keyring.set_keyring(Memory()) + seal.reset() + yield tmp_path + keyring.set_keyring(before) + seal.reset() + + +def test_choices_the_window_makes_are_sealed_and_stand(sealed): + from app.agent import approvals, consent + + consent._remember("claude") + approvals.set_full_faith(True) + assert consent.state()["seal"] == "ok" and consent.state()["always"] == ["claude"] + assert approvals.full_faith() is True + + +def test_a_client_added_by_hand_is_caught_and_treated_as_ask(sealed): + from app.agent import consent + + consent._remember("claude") + stored = json.loads((sealed / "agents.json").read_text()) + stored["allowed"].append("intruder") + (sealed / "agents.json").write_text(json.dumps(stored)) + state = consent.state() + assert state["sealBroken"] is True and state["always"] == [] + + +def test_full_faith_written_by_hand_is_ignored(sealed): + from app.agent import approvals + + (sealed / "approvals.json").write_text(json.dumps({"fullFaith": True})) + assert approvals.seal_state() == "broken" and approvals.full_faith() is False + + +def test_safe_values_without_a_seal_are_not_reported_broken(sealed): + from app.agent import consent + + (sealed / "agents.json").write_text(json.dumps({"allowed": []})) + assert consent.state()["sealBroken"] is False + + +def test_without_a_keychain_the_stored_values_stand(tmp_path, monkeypatch): + from app.agent import approvals, consent + from app.core import seal + + monkeypatch.setenv("FORMENCODER_DATA_DIR", str(tmp_path)) + before = keyring.get_keyring() + keyring.set_keyring(Missing()) + seal.reset() + try: + (tmp_path / "agents.json").write_text(json.dumps({"allowed": ["claude"]})) + state = consent.state() + assert state["seal"] == "unavailable" and state["always"] == ["claude"] + approvals.set_full_faith(False) + assert json.loads((tmp_path / "approvals.json").read_text()) == {"fullFaith": False} + finally: + keyring.set_keyring(before) + seal.reset() diff --git a/backend/tests/test_window_key.py b/backend/tests/test_window_key.py new file mode 100644 index 0000000..878f4f7 --- /dev/null +++ b/backend/tests/test_window_key.py @@ -0,0 +1,138 @@ +import json +import re + +import pytest +from starlette.websockets import WebSocketDisconnect + +from conftest import ENGINE_PORT, LOCAL_HEADER, inapp_token, window_ticket + +READS = {"GET", "HEAD", "OPTIONS"} +OPEN = {("POST", "/mcp"), ("POST", "/api/window/key"), ("POST", "/api/rpc"), ("POST", "/api/family/hooks/formcut")} +LOOPBACK = {"host": f"127.0.0.1:{ENGINE_PORT}"} +REFUSED = {"detail": "Only the formencoder window can do this"} + + +def write_operations(app): + return [(m.upper(), path) for path, item in app.openapi()["paths"].items() for m in item if m.upper() not in READS] + + +def test_the_open_list_is_short_and_named(): + from app.core import window_key + + assert set(window_key.OPEN) == {path for _, path in OPEN} + + +def test_every_write_route_needs_the_window_key(app, bare): + ops = write_operations(app) + assert len(ops) >= 15 + answered = [] + for method, path in ops: + if (method, path) in OPEN: + continue + url = re.sub(r"\{[^}]+\}", "x", path) + for headers in ({LOCAL_HEADER: "1"}, {LOCAL_HEADER: "1", "x-formencoder-window-key": "x" * 43}): + r = bare.request(method, url, json={}, headers=headers) + if r.status_code != 403 or r.json() != REFUSED: + answered.append(f"{method} {path} {r.status_code}") + assert not answered, "write routes that answer without the window key (add the key, or name the route in window_key.OPEN with its caller): " + ", ".join(answered) + + +def test_the_window_key_lets_the_window_write(client, tmp_path): + r = client.post("/api/fs/mkdir", json={"path": str(tmp_path / "made")}, headers={LOCAL_HEADER: "1"}) + assert r.status_code == 200 and (tmp_path / "made").is_dir() + + +def test_the_bootstrap_answers_once_then_refuses(bare, monkeypatch): + from app.core import window_key + + monkeypatch.setitem(window_key.STATE, "claimed", False) + monkeypatch.setitem(window_key.STATE, "secondClaim", False) + first = bare.post("/api/window/key", headers={LOCAL_HEADER: "1"}) + assert first.status_code == 200 and first.json()["key"] == window_key.KEY + again = bare.post("/api/window/key", headers={LOCAL_HEADER: "1"}) + assert again.status_code == 409 and window_key.KEY not in again.text + assert bare.get("/api/system").json()["secondWindowClaim"] is True + + +def test_the_bootstrap_does_not_exist_when_the_shell_holds_the_key(bare, monkeypatch): + monkeypatch.setenv("FORMENCODER_WINDOW_KEY_STDOUT", "1") + assert bare.post("/api/window/key", headers={LOCAL_HEADER: "1"}).status_code == 404 + + +def test_a_ticket_needs_the_key_and_works_once(client, bare): + assert bare.post("/api/window/ticket", headers={LOCAL_HEADER: "1"}).status_code == 403 + from app.core import window_key + + ticket = client.post("/api/window/ticket", headers={LOCAL_HEADER: "1"}).json()["ticket"] + assert window_key.spend(ticket) is True + assert window_key.spend(ticket) is False + + +def _ask(ws, method, params=None): + ws.send_text(json.dumps({"jsonrpc": "2.0", "id": 7, "method": method, "params": params or {}})) + while True: + got = ws.receive_json() + if got.get("id") == 7: + return got + + +@pytest.mark.parametrize("method,params", [("agents.fullFaith", {"on": True}), ("agents.decide", {"id": 1, "allow": True}), ("agents.approvals", {}), ("command.execute", {"command": "app.capabilities", "params": {}})]) +def test_a_socket_without_a_ticket_has_no_rights(bare, method, params): + from app.agent import approvals + from app.engine.host import host + + with bare.websocket_connect("/api/live?kind=ui", headers=LOOPBACK) as ws: + assert ws.receive_json()["type"] == "hello" + assert not host.bus.windows() + assert _ask(ws, method, params)["error"]["message"] == REFUSED["detail"] + assert approvals.full_faith() is False + + +def test_a_socket_with_a_ticket_is_the_window(bare): + from app.engine.host import host + + with bare.websocket_connect(f"/api/live?kind=ui&ticket={window_ticket()}", headers=LOOPBACK) as ws: + assert ws.receive_json()["type"] == "hello" + assert len(host.bus.windows()) == 1 + assert "result" in _ask(ws, "agents.approvals") + + +def test_the_terminal_socket_needs_a_ticket(bare): + with pytest.raises(WebSocketDisconnect): + with bare.websocket_connect("/api/terminal/ws?cols=80&rows=24", headers=LOOPBACK) as ws: + ws.receive_text() + + +def test_each_window_terminal_has_its_own_token_and_it_dies_with_the_terminal(): + from app.agent import consent + from app.routers.terminal import _environment + + env = _environment("http://127.0.0.1:1", None) + assert "FORMENCODER_AGENT_TOKEN" not in env + token = consent.issue() + assert consent.inapp(token) + consent.revoke(token) + assert not consent.inapp(token) + assert not consent.inapp(inapp_token() + "x") + + +def test_a_terminal_an_agent_opens_carries_no_token(client): + import asyncio + + from app.agent import consent + from app.routers.terminal import hub + + async def run(): + before = set(consent.TOKENS) + term = hub.open("probe", None, 80, 24, "http://127.0.0.1:1") + try: + assert term.token is None and set(consent.TOKENS) == before + finally: + hub.close(term.id) + window = hub.open("window", None, 80, 24, "http://127.0.0.1:1", trusted=True) + token = window.token + assert consent.inapp(token) + hub.close(window.id) + assert not consent.inapp(token) + + asyncio.run(run()) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index fa36979..52b4ded 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -212,3 +212,12 @@ Refers to `ui/demos.ts` `stage`, `backend/app/routers/files.py` `upload` · kind Refers to `ui/file-dialog.ts` the Save button · kind: fix · logged: v0.8.2 · 2026-11-10 - Save joined the folder and name and then collapsed every run of slashes to one separator, which turned `\\server\share\out` into `\server\share\out`, a folder on the current drive. The name is now joined to the folder with one separator, added only when the folder does not already end with it, and nothing else is rewritten. Checked with `tsc --noEmit`; not run on Windows. + +## The page holds the window key (unreleased, after 0.8.4) + +Refers to `engine/window-key.ts`, `engine/client.ts` `LOCAL_HEADERS`, `api`, `windowTicket`, `Client.connect`, `panels/terminal.ts` `connect` · kind: fix · logged: unreleased · 2026-11-19 + +- The engine now refuses changes that do not carry `x-formencoder-window-key` (see `backend/HASHOUT_LOG.md`, "The window key"). `loadWindowKey` takes the key once when `engine/client.ts` loads: the global `__FORMENCODER_WINDOW_KEY` that the desktop shell sets (read, then deleted), else `POST /api/window/key` (development; kept in `sessionStorage` so a reload of the same tab keeps working when the engine answers 409 the second time). The key is written into `LOCAL_HEADERS`, so `api()` and the three raw `fetch` calls in `ext/extensions.ts` that spread `LOCAL_HEADERS` all send it; `api()` waits for it first. +- Sockets take a one-time ticket: `windowTicket()` asks `POST /api/window/ticket` before each live socket (re)connect and each terminal socket. `Client.connect` and the terminal panel's `connect` became async for that one await; nothing in the DOM changes. +- Other network calls in `src`: the demo file reads in `ui/demos.ts` are GETs of static files and need nothing. +- Checked against the Vite dev server (on a spare port, with the engine's CORS origins set to it) in headless Chrome: the page booted to "Engine ready", took the key (in `sessionStorage`, no global left), the engine counted 1 window, the live and terminal sockets opened with tickets (the terminal showed a prompt), `POST /api/fs/mkdir` from the page and `api('/api/agents/workspace')` answered 200, a command and `agents.approvals` over the live socket answered, and every non-GET request but the bootstrap carried the key. After a reload the bootstrap answered 409, the page reused the stored key and the engine again counted 1 window. Not run: the desktop shell (it cannot be built here). diff --git a/frontend/src/engine/client.ts b/frontend/src/engine/client.ts index d5533cd..ff8c77a 100644 --- a/frontend/src/engine/client.ts +++ b/frontend/src/engine/client.ts @@ -1,7 +1,12 @@ import { Emitter } from './events'; +import { loadWindowKey, WINDOW_KEY_HEADER } from './window-key'; export const LOCAL_HEADERS: Record = { 'x-formencoder-local': '1', 'x-formencoder-source': 'ui' }; +const keyReady: Promise = loadWindowKey().then((key) => { + if (key) LOCAL_HEADERS[WINDOW_KEY_HEADER] = key; +}); + export interface ServerEvent { type: string; source?: string; @@ -44,7 +49,17 @@ export function wsUrl(path: string): string { return `${proto}//${location.host}${path}`; } +export async function windowTicket(): Promise { + try { + const body = await api<{ ticket?: unknown }>('/api/window/ticket', { method: 'POST', body: '{}' }); + return typeof body.ticket === 'string' ? body.ticket : ''; + } catch { + return ''; + } +} + export async function api(path: string, init: RequestInit = {}): Promise { + await keyReady; const headers = new Headers(init.headers); for (const [k, v] of Object.entries(LOCAL_HEADERS)) headers.set(k, v); if (init.body && typeof init.body === 'string' && !headers.has('content-type')) headers.set('content-type', 'application/json'); @@ -63,8 +78,9 @@ export class Client { private retry = 250; connected = false; - connect(): void { - const ws = new WebSocket(wsUrl('/api/live?kind=ui')); + async connect(): Promise { + const ticket = await windowTicket(); + const ws = new WebSocket(wsUrl(`/api/live?kind=ui&ticket=${encodeURIComponent(ticket)}`)); this.ws = ws; ws.onopen = () => { this.retry = 250; @@ -76,7 +92,7 @@ export class Client { for (const p of this.pending.values()) p.reject(new RpcFailure('the engine connection closed', -1)); this.pending.clear(); if (was) this.events.emit('close', undefined); - window.setTimeout(() => this.connect(), this.retry); + window.setTimeout(() => void this.connect(), this.retry); this.retry = Math.min(4000, this.retry * 2); }; } diff --git a/frontend/src/engine/window-key.ts b/frontend/src/engine/window-key.ts new file mode 100644 index 0000000..842181b --- /dev/null +++ b/frontend/src/engine/window-key.ts @@ -0,0 +1,28 @@ +export const WINDOW_KEY_HEADER = 'x-formencoder-window-key'; +const STORE = 'formencoder-window-key'; + +function remembered(): string { + try { return sessionStorage.getItem(STORE) ?? ''; } catch { return ''; } +} + +function remember(value: string): void { + try { sessionStorage.setItem(STORE, value); } catch { return; } +} + +export async function loadWindowKey(): Promise { + const holder = window as unknown as { __FORMENCODER_WINDOW_KEY?: unknown }; + const given = holder.__FORMENCODER_WINDOW_KEY; + delete holder.__FORMENCODER_WINDOW_KEY; + if (typeof given === 'string' && given) return given; + try { + const res = await fetch('/api/window/key', { method: 'POST', headers: { 'x-formencoder-local': '1' } }); + const body = res.ok ? await res.json() as { key?: unknown } : {}; + if (typeof body.key === 'string' && body.key) { + remember(body.key); + return body.key; + } + } catch { + return remembered(); + } + return remembered(); +} diff --git a/frontend/src/panels/terminal.ts b/frontend/src/panels/terminal.ts index 8187d41..975a5e5 100644 --- a/frontend/src/panels/terminal.ts +++ b/frontend/src/panels/terminal.ts @@ -1,5 +1,5 @@ import type { Ctx } from '../app/ctx'; -import { api, wsUrl } from '../engine/client'; +import { api, windowTicket, wsUrl } from '../engine/client'; import type { Panel } from '../ui/dock'; import { el, q, setClass, setText } from '../ui/dom'; import { icon } from '../ui/icons'; @@ -114,10 +114,11 @@ export class TerminalPanel implements Panel { this.connect(); } - private connect(launch?: string): void { + private async connect(launch?: string): Promise { const t = this.term; if (!t) return; - const ws = new WebSocket(wsUrl(`/api/terminal/ws?cols=${t.cols}&rows=${t.rows}${launch ? `&launch=${launch}` : ''}`)); + const ticket = await windowTicket(); + const ws = new WebSocket(wsUrl(`/api/terminal/ws?cols=${t.cols}&rows=${t.rows}&ticket=${encodeURIComponent(ticket)}${launch ? `&launch=${launch}` : ''}`)); this.ws = ws; ws.onmessage = (ev) => { const s = String(ev.data); diff --git a/setup/freeze_backend b/setup/freeze_backend index 593e105..54d7504 100755 --- a/setup/freeze_backend +++ b/setup/freeze_backend @@ -18,7 +18,7 @@ pyinstaller --noconfirm --clean --onefile --name formencoder-engine \ --add-data "$FORMENCODER_ROOT/.claude/skills${sep}skills" \ --add-data "$FORMENCODER_ROOT/backend/app/resources${sep}resources" \ --add-data "$FORMENCODER_ROOT/src-tauri/binaries/ffmpeg-licence.json${sep}." \ - --collect-all fe_core --collect-submodules app --collect-submodules uvicorn \ + --collect-all fe_core --collect-submodules app --collect-submodules uvicorn --collect-submodules keyring \ "$FORMENCODER_ROOT/backend/formencoder_engine.py" mkdir -p "$FORMENCODER_ROOT/src-tauri/binaries" out="$FORMENCODER_ROOT/src-tauri/binaries/formencoder-engine-${triple}${ext}" diff --git a/setup/freeze_backend.bat b/setup/freeze_backend.bat index 92fe0ea..fe7c5fc 100644 --- a/setup/freeze_backend.bat +++ b/setup/freeze_backend.bat @@ -12,7 +12,7 @@ if not exist frontend\dist\index.html call setup\build_frontend.bat cd backend if exist build\pyinstaller rmdir /s /q build\pyinstaller if exist dist-engine rmdir /s /q dist-engine -pyinstaller --noconfirm --clean --onefile --name formencoder-engine --distpath dist-engine --workpath build\pyinstaller --specpath build\pyinstaller --add-data "%ROOT%\frontend\dist;frontend_dist" --add-data "%ROOT%\backend\app\agent\templates;agent_templates" --add-data "%ROOT%\.claude\skills;skills" --add-data "%ROOT%\backend\app\resources;resources" --add-data "%ROOT%\src-tauri\binaries\ffmpeg-licence.json;." --collect-all fe_core --collect-submodules app --collect-submodules uvicorn --collect-submodules winpty "%ROOT%\backend\formencoder_engine.py" || exit /b 1 +pyinstaller --noconfirm --clean --onefile --name formencoder-engine --distpath dist-engine --workpath build\pyinstaller --specpath build\pyinstaller --add-data "%ROOT%\frontend\dist;frontend_dist" --add-data "%ROOT%\backend\app\agent\templates;agent_templates" --add-data "%ROOT%\.claude\skills;skills" --add-data "%ROOT%\backend\app\resources;resources" --add-data "%ROOT%\src-tauri\binaries\ffmpeg-licence.json;." --collect-all fe_core --collect-submodules app --collect-submodules uvicorn --collect-submodules keyring --collect-submodules winpty "%ROOT%\backend\formencoder_engine.py" || exit /b 1 if not exist "%ROOT%\src-tauri\binaries" mkdir "%ROOT%\src-tauri\binaries" copy /y dist-engine\formencoder-engine.exe "%ROOT%\src-tauri\binaries\formencoder-engine-%TRIPLE%.exe" >nul "%ROOT%\src-tauri\binaries\formencoder-engine-%TRIPLE%.exe" --selfcheck diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 60ee230..e67d1dc 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -84,6 +84,7 @@ fn main() { .sidecar("formencoder-engine") .expect("sidecar binary is bundled") .env("FORMENCODER_PORT", "0") + .env("FORMENCODER_WINDOW_KEY_STDOUT", "1") .env("FORMENCODER_PARENT_PID", std::process::id().to_string()); if let Some(files) = opened_files() { sidecar = sidecar.env("FORMENCODER_OPEN", files); @@ -93,12 +94,19 @@ fn main() { tauri::async_runtime::spawn(async move { let pattern = regex::Regex::new(r"http://127\.0\.0\.1:(\d+)").unwrap(); + let key_pattern = regex::Regex::new(r"formencoder-window-key: ([A-Za-z0-9_-]{32,})").unwrap(); let mut port: Option = None; + let mut key: Option = None; while let Some(event) = rx.recv().await { let line = match event { - CommandEvent::Stdout(bytes) | CommandEvent::Stderr(bytes) => { - String::from_utf8_lossy(&bytes).into_owned() + CommandEvent::Stdout(bytes) => { + let text = String::from_utf8_lossy(&bytes).into_owned(); + if key.is_none() { + key = key_pattern.captures(&text).map(|found| found[1].to_string()); + } + text } + CommandEvent::Stderr(bytes) => String::from_utf8_lossy(&bytes).into_owned(), CommandEvent::Terminated(_) => break, _ => continue, }; @@ -133,8 +141,15 @@ fn main() { .background_color(reveal::BACKGROUND) .inner_size(width, height) .min_inner_size(MIN_LOGICAL.0, MIN_LOGICAL.1) - .center() - .build(); + .center(); + let origin = format!("http://127.0.0.1:{found}"); + let built = match &key { + Some(value) => built.initialization_script(format!( + "if (window.location.origin === {origin:?}) {{ window.__FORMENCODER_WINDOW_KEY = {value:?}; }}" + )), + None => built, + } + .build(); match built { Ok(window) => reveal::conceal(&window), Err(_) => close_splash(&handle), From 6218e4d866fcda191529a81411cf61615b627d18 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 19:27:06 -0500 Subject: [PATCH 02/30] fix(agents): only the window can change the preferences that pick a program or allow replacing files prefs.set had no approval reason, so an agent past consent could change any preference. ffmpegDir picks the program run as FFmpeg, rawDecoders names programs run on camera raw sources, incrementNames off lets an output replace an existing file, and cacheFolder decides where cache trimming removes old files. rpc.execute and rpc.batch now refuse a prefs.set touching any of these four unless it comes from the window's socket (ui), the engine itself (engine, the FFmpeg download refresh) or files opened with the app (desktop). Other preferences are unchanged. Checked by running before the test, with FORMENCODER_AGENTS=allow: MCP execute and batch and the command line were refused for each of the four and could still set chime; the window's socket set incrementNames and ffmpegDir. Then tests/test_window_prefs.py. --- backend/HASHOUT_LOG.md | 9 +++++++ backend/app/engine/rpc.py | 14 ++++++++++ backend/tests/test_window_prefs.py | 42 ++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 backend/tests/test_window_prefs.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 62aaaa6..cb08176 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -216,3 +216,12 @@ Refers to `core/window_key.py`, `core/seal.py`, `main.py`, `routers/system.py`, - `keyring==25.7.0` is in `requirements.txt` and `requirements_macos.txt`, `setup/freeze_backend(.bat)` collect its submodules, and `NOTICE.md` has rows for it and its dependencies. - Checked by running, before the tests were written: a sweep of `app.openapi()` write operations with no key went from 15 answered of 15 to 4 answered of 17 (exactly the open list; the two new routes are the bootstrap and the ticket). The sidecar entry with the variable set printed the key line first and the address second and answered the bootstrap with 404. From source: the bootstrap answered 200 then 409; the window socket with a ticket answered `ui.state` and `agents.approvals`; the same ticket again, and a socket without one, were refused for `agents.fullFaith`, `agents.decide` and `command.execute` and counted as 0 windows; the terminal socket was refused without a ticket and opened with one, its shell holding a token. MCP and the command line gave the same answers as before under `ask` (no window: refused; window allows: runs), `allow` and `deny`. The seal with an in-memory keyring backend: window writes read `ok`, a client added by hand and full faith set by hand read `broken` and are ignored, a keychain that raises reads `unavailable` and the values stand. The page against the Vite dev server in headless Chrome: see `frontend/HASHOUT_LOG.md`. Then `tests/test_window_key.py` and `tests/test_seal.py`; `conftest.py`'s `client` now sends the key, a new `bare` client does not, and `inapp_token()` issues a token. +## Window-only preferences (unreleased, after 0.8.4) + +Refers to `engine/rpc.py` `window_only`, `WINDOW_PREFS`, `WINDOW_SOURCES`, `execute`, `batch` · kind: fix · logged: unreleased · 2026-11-19 + +- `prefs.set` is not destructive in the registry and no approval reason covered it, so an agent past consent could change any preference. Four of them decide which program runs or whether a file is replaced or removed: `ffmpegDir` (the first place the FFmpeg locator looks), `incrementNames` (off, an output whose file exists is written over, since FFmpeg always gets `-y`), `rawDecoders` (each entry's `command` is run on camera raw sources) and `cacheFolder` (cache trimming removes the oldest files in that folder once it is over `cacheLimitGB`). +- `rpc.execute` and `rpc.batch` are the one funnel for every caller that names a source (the live socket, `/api/rpc`, MCP tools, the formcut hook, desktop open). A `prefs.set` that touches any of the four from a source other than `ui` (the window's socket), `engine` (the engine's own refresh of `ffmpegDir` after the FFmpeg download) or `desktop` (files opened with the app) is refused with -32003 and a one-line reason, before the engine is called; other preferences in the same call are not written either. The window's Preferences dialog is unchanged. `/api/rpc` already turns a caller naming itself `ui` into `cli`. +- Left alone: `logFolder` (logs append), `outputFolder` (outputs are still renamed while `incrementNames` is on), `openh264` (picks a library that is only installed after its pinned check), and the `overwrite` flag of `captions.transcribe`, which is a command parameter, not a preference. +- Checked by running, before the test: with `FORMENCODER_AGENTS=allow`, MCP `execute` of `prefs.set` with each of the four was refused, `chime` was set; an MCP `batch` and the command line (`setup/fe.py exec prefs.set ...`) were refused for `incrementNames`, the command line set `chime`; the window's socket set `incrementNames` and `ffmpegDir`. Then `tests/test_window_prefs.py`. + diff --git a/backend/app/engine/rpc.py b/backend/app/engine/rpc.py index d663ea1..e5045ba 100644 --- a/backend/app/engine/rpc.py +++ b/backend/app/engine/rpc.py @@ -19,6 +19,8 @@ def __init__(self, message: str, code: int = -32000, data: Any = None): _query_ids: set[str] | None = None _QUEUE_KEYS = ("preset", "format", "settings", "folder", "outputs", "start") +WINDOW_PREFS = ("ffmpegDir", "incrementNames", "rawDecoders", "cacheFolder") +WINDOW_SOURCES = ("ui", "engine", "desktop") def _dumps(params: Any) -> str: @@ -36,9 +38,18 @@ def query_ids() -> set[str]: return _query_ids +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 + touched = [k for k in WINDOW_PREFS if k in params["values"]] + if touched: + raise RpcError(f"Only the person, in the formencoder window (Preferences), can change {', '.join(touched)}: it decides which program runs or whether an existing file is replaced or removed.", -32003) + + async def execute(command: str, params: Any = None, source: str = "ui") -> Any: if not isinstance(command, str) or not command: raise RpcError("missing `command`", -32602) + window_only(command, params, source) try: raw = await host.call(lambda e: e.execute(command, _dumps(params), source)) except ValueError as exc: @@ -49,6 +60,9 @@ async def execute(command: str, params: Any = None, source: str = "ui") -> Any: async def batch(steps: list, label: str | None, atomic: bool, source: str) -> Any: + for step in steps if isinstance(steps, list) else []: + if isinstance(step, dict): + window_only(step.get("command"), step.get("params"), source) try: raw = await host.call(lambda e: e.batch(json.dumps(steps), label, atomic, source)) except ValueError as exc: diff --git a/backend/tests/test_window_prefs.py b/backend/tests/test_window_prefs.py new file mode 100644 index 0000000..463fdd0 --- /dev/null +++ b/backend/tests/test_window_prefs.py @@ -0,0 +1,42 @@ +import pytest + +from conftest import LOCAL_HEADER, set_policy + +MESSAGE = "Only the person, in the formencoder window (Preferences), can change" + + +@pytest.fixture +def allowed(): + set_policy("allowed") + yield + set_policy("ask") + + +def rpc(client, method, params, source="cli"): + return client.post("/api/rpc", json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, headers={LOCAL_HEADER: "1", "x-formencoder-source": source}).json() + + +@pytest.mark.parametrize("values", [{"ffmpegDir": "/tmp/formencoder-elsewhere"}, {"incrementNames": False}, {"rawDecoders": [{"extensions": ["r3d"], "command": "/bin/true"}]}, {"cacheFolder": "/tmp"}]) +def test_agents_cannot_change_window_only_preferences(client, allowed, values): + out = rpc(client, "command.execute", {"command": "prefs.set", "params": {"values": values}}) + assert MESSAGE in out["error"]["message"] + batch = rpc(client, "command.batch", {"steps": [{"command": "prefs.set", "params": {"values": 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") + assert MESSAGE in out["error"]["message"] + + +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 + + +def test_the_window_can_change_them(): + from app.engine import rpc as engine_rpc + + engine_rpc.window_only("prefs.set", {"values": {"incrementNames": False, "ffmpegDir": ""}}, "ui") + with pytest.raises(engine_rpc.RpcError): + engine_rpc.window_only("prefs.set", {"values": {"ffmpegDir": ""}}, "mcp:agent") From 2725e9e98f10bc50cb03b79d83d821f30e30b348 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 19:29:34 -0500 Subject: [PATCH 03/30] fix(ffmpeg): download from formai-binaries, falling back to formcut-binaries The binaries repository is being renamed to nodemode-dev/formai-binaries. ffmpeg_fetch.sources() now returns the archive under formai-binaries first and formcut-binaries second; fetch() and setup/bundle_ffmpeg.py try them in order and move on when an address cannot be fetched or its files do not match the SHA-256 record, installing nothing that does not match. FORMENCODER_FFMPEG_RELEASE, when set, stays the only address; it is now documented in .docs/BRANCHING.md, src-tauri/ffmpeg/README.md and backend/.env.example. The tag, asset names, install folder and variable names are unchanged. NOTICE.md, BRANCHING.md and the ffmpeg resource README name formai-binaries and say older builds use the older name, which keeps working; ffmpeg-licence.json names no address and is unchanged. Checked by running before the tests: against a local server, wrong bytes or a 404 from the first address installed the matching archive from the second, wrong bytes from both installed nothing, and the override was the only address asked; bundle_ffmpeg.main staged from the second address, stopped on two mismatches and exited 0 on two 404s. On the real network the new address answers 404 today and a real fetch installed the 12 recorded files from formcut-binaries. Then tests/test_ffmpeg_fetch.py. --- .docs/BRANCHING.md | 2 +- NOTICE.md | 2 +- backend/.env.example | 2 + backend/HASHOUT_LOG.md | 8 +++ backend/app/ffmpeg_fetch.py | 49 +++++++++----- backend/tests/test_ffmpeg_fetch.py | 105 +++++++++++++++++++++++++++++ setup/bundle_ffmpeg.py | 29 +++++--- src-tauri/ffmpeg/README.md | 2 +- 8 files changed, 169 insertions(+), 30 deletions(-) create mode 100644 backend/tests/test_ffmpeg_fetch.py diff --git a/.docs/BRANCHING.md b/.docs/BRANCHING.md index 3c29b68..ae1f0b8 100644 --- a/.docs/BRANCHING.md +++ b/.docs/BRANCHING.md @@ -5,6 +5,6 @@ - **Commits** follow Conventional Commits with the version in the summary, for example `fix(core): keep the source range when a preset is applied (0.1.1)`. The commit identity is `nodemode-ai `. - **Versions** are `v*.*.*` with dots, everywhere: `frontend/package.json` and its lockfile, `frontend/src/version.ts`, `backend/app/__init__.py`, `native/Cargo.toml` (the workspace version), the seven fencoder entries in `native/Cargo.lock`, `native/fencoder-py/pyproject.toml`, `src-tauri/Cargo.toml`, its `Cargo.lock`, `src-tauri/tauri.conf.json`, the version line in `README.md` and the deliverable zip names. Bump all of them in one commit, the last of a series. - **Engine commands.** A change to the engine's commands, formats, presets or MCP tools is followed in the same commit by `./formencoder agents sync`, so the harness references follow the engine. -- **FFmpeg.** The pinned build is changed only by replacing `src-tauri/binaries/ffmpeg-licence.json` with a new record from the formcut-binaries release, together with its `LGPL-2.1.txt` and `THIRD-PARTY-NOTICES.txt`, in one commit. Never point the fetch or the bundle at a build that is not recorded there. +- **FFmpeg.** The pinned build is changed only by replacing `src-tauri/binaries/ffmpeg-licence.json` with a new record from the formai-binaries release (`nodemode-dev/formai-binaries`; builds made before the rename use the older name, formcut-binaries, which keeps working), together with its `LGPL-2.1.txt` and `THIRD-PARTY-NOTICES.txt`, in one commit. Never point the fetch or the bundle at a build that is not recorded there. The fetch and `setup/bundle_ffmpeg.py` try formai-binaries first and formcut-binaries second, and install only files that match the record; `FORMENCODER_FFMPEG_RELEASE` (a release folder URL such as `https://example.org/ffmpeg-7.1.5-2`) replaces both as the only address, with the same check. - **Releases.** formencoder builds nothing in this repository. After the version bump lands on main, push a branch `compile_vX.Y.Z` cut from that commit. CI runs on it, and formcompiler (`nodemode-ai/formcompiler`) picks it up on its next 8-hourly watch run, or at once when its watch is run by hand. It builds macOS (Apple silicon and Intel), Linux and Windows bundles with the pinned FFmpeg and opens a draft release `formencoder-vX.Y.Z` on formcompiler's release page, which carries the FFmpeg source. Review the draft, then publish it there. Compile branches are kept as the record of what was built. - **Wiki.** Edit pages in `.docs/wiki/`, never in the GitHub wiki interface. `.github/workflows/wiki.yml` publishes the folder when it changes on main. The wiki needs one page created by hand once before the first publish. diff --git a/NOTICE.md b/NOTICE.md index 97c8de6..98847ee 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -4,7 +4,7 @@ formencoder is licensed under the Apache License 2.0 (`LICENSE`). It includes or | Component | Use | License | | --- | --- | --- | -| FFmpeg 7.1.5, LGPL build from the formcut-binaries release (`ffmpeg-lgpl-7.1.5-2`), with libopus, libvpx and the hardware interfaces (libva, libdrm, nv-codec-headers, AMF) listed in `src-tauri/binaries/THIRD-PARTY-NOTICES.txt` | decoding, filtering and encoding, run as a separate program (`ffmpeg`, `ffprobe`) and never linked; bundled in the desktop app or downloaded on first run, each file checked against `src-tauri/binaries/ffmpeg-licence.json` | LGPL-2.1-or-later (`src-tauri/binaries/LGPL-2.1.txt`); the libraries' own permissive licences in `THIRD-PARTY-NOTICES.txt` | +| FFmpeg 7.1.5, LGPL build from the formai-binaries release (`ffmpeg-lgpl-7.1.5-2`; builds made before the rename name it formcut-binaries, which keeps working), with libopus, libvpx and the hardware interfaces (libva, libdrm, nv-codec-headers, AMF) listed in `src-tauri/binaries/THIRD-PARTY-NOTICES.txt` | decoding, filtering and encoding, run as a separate program (`ffmpeg`, `ffprobe`) and never linked; bundled in the desktop app or downloaded on first run, each file checked against `src-tauri/binaries/ffmpeg-licence.json` | LGPL-2.1-or-later (`src-tauri/binaries/LGPL-2.1.txt`); the libraries' own permissive licences in `THIRD-PARTY-NOTICES.txt` | | BBC bmx v1.6 (`bmxtranswrap`, `mxf2raw`), with its bundled libMXF, libMXF++, expat and uriparser | AS-10, AS-11 OP1a, AS-11 D10 and P2 OP-Atom wrapping and read-back, run as separate programs; built from the pinned tag by `./formencoder install-tools` and staged in `src-tauri/tools` for the desktop bundles | BSD-3-Clause (expat MIT, uriparser BSD-3-Clause); texts in `tools/licences` | | asdcplib rel_2_13_2 (`asdcp-wrap`, `asdcp-info`), built without OpenSSL and Xerces | DCP picture and sound track files, run as separate programs | BSD-3-Clause; text in `tools/licences` | | OpenJPEG v2.5.3 (`opj_compress`), with its bundled libpng, libtiff, lcms2 and zlib | DCI cinema-profile JPEG 2000 frames for DCP, run as a separate program | BSD-2-Clause (libpng, libtiff, lcms2 MIT, zlib licences); text in `tools/licences` | diff --git a/backend/.env.example b/backend/.env.example index 202e2d5..3c42103 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -5,3 +5,5 @@ FORMENCODER_CORS_ORIGINS=http://localhost:5270,http://127.0.0.1:5270,http://loca FORMENCODER_DIST= FORMENCODER_AGENTS=ask FORMENCODER_FFMPEG_DIR= +FORMENCODER_FFMPEG_AUTO=1 +FORMENCODER_FFMPEG_RELEASE= diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index cb08176..e9bb45f 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -225,3 +225,11 @@ Refers to `engine/rpc.py` `window_only`, `WINDOW_PREFS`, `WINDOW_SOURCES`, `exec - Left alone: `logFolder` (logs append), `outputFolder` (outputs are still renamed while `incrementNames` is on), `openh264` (picks a library that is only installed after its pinned check), and the `overwrite` flag of `captions.transcribe`, which is a command parameter, not a preference. - Checked by running, before the test: with `FORMENCODER_AGENTS=allow`, MCP `execute` of `prefs.set` with each of the four was refused, `chime` was set; an MCP `batch` and the command line (`setup/fe.py exec prefs.set ...`) were refused for `incrementNames`, the command line set `chime`; the window's socket set `incrementNames` and `ffmpegDir`. Then `tests/test_window_prefs.py`. +## FFmpeg comes from formai-binaries, with formcut-binaries as the fallback (unreleased, after 0.8.4) + +Refers to `ffmpeg_fetch.py` `SOURCES`, `sources`, `fetch`; `setup/bundle_ffmpeg.py` `main` · kind: fix · logged: unreleased · 2026-11-19 + +- The binaries repository is being renamed from `nodemode-dev/formcut-binaries` to `nodemode-dev/formai-binaries`; until then the new address answers 404, after it the old one redirects. `SOURCES` holds both, new first. `sources(data, triple)` returns the archive URL under each, or only the one under `FORMENCODER_FFMPEG_RELEASE` when that is set (a release folder URL; previously undocumented, now in `.docs/BRANCHING.md`, `src-tauri/ffmpeg/README.md` and `backend/.env.example`). The tag, the asset names, the install folder and the variable names are unchanged. +- `fetch` tries each address in order; a download error, an archive that does not open, a missing file or a file whose SHA-256 differs from the record moves on to the next address, and `install` copies nothing until every file has matched. When none works, `fetch` raises one error naming every address and why; its result's `source` names the address that answered. `bundle_ffmpeg.py` loops the same way and empties the stage after a refused archive; it still exits 0 with a notice when no address could be fetched (the app downloads on first run), and stops the build when an address answered with files that do not match. +- Checked by running, before the tests: against a local server, wrong bytes from the first address and a 404 from it both installed the matching archive from the second; wrong bytes from both installed nothing; with the override set only it was asked, also when it answered 404. `bundle_ffmpeg.main` against the same server staged from the second address, stopped on two mismatches and exited 0 on two 404s. On the real network the new address answers 404 and the old one 302, and a real `fetch` into a scratch HOME installed the 12 recorded files from formcut-binaries. Then `tests/test_ffmpeg_fetch.py`. `src-tauri/binaries/ffmpeg-licence.json` names no address and is unchanged; the history lines above that name formcut-binaries stay as written. + diff --git a/backend/app/ffmpeg_fetch.py b/backend/app/ffmpeg_fetch.py index 4f3bfeb..99e51a1 100644 --- a/backend/app/ffmpeg_fetch.py +++ b/backend/app/ffmpeg_fetch.py @@ -12,7 +12,10 @@ from pathlib import Path from typing import Callable -RELEASE = "https://github.com/nodemode-dev/formcut-binaries/releases/download" +SOURCES = ( + "https://github.com/nodemode-dev/formai-binaries/releases/download", + "https://github.com/nodemode-dev/formcut-binaries/releases/download", +) DOCUMENTS = ("LGPL-2.1.txt", "THIRD-PARTY-NOTICES.txt", "README.md") @@ -55,10 +58,11 @@ def release(data: dict) -> str: return data.get("release") or ((data.get("source") or {}).get("ffmpeg") or {}).get("version", "") -def source(data: dict, triple: str) -> str: +def sources(data: dict, triple: str) -> list[str]: name = release(data) - base = os.environ.get("FORMENCODER_FFMPEG_RELEASE") or f"{RELEASE}/ffmpeg-{name}" - return f"{base.rstrip('/')}/ffmpeg-lgpl-{name}-{triple}.tar.gz" + override = os.environ.get("FORMENCODER_FFMPEG_RELEASE") + bases = [override] if override else [f"{base}/ffmpeg-{name}" for base in SOURCES] + return [f"{base.rstrip('/')}/ffmpeg-lgpl-{name}-{triple}.tar.gz" for base in bases] def _digest(path: Path) -> str: @@ -111,20 +115,29 @@ def fetch(report: Callable[[float, str], None]) -> dict: files = pins(data, triple) if not files: raise ValueError(f"no FFmpeg build is recorded for {triple}; install FFmpeg and set its folder in Preferences") - url, folder = source(data, triple), user_folder() - with tempfile.TemporaryDirectory() as scratch: - archive = Path(scratch) / "ffmpeg.tar.gz" - report(0.02, "downloading FFmpeg") - with urllib.request.urlopen(url, timeout=120) as r, archive.open("wb") as out: - total = int(r.headers.get("content-length") or 0) - done = 0 - for chunk in iter(lambda: r.read(1 << 20), b""): - out.write(chunk) - done += len(chunk) - if total: - report(0.85 * done / total, "downloading FFmpeg") - report(0.9, "checking every file against the record") - count = install(archive, files, folder) + folder = user_folder() + failures: list[str] = [] + for url in sources(data, triple): + try: + with tempfile.TemporaryDirectory() as scratch: + archive = Path(scratch) / "ffmpeg.tar.gz" + report(0.02, "downloading FFmpeg") + with urllib.request.urlopen(url, timeout=120) as r, archive.open("wb") as out: + total = int(r.headers.get("content-length") or 0) + done = 0 + for chunk in iter(lambda: r.read(1 << 20), b""): + out.write(chunk) + done += len(chunk) + if total: + report(0.85 * done / total, "downloading FFmpeg") + report(0.9, "checking every file against the record") + count = install(archive, files, folder) + except (OSError, ValueError, tarfile.TarError) as error: + failures.append(f"{url}: {error}") + continue + break + else: + raise ValueError("FFmpeg could not be installed; " + "; ".join(failures)) (folder / "ffmpeg-licence.json").write_text(json.dumps(data, indent=1), encoding="utf-8") report(1.0, "FFmpeg installed") return {"folder": str(folder), "files": count, "source": url} diff --git a/backend/tests/test_ffmpeg_fetch.py b/backend/tests/test_ffmpeg_fetch.py new file mode 100644 index 0000000..793adaf --- /dev/null +++ b/backend/tests/test_ffmpeg_fetch.py @@ -0,0 +1,105 @@ +import hashlib +import http.server +import io +import tarfile +import threading + +import pytest + +GOOD = b"#!/bin/sh\necho pinned\n" + + +def archive(content): + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as t: + info = tarfile.TarInfo("build/ffmpeg") + info.size = len(content) + t.addfile(info, io.BytesIO(content)) + return buf.getvalue() + + +@pytest.fixture +def served(tmp_path, monkeypatch): + from app import ffmpeg_fetch + + routes, hits = {}, [] + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + hits.append(self.path.split("/")[1]) + body = routes.get(self.path) + self.send_response(200 if body is not None else 404) + self.end_headers() + if body is not None: + self.wfile.write(body) + + def log_message(self, *args): + pass + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + base = f"http://127.0.0.1:{server.server_address[1]}" + triple = ffmpeg_fetch.host_triple() + record = {"release": "7.1.5-2", "targets": {triple: {"files": [{"path": "ffmpeg", "sha256": hashlib.sha256(GOOD).hexdigest()}]}}} + monkeypatch.setattr(ffmpeg_fetch, "record", lambda: record) + monkeypatch.setattr(ffmpeg_fetch, "SOURCES", (base + "/formai", base + "/formcut")) + monkeypatch.setattr(ffmpeg_fetch, "user_folder", lambda: tmp_path / "ffmpeg") + monkeypatch.delenv("FORMENCODER_FFMPEG_RELEASE", raising=False) + name = f"/ffmpeg-7.1.5-2/ffmpeg-lgpl-7.1.5-2-{triple}.tar.gz" + yield {"routes": routes, "hits": hits, "base": base, "name": name, "folder": tmp_path / "ffmpeg"} + server.shutdown() + + +def test_the_new_address_comes_first_and_the_old_one_second(monkeypatch): + from app import ffmpeg_fetch + + monkeypatch.delenv("FORMENCODER_FFMPEG_RELEASE", raising=False) + urls = ffmpeg_fetch.sources({"release": "7.1.5-2"}, "x86_64-unknown-linux-gnu") + assert urls == [ + "https://github.com/nodemode-dev/formai-binaries/releases/download/ffmpeg-7.1.5-2/ffmpeg-lgpl-7.1.5-2-x86_64-unknown-linux-gnu.tar.gz", + "https://github.com/nodemode-dev/formcut-binaries/releases/download/ffmpeg-7.1.5-2/ffmpeg-lgpl-7.1.5-2-x86_64-unknown-linux-gnu.tar.gz", + ] + + +def test_the_override_is_the_only_address(monkeypatch): + from app import ffmpeg_fetch + + monkeypatch.setenv("FORMENCODER_FFMPEG_RELEASE", "https://mirror.example/ffmpeg-7.1.5-2/") + assert ffmpeg_fetch.sources({"release": "7.1.5-2"}, "t") == ["https://mirror.example/ffmpeg-7.1.5-2/ffmpeg-lgpl-7.1.5-2-t.tar.gz"] + + +def test_wrong_bytes_from_the_first_address_fall_back_to_the_second(served): + from app import ffmpeg_fetch + + served["routes"]["/formai" + served["name"]] = archive(b"other bytes\n") + served["routes"]["/formcut" + served["name"]] = archive(GOOD) + out = ffmpeg_fetch.fetch(lambda p, m: None) + assert served["hits"] == ["formai", "formcut"] and "/formcut/" in out["source"] + assert (served["folder"] / "ffmpeg").read_bytes() == GOOD + + +def test_a_missing_first_address_falls_back_to_the_second(served): + from app import ffmpeg_fetch + + served["routes"]["/formcut" + served["name"]] = archive(GOOD) + assert "/formcut/" in ffmpeg_fetch.fetch(lambda p, m: None)["source"] + + +def test_nothing_is_installed_when_no_address_matches(served): + from app import ffmpeg_fetch + + served["routes"]["/formai" + served["name"]] = archive(b"x\n") + served["routes"]["/formcut" + served["name"]] = archive(b"y\n") + with pytest.raises(ValueError): + ffmpeg_fetch.fetch(lambda p, m: None) + assert not (served["folder"] / "ffmpeg").exists() + + +def test_with_the_override_set_the_built_in_addresses_are_not_tried(served, monkeypatch): + from app import ffmpeg_fetch + + served["routes"]["/formcut" + served["name"]] = archive(GOOD) + monkeypatch.setenv("FORMENCODER_FFMPEG_RELEASE", served["base"] + "/mirror/ffmpeg-7.1.5-2") + with pytest.raises(ValueError): + ffmpeg_fetch.fetch(lambda p, m: None) + assert served["hits"] == ["mirror"] diff --git a/setup/bundle_ffmpeg.py b/setup/bundle_ffmpeg.py index f537316..416de37 100644 --- a/setup/bundle_ffmpeg.py +++ b/setup/bundle_ffmpeg.py @@ -4,6 +4,7 @@ import argparse import shutil import sys +import tarfile import tempfile import urllib.request from pathlib import Path @@ -37,15 +38,25 @@ def main() -> int: if not files: print(f"::notice::no FFmpeg build is recorded for {triple}; this app downloads it on first run") return 0 - url = ffmpeg_fetch.source(record, triple) - with tempfile.TemporaryDirectory() as scratch: - archive = Path(scratch) / "ffmpeg.tar.gz" - try: - urllib.request.urlretrieve(url, archive) - except OSError as error: - print(f"::notice::{url} could not be fetched ({error}); this app downloads FFmpeg on first run") - return 0 - count = ffmpeg_fetch.install(archive, files, STAGE) + count, refused = 0, [] + for url in ffmpeg_fetch.sources(record, triple): + with tempfile.TemporaryDirectory() as scratch: + archive = Path(scratch) / "ffmpeg.tar.gz" + try: + urllib.request.urlretrieve(url, archive) + count = ffmpeg_fetch.install(archive, files, STAGE) + except (OSError, ValueError, tarfile.TarError) as error: + print(f"::notice::{url} could not be used ({error})") + if not isinstance(error, OSError): + refused.append(f"{url}: {error}") + clear(STAGE) + continue + break + if not count and refused: + raise SystemExit("no download matched the pinned record: " + "; ".join(refused)) + if not count: + print("::notice::no address could be fetched; this app downloads FFmpeg on first run") + return 0 suffix = ".exe" if triple.endswith("windows-msvc") else "" for program in ("ffmpeg", "ffprobe"): named = STAGE / f"{program}-{triple}{suffix}" diff --git a/src-tauri/ffmpeg/README.md b/src-tauri/ffmpeg/README.md index b4fd5fb..1e63bfe 100644 --- a/src-tauri/ffmpeg/README.md +++ b/src-tauri/ffmpeg/README.md @@ -1,6 +1,6 @@ # src-tauri/ffmpeg -`setup/bundle_ffmpeg.py --target [triple]` fills this folder with the LGPL FFmpeg 7.1 build recorded in `src-tauri/binaries/ffmpeg-licence.json` (the same builds formcut ships, from the formcut-binaries release), after checking every file against that record. `setup/desktop_build` and the desktop workflow run it before `tauri build`, and Tauri bundles the folder as the app's `ffmpeg` resource: +`setup/bundle_ffmpeg.py --target [triple]` fills this folder with the LGPL FFmpeg 7.1 build recorded in `src-tauri/binaries/ffmpeg-licence.json` (the same builds formcut ships, from the formai-binaries release, with the older formcut-binaries address as a fallback; builds made before the rename use only the older name, which keeps working), after checking every file against that record. `FORMENCODER_FFMPEG_RELEASE` set to a release folder URL makes that folder the only address, with the same check. `setup/desktop_build` and the desktop workflow run it before `tauri build`, and Tauri bundles the folder as the app's `ffmpeg` resource: - macOS: `formencoder.app/Contents/Resources/ffmpeg` - Windows: `ffmpeg` beside `formencoder.exe` From f8bd4b340fd25ac611a0209c9a13c2512c22ea1f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 19:30:20 -0500 Subject: [PATCH 04/30] docs(agents): state the real counts: 29 curated tools, 125 in the full profile Counted from source: tools.TOOLS has 29 entries and the engine's registry gives 96 more command tools, 125 in the full profile. The core profile (Cursor) lists the 29 curated tools only. AGENTS.md said 21 and 27 in one sentence, the wiki's Agents page listed 21 and the skillset's agent-substrate table said 21; each now says 29 curated (core) and 125 in the full profile, and the wiki lists all 29. The generated harness references already said 29: ./formencoder agents sync --check reports them in step. --- .../sub-skills/agent-substrate/SUB-SKILL.md | 2 +- .docs/wiki/Agents.md | 2 +- AGENTS.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.claude/skills/formencoder-skillset/sub-skills/agent-substrate/SUB-SKILL.md b/.claude/skills/formencoder-skillset/sub-skills/agent-substrate/SUB-SKILL.md index f54cf34..65536a6 100644 --- a/.claude/skills/formencoder-skillset/sub-skills/agent-substrate/SUB-SKILL.md +++ b/.claude/skills/formencoder-skillset/sub-skills/agent-substrate/SUB-SKILL.md @@ -9,7 +9,7 @@ description: Changing how agents drive formencoder. Use for the MCP tools and gu | Path | Holds | | --- | --- | -| `backend/app/agent/tools.py` | `INSTRUCTIONS`, `WORKFLOW`, `GUIDES`, `TOOLS` (21 curated tools) and their handlers; one tool per registry command built by `command_tools()` and served by profile (`full`, `core`, `core,[category]...`, chosen with `--profile` or `x-formencoder-mcp-profile`); `RESOURCES`, `RESOURCE_TEMPLATES` and `read_resource`; `RECIPES` and `prompt()` | +| `backend/app/agent/tools.py` | `INSTRUCTIONS`, `WORKFLOW`, `GUIDES`, `TOOLS` (29 curated tools, the core profile; the full profile adds one per command, 125 today) and their handlers; one tool per registry command built by `command_tools()` and served by profile (`full`, `core`, `core,[category]...`, chosen with `--profile` or `x-formencoder-mcp-profile`); `RESOURCES`, `RESOURCE_TEMPLATES` and `read_resource`; `RECIPES` and `prompt()` | | `backend/app/agent/workspace.py` `CLIENT_PROFILES` | which profile each client gets (Claude Code and Codex full, Cursor core) in every config formencoder writes | | `backend/app/routers/mcp.py` | Streamable HTTP MCP at `/mcp` | | `backend/app/agent/stdio.py`, `setup/mcp_stdio.py` | the stdio relay `./formencoder mcp`, which finds or starts the engine | diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index 535ce7b..01ccdec 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -12,7 +12,7 @@ formencoder's engine exposes every command to agents through MCP, the same comma ## The tools -21 tools: `status`, `list_commands`, `describe_command`, `execute`, `batch`, `probe`, `encode`, `queue`, `export_settings`, `preview_frame`, `contact_sheet`, `wait`, `verify`, `presets`, `formats`, `watch_folder`, `family`, `log`, `history`, `ui`, `guide`. `encode` queues, encodes, waits and verifies in one call; `preview_frame` and `contact_sheet` render frames through an output's exact settings so an agent looks before it encodes; `verify` probes the file against its settings. +29 curated tools: `status`, `list_commands`, `describe_command`, `execute`, `batch`, `probe`, `encode`, `queue`, `export_settings`, `preview_frame`, `contact_sheet`, `wait`, `verify`, `presets`, `formats`, `watch_folder`, `family`, `log`, `history`, `ui`, `guide`, `approval_status`, `terminal_list`, `terminal_open`, `terminal_send`, `terminal_read`, `terminal_close`, `extensions_list`, `extension_command`. The core profile (Cursor) lists these 29; the full profile (Claude Code and Codex) adds one tool per engine command, such as `queue_add_source`, 125 tools in all today (`.claude/skills/formencoder-harness/references/tools.md` and `commands.md` are generated from the engine and list them). `encode` queues, encodes, waits and verifies in one call; `preview_frame` and `contact_sheet` render frames through an output's exact settings so an agent looks before it encodes; `verify` probes the file against its settings. ## The skill diff --git a/AGENTS.md b/AGENTS.md index 70bfa42..c071232 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ The media encoder of the form family: vanilla TypeScript and Vite interface, Pyt When the person wants media encoded, transcoded, normalised, captioned, ingested, proxied or delivered with formencoder, use the `formencoder` MCP server's tools guided by the `formencoder-harness` skill in `.agents/skills/formencoder-harness` (its `references/tools.md` lists every tool; `references/commands.md` every command; `references/presets.md` and `references/formats.md` the presets and settings). Start with `status`, `probe` the sources, encode with `encode` or `queue.addSource` plus `export_settings`, look with `preview_frame`, and `verify` every output before reporting it. -The MCP server is configured here in `.codex/config.toml` (Codex) and `.cursor/mcp.json` (Cursor); both run `./formencoder mcp`, which starts the engine when it is not running. Codex loads the full profile (the 21 curated tools plus one tool per engine command, such as `queue_add_source`) and Cursor the core profile (the 27 curated tools; `execute` reaches every command). From any other folder, `./formencoder agents install` sets Claude Code, Codex and Cursor up for the user account. Without MCP, the `./formencoder` command line has the same surface: any command as `./formencoder [id] --name value` (`--help` after the id lists its flags), and `encode`, `queue`, `commands`, `describe`, `exec`, `batch`, `presets`, `probe`, `frame`, `wait`. +The MCP server is configured here in `.codex/config.toml` (Codex) and `.cursor/mcp.json` (Cursor); both run `./formencoder mcp`, which starts the engine when it is not running. Codex loads the full profile (the 29 curated tools plus one tool per engine command, such as `queue_add_source`: 125 tools today) and Cursor the core profile (the same 29 curated tools only; `execute` reaches every command). From any other folder, `./formencoder agents install` sets Claude Code, Codex and Cursor up for the user account. Without MCP, the `./formencoder` command line has the same surface: any command as `./formencoder [id] --name value` (`--help` after the id lists its flags), and `encode`, `queue`, `commands`, `describe`, `exec`, `batch`, `presets`, `probe`, `frame`, `wait`. ## Changing formencoder's code From 113a9524e592a0214fad495090ce980d70d8e246 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 20:51:20 -0500 Subject: [PATCH 05/30] fix(engine): outputs and inputs are local files, never an address or a stream FFmpeg reads an argument that starts with a name and a colon (tcp:, udp:, http:, rtmp:, ftp:, pipe:, file: and others) as a protocol. An output path or folder was passed on as given, so an encode could be sent to a network address, and inputs given as a numbered pattern skipped the exists check. Every output now goes through paths::local_output in runner::encode: an address or stream is refused with a message, anything else is made absolute. pipeline::build checks again, make_output and queue.setOutput refuse at once, and Engine::output_path returns the absolute path. The source, a stitched part and the audio source are refused when they are addresses (path_list, ffmpeg::probe, pipeline::build, runner::run). Run with a 1 second clip and the rebuilt fe_core against loopback listeners: before, tcp, http, rtmp and ftp outputs made 5 connections and folders named after the scheme appeared in the working directory; after, all seven kinds of address and an http folder are refused, a stored tcp folder fails at start, listeners see 0 connections, and plain, relative, ~ and leading-dash paths encode at their absolute path. Inputs: 39 connections before, 0 after. A playlist file naming an address was not followed by ffmpeg 6.1 even before. Then tests/test_local_paths.py (11 pass). --- backend/tests/test_local_paths.py | 119 ++++++++++++++++++ native/HASHOUT_LOG.md | 10 ++ native/fencoder-commands/src/commands.rs | 1 + .../src/commands/queue_cmds.rs | 6 + native/fencoder-core/src/paths.rs | 31 +++++ native/fencoder-engine/src/engine.rs | 10 ++ native/fencoder-io/src/ffmpeg.rs | 4 + native/fencoder-plan/src/pipeline.rs | 20 ++- native/fencoder-run/src/runner.rs | 3 + 9 files changed, 203 insertions(+), 1 deletion(-) create mode 100644 backend/tests/test_local_paths.py diff --git a/backend/tests/test_local_paths.py b/backend/tests/test_local_paths.py new file mode 100644 index 0000000..649a269 --- /dev/null +++ b/backend/tests/test_local_paths.py @@ -0,0 +1,119 @@ +import json +import shutil +import socket +import threading + +import pytest + +pytestmark = pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg is not installed") + +ADDRESSES = [ + "tcp://127.0.0.1:{port}/out.mkv", + "udp://127.0.0.1:{port}/out.mkv", + "http://127.0.0.1:{port}/out.mp4", + "rtmp://127.0.0.1:{port}/live/out", + "ftp://127.0.0.1:{port}/out.mp4", + "pipe:1", + "file:{tmp}/via-file-scheme.mp4", +] + + +class Listener: + def __init__(self): + self.sock = socket.socket() + self.sock.bind(("127.0.0.1", 0)) + self.sock.listen(8) + self.sock.settimeout(0.1) + self.port = self.sock.getsockname()[1] + self.connections = 0 + self.stop = threading.Event() + self.thread = threading.Thread(target=self.loop, daemon=True) + self.thread.start() + + def loop(self): + while not self.stop.is_set(): + try: + conn, _ = self.sock.accept() + except OSError: + continue + self.connections += 1 + conn.close() + + def close(self): + self.stop.set() + self.thread.join(2) + self.sock.close() + + +@pytest.fixture +def listener(): + held = Listener() + yield held + held.close() + + +def add(d, clip, **output): + return d.run("queue.addSource", paths=[str(clip)], outputs=[{"preset": "system/match-source-high", **output}])["output"] + + +@pytest.mark.parametrize("template", ADDRESSES) +def test_an_output_that_is_an_address_is_refused_when_it_is_set(driver, clip2, tmp_path, listener, template): + d = driver() + path = template.format(port=listener.port, tmp=tmp_path) + message = d.refuses("queue.addSource", paths=[str(clip2)], outputs=[{"preset": "system/match-source-high", "path": path}]) + assert "not a file path on this computer" in message + assert listener.connections == 0 + assert d.run("queue.list")["items"] == [] + + +def test_an_output_folder_that_is_an_address_is_refused_and_no_folder_is_made(driver, clip2, tmp_path, listener, monkeypatch): + monkeypatch.chdir(tmp_path) + d = driver() + assert "not a file path on this computer" in d.refuses("queue.addSource", paths=[str(clip2)], preset="system/match-source-high", folder=f"http://127.0.0.1:{listener.port}/dir") + oid = add(d, clip2, folder=str(tmp_path / "out")) + assert "not a file path on this computer" in d.refuses("queue.setOutput", refs=[oid], folder=f"tcp://127.0.0.1:{listener.port}/dir") + assert "not a file path on this computer" in d.refuses("queue.setOutput", refs=[oid], path="pipe:1") + assert listener.connections == 0 + assert sorted(p.name for p in tmp_path.iterdir() if p.name != "data") == [] + + +def test_a_stored_output_folder_that_is_an_address_fails_the_job_and_connects_nowhere(driver, clip2, tmp_path, listener, monkeypatch): + monkeypatch.chdir(tmp_path) + d = driver() + d.run("prefs.set", values={"outputFolder": f"tcp://127.0.0.1:{listener.port}/dir"}) + oid = d.run("queue.addSource", paths=[str(clip2)], preset="system/match-source-high")["output"] + d.run("queue.start") + row = d.finish(oid) + assert row["status"] == "failed" + assert "not a file path on this computer" in row["error"] + assert listener.connections == 0 + assert not (tmp_path / "tcp:").exists() + + +def test_plain_paths_still_encode_and_are_written_at_an_absolute_path(driver, clip2, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + d = driver() + wanted = { + "absolute": (str(tmp_path / "plain.mp4"), tmp_path / "plain.mp4"), + "relative": ("rel/out.mp4", tmp_path / "rel" / "out.mp4"), + "dash": ("-an.mp4", tmp_path / "-an.mp4"), + } + ids = {name: add(d, clip2, path=given) for name, (given, _) in wanted.items()} + d.run("queue.start") + for name, (_, expect) in wanted.items(): + row = d.finish(ids[name]) + assert row["status"] == "done", (name, row) + assert row["path"] == str(expect) + assert expect.is_file() + + +def test_an_input_that_is_an_address_is_refused_and_nothing_is_fetched(driver, tmp_path, listener): + import fe_core + + d = driver() + for pattern in ("http://127.0.0.1:{port}/x.mp4", "http://127.0.0.1:{port}/f_%06d.png", "tcp://127.0.0.1:{port}/f_%06d.png"): + given = pattern.format(port=listener.port) + assert "not a file on this computer" in d.refuses("queue.addSource", paths=[given], preset="system/match-source-high") + info = json.loads(fe_core.probe(given)) + assert "not a file on this computer" in info["error"] + assert listener.connections == 0 diff --git a/native/HASHOUT_LOG.md b/native/HASHOUT_LOG.md index 0bd9bcd..6e81dd5 100644 --- a/native/HASHOUT_LOG.md +++ b/native/HASHOUT_LOG.md @@ -186,3 +186,13 @@ Refers to `fencoder-run/src/runner.rs` `copy`, `write_part`, `same_file`, `resol - A folder ingested into a folder inside itself that does not exist yet (`CARD` into `CARD/backup`) was not refused, because `fs::canonicalize` of a missing folder is an error and the check was skipped, so the copy walked into `CARD/backup/CARD/...`. `resolved` canonicalises the nearest existing ancestor and appends the rest lexically (`..` pops, `.` is dropped). - Checked with `backend/tests/test_ingest.py`: the hard link tests (size and MD5) and the nested folder test fail on 0.8.2 (source 0 bytes; status done) and pass now; `cargo check --workspace --locked` with `-D warnings` passes on macOS and for `x86_64-pc-windows-msvc`. +## Outputs are local files, inputs are local files (unreleased, after 0.8.4) + +Refers to `fencoder-core/src/paths.rs` `has_scheme`, `local_input`, `local_output`, `absolute_or_same`; `fencoder-run/src/runner.rs` `encode`, `run`; `fencoder-plan/src/pipeline.rs` `build`; `fencoder-engine/src/engine.rs` `make_output`, `output_path`; `fencoder-commands/src/commands.rs` `path_list`; `fencoder-io/src/ffmpeg.rs` `probe` · kind: fix · logged: unreleased · 2026-11-19 + +- FFmpeg treats an argument that starts with `name:` (`tcp:`, `udp:`, `http:`, `rtmp:`, `ftp:`, `pipe:`, `file:` and others) as a protocol, not a file. An output path or folder was passed on as given, so such a value sent the encode to that address, and the folder for it was made under the engine's working directory. A leading `-` and a relative path were passed as given too. +- Every output now passes `paths::local_output`: `~` expanded, a value that starts with two or more scheme characters and a colon refused with a message that says to start with `./` if the colon is really in the name (a Windows drive letter is one character and stays a path), then made absolute with `std::path::absolute`, which does not touch the disk. The one place all outputs go through is `runner::encode` (first line, so a family source is not waited for first); `pipeline::build` checks again for the command-line preview and `encode.command`, and the secondary files (elementary audio, sidecars, `.fe-part`) are derived from the checked path. The pass log and the x265 stats file live in the job folder, which `build` makes absolute. `make_output` and `queue.setOutput` refuse a path or folder at once, so an agent or the window gets the message when the output is set, not when the encode starts. `Engine::output_path` now returns the absolute path, so the busy and incremented names compare like with like. +- Inputs: the app has no feature that reads from the network, and the engine's own `-f concat` list names only PNG files it wrote. `path_list` skipped its exists check for a `%0` pattern, so `http://host/f_%06d.png` went to ffprobe; it now refuses an address. `ffmpeg::probe` returns an error for one (so a loaded queue or a watch result cannot reach the network through it), `pipeline::build` refuses one for the source, a stitched part or the audio source, and `runner::run` refuses one for an analysis or a transcribe job. A playlist or concat file on disk that names an address is not followed by this FFmpeg (6.1): it fetched nothing in the run below, so no protocol whitelist was added. +- Not changed: the ingest copy destination and the transcribe sidecars are written with `std::fs`, not FFmpeg, so a `name:` value there makes a folder, not a connection. Output folders are not limited to a list: the person chooses where files go, and the operating system decides what the engine may write. +- Checked with a 1 second test clip and the real engine (`fe_core`, rebuilt with `maturin develop --release`) and local listeners on loopback: before, `tcp://`, `http://`, `rtmp://` and `ftp://` outputs made 5 connections and sent 1.9 kB, and `file:`, `pipe:`, `tcp:` folders appeared in the working directory; after, all of `tcp`, `http`, `udp`, `rtmp`, `ftp`, `pipe:1`, `file:` and an `http://` folder are refused when the output is set, a stored output made into `tcp://` through the output folder preference fails with the same message when the encode starts, listeners saw 0 connections and no folder was made. `-an.mp4`, a relative path, `~/x.mp4` and a plain absolute path encode and are written at the absolute path. Inputs: `probe` and `queue.addSource` on `http://` and `tcp://` (also with `%06d`) made 39 connections to the listener; now 0. + diff --git a/native/fencoder-commands/src/commands.rs b/native/fencoder-commands/src/commands.rs index 3fd40a0..4b68f0a 100644 --- a/native/fencoder-commands/src/commands.rs +++ b/native/fencoder-commands/src/commands.rs @@ -122,6 +122,7 @@ fn path_list(p: &Value, key: &str) -> Res> { let mut out = Vec::new(); for x in list { let e = paths::expand(&x); + paths::local_input(&e, "the input")?; if !e.contains("%0") && !Path::new(&e).exists() { return Err(format!("no file at {x}")); } diff --git a/native/fencoder-commands/src/commands/queue_cmds.rs b/native/fencoder-commands/src/commands/queue_cmds.rs index bed4573..abd892e 100644 --- a/native/fencoder-commands/src/commands/queue_cmds.rs +++ b/native/fencoder-commands/src/commands/queue_cmds.rs @@ -255,6 +255,12 @@ pub(super) fn set_output(e: &mut Engine, p: &Value) -> Res { if s(p, "path").is_some() && pairs.len() > 1 { return Err("a path names one file; pass folder to change several outputs".into()); } + if let Some(path) = s(p, "path") { + paths::local_output(path, "the output path")?; + } + if let Some(f) = s(p, "folder") { + paths::local_output(f, "the output folder")?; + } let mut ids_out = Vec::new(); for (i, j) in pairs { let o = &mut e.items_mut()[i]["outputs"][j]; diff --git a/native/fencoder-core/src/paths.rs b/native/fencoder-core/src/paths.rs index 2222d0f..844d50c 100644 --- a/native/fencoder-core/src/paths.rs +++ b/native/fencoder-core/src/paths.rs @@ -82,6 +82,37 @@ pub fn expand(p: &str) -> String { p.to_string() } +pub fn has_scheme(p: &str) -> bool { + let b = p.as_bytes(); + let n = b.iter().take_while(|c| c.is_ascii_alphanumeric() || matches!(c, b'+' | b'-' | b'.')).count(); + n >= 2 && b[0].is_ascii_alphabetic() && b.get(n) == Some(&b':') +} + +pub fn local_input(p: &str, what: &str) -> Result<(), String> { + if has_scheme(p) { + return Err(format!("{what} {p} is not a file on this computer; formencoder reads local files only (start a relative path with ./ if the name really has a colon)")); + } + Ok(()) +} + +pub fn absolute_or_same(p: &str) -> String { + if has_scheme(p) { + return p.to_string(); + } + std::path::absolute(p).map(|a| a.to_string_lossy().into_owned()).unwrap_or_else(|_| p.to_string()) +} + +pub fn local_output(p: &str, what: &str) -> Result { + let e = expand(p); + if e.is_empty() || e.contains('\0') { + return Err(format!("{what} is not a usable file path")); + } + if has_scheme(&e) { + return Err(format!("{what} {e} is not a file path on this computer; formencoder writes local files only (start a relative path with ./ if the name really has a colon)")); + } + std::path::absolute(&e).map(|a| a.to_string_lossy().into_owned()).map_err(|x| format!("{what} {e}: {x}")) +} + pub fn platform_data(app: &str) -> PathBuf { if cfg!(target_os = "macos") { home().join("Library").join("Application Support").join(app) diff --git a/native/fencoder-engine/src/engine.rs b/native/fencoder-engine/src/engine.rs index 13582f4..702b151 100644 --- a/native/fencoder-engine/src/engine.rs +++ b/native/fencoder-engine/src/engine.rs @@ -308,6 +308,12 @@ impl Engine { if let Some(sv) = given { s = settings::apply_patch(&s, sv)?; } + if let Some(p) = path.filter(|p| !p.is_empty()) { + paths::local_output(p, "the output path")?; + } + if let Some(f) = folder.filter(|f| !f.is_empty()) { + paths::local_output(f, "the output folder")?; + } Ok(json!({"id": new_id("o"), "kind": kind, "settings": s, "folder": folder.map(|f| paths::expand(f)), "path": path.map(|p| paths::expand(p)), "skip": false})) } @@ -318,6 +324,10 @@ impl Engine { } pub fn output_path(&self, item: &Value, output: &Value) -> String { + paths::absolute_or_same(&self.planned_output(item, output)) + } + + fn planned_output(&self, item: &Value, output: &Value) -> String { let s = &output["settings"]; if let Some(p) = output["path"].as_str().filter(|p| !p.is_empty()) { let mut pb = PathBuf::from(p); diff --git a/native/fencoder-io/src/ffmpeg.rs b/native/fencoder-io/src/ffmpeg.rs index b3eb8b3..97cc51e 100644 --- a/native/fencoder-io/src/ffmpeg.rs +++ b/native/fencoder-io/src/ffmpeg.rs @@ -370,6 +370,10 @@ pub fn probe(path: &str, frame_rate: Option) -> Value { "size": fs::metadata(p).map(|m| m.len()).unwrap_or(0), "kind": kind_of(path), "duration": 0.0, "bitrate": 0, "container": "", "video": null, "audio": [], "subtitles": [], "timecode": null, "tags": {}, }); + if paths::has_scheme(path) { + info["error"] = json!("not a file on this computer; formencoder reads local files only"); + return info; + } let mut pre: Vec = Vec::new(); let mut target = path.to_string(); if let Some(sq) = &seq { diff --git a/native/fencoder-plan/src/pipeline.rs b/native/fencoder-plan/src/pipeline.rs index ae697c0..ccabca1 100644 --- a/native/fencoder-plan/src/pipeline.rs +++ b/native/fencoder-plan/src/pipeline.rs @@ -10,7 +10,7 @@ use crate::formats::{self, acodec, vcodec}; use crate::settings::{self, loudness_standards}; use crate::text::{self, Rgba, Timecode}; use crate::util::{Res, rate_str}; -use crate::{colour, encoders, ffmpeg, metadata}; +use crate::{colour, encoders, ffmpeg, metadata, paths}; #[derive(Clone, Default)] pub struct Source { @@ -852,6 +852,24 @@ pub fn build(src: &Source, s: &Value, output: &str, work: &Path, opt: &BuildOpti let info = &src.info; let fmt = formats::get(s["format"].as_str().unwrap_or("h264"))?; let fmt_id = s["format"].as_str().unwrap_or("h264"); + if src.stitch.is_empty() { + paths::local_input(&src.path, "the source")?; + } + for (p, _) in &src.stitch { + paths::local_input(p, "a stitched source")?; + } + if let Some(a) = &src.audio_path { + paths::local_input(a, "the audio source")?; + } + let kept; + let output = if opt.preview_at.is_some() { + output + } else { + kept = paths::local_output(output, "the output path")?; + kept.as_str() + }; + let work_abs = paths::absolute_or_same(&work.to_string_lossy()); + let work = Path::new(&work_abs); let mut plan = Plan { output: output.into(), ..Default::default() }; let _ = fs::create_dir_all(work); let fmt_video = !fmt["video"].as_array().map(|a| a.is_empty()).unwrap_or(true); diff --git a/native/fencoder-run/src/runner.rs b/native/fencoder-run/src/runner.rs index d6adbb4..2c9174c 100644 --- a/native/fencoder-run/src/runner.rs +++ b/native/fencoder-run/src/runner.rs @@ -170,7 +170,9 @@ pub fn start(item: Value, output: Value, out_path: String, prefs: Value) -> Job fn run(ctx: Ctx, item: Value, output: Value, out_path: String) { let started = now(); let kind = output["kind"].as_str().unwrap_or("encode").to_string(); + let refused = if kind == "copy" || matches!(item["kind"].as_str(), Some("stitch" | "family")) { Ok(()) } else { paths::local_input(item["path"].as_str().unwrap_or(""), "the source") }; let outcome: Res = match kind.as_str() { + _ if refused.is_err() => Err(refused.err().unwrap_or_default()), "copy" => copy(&ctx, &item, &output), "analysis" => { let c2 = &ctx; @@ -287,6 +289,7 @@ fn source_for(ctx: &Ctx, item: &Value) -> Res<(Source, Option)> { } fn encode(ctx: &Ctx, item: &Value, output: &Value, planned_path: &str) -> Res { + let planned_path = paths::local_output(planned_path, "the output path")?; let mut s = settings::normalize(&output["settings"])?; let (src, tmp) = source_for(ctx, item)?; let base = if item["kind"] == "family" || (item["kind"] == "file" && crate::raw::decoder_for(item["path"].as_str().unwrap_or("")).is_some()) { 0.3 } else { 0.0 }; From 86388801c10e892aa624f4f91fbb1feff1a9db92 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 21:03:50 -0500 Subject: [PATCH 06/30] fix(window): a reload uses the kept window key before asking the bootstrap again In development the page asked POST /api/window/key first and fell back to the key kept in sessionStorage, so each reload after the first was refused with 409 and the engine logged a second claim that never happened. The kept key is now tried first (checked with POST /api/window/ticket) and the bootstrap is asked only when it is missing or no longer works. Run in headless Chrome against the engine from source and the Vite dev server: a load and two reloads, each followed by a write from the page. Before: bootstrap 200, 409, 409 and secondWindowClaim true. After: one request, secondWindowClaim false, all writes succeed. --- frontend/HASHOUT_LOG.md | 7 +++++++ frontend/src/engine/window-key.ts | 11 +++++++++++ 2 files changed, 18 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 52b4ded..dfbfb87 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -221,3 +221,10 @@ Refers to `engine/window-key.ts`, `engine/client.ts` `LOCAL_HEADERS`, `api`, `wi - Sockets take a one-time ticket: `windowTicket()` asks `POST /api/window/ticket` before each live socket (re)connect and each terminal socket. `Client.connect` and the terminal panel's `connect` became async for that one await; nothing in the DOM changes. - Other network calls in `src`: the demo file reads in `ui/demos.ts` are GETs of static files and need nothing. - Checked against the Vite dev server (on a spare port, with the engine's CORS origins set to it) in headless Chrome: the page booted to "Engine ready", took the key (in `sessionStorage`, no global left), the engine counted 1 window, the live and terminal sockets opened with tickets (the terminal showed a prompt), `POST /api/fs/mkdir` from the page and `api('/api/agents/workspace')` answered 200, a command and `agents.approvals` over the live socket answered, and every non-GET request but the bootstrap carried the key. After a reload the bootstrap answered 409, the page reused the stored key and the engine again counted 1 window. Not run: the desktop shell (it cannot be built here). + +## A reload tries the kept key before it asks again (unreleased, after 0.8.4) + +Refers to `engine/window-key.ts` `loadWindowKey`, `keyWorks` · kind: fix · logged: unreleased · 2026-11-19 + +- In development `loadWindowKey` asked `POST /api/window/key` first and used `sessionStorage` only when that failed. The bootstrap answers once, so every reload after the first got 409 and the engine logged a second claim (`secondWindowClaim`) that no second window had made. It now tries the kept key first, checking it with `POST /api/window/ticket` (the cheapest route that needs the key), and asks the bootstrap only when the kept key is missing or no longer works, as after the engine restarted. The packaged global still comes first. +- Checked in headless Chrome against the engine from source and the Vite dev server on spare ports: a load and two reloads, each followed by a write from the page (`api('/api/fs/mkdir')`). Before: 3 bootstrap requests (200, 409, 409), `secondWindowClaim` true. After: 1 request (200), `secondWindowClaim` false, all three writes 200. diff --git a/frontend/src/engine/window-key.ts b/frontend/src/engine/window-key.ts index 842181b..1921430 100644 --- a/frontend/src/engine/window-key.ts +++ b/frontend/src/engine/window-key.ts @@ -9,11 +9,22 @@ function remember(value: string): void { try { sessionStorage.setItem(STORE, value); } catch { return; } } +async function keyWorks(value: string): Promise { + try { + const res = await fetch('/api/window/ticket', { method: 'POST', headers: { 'x-formencoder-local': '1', [WINDOW_KEY_HEADER]: value } }); + return res.ok; + } catch { + return false; + } +} + export async function loadWindowKey(): Promise { const holder = window as unknown as { __FORMENCODER_WINDOW_KEY?: unknown }; const given = holder.__FORMENCODER_WINDOW_KEY; delete holder.__FORMENCODER_WINDOW_KEY; if (typeof given === 'string' && given) return given; + const kept = remembered(); + if (kept && await keyWorks(kept)) return kept; try { const res = await fetch('/api/window/key', { method: 'POST', headers: { 'x-formencoder-local': '1' } }); const body = res.ok ? await res.json() as { key?: unknown } : {}; From 845467aec13884074436b2bc5da0639fac8ab7cc Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 21:54:13 -0500 Subject: [PATCH 07/30] fix(shell): the engine gets as long to start as before; the 10 seconds cover only the key On origin/main the shell waited for the engine's address line with no limit and still does. Once the address line has arrived, it now waits at most 10 seconds for the window key if the key was not already read; when that runs out, the existing engine-failed-to-start dialog is shown and no window is opened. An engine that exits before printing its address takes the existing failure path at once. Checked: the engine from source printed the key line before the address line. The shell cannot be compiled here; the loops were run unchanged in a scratch crate against six fake event streams (key then address; address then silence for 11 seconds; 25 seconds of nothing then key and address, which opens; address then key 3 seconds later; exit before address; address with no key). The packaged app was not run. --- backend/HASHOUT_LOG.md | 8 ++++++++ src-tauri/src/main.rs | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index e9bb45f..2d76ebc 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -233,3 +233,11 @@ Refers to `ffmpeg_fetch.py` `SOURCES`, `sources`, `fetch`; `setup/bundle_ffmpeg. - `fetch` tries each address in order; a download error, an archive that does not open, a missing file or a file whose SHA-256 differs from the record moves on to the next address, and `install` copies nothing until every file has matched. When none works, `fetch` raises one error naming every address and why; its result's `source` names the address that answered. `bundle_ffmpeg.py` loops the same way and empties the stage after a refused archive; it still exits 0 with a notice when no address could be fetched (the app downloads on first run), and stops the build when an address answered with files that do not match. - Checked by running, before the tests: against a local server, wrong bytes from the first address and a 404 from it both installed the matching archive from the second; wrong bytes from both installed nothing; with the override set only it was asked, also when it answered 404. `bundle_ffmpeg.main` against the same server staged from the second address, stopped on two mismatches and exited 0 on two 404s. On the real network the new address answers 404 and the old one 302, and a real `fetch` into a scratch HOME installed the 12 recorded files from formcut-binaries. Then `tests/test_ffmpeg_fetch.py`. `src-tauri/binaries/ffmpeg-licence.json` names no address and is unchanged; the history lines above that name formcut-binaries stay as written. +## The shell gives the engine as long to start as before; 10 seconds cover only the key (unreleased, after 0.8.4) + +Refers to `src-tauri/src/main.rs` `setup` (the loop that reads the engine's first lines) · kind: fix · logged: unreleased · 2026-11-19 + +- On `origin/main` the loop waited for the address line with no limit, and it still does: a first launch of a packaged engine can take longer than 10 seconds (cold disk, a scan, unpacking) and must not end in "engine failed to start" on a healthy app. The 10 seconds start only when the address line has arrived (`Instant::now() + 10 s` taken after the first loop breaks on a port), and cover only a key that was not already read. The engine prints the key line before the address line, flushed, so the key is normally in hand by then; the wait is for a line read out of order or an engine too old to print a key. When it runs out with no key, `port` is cleared and the existing "engine failed to start" dialog and exit are taken, so no window opens. An engine that ends before printing its address leaves the first loop on `Terminated` or a closed channel and takes that path at once, as before. +- Same shape as the FormPath shell: a second loop with `try_recv` and a 20 ms `spawn_blocking` sleep, which needs no crate beyond the ones the shell already has (tauri 2 `async_runtime`, the shell plugin's receiver, `std`). +- Checked: the engine from source with `FORMENCODER_WINDOW_KEY_STDOUT=1` printed the key line first and the `Uvicorn running on` line second, each flushed. The shell cannot be compiled here (no system WebKit); `rustfmt --check` parses the file and reports only the differences that were there before. The two loops were copied unchanged into a scratch crate outside the repo (tokio 1.53.2 as in `Cargo.lock`, `regex`) and run against fake event streams: key and address together opened the window at once; the address and then nothing for 11 seconds gave no window after 10.0 seconds; nothing for 25 seconds and then key and address opened the window after 25.0 seconds (the case the old app also allowed); the address and the key 3 seconds later opened the window; an exit before the address gave no window at once; an address with no key at all gave no window after 10.0 seconds. Not run: the packaged app. + diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index e67d1dc..b0d22ed 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -117,6 +117,26 @@ fn main() { } } } + let grace = std::time::Instant::now() + std::time::Duration::from_secs(10); + while port.is_some() && key.is_none() && std::time::Instant::now() < grace { + match rx.try_recv() { + Ok(CommandEvent::Stdout(bytes)) => { + key = key_pattern + .captures(&String::from_utf8_lossy(&bytes)) + .map(|found| found[1].to_string()); + } + Ok(_) => {} + Err(_) => { + let _ = tauri::async_runtime::spawn_blocking(|| { + std::thread::sleep(std::time::Duration::from_millis(20)) + }) + .await; + } + } + } + if key.is_none() { + port = None; + } match port { Some(found) => { let url: tauri::Url = format!("http://127.0.0.1:{found}") From 1fc7d2d9c17666b082fb3433daef0df007a67577 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 22:06:52 -0500 Subject: [PATCH 08/30] test(ffmpeg): the error names both addresses when both fail Re-ran the download fallback against a loopback server for the case not run before. With both addresses answering 404, both answering wrong bytes, and the first wrong bytes with the second 404, fetch raised one error naming both addresses and the reason for each, and installed nothing. The existing test for no matching address now asserts both addresses are in the error. No code change. --- backend/HASHOUT_LOG.md | 1 + backend/tests/test_ffmpeg_fetch.py | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 2d76ebc..a76acf4 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -232,6 +232,7 @@ Refers to `ffmpeg_fetch.py` `SOURCES`, `sources`, `fetch`; `setup/bundle_ffmpeg. - The binaries repository is being renamed from `nodemode-dev/formcut-binaries` to `nodemode-dev/formai-binaries`; until then the new address answers 404, after it the old one redirects. `SOURCES` holds both, new first. `sources(data, triple)` returns the archive URL under each, or only the one under `FORMENCODER_FFMPEG_RELEASE` when that is set (a release folder URL; previously undocumented, now in `.docs/BRANCHING.md`, `src-tauri/ffmpeg/README.md` and `backend/.env.example`). The tag, the asset names, the install folder and the variable names are unchanged. - `fetch` tries each address in order; a download error, an archive that does not open, a missing file or a file whose SHA-256 differs from the record moves on to the next address, and `install` copies nothing until every file has matched. When none works, `fetch` raises one error naming every address and why; its result's `source` names the address that answered. `bundle_ffmpeg.py` loops the same way and empties the stage after a refused archive; it still exits 0 with a notice when no address could be fetched (the app downloads on first run), and stops the build when an address answered with files that do not match. - Checked by running, before the tests: against a local server, wrong bytes from the first address and a 404 from it both installed the matching archive from the second; wrong bytes from both installed nothing; with the override set only it was asked, also when it answered 404. `bundle_ffmpeg.main` against the same server staged from the second address, stopped on two mismatches and exited 0 on two 404s. On the real network the new address answers 404 and the old one 302, and a real `fetch` into a scratch HOME installed the 12 recorded files from formcut-binaries. Then `tests/test_ffmpeg_fetch.py`. `src-tauri/binaries/ffmpeg-licence.json` names no address and is unchanged; the history lines above that name formcut-binaries stay as written. +- Re-run on 2026-11-19 against a loopback server for the one case not run before: with both addresses answering 404, with both answering wrong bytes, and with the first wrong bytes and the second 404, `fetch` raised one `ValueError` that names both addresses and the reason for each, and nothing was installed. `test_nothing_is_installed_when_no_address_matches` now asserts both addresses are in the error. ## The shell gives the engine as long to start as before; 10 seconds cover only the key (unreleased, after 0.8.4) diff --git a/backend/tests/test_ffmpeg_fetch.py b/backend/tests/test_ffmpeg_fetch.py index 793adaf..a8837f8 100644 --- a/backend/tests/test_ffmpeg_fetch.py +++ b/backend/tests/test_ffmpeg_fetch.py @@ -90,8 +90,9 @@ def test_nothing_is_installed_when_no_address_matches(served): served["routes"]["/formai" + served["name"]] = archive(b"x\n") served["routes"]["/formcut" + served["name"]] = archive(b"y\n") - with pytest.raises(ValueError): + with pytest.raises(ValueError) as caught: ffmpeg_fetch.fetch(lambda p, m: None) + assert (served["base"] + "/formai") in str(caught.value) and (served["base"] + "/formcut") in str(caught.value) assert not (served["folder"] / "ffmpeg").exists() From 973b6434c098269380cda8c672b4723436a324fb Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 22:29:03 -0500 Subject: [PATCH 09/30] feat(agents): tell the person when the saved agent permission was changed outside the app When the stored agent choice (the Allow Always list or full faith) fails its seal, the engine ignores the edit and reports sealBroken in /api/agents/status. The Permissions section of the Agents panel now shows one sentence: "The saved agent permission was changed outside FormEncoder, so it is back to Ask." The sentence is always in the markup with visibility hidden, so its space is reserved and showing it only toggles a class on that node. It stays while the seal is reported broken and goes after Forget all or a new sealed choice. The app has no i18n table, so there is no language file to update. Checked in headless Chrome against the engine from source with a stand-in keyring and the Vite dev server: hidden with the choice intact; after a hand edit of agents.json the status reported sealBroken and the sentence showed in the same box it reserved, sections unchanged between shown and hidden; Forget all hid it again. tsc was not run for this commit separately; see the build report. --- frontend/HASHOUT_LOG.md | 9 +++++++++ frontend/src/panels/agents.ts | 4 +++- frontend/src/styles/base.css | 2 ++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index dfbfb87..07e3076 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -228,3 +228,12 @@ Refers to `engine/window-key.ts` `loadWindowKey`, `keyWorks` · kind: fix · log - In development `loadWindowKey` asked `POST /api/window/key` first and used `sessionStorage` only when that failed. The bootstrap answers once, so every reload after the first got 409 and the engine logged a second claim (`secondWindowClaim`) that no second window had made. It now tries the kept key first, checking it with `POST /api/window/ticket` (the cheapest route that needs the key), and asks the bootstrap only when the kept key is missing or no longer works, as after the engine restarted. The packaged global still comes first. - Checked in headless Chrome against the engine from source and the Vite dev server on spare ports: a load and two reloads, each followed by a write from the page (`api('/api/fs/mkdir')`). Before: 3 bootstrap requests (200, 409, 409), `secondWindowClaim` true. After: 1 request (200), `secondWindowClaim` false, all three writes 200. + +## A broken seal is told in the Agents panel (unreleased, after 0.8.4) + +Refers to `panels/agents.ts` `AgentsPanel` `load`, `styles/base.css` `.fx-agents-seal` · kind: feat · logged: unreleased · 2026-11-19 + +- When the stored agent choice (the Allow Always list or full faith) was changed outside the app, the engine ignores the edit and reports `consent.sealBroken` in `/api/agents/status`; until now the page showed nothing. The Permissions section of the Agents panel, where the person sees and changes that choice, now has one sentence under the allowed line: "The saved agent permission was changed outside FormEncoder, so it is back to Ask." +- The sentence is always in the markup with `visibility: hidden`, so its space is reserved from the first paint and showing it moves nothing; `load` toggles only the class `is-shown` on that one node (`setClass`, which writes only on a change). It is read each time the panel is shown, and stays while the engine reports a broken seal: it goes when the person presses Forget all or makes a choice that is sealed again. The cost is one blank line in the section when nothing is wrong. +- The panel has no i18n table: every string in `src` is English literal, so there is nothing to add per language. +- Checked in headless Chrome against the engine from source with a stand-in keyring (a file-backed backend in a launcher script outside the repo) and the Vite dev server on spare ports: with the choice intact the node was hidden; after a hand edit of `agents.json` (an entry added, seal left as it was) the status reported `sealBroken` true, and with the Agents tab shown again the node was visible, in the warning colour, with the same box as when hidden and the three section boxes unchanged between shown and hidden. Between the intact and broken states the allowed line itself changes (the list is empty, so its default sentence shows), which moved the sections below it by 16 px; that is the existing behaviour of that line, not of the new node. Forget all hid the node again and the status went back to `sealBroken` false. diff --git a/frontend/src/panels/agents.ts b/frontend/src/panels/agents.ts index f720ba1..e42b9da 100644 --- a/frontend/src/panels/agents.ts +++ b/frontend/src/panels/agents.ts @@ -15,7 +15,7 @@ interface Activity { interface AgentStatus { workspace: { path: string; mcp: { command: string; args: string[] } }; - consent: { policy: string; session: string[]; always: string[] }; + consent: { policy: string; session: string[]; always: string[]; sealBroken?: boolean }; clients: Record; windows: number; activity: Activity[]; @@ -44,6 +44,7 @@ export class AgentsPanel implements Panel {
${icon('lock', 14)}Permissions
+
The saved agent permission was changed outside FormEncoder, so it is back to Ask.
@@ -101,6 +102,7 @@ export class AgentsPanel implements Panel { for (const b of Array.from(this.el.querySelectorAll('[data-install]'))) setClass(b, 'is-missing', !s.clients[b.dataset.install as string]); const allowed = [...s.consent.always.map((c) => `${c} (always)`), ...s.consent.session.filter((c) => !s.consent.always.includes(c)).map((c) => `${c} (this session)`)]; setText(q(this.el, '.fx-agents-allowed'), allowed.length ? allowed.join(', ') : `Policy: ${s.consent.policy}. Agents from the Terminal panel are always trusted; others ask once.`); + setClass(q(this.el, '.fx-agents-seal'), 'is-shown', s.consent.sealBroken === true); if (!this.feed.length) this.feed = s.activity.filter((a) => a.source !== 'ui'); this.renderFeed(); const ap = await this.ctx.client.call<{ fullFaith: boolean }>('agents.approvals'); diff --git a/frontend/src/styles/base.css b/frontend/src/styles/base.css index 74d128c..7c380b9 100644 --- a/frontend/src/styles/base.css +++ b/frontend/src/styles/base.css @@ -174,6 +174,8 @@ body.theme-light .cv-menu, body.theme-light .cv-dialog, body.theme-light .cv-toa .fx-agents-kv { display: grid; grid-template-columns: 90px minmax(0, 1fr); align-items: baseline; gap: 8px; font-size: var(--fs-11); } .fx-agents-kv code { overflow: hidden; color: var(--text-primary); font-family: var(--font-mono); text-overflow: ellipsis; white-space: nowrap; user-select: text; -webkit-user-select: text; } .fx-agents-allowed { color: var(--text-secondary); font-size: var(--fs-11); line-height: 1.45; } +.fx-agents-seal { visibility: hidden; color: var(--warn); font-size: var(--fs-11); line-height: 1.45; } +.fx-agents-seal.is-shown { visibility: visible; } .fx-agents-feed { display: flex; flex-direction: column; flex: 1; min-height: 0; overflow: auto; } .fx-act { display: grid; grid-template-columns: 62px 74px minmax(0, 1fr); gap: 8px; flex: none; padding: 3px 0; border-bottom: 1px solid var(--line-0); font-size: var(--fs-11); } .fx-act-t { color: var(--text-muted); font-variant-numeric: tabular-nums; } From 1b941d50b24c48256c3cd47f31a9c86a2af12a00 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 22:29:33 -0500 Subject: [PATCH 10/30] feat(theme): AMOLED Black, a true-black theme for OLED screens Adds the amoled profile (label AMOLED Black, oled flag) to THEMES and to the pre-paint table in index.html, so a reload paints black on the first frame. applyTheme sets data-oled on html for an oled profile and removes it for every other. :root[data-oled] sets the hover tint and soft border to 10% and 12% white and --line-0 to --border-color so pane outlines stay visible. Measured surfaces that were not black get a data-oled rule: the title bar, the Form Family, Watch, Encoding, Effects and Publish cards, the Export Settings summary box and the modal scrim. The accent is the app's own. The theme picker is built from THEMES and lists it. Checked in headless Chrome at 1440 by 900 with 4x CPU throttle, a slow network and the cache off: cold load and hard reload with amoled saved show #000000 at every sample until the app is revealed, then only content; a live switch to AMOLED Black and back adds, removes and moves no element (717 elements); tsc --noEmit exits 0. Not checked: the desktop app, a real OLED screen, hover contrast in a screenshot. --- frontend/HASHOUT_LOG.md | 24 ++++++++++++++++++++++++ frontend/index.html | 5 ++++- frontend/src/styles/base.css | 2 ++ frontend/src/styles/fe.css | 2 ++ frontend/src/styles/tokens.css | 5 +++++ frontend/src/ui/themes.ts | 7 +++++-- 6 files changed, 42 insertions(+), 3 deletions(-) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 07e3076..14832d8 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -237,3 +237,27 @@ Refers to `panels/agents.ts` `AgentsPanel` `load`, `styles/base.css` `.fx-agents - The sentence is always in the markup with `visibility: hidden`, so its space is reserved from the first paint and showing it moves nothing; `load` toggles only the class `is-shown` on that one node (`setClass`, which writes only on a change). It is read each time the panel is shown, and stays while the engine reports a broken seal: it goes when the person presses Forget all or makes a choice that is sealed again. The cost is one blank line in the section when nothing is wrong. - The panel has no i18n table: every string in `src` is English literal, so there is nothing to add per language. - Checked in headless Chrome against the engine from source with a stand-in keyring (a file-backed backend in a launcher script outside the repo) and the Vite dev server on spare ports: with the choice intact the node was hidden; after a hand edit of `agents.json` (an entry added, seal left as it was) the status reported `sealBroken` true, and with the Agents tab shown again the node was visible, in the warning colour, with the same box as when hidden and the three section boxes unchanged between shown and hidden. Between the intact and broken states the allowed line itself changes (the list is empty, so its default sentence shows), which moved the sections below it by 16 px; that is the existing behaviour of that line, not of the new node. Forget all hid the node again and the status went back to `sealBroken` false. + +## AMOLED Black: the theme profile (unreleased, after 0.8.4) + +Refers to `ui/themes.ts` `ThemeProfile`, `THEMES`, `applyTheme` · kind: feat · logged: unreleased · 2026-11-19 + +- A true-black theme for OLED screens, id `amoled`, label "AMOLED Black", ported from the family reference (FormTxt): `--bg-primary`, `--bg-secondary`, `--bg-node` and `--canvas-bg` are `#000000`, `--bg-tertiary` is `#141414` (inputs, menus and selected rows use it as their only fill), `--border-color` `#262626`, `--border-light` `#3a3a3a`, text `#ededed`, `#a6a6a6`, `#858585` (17.9, 8.6 and 5.7 to 1 on black), `--grid-color` `#262626`. The accent is formencoder's own. This app's token names match the formvis system, so no mapping was needed. That makes sixteen profiles; the older "fifteen" in this log and in the demo READMEs counted before it. +- `ThemeProfile` gains `oled?: boolean`; `applyTheme` sets `data-oled` on `html` for an oled profile and removes it for every other, touching the attribute only when it changes. CSS hangs its exceptions on `data-oled`, not on the id. The theme picker (`ui/prefs.ts`) builds its chips from `THEMES`, so it lists the profile with no new control. +- Not changed: `applyTheme` has never updated the inline `html` background the pre-paint script sets, so after a live switch `html` keeps the first theme's colour behind `body`; `body` covers the whole window, so nothing shows, and it is the same for every theme. + +## AMOLED Black: the pre-paint script (unreleased, after 0.8.4) + +Refers to `index.html` inline script `OLED`, `PROFILES` · kind: feat · logged: unreleased · 2026-11-19 + +- The inline script is a second copy of the profile table, so the `amoled` row is there too, with an `OLED = { 'amoled': 1 }` table that sets `data-oled` beside the variables before the first paint. A theme in one table and not the other would paint Studio Dark first and then switch. The script already sets the `html` background to the profile's `--bg-primary`, so no extra critical style was needed: the first frame of a cold load with `amoled` saved is black. + +## AMOLED Black: the tokens and the surfaces that were not black (unreleased, after 0.8.4) + +Refers to `styles/tokens.css` `:root[data-oled]`, `styles/base.css` `.cv-titlebar`, `.cv-scrim`, `styles/fe.css` `.fe-w-item`, `.fe-enc-row`, `.fe-f-app`, `.fe-fx`, `.fe-pub`, `.fe-demo-card`, `.fe-es-summary` · kind: feat · logged: unreleased · 2026-11-19 + +- `:root[data-oled]` sets `--bg-hover` to 10% white and `--border-soft` to 12% white (the usual 6% and 8% are too close to black to read) and `--line-0` to `--border-color`: `--line-0` is the colour of every pane outline and divider and is a mix of the background with black, which is black on a black theme, so the panes lost their edges. `--line-0` is used only for borders. `--surface-1` is not remapped globally: it is also the hover fill of rows and tabs, which would vanish. +- Found by measuring, in headless Chrome on the Default workspace with a source in the queue (every element over 12,000 px2 with a non-black fill or a background image) and with Export Settings open: the title bar (a gradient from `--surface-2` to `--surface-1`, `#090909` at the bottom), the Form Family app cards, the cards that the Queue (Watch rows), Encoding rows, Effects and Publish use (`--surface-1`), the Export Settings summary box (`#090909`, no border, so it keeps a 1px inset line in `--border-color`), and the modal scrim (a purple-black at 45%, which made the dimmed frame `#040306`). Each now has a `data-oled` rule using `--bg-primary` or black. The queue list, the Preset Browser, the Log, Media Info, the Export Settings preview and its dialog were already `#000000`. +- Left as they are by design: the `#141414` fields and menus, tab pills (`--surface-raised`), the selected row tint (accent at 10%), small thumbnails (`.fe-m-thumb`, `#090909`, 34 by 24 px) and the accent. +- Checked: headless Chrome 1440 by 900, 4x CPU throttle (`Emulation.setCPUThrottlingRate`), 150 ms and 1.6 Mbit/s network, cache off, engine from source and Vite dev server on spare ports. Cold load and hard reload with `amoled` saved, about 150 screenshots each, 5 sample points (inset 14 px from the corners, and the centre) on each of the window, title bar, status bar, the four dock areas, queue, preset browser and log or encoding pane: every sample is `#000000` until the app is revealed at about 9.5 s (8.5 s for one sample); after that the only non-black samples are content (logo, tab pill, text, an icon, one error toast that appeared at 8.5 s in the bottom right corner; its cause was not looked into). Live switch Studio Dark to AMOLED Black and back: 717 elements before and after, none added or removed (MutationObserver), none moved (bounding boxes), `data-oled` set and removed. +- Not checked: hover and press contrast in a screenshot, the Settings picker in a screenshot, a running encode's live preview, the desktop app, a real OLED screen. diff --git a/frontend/index.html b/frontend/index.html index c6afee1..f354d01 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -19,6 +19,7 @@ var DEFAULT_THEME = 'studio'; var DEFAULT_ACCENT = '#f2545b'; var LIGHT = { 'light': 1, 'sand': 1 }; + var OLED = { 'amoled': 1 }; var PROFILES = { 'studio': ['#111111', '#17151b', '#222127', '#2a2a2a', '#34333a', '#f7f7f7', '#a4a4a4', '#717072', '#1c1b1d', '#5e5e60', '#191919'], 'nodemode-dark': ['#0a0a0a', '#121218', '#1a1a24', '#2a2a35', '#3a3a48', '#e8e8ee', '#a8a8b8', '#6a6a7a', '#0a0a0a', 'rgba(255,255,255,0.04)'], @@ -34,7 +35,8 @@ 'ocean': ['#06131c', '#0a1c29', '#10293c', '#1d425e', '#285578', '#e2eef7', '#96b6cc', '#5b7d94', '#06131c', 'rgba(150,210,255,0.06)'], 'rose': ['#170b10', '#211117', '#301a22', '#4d2b38', '#653a49', '#f5e7ec', '#cfa5b3', '#966b7b', '#170b10', 'rgba(255,190,215,0.05)'], 'terminal': ['#050d05', '#0a140a', '#102010', '#1f3d1f', '#2b522b', '#d8f5d8', '#8fce8f', '#568a56', '#050d05', 'rgba(120,255,120,0.06)'], - 'contrast': ['#000000', '#0a0a0a', '#161616', '#555555', '#777777', '#ffffff', '#d8d8d8', '#9a9a9a', '#000000', 'rgba(255,255,255,0.10)'] + 'contrast': ['#000000', '#0a0a0a', '#161616', '#555555', '#777777', '#ffffff', '#d8d8d8', '#9a9a9a', '#000000', 'rgba(255,255,255,0.10)'], + 'amoled': ['#000000', '#000000', '#141414', '#262626', '#3a3a3a', '#ededed', '#a6a6a6', '#858585', '#000000', '#262626', '#000000'] }; var NAMES = ['--bg-primary', '--bg-secondary', '--bg-tertiary', '--border-color', '--border-light', '--text-primary', '--text-secondary', '--text-muted', '--canvas-bg', '--grid-color']; var theme = DEFAULT_THEME, accent = DEFAULT_ACCENT, intensity = 1; @@ -43,6 +45,7 @@ if (raw) { var s = JSON.parse(raw); if (s.theme && PROFILES[s.theme]) theme = s.theme; if (s.accentColor) accent = s.accentColor; if (typeof s.intensity === 'number') intensity = Math.min(1.5, Math.max(0, s.intensity)); } } catch (e) { theme = DEFAULT_THEME; } var p = PROFILES[theme], root = document.documentElement, i; + if (OLED[theme]) root.setAttribute('data-oled', ''); for (i = 0; i < NAMES.length; i++) root.style.setProperty(NAMES[i], p[i]); root.style.setProperty('--bg-node', p[10] || p[1]); root.style.setProperty('--shadow-lg', LIGHT[theme] ? '0 4px 14px rgba(96, 90, 70, 0.16)' : '0 8px 32px rgba(0, 0, 0, 0.5)'); diff --git a/frontend/src/styles/base.css b/frontend/src/styles/base.css index 7c380b9..c5ea9a7 100644 --- a/frontend/src/styles/base.css +++ b/frontend/src/styles/base.css @@ -7,6 +7,7 @@ body { font-size: var(--fs-12); line-height: 1.35; } .cv-app { display: grid; grid-template-rows: var(--cv-titlebar-h) minmax(0, 1fr) var(--cv-status-h); height: 100%; background: var(--bg-primary); color: var(--text-primary); user-select: none; -webkit-user-select: none; } .cv-titlebar { display: grid; grid-template-columns: auto auto minmax(0, 1fr) auto; align-items: center; column-gap: var(--space-3); padding: 0 var(--space-3); background: linear-gradient(to bottom, var(--surface-2), var(--surface-1)); border-bottom: 1px solid var(--line-0); min-width: 0; } +:root[data-oled] .cv-titlebar { background: var(--bg-primary); } .cv-brand { display: inline-flex; align-items: center; gap: var(--space-2); color: var(--accent-color); } .cv-brand-name { color: var(--text-primary); font-size: var(--fs-13); font-weight: 600; letter-spacing: 0.2px; } .cv-menubar { display: flex; align-items: center; gap: 2px; } @@ -72,6 +73,7 @@ body { font-size: var(--fs-12); line-height: 1.35; } .cv-scrim { position: fixed; inset: 0; z-index: var(--z-modal); display: flex; align-items: center; justify-content: center; background: rgba(8, 6, 14, 0.45); backdrop-filter: blur(14px) saturate(0.9); -webkit-backdrop-filter: blur(14px) saturate(0.9); } .cv-scrim[hidden] { display: none; } +:root[data-oled] .cv-scrim { background: rgba(0, 0, 0, 0.45); } .cv-dialog { width: min(var(--cv-dialog-w, 440px), calc(100vw - 48px)); max-height: calc(100vh - 64px); display: grid; grid-template-rows: auto minmax(0, 1fr) auto; border: 1px solid var(--line-3); border-radius: 14px; background: var(--surface-2); box-shadow: 0 30px 80px rgba(0, 0, 0, 0.6); outline: none; } .cv-dialog-head { display: grid; grid-template-columns: 1fr auto; align-items: center; height: 44px; padding: 0 var(--space-2) 0 var(--space-4); border-bottom: 1px solid var(--border-color); } .cv-dialog-title { font-size: 16px; font-weight: 600; color: var(--text-primary); } diff --git a/frontend/src/styles/fe.css b/frontend/src/styles/fe.css index eae3931..a014ade 100644 --- a/frontend/src/styles/fe.css +++ b/frontend/src/styles/fe.css @@ -344,3 +344,5 @@ .fe-sc-row.is-changed .fe-sc-label { color: var(--text-primary); } .fe-raw-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 10px; align-items: start; } .fe-raw-json { width: 100%; min-height: 120px; resize: vertical; font-family: var(--font-mono); font-size: var(--fs-11); } +:root[data-oled] .fe-es-summary { background: var(--bg-primary); box-shadow: inset 0 0 0 1px var(--border-color); } +:root[data-oled] .fe-w-item,:root[data-oled] .fe-enc-row, :root[data-oled] .fe-f-app, :root[data-oled] .fe-fx, :root[data-oled] .fe-pub, :root[data-oled] .fe-demo-card { background: var(--bg-primary); } diff --git a/frontend/src/styles/tokens.css b/frontend/src/styles/tokens.css index 9f24c76..d2eb56b 100644 --- a/frontend/src/styles/tokens.css +++ b/frontend/src/styles/tokens.css @@ -116,6 +116,11 @@ --glass-filter: blur(40px) saturate(1.8); --glass-shadow: 0 22px 56px rgba(0, 0, 0, 0.45), 0 2px 8px rgba(0, 0, 0, 0.25); } +:root[data-oled] { + --bg-hover: rgba(255, 255, 255, 0.1); + --border-soft: rgba(255, 255, 255, 0.12); + --line-0: var(--border-color); +} body.theme-light { color-scheme: light; diff --git a/frontend/src/ui/themes.ts b/frontend/src/ui/themes.ts index 80802a4..cf5f0fc 100644 --- a/frontend/src/ui/themes.ts +++ b/frontend/src/ui/themes.ts @@ -1,4 +1,4 @@ -export interface ThemeProfile { label: string; vars: Record; light?: boolean } +export interface ThemeProfile { label: string; vars: Record; light?: boolean; oled?: boolean } export const THEMES: Record = { 'studio': { label: 'Studio Dark', vars: { '--bg-primary': '#111111', '--bg-secondary': '#17151b', '--bg-tertiary': '#222127', '--border-color': '#2a2a2a', '--border-light': '#34333a', '--text-primary': '#f7f7f7', '--text-secondary': '#a4a4a4', '--text-muted': '#717072', '--canvas-bg': '#1c1b1d', '--grid-color': '#5e5e60', '--bg-node': '#191919' } }, @@ -15,7 +15,9 @@ export const THEMES: Record = { 'ocean': { label: 'Deep Ocean', vars: { '--bg-primary': '#06131c', '--bg-secondary': '#0a1c29', '--bg-tertiary': '#10293c', '--border-color': '#1d425e', '--border-light': '#285578', '--text-primary': '#e2eef7', '--text-secondary': '#96b6cc', '--text-muted': '#5b7d94', '--canvas-bg': '#06131c', '--grid-color': 'rgba(150,210,255,0.06)', '--node-shadow': '0 8px 22px rgba(0,10,20,0.6)' } }, 'rose': { label: 'Rose Noir', vars: { '--bg-primary': '#170b10', '--bg-secondary': '#211117', '--bg-tertiary': '#301a22', '--border-color': '#4d2b38', '--border-light': '#653a49', '--text-primary': '#f5e7ec', '--text-secondary': '#cfa5b3', '--text-muted': '#966b7b', '--canvas-bg': '#170b10', '--grid-color': 'rgba(255,190,215,0.05)', '--node-shadow': '0 6px 18px rgba(25,0,10,0.55)' } }, 'terminal': { label: 'Terminal Green', vars: { '--bg-primary': '#050d05', '--bg-secondary': '#0a140a', '--bg-tertiary': '#102010', '--border-color': '#1f3d1f', '--border-light': '#2b522b', '--text-primary': '#d8f5d8', '--text-secondary': '#8fce8f', '--text-muted': '#568a56', '--canvas-bg': '#050d05', '--grid-color': 'rgba(120,255,120,0.06)', '--node-shadow': '0 6px 18px rgba(0,10,0,0.6)' } }, - 'contrast': { label: 'High Contrast', vars: { '--bg-primary': '#000000', '--bg-secondary': '#0a0a0a', '--bg-tertiary': '#161616', '--border-color': '#555555', '--border-light': '#777777', '--text-primary': '#ffffff', '--text-secondary': '#d8d8d8', '--text-muted': '#9a9a9a', '--canvas-bg': '#000000', '--grid-color': 'rgba(255,255,255,0.10)', '--node-shadow': '0 0 0 1px #666' } },}; + 'contrast': { label: 'High Contrast', vars: { '--bg-primary': '#000000', '--bg-secondary': '#0a0a0a', '--bg-tertiary': '#161616', '--border-color': '#555555', '--border-light': '#777777', '--text-primary': '#ffffff', '--text-secondary': '#d8d8d8', '--text-muted': '#9a9a9a', '--canvas-bg': '#000000', '--grid-color': 'rgba(255,255,255,0.10)', '--node-shadow': '0 0 0 1px #666' } }, + 'amoled': { label: 'AMOLED Black', oled: true, vars: { '--bg-primary': '#000000', '--bg-secondary': '#000000', '--bg-tertiary': '#141414', '--bg-node': '#000000', '--border-color': '#262626', '--border-light': '#3a3a3a', '--text-primary': '#ededed', '--text-secondary': '#a6a6a6', '--text-muted': '#858585', '--canvas-bg': '#000000', '--grid-color': '#262626' } }, +}; export const DEFAULT_THEME = 'studio'; export const DEFAULT_ACCENT = '#f2545b'; @@ -55,6 +57,7 @@ export function applyTheme(choice: ThemeChoice = readChoice()): void { const theme = THEMES[choice.theme] || THEMES[DEFAULT_THEME]; for (const [k, v] of Object.entries(theme.vars)) root.style.setProperty(k, v); document.body.classList.toggle('theme-light', !!theme.light); + if (theme.oled) { if (!root.hasAttribute('data-oled')) root.setAttribute('data-oled', ''); } else if (root.hasAttribute('data-oled')) root.removeAttribute('data-oled'); root.style.setProperty('--bg-node', theme.vars['--bg-node'] || theme.vars['--bg-secondary']); root.style.setProperty('--shadow-lg', theme.light ? '0 4px 14px rgba(96, 90, 70, 0.16)' From dafc6103bf92d0862752c02606b2ed6f12e363ab Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 18 Nov 2026 22:54:48 -0500 Subject: [PATCH 11/30] feat(agents): agents/manifest.json says what the app offers agents The agents sync writes agents/manifest.json from the tool registry, the skills folder and the extension host, and --check names the file when it drifts. The dock part is one declared value in setup/agents.py. PARITY.md now says 29 curated and 125 tools. --- CLAUDE.md | 2 +- agents/manifest.json | 313 ++++++++++++++++++++++++++ backend/HASHOUT_LOG.md | 10 + backend/tests/test_agents_manifest.py | 23 ++ docs/PARITY.md | 2 +- setup/agents.py | 37 ++- 6 files changed, 383 insertions(+), 4 deletions(-) create mode 100644 agents/manifest.json create mode 100644 backend/tests/test_agents_manifest.py diff --git a/CLAUDE.md b/CLAUDE.md index 58de8f0..0208c1e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -20,7 +20,7 @@ The media encoder of the form family beside formcut, formvfx, formwav and formvi ## After changing the MCP tools or the engine's commands, formats or presets -Run `./formencoder agents sync` so `.claude/skills/formencoder-harness/references/` and the `.agents/skills` mirror follow; `./formencoder agents sync --check` fails while they drift. +Run `./formencoder agents sync` so `.claude/skills/formencoder-harness/references/` and the `.agents/skills` mirror follow; `./formencoder agents sync --check` fails while they drift. The same sync writes `agents/manifest.json` (the tools, skills and dock the app offers agents; the family spec reads it); the dock part is the `DOCK` value in `setup/agents.py`, kept by hand. ## Trademarks, copyright and licences diff --git a/agents/manifest.json b/agents/manifest.json new file mode 100644 index 0000000..36e71f3 --- /dev/null +++ b/agents/manifest.json @@ -0,0 +1,313 @@ +{ + "format": "form-agent-manifest", + "version": 1, + "app": "formencoder", + "mcp": { + "tools": [ + "status", + "list_commands", + "describe_command", + "execute", + "batch", + "probe", + "encode", + "queue", + "export_settings", + "preview_frame", + "contact_sheet", + "wait", + "verify", + "presets", + "formats", + "watch_folder", + "family", + "log", + "history", + "ui", + "guide", + "approval_status", + "terminal_list", + "terminal_open", + "terminal_send", + "terminal_read", + "extensions_list", + "extension_command", + "terminal_close", + "queue_list", + "queue_add_source", + "queue_add_folder", + "queue_add_output", + "queue_duplicate", + "queue_remove", + "queue_clear_done", + "queue_set_preset", + "queue_set_format", + "queue_set_settings", + "queue_get_settings", + "settings_apply", + "queue_set_output", + "queue_set_range", + "queue_interpret", + "queue_reorder", + "queue_skip", + "queue_reset_status", + "queue_start", + "queue_pause", + "queue_stop", + "queue_stop_current", + "queue_auto_encode_watch", + "queue_stitch", + "queue_select", + "queue_save", + "queue_open", + "encode_status", + "encode_report", + "encode_estimate", + "encode_command", + "encode_verify", + "preset_list", + "preset_get", + "preset_create", + "preset_update", + "preset_delete", + "preset_duplicate", + "preset_new_group", + "preset_alias", + "preset_import", + "preset_export", + "preset_reveal", + "ingest_copy", + "proxy_create", + "captions_transcribe", + "captions_models", + "analyze_media", + "watch_list", + "watch_add", + "watch_remove", + "watch_set_active", + "watch_chain", + "watch_add_output", + "watch_set_output", + "watch_remove_output", + "watch_scan", + "format_list", + "format_describe", + "format_encoders", + "media_roots", + "media_browse", + "media_probe", + "captions_read", + "captions_convert", + "metadata_templates", + "metadata_save_template", + "metadata_delete_template", + "lut_list", + "lut_install", + "log_read", + "log_clear", + "prefs_get", + "prefs_set", + "prefs_reset", + "prefs_cache_info", + "plugin_list", + "plugin_run", + "plugin_result", + "shortcuts_list", + "shortcuts_set", + "shortcuts_reset", + "tools_list", + "prefs_clean_cache", + "family_queue", + "family_resolved", + "publish_result", + "edit_undo", + "edit_redo", + "history_list", + "ui_panel", + "ui_workspace", + "ui_export_settings", + "ui_toast", + "app_capabilities", + "app_status" + ], + "read_only": [ + "status", + "list_commands", + "describe_command", + "probe", + "preview_frame", + "contact_sheet", + "wait", + "verify", + "formats", + "log", + "guide", + "approval_status", + "terminal_list", + "terminal_read", + "extensions_list", + "queue_list", + "queue_get_settings", + "settings_apply", + "queue_select", + "queue_save", + "encode_status", + "encode_report", + "encode_estimate", + "encode_command", + "encode_verify", + "preset_list", + "preset_get", + "preset_reveal", + "captions_models", + "watch_list", + "format_list", + "format_describe", + "format_encoders", + "media_roots", + "media_browse", + "media_probe", + "captions_read", + "metadata_templates", + "lut_list", + "log_read", + "prefs_get", + "prefs_cache_info", + "plugin_list", + "plugin_result", + "shortcuts_list", + "tools_list", + "family_resolved", + "history_list", + "ui_panel", + "ui_workspace", + "ui_export_settings", + "ui_toast", + "app_capabilities", + "app_status" + ], + "approval_gated": [ + "execute", + "batch", + "encode", + "queue", + "export_settings", + "presets", + "watch_folder", + "family", + "history", + "ui", + "terminal_open", + "terminal_send", + "extension_command", + "terminal_close", + "queue_add_source", + "queue_add_folder", + "queue_add_output", + "queue_duplicate", + "queue_remove", + "queue_clear_done", + "queue_set_preset", + "queue_set_format", + "queue_set_settings", + "queue_set_output", + "queue_set_range", + "queue_interpret", + "queue_reorder", + "queue_skip", + "queue_reset_status", + "queue_start", + "queue_pause", + "queue_stop", + "queue_stop_current", + "queue_auto_encode_watch", + "queue_stitch", + "queue_open", + "preset_create", + "preset_update", + "preset_delete", + "preset_duplicate", + "preset_new_group", + "preset_alias", + "preset_import", + "preset_export", + "ingest_copy", + "proxy_create", + "captions_transcribe", + "analyze_media", + "watch_add", + "watch_remove", + "watch_set_active", + "watch_chain", + "watch_add_output", + "watch_set_output", + "watch_remove_output", + "watch_scan", + "captions_convert", + "metadata_save_template", + "metadata_delete_template", + "lut_install", + "log_clear", + "prefs_set", + "prefs_reset", + "plugin_run", + "shortcuts_set", + "shortcuts_reset", + "prefs_clean_cache", + "family_queue", + "publish_result", + "edit_undo", + "edit_redo" + ], + "transports": [ + "stdio", + "http" + ] + }, + "skills": [ + { + "name": "formencoder-harness", + "sub_skills": [ + "captions-and-metadata", + "effects-and-loudness", + "export-settings", + "form-family-bridge", + "harness-director", + "publish", + "queue-and-presets", + "recipes", + "session-and-connection", + "ui-automation", + "verification", + "watch-folders-and-ingest" + ] + }, + { + "name": "formencoder-skillset", + "sub_skills": [ + "agent-substrate", + "desktop-and-release", + "engine-core", + "engine-service", + "interface", + "verification" + ] + } + ], + "dock": { + "present": true, + "positions": [ + "left", + "right", + "bottom", + "floating" + ], + "tabs": [ + "terminal", + "agents" + ] + }, + "extensions": { + "host_api": "1" + } +} diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index a76acf4..466d16d 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -242,3 +242,13 @@ Refers to `src-tauri/src/main.rs` `setup` (the loop that reads the engine's firs - Same shape as the FormPath shell: a second loop with `try_recv` and a 20 ms `spawn_blocking` sleep, which needs no crate beyond the ones the shell already has (tauri 2 `async_runtime`, the shell plugin's receiver, `std`). - Checked: the engine from source with `FORMENCODER_WINDOW_KEY_STDOUT=1` printed the key line first and the `Uvicorn running on` line second, each flushed. The shell cannot be compiled here (no system WebKit); `rustfmt --check` parses the file and reports only the differences that were there before. The two loops were copied unchanged into a scratch crate outside the repo (tokio 1.53.2 as in `Cargo.lock`, `regex`) and run against fake event streams: key and address together opened the window at once; the address and then nothing for 11 seconds gave no window after 10.0 seconds; nothing for 25 seconds and then key and address opened the window after 25.0 seconds (the case the old app also allowed); the address and the key 3 seconds later opened the window; an exit before the address gave no window at once; an address with no key at all gave no window after 10.0 seconds. Not run: the packaged app. +## agents/manifest.json says what the app offers agents (unreleased, after 0.8.4) + +Refers to `setup/agents.py` `manifest_text`, `sync`; `agents/manifest.json`; `backend/tests/test_agents_manifest.py` · kind: feat · logged: unreleased · 2026-11-18 + +- The family spec (formadaptor, `spec/agent-manifest.schema.json`) reads this file at each released tag, so the gateway, the skills installer and the site stop carrying hand-typed tool counts. `./formencoder agents sync` writes it with the generated references and `--check` names `agents/manifest.json` when the committed file is not what would be written. `app` is `formencoder`, the file name of the app's entry in formcompiler `apps/`. +- Every field but the dock is read from the source. `mcp.tools` is `TOOLS` followed by one tool per registry command, built by `tools._command_tool` and skipping a name a curated tool already has, the same rule as `tools.command_tools()` (the full profile, which is what `tools/list` returns with no profile). `read_only` is the `readOnlyHint` each listed tool carries. `approval_gated` follows the consent gate (`routers/mcp.py`: `mutating = not tools.read_only(name)`): the curated tools not in `READ_ONLY` and the commands whose `query` flag is false, so it is every tool that is not read-only; `consent.gate` asks about each of them when the policy is ask and the client was not allowed. The per-call asks of `approvals.guard` (uploads, deletes, overwrites) come on top of that and are not a property of a tool, so they are not listed. `transports` is `stdio` (`setup/mcp_stdio.py`, `./formencoder mcp`) and `http` (`POST /mcp`). `skills` are the folders of `.claude/skills` with a `SKILL.md`, each with the sub-skill folders that hold a `SUB-SKILL.md`, sorted. `extensions.host_api` is `formext_host.API`. +- `DOCK` in `setup/agents.py` is the one declared value. It is read by hand from `frontend/src/ui/dock.ts` and `frontend/src/app/app.ts`: the family's dock here is the panel dock, where the Terminal and Agents panels (`terminal`, `agents`) sit in tab groups and can be placed in the left, right or bottom area or torn out to a floating group (the Agent workspace puts both on the right; `Dock.home` defaults them to the bottom). The area `center` exists but is not a position the schema knows. Update the value when the dock changes; nothing checks it. +- Checked by running, before the test: sync wrote 125 tools, 54 read-only (15 curated and 39 query commands), 71 approval-gated, 2 skills and 18 sub-skills; `scripts/manifest.py check agents/manifest.json --app formencoder` in formadaptor accepted it; `--check` exited 0; the engine from source on port 28900 answered `tools/list` with the same 125 names in the same order and the same read-only set. In a copy outside the tree, renaming one tool in the manifest and, separately, dropping `read=True` from `status` in the copy of `tools.py` each made `--check` exit 1 and name `agents/manifest.json`. `docs/PARITY.md` still said 21 curated and 123 tools; it now says 29 and 125 (the older HASHOUT entries keep the counts of their day). +- Each `Engine()` in the sync creates a data folder under the system temp (existing behaviour of the script); the manifest adds one more per run. + diff --git a/backend/tests/test_agents_manifest.py b/backend/tests/test_agents_manifest.py new file mode 100644 index 0000000..39ef198 --- /dev/null +++ b/backend/tests/test_agents_manifest.py @@ -0,0 +1,23 @@ +import json +import subprocess +import sys + +from conftest import REPO, tool_catalogue + +MANIFEST = REPO / "agents" / "manifest.json" + + +def test_the_committed_manifest_is_current(): + done = subprocess.run([sys.executable, "-I", str(REPO / "setup" / "agents.py"), "sync", "--check"], capture_output=True, text=True, timeout=180) + assert done.returncode == 0, done.stdout + done.stderr + assert "agents/manifest.json" not in done.stdout + + +def test_the_manifest_lists_the_tools_the_server_lists(): + doc = json.loads(MANIFEST.read_text(encoding="utf-8")) + mcp = doc["mcp"] + assert doc["app"] == "formencoder" + assert mcp["tools"] == [t["name"] for t in tool_catalogue()] + assert set(mcp["read_only"]) <= set(mcp["tools"]) + assert set(mcp["approval_gated"]) == set(mcp["tools"]) - set(mcp["read_only"]) + assert mcp["transports"] == ["stdio", "http"] diff --git a/docs/PARITY.md b/docs/PARITY.md index 44c9145..44f57a5 100644 --- a/docs/PARITY.md +++ b/docs/PARITY.md @@ -125,7 +125,7 @@ Media Encoder's own documentation backs every row; 33 rows also carry an indepen ## Beyond Media Encoder (not scored) -- 85. AI agent control (MCP server, agent terminal): formencoder Full (The formencoder MCP server over Streamable HTTP and stdio (21 curated tools plus one tool per engine command, 123 in the full profile, with resources and recipe prompts), every command also runnable as ./formencoder ID --name value, terminals agents open, type into and read in front of the person, consequential actions held for the person's approval unless they turn on full faith, consent per client, the formencoder-harness skill, and an embedded terminal that starts Claude Code, Codex and Cursor already connected. Verified: MCP encode, preview and verify.) +- 85. AI agent control (MCP server, agent terminal): formencoder Full (The formencoder MCP server over Streamable HTTP and stdio (29 curated tools plus one tool per engine command, 125 in the full profile, with resources and recipe prompts), every command also runnable as ./formencoder ID --name value, terminals agents open, type into and read in front of the person, consequential actions held for the person's approval unless they turn on full faith, consent per client, the formencoder-harness skill, and an embedded terminal that starts Claude Code, Codex and Cursor already connected. Verified: MCP encode, preview and verify.) ## Method diff --git a/setup/agents.py b/setup/agents.py index 16042a4..51931c9 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -2,8 +2,8 @@ """./formencoder agents: Claude Code, Codex and Cursor driving formencoder. sync [--check] regenerate the formencoder-harness skill's generated references from the engine (commands, MCP tools, - presets, formats and settings) and mirror .claude/skills/formencoder-harness to .agents/skills; - --check exits 1 when anything drifted + presets, formats and settings), mirror .claude/skills/formencoder-harness to .agents/skills and write + agents/manifest.json (what the app offers agents); --check exits 1 when anything drifted install [--dry-run] [claude|codex|cursor ...] set the clients up for this user account: the MCP server and the skill (all three by default) status which clients are on this computer and whether the skill is in step @@ -23,6 +23,9 @@ BACKEND = ROOT / "backend" SKILL = ROOT / ".claude" / "skills" / "formencoder-harness" MIRROR = ROOT / ".agents" / "skills" / "formencoder-harness" +SKILLS = ROOT / ".claude" / "skills" +MANIFEST = ROOT / "agents" / "manifest.json" +DOCK = {"present": True, "positions": ["left", "right", "bottom", "floating"], "tabs": ["terminal", "agents"]} 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." @@ -219,6 +222,30 @@ def generate() -> dict[str, str]: return {k: v.replace(" — ", " · ").replace("—", "·") for k, v in docs.items()} +def manifest_text(eng: Engine) -> str: + from app.agent.tools import NAMES, READ_ONLY, TOOLS, _command_tool + from app.services.formext_host import API + + listed = list(TOOLS) + gated = [t["name"] for t in TOOLS if t["name"] not in READ_ONLY] + seen = set(NAMES) + for r in eng.commands(): + name = r.get("mcpName") + if name and name not in seen: + seen.add(name) + listed.append(_command_tool(r)) + if not r.get("query"): + gated.append(name) + skills = [{"name": s.name, "sub_skills": sorted(p.parent.name for p in s.glob("sub-skills/*/SUB-SKILL.md"))} + for s in sorted(SKILLS.iterdir()) if (s / "SKILL.md").is_file()] + doc = {"format": "form-agent-manifest", "version": 1, "app": "formencoder", + "mcp": {"tools": [t["name"] for t in listed], + "read_only": [t["name"] for t in listed if t["annotations"].get("readOnlyHint")], + "approval_gated": gated, "transports": ["stdio", "http"]}, + "skills": skills, "dock": DOCK, "extensions": {"host_api": API}} + return json.dumps(doc, indent=2) + "\n" + + def _mcp_name(cid: str) -> str: return "".join("_" if ch == "." else ("_" + ch.lower() if ch.isupper() else ch) for ch in cid) @@ -273,6 +300,12 @@ def sync(check: bool) -> int: for p in problems: print(f"agents: surface: {p}") drift = ["the registry, the MCP tools and the command line disagree"] if problems else [] + wanted = manifest_text(Engine()) + if not MANIFEST.exists() or MANIFEST.read_text(encoding="utf-8") != wanted: + drift.append(str(MANIFEST.relative_to(ROOT))) + if not check: + MANIFEST.parent.mkdir(parents=True, exist_ok=True) + MANIFEST.write_text(wanted, encoding="utf-8") for name, text in generate().items(): ref = SKILL / "references" / name if not ref.exists() or ref.read_text(encoding="utf-8") != text: From 90c74e591ee217b5b7cdedc4de6f6d6b6e7ae3be Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 00:25:57 -0500 Subject: [PATCH 12/30] fix(agents): FORMENCODER_AGENTS can block outside agents but can no longer switch the question off The variable can still refuse outside agents (deny). It can no longer loosen: allow, like any value other than deny, now leaves the stored choice in charge, so the outside agent asks in the formencoder window. Before, allow skipped the question for every outside agent and ignored the stored Allow Always list, so whatever could set the engine's environment had the same reach as the person's Allow. The unattended route (FORMENCODER_AGENTS=allow) is gone: an outside agent with no window open is refused its changes and is told to open formencoder or start from the Terminal panel. The no-window message, the README line, the wiki Agents page, the harness skill (and its .agents mirror, written by agents sync) and the skillset verification note say so. The CI smoke step used allow for its encode; it now plays the window: it claims the window key, opens the live socket with a ticket, answers the consent message with Allow, and asserts the window was asked. test_allowed_policy_lets_a_changing_tool_through is replaced by cases that allow still asks and deny blocks even a stored allow, because it asserted the behaviour this removes. test_window_prefs.py used the variable to get agents past the gate; it now puts the sources on the session list. conftest set_policy lost its allowed mode. Ran: /mcp from source on a fresh data folder showed allow reaching the engine before and the window message after (deny and unset as expected, read-only tool unchanged); the CI sequence against an engine from source on a spare port got the consent message and a verified encode; the consent, window prefs, manifest, window key, seal and guard test files pass (5 of the new cases fail on the old code). The CI job itself and the packaged app were not run. --- .../session-and-connection/SUB-SKILL.md | 2 +- .../session-and-connection/SUB-SKILL.md | 2 +- .../sub-skills/verification/SUB-SKILL.md | 2 +- .docs/wiki/Agents.md | 2 +- .github/workflows/ci.yml | 37 ++++++++++++- README.md | 2 +- backend/HASHOUT_LOG.md | 11 ++++ backend/app/agent/consent.py | 4 +- backend/app/core/config.py | 3 +- backend/tests/conftest.py | 2 +- backend/tests/test_f2_consent.py | 55 +++++++++++++++++-- backend/tests/test_window_prefs.py | 7 ++- 12 files changed, 110 insertions(+), 19 deletions(-) diff --git a/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md index df3abe2..0e8d88d 100644 --- a/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -23,7 +23,7 @@ description: How an agent reaches formencoder. Use when the formencoder MCP serv - Reads (`status`, `probe`, `preview_frame`, `contact_sheet`, `verify`, `wait`, `log`, `formats`, `list_commands` and every query command) never ask. - The first change from an outside agent opens a dialog in the formencoder window: **Allow** (this session), **Allow Always** (remembered), **Don't Allow**. Tell the person a prompt is waiting in formencoder when you make the first change. -- `FORMENCODER_AGENTS` on the engine sets the policy: `ask` (default), `allow` (never ask) or `deny` (refuse outside agents; Terminal agents still work). +- `FORMENCODER_AGENTS=deny` on the engine refuses every outside agent (Terminal agents still work). Any other value, `allow` included, leaves the person's stored choice in charge: the engine asks, and only the person can answer in the window. - The Agents panel shows who is allowed and can forget them. ## FFmpeg diff --git a/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md index df3abe2..0e8d88d 100644 --- a/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -23,7 +23,7 @@ description: How an agent reaches formencoder. Use when the formencoder MCP serv - Reads (`status`, `probe`, `preview_frame`, `contact_sheet`, `verify`, `wait`, `log`, `formats`, `list_commands` and every query command) never ask. - The first change from an outside agent opens a dialog in the formencoder window: **Allow** (this session), **Allow Always** (remembered), **Don't Allow**. Tell the person a prompt is waiting in formencoder when you make the first change. -- `FORMENCODER_AGENTS` on the engine sets the policy: `ask` (default), `allow` (never ask) or `deny` (refuse outside agents; Terminal agents still work). +- `FORMENCODER_AGENTS=deny` on the engine refuses every outside agent (Terminal agents still work). Any other value, `allow` included, leaves the person's stored choice in charge: the engine asks, and only the person can answer in the window. - The Agents panel shows who is allowed and can forget them. ## FFmpeg diff --git a/.claude/skills/formencoder-skillset/sub-skills/verification/SUB-SKILL.md b/.claude/skills/formencoder-skillset/sub-skills/verification/SUB-SKILL.md index 658f5a5..a500486 100644 --- a/.claude/skills/formencoder-skillset/sub-skills/verification/SUB-SKILL.md +++ b/.claude/skills/formencoder-skillset/sub-skills/verification/SUB-SKILL.md @@ -33,7 +33,7 @@ A change to settings, formats, presets, effects or the pipeline is verified by e ## Agent paths -Replay tool sequences through `setup/mcp_stdio.py` against a running engine (`FORMENCODER_AGENTS=allow` for unattended runs, `ask` to test the consent dialog with a browser open). Save the images `preview_frame` and `contact_sheet` return and look at them. +Replay tool sequences through `setup/mcp_stdio.py` against a running engine (no variable skips the consent dialog: for an unattended run call read-only tools, or answer the dialog the way CI does, from a from-source run that claims the window key at `/api/window/key` and replies to the `consent` message on the `/api/live` socket; `FORMENCODER_AGENTS=deny` tests the refusal). Save the images `preview_frame` and `contact_sheet` return and look at them. ## Report diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index 01ccdec..dbf0c6b 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -8,7 +8,7 @@ formencoder's engine exposes every command to agents through MCP, the same comma - **From the repository**: `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` run `./formencoder mcp`, which starts the engine when it is not running. The first change asks once in the formencoder window: Allow, Allow Always or Don't Allow. - **From anywhere**: `./formencoder agents install` (or the Agents panel) adds the MCP server and the skill to your Claude Code, Codex and Cursor setup. -`FORMENCODER_AGENTS` sets the policy for outside agents: `ask` (default), `allow` or `deny`. +`FORMENCODER_AGENTS=deny` refuses every outside agent, whatever was allowed before; Terminal agents still work. Any other value, `allow` included, means the stored choice decides (ask by default). Only the person, in the formencoder window, can allow an outside agent, so an unattended outside agent with no window open is refused its changes; start it from the Terminal panel instead. ## The tools diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6e486ee..cf69551 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,7 +91,6 @@ jobs: run: ./formencoder agents sync --check - name: Boot the engine, encode over MCP and verify env: - FORMENCODER_AGENTS: allow FORMENCODER_FFMPEG_AUTO: '0' FORMENCODER_DATA_DIR: ${{ runner.temp }}/fedata run: | @@ -100,6 +99,39 @@ jobs: ffmpeg -loglevel error -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=3 -f lavfi -i sine=frequency=440:duration=3 -c:v mpeg4 -c:a aac -shortest "$clip" (cd backend && python -m uvicorn app.main:app --host 127.0.0.1 --port 8270 &) for i in $(seq 1 60); do curl -sf -H 'x-formencoder-local: 1' http://127.0.0.1:8270/api/health && break; sleep 1; done + python - <<'PY' & + import asyncio + import json + import urllib.request + + import websockets + + base = 'http://127.0.0.1:8270' + + + def post(path, headers=None): + req = urllib.request.Request(base + path, method='POST', data=b'', headers={'x-formencoder-local': '1', **(headers or {})}) + return json.load(urllib.request.urlopen(req)) + + + key = post('/api/window/key')['key'] + ticket = post('/api/window/ticket', {'x-formencoder-window-key': key})['ticket'] + + + async def main(): + async with websockets.connect('ws://127.0.0.1:8270/api/live?ticket=' + ticket) as ws: + async for text in ws: + m = json.loads(text) + if m.get('type') == 'hello': + open('window.ready', 'w').close() + if m.get('type') == 'consent': + await ws.send(json.dumps({'method': 'reply', 'params': {'requestId': m['requestId'], 'value': {'allow': True}}})) + open('window.asked', 'w').write(m['client']) + + + asyncio.run(main()) + PY + for i in $(seq 1 30); do [ -f window.ready ] && break; sleep 1; done printf '%s\n' \ '{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2025-06-18","clientInfo":{"name":"ci"},"capabilities":{}}}' \ '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' \ @@ -116,7 +148,8 @@ jobs: assert not enc.get('isError'), enc text = enc['content'][0]['text'] assert '"done"' in text and '"passed": true' in text, text[:2000] - print('mcp ok:', len(tools), 'tools, preview and a verified encode') + assert open('window.asked').read() == 'mcp:ci', 'the window was not asked' + print('mcp ok:', len(tools), 'tools, preview and a verified encode the window allowed') PY test: diff --git a/README.md b/README.md index 324a103..0fee060 100644 --- a/README.md +++ b/README.md @@ -145,7 +145,7 @@ cd formencoder `./formencoder desktop dev` opens the desktop window instead (run `./formencoder install-desktop` first). On Windows use `formencoder.bat install`, then `formencoder.bat`. -Ports: interface 5270, engine 8270 (`FORMENCODER_PORT`). `FORMENCODER_AGENTS=allow` skips the agent permission prompt. +Ports: interface 5270, engine 8270 (`FORMENCODER_PORT`). `FORMENCODER_AGENTS=deny` refuses every outside agent; no value of it skips the agent permission prompt, which only the person can answer in the formencoder window. > [!IMPORTANT] > **Status:** pre-release. AVC-Intra and vendor camera raw (R3D, ARRIRAW, X-OCN, Canon RAW, BRAW) are Partial, see [`docs/PARITY.md`](docs/PARITY.md). diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 466d16d..6388d79 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -252,3 +252,14 @@ Refers to `setup/agents.py` `manifest_text`, `sync`; `agents/manifest.json`; `ba - Checked by running, before the test: sync wrote 125 tools, 54 read-only (15 curated and 39 query commands), 71 approval-gated, 2 skills and 18 sub-skills; `scripts/manifest.py check agents/manifest.json --app formencoder` in formadaptor accepted it; `--check` exited 0; the engine from source on port 28900 answered `tools/list` with the same 125 names in the same order and the same read-only set. In a copy outside the tree, renaming one tool in the manifest and, separately, dropping `read=True` from `status` in the copy of `tools.py` each made `--check` exit 1 and name `agents/manifest.json`. `docs/PARITY.md` still said 21 curated and 123 tools; it now says 29 and 125 (the older HASHOUT entries keep the counts of their day). - Each `Engine()` in the sync creates a data folder under the system temp (existing behaviour of the script); the manifest adds one more per run. +## FORMENCODER_AGENTS can block outside agents but can no longer switch the question off (unreleased, after 0.8.4) + +Refers to `core/config.py` `agents_policy`; `agent/consent.py` `gate`; `.github/workflows/ci.yml`; `backend/tests/test_f2_consent.py`, `test_window_prefs.py`, `conftest.py` · kind: fix · logged: unreleased · 2026-11-19 + +- Why: the stored choice for outside agents (the sealed Allow Always list) can only be turned on by the person in the window, but the environment value `allow` made `gate` return before it looked at that list or asked anyone, so whatever started the engine could do what only the window may do. formvfx closed the same variable on its branch (commit a1cc9ea); this is the same rule. +- Now: `agents_policy()` returns `deny` only for the value `deny` (any case, spaces trimmed) and `ask` for everything else, `allow` and an empty or unknown value included. `gate` no longer has an allow branch. `deny` still refuses every outside agent before the stored list is read; read-only tools and the in-app token are unchanged; the no-window message no longer suggests the variable. `/api/system` `agentsPolicy` and `/api/agents/consent` `policy` can now only say `ask` or `deny`. +- The earlier entries here that describe `allow` as a policy (consent bullet near the top, the guard differences note, the sealed choices note and the window-only preferences check) describe the engine before this change. +- People who start the engine without a window (scripts, CI) can no longer skip the question. They call read-only tools, start the agent from the Terminal panel, or answer the question as a window does: from a source run, `POST /api/window/key`, `POST /api/window/ticket` with that key, open `/api/live?ticket=...` and reply `{method: reply, params: {requestId, value: {allow: true}}}` to the `consent` message. The CI smoke step does exactly this and also asserts that the window was asked. +- Tests: the old test that pinned `allow` letting a change through is replaced by cases that `allow` (and `ALLOW`, `1`, empty, unknown) still ask, `deny` in any spelling refuses even an agent on the stored list, `allow` neither overrides a window decline nor a stored allow, and the policy function says only `ask` or `deny`. The `allowed` fixture of `test_window_prefs.py` now puts the agent sources on the session list instead of using the variable; `set_policy` in `conftest.py` lost its `allowed` mode. +- Checked by running, before the test: engine from source on a fresh data folder, `/mcp` `tools/call` of `history {action: list}` as an outside agent: with `allow` it ran with no question, with the variable unset it was refused for no window; after the change `allow`, unset and `garbage` are refused for no window and `deny` is refused as turned off; `status` (read-only) ran in every case. The CI sequence ran against an engine from source on a spare port: the stand-in window got the `consent` message for `mcp:ci`, the encode finished verified. + diff --git a/backend/app/agent/consent.py b/backend/app/agent/consent.py index e89d973..ce36d25 100644 --- a/backend/app/agent/consent.py +++ b/backend/app/agent/consent.py @@ -100,7 +100,7 @@ async def gate(source: str, token: str | None, mutating: bool, detail: str = "") if inapp(token): return None policy = config.agents_policy() - if policy == "allow" or not mutating: + if not mutating: return None if policy == "deny": return "Outside agents are turned off (FORMENCODER_AGENTS=deny). Start the agent from formencoder's Terminal panel instead." @@ -111,7 +111,7 @@ async def gate(source: str, token: str | None, mutating: bool, detail: str = "") return "The person declined changes from this agent a moment ago. Ask them in chat before trying again." if not host.bus.windows(): return ("No formencoder window is open to ask the person for permission. Open formencoder (./formencoder boot, then http://localhost:5270, " - "or the desktop app) and allow this agent, start the agent from formencoder's Terminal panel, or set FORMENCODER_AGENTS=allow.") + "or the desktop app) and allow this agent, or start the agent from formencoder's Terminal panel.") reply = await host.bus.ask_window({"type": "consent", "client": source, "detail": detail}, timeout=180) if not reply: return "Nobody answered the permission request in the formencoder window. Ask the person to allow the agent there, then retry." diff --git a/backend/app/core/config.py b/backend/app/core/config.py index e55f04d..d8b248c 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -85,5 +85,4 @@ def cors_origins() -> list[str]: def agents_policy() -> str: - value = os.environ.get("FORMENCODER_AGENTS", "ask").strip().lower() - return value if value in ("ask", "allow", "deny") else "ask" + return "deny" if os.environ.get("FORMENCODER_AGENTS", "").strip().lower() == "deny" else "ask" diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 683e3c8..a36fc90 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -62,7 +62,7 @@ def consent_refusals(): def set_policy(mode): - os.environ["FORMENCODER_AGENTS"] = {"ask": "ask", "blocked": "deny", "allowed": "allow"}[mode] + os.environ["FORMENCODER_AGENTS"] = {"ask": "ask", "blocked": "deny"}[mode] def inapp_token(): diff --git a/backend/tests/test_f2_consent.py b/backend/tests/test_f2_consent.py index 62c21ba..4ed45c6 100644 --- a/backend/tests/test_f2_consent.py +++ b/backend/tests/test_f2_consent.py @@ -75,12 +75,57 @@ def test_blocked_policy_still_refuses_with_a_wrong_token(client): assert call(client, CHANGING_TOOL, {INAPP_HEADER: "wrong-token"})["result"].get("isError") -def test_allowed_policy_lets_a_changing_tool_through(client): - set_policy("allowed") +@pytest.mark.parametrize("value", ["allow", "ALLOW", " allow ", "1", "true", "yes", "", "ask", "nonsense"]) +def test_only_deny_changes_the_policy_and_everything_else_asks(client, monkeypatch, value): + monkeypatch.setenv("FORMENCODER_AGENTS", value) reply = call(client, CHANGING_TOOL) - assert not refused(reply, "no_window") - assert not refused(reply, "blocked") - assert not reply["result"].get("isError") + assert refused(reply, "no_window") + assert reply["result"].get("isError") + + +def test_unset_variable_asks(client, monkeypatch): + monkeypatch.delenv("FORMENCODER_AGENTS", raising=False) + assert refused(call(client, CHANGING_TOOL), "no_window") + + +@pytest.mark.parametrize("value", ["deny", "DENY", " deny "]) +def test_deny_in_any_spelling_blocks(client, monkeypatch, value): + monkeypatch.setenv("FORMENCODER_AGENTS", value) + assert refused(call(client, CHANGING_TOOL), "blocked") + + +def test_deny_blocks_an_agent_the_person_allowed_always(client, monkeypatch): + from app.agent import consent + + monkeypatch.setattr(consent, "_session", {"family-test-agent"}) + monkeypatch.setattr(consent, "_always", lambda: {"family-test-agent"}) + assert not call(client, CHANGING_TOOL)["result"].get("isError") + set_policy("blocked") + reply = call(client, CHANGING_TOOL) + assert refused(reply, "blocked") and reply["result"].get("isError") + + +def test_allow_value_does_not_override_the_stored_choice_or_the_window(client, monkeypatch): + monkeypatch.setenv("FORMENCODER_AGENTS", "allow") + asked = with_window(monkeypatch, {"allow": False}) + reply = call(client, CHANGING_TOOL) + assert len(asked) == 1 and "declined" in text_of(reply) + + +def test_allow_value_still_honours_a_stored_allow(client, monkeypatch): + from app.agent import consent + + monkeypatch.setenv("FORMENCODER_AGENTS", "allow") + monkeypatch.setattr(consent, "_always", lambda: {"family-test-agent"}) + assert not call(client, CHANGING_TOOL)["result"].get("isError") + + +def test_policy_function_reports_only_ask_or_deny(monkeypatch): + from app.core import config + + for value, expected in [("allow", "ask"), ("deny", "deny"), ("", "ask"), ("Deny", "deny"), ("x", "ask")]: + monkeypatch.setenv("FORMENCODER_AGENTS", value) + assert config.agents_policy() == expected def test_inapp_token_skips_the_ask(client): diff --git a/backend/tests/test_window_prefs.py b/backend/tests/test_window_prefs.py index 463fdd0..8b31a54 100644 --- a/backend/tests/test_window_prefs.py +++ b/backend/tests/test_window_prefs.py @@ -6,8 +6,11 @@ @pytest.fixture -def allowed(): - set_policy("allowed") +def allowed(monkeypatch): + from app.agent import consent + + set_policy("ask") + monkeypatch.setattr(consent, "_session", {"cli", "ui"}) yield set_policy("ask") From caff237e928dac468e876c5138606f96d4c08a1d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 00:26:13 -0500 Subject: [PATCH 13/30] docs(demos): the demo READMEs say sixteen themes The demos import the app's own THEMES, which lists sixteen profiles since AMOLED Black was added; the three READMEs still said fifteen. Counted in frontend/src/ui/themes.ts. Text only, nothing run. --- demo/README.md | 2 +- demos/broadcast/README.md | 2 +- demos/inspect/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/demo/README.md b/demo/README.md index 6494fb2..5f3bdb0 100644 --- a/demo/README.md +++ b/demo/README.md @@ -11,7 +11,7 @@ Everything it needs (scripts, styles, fonts, the icon) is inside this folder. No ## What it shows -The interface is the real one: the Studio Dark tokens, the fifteen theme profiles, the dock, the Queue, Preset Browser, Media Info, Encoding and Log panels, the inline icon set and the Export Settings idiom, all imported from `frontend/src/`. The engine behind it is a small TypeScript one written for the browser. +The interface is the real one: the Studio Dark tokens, the sixteen theme profiles, the dock, the Queue, Preset Browser, Media Info, Encoding and Log panels, the inline icon set and the Export Settings idiom, all imported from `frontend/src/`. The engine behind it is a small TypeScript one written for the browser. It opens on four real sources with ten outputs ready to run: three Pexels sea clips with different frame rates and sizes (1280x720 at 29.97 fps, 1280x720 at 25 fps, a vertical 404x720 at 59.94 fps) and a 21 s public-domain LibriVox reading. The outputs include WebM, a GIF of each clip, a still, and the reading normalised to -16 LUFS as Ogg Opus beside a broadcast WAV. The files are in `media/` as JavaScript data packs (a page opened from `file://` cannot fetch local files), loaded when the page starts into rows that are already in the Queue; authors, source pages and licences are in `CREDITS.md`. If a pack fails to load, the built-in generated sample takes its place. Drop your own video or audio file on the window, press the plus in the Queue, or use Open File; the film icon adds the generated sample. diff --git a/demos/broadcast/README.md b/demos/broadcast/README.md index bdaf2e1..9bb4694 100644 --- a/demos/broadcast/README.md +++ b/demos/broadcast/README.md @@ -11,7 +11,7 @@ Everything it needs (script, styles, fonts, icon, the programme) is inside this ## What it shows -The interface is the real one: the Studio Dark tokens, the fifteen theme profiles, the dock and its panels, the inline icons and the Export Settings idiom, all imported from `frontend/src/`. It opens on a 17.4 s programme (aerial waves over a public-domain LibriVox reading, with six caption cues) already measured: the picture carries a timecode, the name and a "FOR REVIEW ONLY" text burned in live, with the captions on top. Sources, authors and licences are in `CREDITS.md`. +The interface is the real one: the Studio Dark tokens, the sixteen theme profiles, the dock and its panels, the inline icons and the Export Settings idiom, all imported from `frontend/src/`. It opens on a 17.4 s programme (aerial waves over a public-domain LibriVox reading, with six caption cues) already measured: the picture carries a timecode, the name and a "FOR REVIEW ONLY" text burned in live, with the captions on top. Sources, authors and licences are in `CREDITS.md`. - **Delivery Profiles.** Broadcast (H.264 EBU R128, H.264 ATSC A/85, broadcast WAV, an XDCAM MXF master marked as desktop only), streaming, social and audio profiles. A profile sets the loudness standard, caption mode, overlays and the output preset together. - **Loudness.** ITU-R BS.1770-4 integrated loudness, loudness range, true peak and the short-term graph for the source and for the delivery, with the target and tolerance band; a matrix of the programme against EBU R128, ATSC A/85, OP-59, ARIB TR-B32, streaming (-14 LUFS) and podcast (-16 LUFS) with the gain each needs; Normalise (linear gain, with a look-ahead limiter when asked). diff --git a/demos/inspect/README.md b/demos/inspect/README.md index 92e2732..7daa8fe 100644 --- a/demos/inspect/README.md +++ b/demos/inspect/README.md @@ -11,7 +11,7 @@ Everything it needs is inside this folder (about 24 MB, mostly the footage). Not ## What it shows -The interface is the real one: Studio Dark tokens, the fifteen themes, the dock, the Media Browser card, Media Info rows and the Outputs list, imported from `frontend/src/`. It opens on a small hike shoot: three Pexels clips of different shapes (1280x720 at 29.97 fps, 1280x640 at 23.976 fps, a vertical 404x720 at 60 fps), a numbered JPEG sequence of clouds at 24 fps, and the outputs made from the first clip: a high and a low bitrate encode, a 960x540 proxy and an animated GIF. A and B are set to the stream clip and its low bitrate encode in Compare view. Sources, authors and licences are in `CREDITS.md`. +The interface is the real one: Studio Dark tokens, the sixteen themes, the dock, the Media Browser card, Media Info rows and the Outputs list, imported from `frontend/src/`. It opens on a small hike shoot: three Pexels clips of different shapes (1280x720 at 29.97 fps, 1280x640 at 23.976 fps, a vertical 404x720 at 60 fps), a numbered JPEG sequence of clouds at 24 fps, and the outputs made from the first clip: a high and a low bitrate encode, a 960x540 proxy and an animated GIF. A and B are set to the stream clip and its low bitrate encode in Compare view. Sources, authors and licences are in `CREDITS.md`. - **Media Browser.** The shoot as cards with thumbnails, frame counts and frame rates; Show in A or B, Create Proxy, Contact Sheet from the context menu. - **Viewer.** Slots A and B take any source or output; A, B and Compare views; frame-accurate stepping with the arrow keys, Home and End, drop-frame timecode at 29.97 and 59.94 fps, frame numbers, In and Out marks, Fit and 1:1 with a synchronised pan, Save Frame (A, B or A and B side by side) and Contact Sheet. From 506af7bfa3db315b41a0ab95356d364f105c3dbf Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 00:26:24 -0500 Subject: [PATCH 14/30] docs: formcompiler is under nodemode-dev Three documents (Releasing wiki page, BRANCHING.md, the desktop-and-release sub-skill) named nodemode-ai/formcompiler; the organisation is nodemode-dev, as README.md already says. The CHANGELOG line that records an old release is left as written. Text only; agents sync --check is in step. --- .../sub-skills/desktop-and-release/SUB-SKILL.md | 2 +- .docs/BRANCHING.md | 2 +- .docs/wiki/Releasing.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.claude/skills/formencoder-skillset/sub-skills/desktop-and-release/SUB-SKILL.md b/.claude/skills/formencoder-skillset/sub-skills/desktop-and-release/SUB-SKILL.md index c3cbc9e..b0ad759 100644 --- a/.claude/skills/formencoder-skillset/sub-skills/desktop-and-release/SUB-SKILL.md +++ b/.claude/skills/formencoder-skillset/sub-skills/desktop-and-release/SUB-SKILL.md @@ -23,7 +23,7 @@ description: Building and releasing formencoder as a desktop app. Use for the Ta | Windows | `x86_64-pc-windows-msvc` | `.msi`, NSIS `.exe` | | Linux | `x86_64-unknown-linux-gnu` | `.deb`, `.rpm`, `.AppImage` | -formcompiler (`nodemode-ai/formcompiler`) builds all four when a `compile_vX.Y.Z` branch is pushed here, and the repo's own `ci.yml` builds the interface, checks the engine on each host, runs the text lint and `agents sync --check`. +formcompiler (`nodemode-dev/formcompiler`) builds all four when a `compile_vX.Y.Z` branch is pushed here, and the repo's own `ci.yml` builds the interface, checks the engine on each host, runs the text lint and `agents sync --check`. ## Releasing diff --git a/.docs/BRANCHING.md b/.docs/BRANCHING.md index ae1f0b8..a14d120 100644 --- a/.docs/BRANCHING.md +++ b/.docs/BRANCHING.md @@ -6,5 +6,5 @@ - **Versions** are `v*.*.*` with dots, everywhere: `frontend/package.json` and its lockfile, `frontend/src/version.ts`, `backend/app/__init__.py`, `native/Cargo.toml` (the workspace version), the seven fencoder entries in `native/Cargo.lock`, `native/fencoder-py/pyproject.toml`, `src-tauri/Cargo.toml`, its `Cargo.lock`, `src-tauri/tauri.conf.json`, the version line in `README.md` and the deliverable zip names. Bump all of them in one commit, the last of a series. - **Engine commands.** A change to the engine's commands, formats, presets or MCP tools is followed in the same commit by `./formencoder agents sync`, so the harness references follow the engine. - **FFmpeg.** The pinned build is changed only by replacing `src-tauri/binaries/ffmpeg-licence.json` with a new record from the formai-binaries release (`nodemode-dev/formai-binaries`; builds made before the rename use the older name, formcut-binaries, which keeps working), together with its `LGPL-2.1.txt` and `THIRD-PARTY-NOTICES.txt`, in one commit. Never point the fetch or the bundle at a build that is not recorded there. The fetch and `setup/bundle_ffmpeg.py` try formai-binaries first and formcut-binaries second, and install only files that match the record; `FORMENCODER_FFMPEG_RELEASE` (a release folder URL such as `https://example.org/ffmpeg-7.1.5-2`) replaces both as the only address, with the same check. -- **Releases.** formencoder builds nothing in this repository. After the version bump lands on main, push a branch `compile_vX.Y.Z` cut from that commit. CI runs on it, and formcompiler (`nodemode-ai/formcompiler`) picks it up on its next 8-hourly watch run, or at once when its watch is run by hand. It builds macOS (Apple silicon and Intel), Linux and Windows bundles with the pinned FFmpeg and opens a draft release `formencoder-vX.Y.Z` on formcompiler's release page, which carries the FFmpeg source. Review the draft, then publish it there. Compile branches are kept as the record of what was built. +- **Releases.** formencoder builds nothing in this repository. After the version bump lands on main, push a branch `compile_vX.Y.Z` cut from that commit. CI runs on it, and formcompiler (`nodemode-dev/formcompiler`) picks it up on its next 8-hourly watch run, or at once when its watch is run by hand. It builds macOS (Apple silicon and Intel), Linux and Windows bundles with the pinned FFmpeg and opens a draft release `formencoder-vX.Y.Z` on formcompiler's release page, which carries the FFmpeg source. Review the draft, then publish it there. Compile branches are kept as the record of what was built. - **Wiki.** Edit pages in `.docs/wiki/`, never in the GitHub wiki interface. `.github/workflows/wiki.yml` publishes the folder when it changes on main. The wiki needs one page created by hand once before the first publish. diff --git a/.docs/wiki/Releasing.md b/.docs/wiki/Releasing.md index 4b3f0c9..22fa1b6 100644 --- a/.docs/wiki/Releasing.md +++ b/.docs/wiki/Releasing.md @@ -3,6 +3,6 @@ 1. Land the work on main with CI green (interface build, the engine on macOS, Windows and Linux, the engine selfcheck, an MCP preview and a verified encode, skill references in step, text lint, shell syntax, `cargo check` of the desktop shell). 2. Bump the version in every site in one commit (see `.docs/BRANCHING.md`). 3. Push a branch named `compile_vX.Y.Z` from that commit, for example `git push origin HEAD:compile_v0.2.8`. CI runs on it. The name must match the version in `src-tauri/tauri.conf.json`, or formcompiler refuses it and says why. -4. formcompiler (`nodemode-ai/formcompiler`) finds the branch on its next watch run (every 8 hours), or at once when its watch is run by hand. Once CI has passed on that commit, it builds macOS arm64 and x64, Linux x64 and Windows x64 bundles with the pinned FFmpeg, attaches the FFmpeg source tarball and its notices, and opens a draft release `formencoder-vX.Y.Z` on its release page. +4. formcompiler (`nodemode-dev/formcompiler`) finds the branch on its next watch run (every 8 hours), or at once when its watch is run by hand. Once CI has passed on that commit, it builds macOS arm64 and x64, Linux x64 and Windows x64 bundles with the pinned FFmpeg, attaches the FFmpeg source tarball and its notices, and opens a draft release `formencoder-vX.Y.Z` on its release page. 5. Signing: the Apple Developer ID, Windows code signing and Tauri updater key secrets are set in formcompiler's repository, never in this one. Updater signatures also publish `latest.json` in the `formencoder-updates` feed. Set `plugins.updater.pubkey` in `src-tauri/tauri.conf.json` to the matching public key to turn update checks on. 6. Check the draft release's assets on formcompiler's release page, then publish it there. Compile branches are kept as the record of what was built. From 3eba6694a90088d2ef7c467e41d0ca79c8b12e92 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 00:26:32 -0500 Subject: [PATCH 15/30] docs(wiki): the Parity links point to docs/PARITY.md The wiki has no Parity page; the row by row grading is docs/PARITY.md in the repository. Home and the sidebar linked to a page that does not exist; they now link to the file. Text only. --- .docs/wiki/Home.md | 2 +- .docs/wiki/_Sidebar.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index 91ea6a6..453a96e 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -13,4 +13,4 @@ Every action in formencoder is a command with an id, so people and agents use th - [Architecture](Architecture) · the Rust encoding engine, the engine service, the interface - [Desktop](Desktop) · the Tauri app, the frozen engine, the bundled FFmpeg - [Releasing](Releasing) · versions, tags, CI -- [Parity](Parity) · formencoder against Media Encoder, row by row +- [Parity](https://github.com/nodemode-dev/formencoder/blob/main/docs/PARITY.md) · formencoder against Media Encoder, row by row diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md index 0003f20..031a68a 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -7,4 +7,4 @@ - [Architecture](Architecture) - [Desktop](Desktop) - [Releasing](Releasing) -- [Parity](Parity) +- [Parity](https://github.com/nodemode-dev/formencoder/blob/main/docs/PARITY.md) From 9fc0cb6adbd79f6496eea1d0c281c2559ceda158 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 02:05:20 -0500 Subject: [PATCH 16/30] feat(agents): the permission question can be answered once, says what it asks, and is withdrawn when it ends Engine side of the shared dock's contract, added beside what the present window reads. The consent event keeps client, detail and requestId and gains id, agent, what, answers (deny, once, session, always), alwaysScope (agent), expiresIn and expiresAt. The answer {allow: true, remember: "once"} (or {allow: true, once: true}) runs this one call and stores nothing, so the next call asks again; the other answers mean what they meant. When a question ends every window gets {type: "withdrawn", requestId, id, of, reason} with reason answered, expired or cancelled. FORMENCODER_AGENTS=deny now refuses changes from every agent, the ones started in the Terminal panel included; reads still work. That is the family rule for Blocked, and the only change the present window can show. The skill, the wiki page and the README line that said terminal agents keep working say what now happens; the .agents copy of the skill was regenerated by ./formencoder agents sync. test_inapp_token_skips_a_blocked_policy pinned the old rule and is replaced by a test of the new one. Verified by running before the tests: engine from source on 34201, two stand-in windows and an outside agent on /mcp. New fields seen in both windows; deny refused; once in both shapes ran and the next call asked; session and always as before; with the limit shortened to 4 s both windows got withdrawn expired and a late answer stored nothing; under deny an outside agent, an agent tab's token and the panel shell's token were refused for changes and allowed to read. agents sync --check in step. --- .../session-and-connection/SUB-SKILL.md | 4 +-- .../session-and-connection/SUB-SKILL.md | 4 +-- .docs/wiki/Agents.md | 2 +- README.md | 2 +- backend/HASHOUT_LOG.md | 14 ++++++++ backend/app/agent/consent.py | 32 +++++++++++++------ backend/app/engine/bus.py | 10 ++++-- backend/app/routers/mcp.py | 3 +- backend/app/routers/rpc.py | 2 +- backend/tests/test_f2_consent.py | 26 +++++++++++++-- 10 files changed, 78 insertions(+), 21 deletions(-) diff --git a/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md index 0e8d88d..c6de4d0 100644 --- a/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -23,7 +23,7 @@ description: How an agent reaches formencoder. Use when the formencoder MCP serv - Reads (`status`, `probe`, `preview_frame`, `contact_sheet`, `verify`, `wait`, `log`, `formats`, `list_commands` and every query command) never ask. - The first change from an outside agent opens a dialog in the formencoder window: **Allow** (this session), **Allow Always** (remembered), **Don't Allow**. Tell the person a prompt is waiting in formencoder when you make the first change. -- `FORMENCODER_AGENTS=deny` on the engine refuses every outside agent (Terminal agents still work). Any other value, `allow` included, leaves the person's stored choice in charge: the engine asks, and only the person can answer in the window. +- `FORMENCODER_AGENTS=deny` on the engine refuses every change from every agent, Terminal agents included (reads still work). Any other value, `allow` included, leaves the person's stored choice in charge: the engine asks, and only the person can answer in the window. - The Agents panel shows who is allowed and can forget them. ## FFmpeg @@ -42,7 +42,7 @@ formencoder encodes with an LGPL FFmpeg build it pins (the same builds formcut s | `The formencoder engine is not running and could not be started` | Ask the person to run `./formencoder boot` in the formencoder folder or open the desktop app, then retry. | | `No formencoder window is open to ask the person for permission` | The policy is `ask` and no window is open. Ask the person to open formencoder (or start the agent from its Terminal panel), then retry. | | `Nobody answered the permission request` | The dialog timed out. Ask the person to answer it in the formencoder window. | -| `Outside agents are turned off (FORMENCODER_AGENTS=deny)` | Only Terminal agents may change the queue. Suggest starting the agent from the Terminal panel. | +| `Outside agents are turned off (FORMENCODER_AGENTS=deny)` | No agent may change the queue, Terminal agents included; reads still work. Only the person can change this, by starting formencoder without that setting. | | `The formencoder engine stopped answering` | The engine exited or is busy past the timeout. `status` again; if it fails, ask the person to restart formencoder. | ## Several windows diff --git a/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md index 0e8d88d..c6de4d0 100644 --- a/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -23,7 +23,7 @@ description: How an agent reaches formencoder. Use when the formencoder MCP serv - Reads (`status`, `probe`, `preview_frame`, `contact_sheet`, `verify`, `wait`, `log`, `formats`, `list_commands` and every query command) never ask. - The first change from an outside agent opens a dialog in the formencoder window: **Allow** (this session), **Allow Always** (remembered), **Don't Allow**. Tell the person a prompt is waiting in formencoder when you make the first change. -- `FORMENCODER_AGENTS=deny` on the engine refuses every outside agent (Terminal agents still work). Any other value, `allow` included, leaves the person's stored choice in charge: the engine asks, and only the person can answer in the window. +- `FORMENCODER_AGENTS=deny` on the engine refuses every change from every agent, Terminal agents included (reads still work). Any other value, `allow` included, leaves the person's stored choice in charge: the engine asks, and only the person can answer in the window. - The Agents panel shows who is allowed and can forget them. ## FFmpeg @@ -42,7 +42,7 @@ formencoder encodes with an LGPL FFmpeg build it pins (the same builds formcut s | `The formencoder engine is not running and could not be started` | Ask the person to run `./formencoder boot` in the formencoder folder or open the desktop app, then retry. | | `No formencoder window is open to ask the person for permission` | The policy is `ask` and no window is open. Ask the person to open formencoder (or start the agent from its Terminal panel), then retry. | | `Nobody answered the permission request` | The dialog timed out. Ask the person to answer it in the formencoder window. | -| `Outside agents are turned off (FORMENCODER_AGENTS=deny)` | Only Terminal agents may change the queue. Suggest starting the agent from the Terminal panel. | +| `Outside agents are turned off (FORMENCODER_AGENTS=deny)` | No agent may change the queue, Terminal agents included; reads still work. Only the person can change this, by starting formencoder without that setting. | | `The formencoder engine stopped answering` | The engine exited or is busy past the timeout. `status` again; if it fails, ask the person to restart formencoder. | ## Several windows diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index dbf0c6b..dd11f03 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -8,7 +8,7 @@ formencoder's engine exposes every command to agents through MCP, the same comma - **From the repository**: `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` run `./formencoder mcp`, which starts the engine when it is not running. The first change asks once in the formencoder window: Allow, Allow Always or Don't Allow. - **From anywhere**: `./formencoder agents install` (or the Agents panel) adds the MCP server and the skill to your Claude Code, Codex and Cursor setup. -`FORMENCODER_AGENTS=deny` refuses every outside agent, whatever was allowed before; Terminal agents still work. Any other value, `allow` included, means the stored choice decides (ask by default). Only the person, in the formencoder window, can allow an outside agent, so an unattended outside agent with no window open is refused its changes; start it from the Terminal panel instead. +`FORMENCODER_AGENTS=deny` refuses every change from every agent, whatever was allowed before, Terminal agents included; reads still work. Any other value, `allow` included, means the stored choice decides (ask by default). Only the person, in the formencoder window, can allow an outside agent, so an unattended outside agent with no window open is refused its changes; start it from the Terminal panel instead. ## The tools diff --git a/README.md b/README.md index 0fee060..c984beb 100644 --- a/README.md +++ b/README.md @@ -145,7 +145,7 @@ cd formencoder `./formencoder desktop dev` opens the desktop window instead (run `./formencoder install-desktop` first). On Windows use `formencoder.bat install`, then `formencoder.bat`. -Ports: interface 5270, engine 8270 (`FORMENCODER_PORT`). `FORMENCODER_AGENTS=deny` refuses every outside agent; no value of it skips the agent permission prompt, which only the person can answer in the formencoder window. +Ports: interface 5270, engine 8270 (`FORMENCODER_PORT`). `FORMENCODER_AGENTS=deny` refuses every change from every agent, the Terminal panel's included; no value of it skips the agent permission prompt, which only the person can answer in the formencoder window. > [!IMPORTANT] > **Status:** pre-release. AVC-Intra and vendor camera raw (R3D, ARRIRAW, X-OCN, Canon RAW, BRAW) are Partial, see [`docs/PARITY.md`](docs/PARITY.md). diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 6388d79..f29001a 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -263,3 +263,17 @@ Refers to `core/config.py` `agents_policy`; `agent/consent.py` `gate`; `.github/ - Tests: the old test that pinned `allow` letting a change through is replaced by cases that `allow` (and `ALLOW`, `1`, empty, unknown) still ask, `deny` in any spelling refuses even an agent on the stored list, `allow` neither overrides a window decline nor a stored allow, and the policy function says only `ask` or `deny`. The `allowed` fixture of `test_window_prefs.py` now puts the agent sources on the session list instead of using the variable; `set_policy` in `conftest.py` lost its `allowed` mode. - Checked by running, before the test: engine from source on a fresh data folder, `/mcp` `tools/call` of `history {action: list}` as an outside agent: with `allow` it ran with no question, with the variable unset it was refused for no window; after the change `allow`, unset and `garbage` are refused for no window and `deny` is refused as turned off; `status` (read-only) ran in every case. The CI sequence ran against an engine from source on a spare port: the stand-in window got the `consent` message for `mcp:ci`, the encode finished verified. +## The permission question carries what a shared dialog needs, can be answered once, and is withdrawn when it ends (unreleased, after 0.8.4) + +Refers to `agent/consent.py` `gate`, `agent_name`, `state`, `ANSWERS`, `ALWAYS_SCOPE`, `ASK_SECONDS`, `BLOCKED`; `engine/bus.py` `ask_window`; `routers/mcp.py`, `routers/rpc.py` (the `what` argument); `backend/tests/test_f2_consent.py` · kind: feat · logged: unreleased · 2026-11-19 + +- Why: the family is moving to one dock module with one dialog for outside agents, and it talks to each engine through a contract (a request id, who asks, what for, which answers exist, what Always covers, when the request ends, and a signal when it is gone). This engine's question had the client, the tool name and a request number only. Everything here is added beside what the present window reads, so that window behaves as before. +- The `consent` event keeps `client`, `detail` and `requestId` and gains: `id` (the request number as text), `agent` (the announced name without its `mcp:` prefix, or `agent`), `what` (plain words: `use the history tool`, `run the command queue.clear`, `run queue.clear` for the command line, `make changes` when nothing is known), `answers` (`deny`, `once`, `session`, `always`: all four this engine honours), `alwaysScope` (`agent`: Allow Always stores that one client name, as before), `expiresIn` (seconds) and `expiresAt` (epoch seconds). `id`, `expiresIn` and `expiresAt` are put on by `ask_window`, so the extension questions carry the two times as well; a question that already has an `id` of its own (the extension run) keeps it. +- Allow once: the answer `{allow: true, remember: "once"}` (or FormVis's shape `{allow: true, once: true}`) lets this one call run and stores nothing, so the next call asks again. `none` and a missing `allow` still decline for ten minutes, `session` and `always` mean what they meant; an allow with any other `remember` is still a session allow, which is what the present window's Allow button sends. +- Withdrawal: when a question ends, every window gets `{type: "withdrawn", requestId, id, of, reason}` with `of` the question's type (`consent`, `extensions`) and `reason` `answered`, `expired` or `cancelled`. The present page ignores event types it does not know (`engine/client.ts` `KNOWN`), checked in the source. +- `ASK_SECONDS` (180) is the time limit as a module value so a run can shorten it; `/api/agents/consent` and the `consent` block of `/api/agents/status` also report `answers`, `alwaysScope`, `askSeconds` and `blockedStopsTabs`. +- Blocked now stops every agent. `FORMENCODER_AGENTS=deny` used to refuse outside agents and let a call with a terminal's token through; the family rule (DOCK_SPEC_2, A3) is that Blocked stops the app's own agent tabs too, so `gate` checks the policy before the token. Reads are never refused, for a token as for anyone. The refusal sentence no longer advises the Terminal panel. This is the one change the present window can show, and only when the engine was started with `deny`. The older entries here that say terminal agents keep working under `deny` describe the engine before this. +- `detail` is left exactly as it was (the tool name from `/mcp`, empty from `/api/rpc`) because the present dialog prints it. +- Checked by running, before the tests: engine from source on 34201 with a fresh data folder and a stand-in keyring, two stand-in windows on `/api/live`, an outside agent on `/mcp`. Both windows got the same question with the new fields; Don't Allow refused and both windows got `withdrawn` `answered`; `once` in both shapes ran the call and the next call asked again; `session` and `always` did not ask again and `always` was written sealed; with the limit shortened to 4 s the agent was refused after 4.0 s, both windows got `withdrawn` `expired` and a late Allow Always stored nothing. With `deny`: an outside agent, a call with an agent tab's token, one with the panel shell's token and the command line with a token were all refused for changes and allowed to read, and no window was asked. +- Tests: `test_f2_consent.py` gained the once cases and the question's fields; `test_inapp_token_skips_a_blocked_policy` pinned the old rule and is replaced by `test_blocked_policy_stops_an_inapp_token_too_and_still_lets_it_read`. The bus cases are in `test_dock_engine.py` with the next entry. + diff --git a/backend/app/agent/consent.py b/backend/app/agent/consent.py index ce36d25..e8f556d 100644 --- a/backend/app/agent/consent.py +++ b/backend/app/agent/consent.py @@ -10,6 +10,11 @@ TOKENS: set[str] = set() _session: set[str] = set() _declined: dict[str, float] = {} +ANSWERS = ("deny", "once", "session", "always") +ALWAYS_SCOPE = "agent" +ASK_SECONDS = 180.0 +BLOCKED = ("Outside agents are turned off (FORMENCODER_AGENTS=deny), and so are agents started inside formencoder. " + "Only the person can change this, by starting formencoder without that setting.") _READ_RPC = {"command.list", "command.describe", "ui.state", "menu.bar", "frame.png", "encode.wait", "engine.info", "activity.list", "family.discover", "family.sources", "publish.destinations", "agents.approvals", "extensions.list"} @@ -89,21 +94,26 @@ def client_key(source: str) -> str: return source.split(":", 1)[-1].strip().lower() or "agent" +def agent_name(source: str) -> str: + return source.split(":", 1)[-1].strip()[:60] or "agent" + + def state() -> dict: from . import approvals seals = seal.summary([seal_state(), approvals.seal_state()]) - return {"policy": config.agents_policy(), "session": sorted(_session), "always": sorted(_always()), "seal": seals, "sealBroken": seals == "broken"} + return {"policy": config.agents_policy(), "session": sorted(_session), "always": sorted(_always()), "seal": seals, "sealBroken": seals == "broken", + "answers": list(ANSWERS), "alwaysScope": ALWAYS_SCOPE, "askSeconds": ASK_SECONDS, "blockedStopsTabs": True} -async def gate(source: str, token: str | None, mutating: bool, detail: str = "") -> str | None: - if inapp(token): - return None - policy = config.agents_policy() +async def gate(source: str, token: str | None, mutating: bool, detail: str = "", what: str = "") -> str | None: if not mutating: return None + policy = config.agents_policy() if policy == "deny": - return "Outside agents are turned off (FORMENCODER_AGENTS=deny). Start the agent from formencoder's Terminal panel instead." + return BLOCKED + if inapp(token): + return None key = client_key(source) if key in _session or key in _always(): return None @@ -112,13 +122,17 @@ async def gate(source: str, token: str | None, mutating: bool, detail: str = "") if not host.bus.windows(): return ("No formencoder window is open to ask the person for permission. Open formencoder (./formencoder boot, then http://localhost:5270, " "or the desktop app) and allow this agent, or start the agent from formencoder's Terminal panel.") - reply = await host.bus.ask_window({"type": "consent", "client": source, "detail": detail}, timeout=180) + asked = what or (f"use the {detail} tool" if detail else "make changes") + question = {"type": "consent", "client": source, "detail": detail, "agent": agent_name(source), "what": asked, "answers": list(ANSWERS), "alwaysScope": ALWAYS_SCOPE} + reply = await host.bus.ask_window(question, timeout=ASK_SECONDS) if not reply: return "Nobody answered the permission request in the formencoder window. Ask the person to allow the agent there, then retry." if reply.get("allow"): - if reply.get("remember") == "always": + remember = "once" if reply.get("once") else reply.get("remember") + if remember == "always": _remember(key) - _session.add(key) + if remember != "once": + _session.add(key) return None _declined[key] = time.monotonic() + 600 return "The person declined changes from this agent. Ask them in chat what they want instead." diff --git a/backend/app/engine/bus.py b/backend/app/engine/bus.py index 58a587e..07d3c62 100644 --- a/backend/app/engine/bus.py +++ b/backend/app/engine/bus.py @@ -2,6 +2,7 @@ import asyncio import itertools +import time from dataclasses import dataclass, field @@ -65,18 +66,23 @@ async def ask_window(self, message: dict, timeout: float, first: bool = False) - rid = next(self._ids) fut: asyncio.Future = asyncio.get_running_loop().create_future() self._replies[rid] = fut - payload = {**message, "requestId": rid} + payload = {"id": str(rid), **message, "requestId": rid, "expiresIn": timeout, "expiresAt": time.time() + timeout} for w in windows: try: w.queue.put_nowait(payload) except asyncio.QueueFull: pass + reason = "cancelled" try: - return await asyncio.wait_for(fut, timeout) + reply = await asyncio.wait_for(fut, timeout) + reason = "answered" + return reply except asyncio.TimeoutError: + reason = "expired" return None finally: self._replies.pop(rid, None) + self._deliver({"type": "withdrawn", "requestId": rid, "id": str(rid), "of": message.get("type"), "reason": reason}, ("ui",)) def answer(self, rid: int, value: dict) -> bool: fut = self._replies.get(rid) diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index 020e961..a88443d 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -80,7 +80,8 @@ async def mcp(request: Request) -> Response: out = _err(rid, -32602, f"No tool named {name}") else: mutating = not tools.read_only(name) and not (name == "execute" and consent.query_command(args.get("command"))) - denied = await consent.gate(client, token, mutating, detail=name) + what = f"run the command {args.get('command')}"[:120] if name == "execute" and isinstance(args.get("command"), str) else "" + denied = await consent.gate(client, token, mutating, detail=name, what=what) out = _ok(rid, tools.fail(denied) if denied else await tools.call(name, args, client), modern) else: out = _err(rid, -32601, f"Method not found: {method}") diff --git a/backend/app/routers/rpc.py b/backend/app/routers/rpc.py index 5c777da..fe05aa1 100644 --- a/backend/app/routers/rpc.py +++ b/backend/app/routers/rpc.py @@ -48,7 +48,7 @@ async def call(request: Request) -> Response: if source.strip().lower() == "ui": source = "cli" rid = message.get("id") if isinstance(message, dict) else None - denied = await consent.gate(source, request.headers.get("x-formencoder-agent-token"), mutating=consent.mutating_rpc(message)) + denied = await consent.gate(source, request.headers.get("x-formencoder-agent-token"), mutating=consent.mutating_rpc(message), what=f"run {_label(message)}"[:120]) if denied: return Response(json.dumps({"jsonrpc": "2.0", "id": rid, "error": {"code": -32003, "message": denied}}), media_type="application/json") why = await _reasons(message) diff --git a/backend/tests/test_f2_consent.py b/backend/tests/test_f2_consent.py index 4ed45c6..bdeac87 100644 --- a/backend/tests/test_f2_consent.py +++ b/backend/tests/test_f2_consent.py @@ -134,9 +134,11 @@ def test_inapp_token_skips_the_ask(client): assert not reply["result"].get("isError") -def test_inapp_token_skips_a_blocked_policy(client): +def test_blocked_policy_stops_an_inapp_token_too_and_still_lets_it_read(client): set_policy("blocked") - assert not refused(call(client, CHANGING_TOOL, {INAPP_HEADER: inapp_token()}), "blocked") + token = inapp_token() + assert refused(call(client, CHANGING_TOOL, {INAPP_HEADER: token}), "blocked") + assert not call(client, READ_TOOL, {INAPP_HEADER: token})["result"].get("isError") @pytest.mark.parametrize("token", ["", "wrong-token", "x" * 64]) @@ -167,3 +169,23 @@ def test_decline_of_one_agent_does_not_block_another(client, monkeypatch): assert call(client, CHANGING_TOOL, agent="agent-one")["result"].get("isError") with_window(monkeypatch, {"allow": True}) assert not call(client, CHANGING_TOOL, agent="agent-two")["result"].get("isError") + + +@pytest.mark.parametrize("answer", [{"allow": True, "remember": "once"}, {"allow": True, "once": True}]) +def test_allow_once_runs_this_call_and_the_next_one_asks_again(client, monkeypatch, answer): + from app.agent import consent + + asked = with_window(monkeypatch, answer) + first = call(client, CHANGING_TOOL) + second = call(client, CHANGING_TOOL) + assert not first["result"].get("isError") and not second["result"].get("isError") + assert len(asked) == 2 + assert consent.state()["session"] == [] and consent.state()["always"] == [] + + +def test_the_question_says_who_asks_for_what_and_which_answers_there_are(client, monkeypatch): + asked = with_window(monkeypatch, {"allow": False}) + call(client, CHANGING_TOOL, agent="Some-Agent") + name, _ = CHANGING_TOOL + assert asked[0] == asked[0] | {"type": "consent", "client": "mcp:Some-Agent", "detail": name, "agent": "Some-Agent", "what": f"use the {name} tool", + "answers": ["deny", "once", "session", "always"], "alwaysScope": "agent"} From 61398c43823c3b209c2677a6d173cec399d0ce9a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 02:07:17 -0500 Subject: [PATCH 17/30] feat(terminal): Claude Code, Codex and Cursor as engine-started tabs with their own tokens, and one agent status call Engine side of the shared dock's contract; the present Terminal panel's socket, launch buttons, /status and /sessions are as they were. GET /api/terminal/agents (window key) says for claude, codex and cursor: installed, path, version (the program's own --version line, kept 60 s), signedIn (null: the engine cannot tell), the install line, title and program name. The engine never calls it itself. POST /api/terminal/tabs {kind, cols, rows, cwd, title, prompt, resume} opens a window tab: shell, claude, codex or cursor. An agent kind runs the program as the tab's own process with a token of its own in the child's environment, never on the command line; the token ends when the program exits, on restart and on close. A shell tab opened this way has no token. GET /api/terminal/tabs lists them; they are closed, restarted and attached through the existing /sessions/{id} routes and /ws. Window tabs are kept out of /sessions, the terminals event and the terminal_* tools. Rows gained kind and alive; windows also get terminalTabs. The socket's typed=1 mode sends control as JSON in binary frames (hello, exit, restart, closed, gone) and takes input and resize as JSON text, so an exit cannot be mistaken for output. Without typed nothing changes. A program that cannot be started now ends its forked child with status 127. Verified by running before the tests: engine from source on 34201 with stand-in claude, codex and cursor-agent scripts on its PATH and without them; token in /proc//environ and absent from ps -eo args, refused after exit, restart and close; the present page's terminal, status and consent calls replayed unchanged. Write routes without the key: 13 of 13 refused before, 14 of 14 after. Not verified: the real Codex and Cursor programs (neither is on this machine), so whether they hand the token to the MCP bridge they start is unknown. Whole suite: 245 passed, 4 failed, the same 4 in test_functions.py as before this work (231 passed, 4 failed). --- backend/HASHOUT_LOG.md | 15 +++ backend/app/agent/tools.py | 2 +- backend/app/routers/terminal.py | 160 +++++++++++++++++++++++--- backend/tests/test_dock_engine.py | 184 ++++++++++++++++++++++++++++++ 4 files changed, 347 insertions(+), 14 deletions(-) create mode 100644 backend/tests/test_dock_engine.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index f29001a..b00b3f0 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -277,3 +277,18 @@ Refers to `agent/consent.py` `gate`, `agent_name`, `state`, `ANSWERS`, `ALWAYS_S - Checked by running, before the tests: engine from source on 34201 with a fresh data folder and a stand-in keyring, two stand-in windows on `/api/live`, an outside agent on `/mcp`. Both windows got the same question with the new fields; Don't Allow refused and both windows got `withdrawn` `answered`; `once` in both shapes ran the call and the next call asked again; `session` and `always` did not ask again and `always` was written sealed; with the limit shortened to 4 s the agent was refused after 4.0 s, both windows got `withdrawn` `expired` and a late Allow Always stored nothing. With `deny`: an outside agent, a call with an agent tab's token, one with the panel shell's token and the command line with a token were all refused for changes and allowed to read, and no window was asked. - Tests: `test_f2_consent.py` gained the once cases and the question's fields; `test_inapp_token_skips_a_blocked_policy` pinned the old rule and is replaced by `test_blocked_policy_stops_an_inapp_token_too_and_still_lets_it_read`. The bus cases are in `test_dock_engine.py` with the next entry. +## Agent programs as tabs of their own, one status call, and a socket mode that keeps control apart from output (unreleased, after 0.8.4) + +Refers to `routers/terminal.py` `PROGRAMS`, `_version`, `_program`, `agent_programs`, `Session.__init__`, `Term` (`kind`, `window`, `argv`, `_ended`, `restart`, `close`, `row`), `Hub.tabs`, `Hub.listed`, `Hub.changed`, `tabs`, `open_tab`, `terminal` (the `typed` mode); `agent/tools.py` `_terminal`; `backend/tests/test_dock_engine.py` · kind: feat · logged: unreleased · 2026-11-19 + +- Why: the shared dock opens Claude Code, Codex and Cursor as tabs the engine starts, each with a token of its own, asks one call for what is installed, and needs to tell an exit from output. Today the panel has one private shell and types a program's name into it. Nothing the present panel uses is changed: the socket without `typed`, `launch`, `/status`, `/sessions` and the token in the panel shell are as they were. +- `GET /api/terminal/agents` (window key): `{agents: {claude, codex, cursor}}`, each `{installed, path, version, signedIn, install, title, program}`. Found with `shutil.which` on the engine's PATH, as `/status` does. `version` is the first line ` --version` prints (5 s limit, kept 60 s per path, run without the engine's `FORMENCODER_*` variables); `signedIn` is always `null`, because nothing here can tell without running the program in a way that could reach a model; `install` is a command line. The engine never calls this itself. +- `POST /api/terminal/tabs {kind, cols, rows, cwd, title, prompt, resume}` opens a window tab. `kind` is `shell` (default), `claude`, `codex` or `cursor`. An agent kind runs the found program as the tab's own process (not typed into a shell) in the agent workspace, with a token of its own in the child's environment as `FORMENCODER_AGENT_TOKEN`; the command line holds the program's path, `--resume ` (claude only) and the prompt as one argument (after `--` when it starts with a dash), never the token. The token dies when the program exits, when the tab is restarted (the new process gets a new one) and when the tab is closed. A `shell` tab opened here carries no token, which is the family rule; the present panel's own shell keeps its token (left for the port, see the report). Refusals carry a code in `detail`: 404 `not_installed` (with `install`), 422 `unknown_kind`, `bad_prompt`, `bad_resume`, 500 `failed`. +- `GET /api/terminal/tabs` (window key) lists window tabs oldest first. A window tab is closed, restarted, renamed and typed into through the existing `/sessions/{id}` routes and attached with `/ws?session=`. Restart runs the agent again. +- Window tabs are the window's: they are not in `/sessions`, not in the `terminals` event and not reachable by the `terminal_*` tools (`Hub.listed` answers as for an id that does not exist). Every row gained `kind` (`shell`, `claude`, `codex`, `cursor`, or `agent` for a terminal an outside agent opened) and `alive`. A second event, `terminalTabs {tabs}`, goes to windows beside `terminals`. +- The socket's `typed=1` mode: output stays text frames; control is JSON in binary frames, `hello {id, kind, alive}` first on every attach, then the replay, then `exit`, `restart`, `closed` (the engine then closes the socket) and `gone {id}` with close code 4404 for a tab that does not exist (without `typed` such an attach still opens a private shell, as before). The window sends `{type: input, data}` and `{type: resize, cols, rows}` as JSON text; anything else is ignored. Without `typed` every frame is what it was, the `{"exit": true}` text included. +- `Session` leaves the forked child with status 127 when the program cannot be started, instead of letting it run on as a copy of the engine. +- Codex and Cursor reach this engine's MCP server through the workspace's `.codex/config.toml` and `.cursor/mcp.json`, which run `formencoder mcp` (the stdio bridge), and the bridge reads the token from its environment. Whether Codex and Cursor pass `FORMENCODER_AGENT_TOKEN` on to an MCP server they start could not be checked here (neither program is on this machine); if one does not, its bridge has no token and the person is asked, which is the safe side. The config entry that names the variable for the client to forward is left for the port, to be tried with the real programs. +- Checked by running, before the tests: engine from source on 34201 with stand-in `claude`, `codex` and `cursor-agent` scripts first on its PATH. Status gave the three with their version lines; each kind opened a tab whose process had the token in `/proc//environ` while `ps -eo args` did not show it; the three tokens differed; each let a change through with no window open and was refused after exit, after restart (old one) and after close; the prompt and resume id arrived as arguments; an outside agent's `terminal_list` and `terminal_read` did not see the tabs; the typed socket gave `hello`, text, `exit`, `restart` on the same stream, `closed`, and `gone`. With PATH `/usr/bin:/bin`: all three not installed with install lines, opening each 404 `not_installed`. The present page's calls replayed: the panel socket (raw text in, text out, NUL resize, `launch`, `{"exit": true}`), `/status`, `/sessions`, the old `POST /sessions` with `launch`, restart on an attached old stream, `/api/agents/status`, `/api/agents/forget`, and the three consent answers the page sends. Write routes without the key: 17 operations, 4 open by name, 13 refused before; 18, 4 and 14 after, none answered. +- Tests: `backend/tests/test_dock_engine.py`, written after the runs above. + diff --git a/backend/app/agent/tools.py b/backend/app/agent/tools.py index 1d8ffc1..bbc3939 100644 --- a/backend/app/agent/tools.py +++ b/backend/app/agent/tools.py @@ -483,7 +483,7 @@ async def _terminal(name: str, args: dict, source: str) -> dict: term = hub.open(args.get("title"), args.get("cwd"), 120, 32, f"http://127.0.0.1:{config.PORT}", run=args.get("command") or None) term.opener = source return text({**term.row(), "next": "terminal_send {session, text} to type, terminal_read {session} to read"}) - term = hub.get(str(args["session"])) + term = hub.listed(str(args["session"])) if name == "terminal_send": before = term.offset term.write(str(args["text"]) + ("\r" if args.get("enter", True) else "")) diff --git a/backend/app/routers/terminal.py b/backend/app/routers/terminal.py index 3ce5c59..eec3274 100644 --- a/backend/app/routers/terminal.py +++ b/backend/app/routers/terminal.py @@ -3,9 +3,11 @@ import contextlib import json import os +import re import shutil import signal import struct +import subprocess import threading import time @@ -17,6 +19,37 @@ router = APIRouter(prefix="/api/terminal", tags=["terminal"]) POSIX = os.name == "posix" AGENTS = {"claude": "claude", "codex": "codex", "cursor": "cursor-agent"} +PROGRAMS = { + "claude": {"title": "Claude Code", "install": "irm https://claude.ai/install.ps1 | iex" if os.name == "nt" else "curl -fsSL https://claude.ai/install.sh | bash"}, + "codex": {"title": "Codex", "install": "npm install -g @openai/codex"}, + "cursor": {"title": "Cursor", "install": "curl https://cursor.com/install -fsS | bash"}, +} +RESUME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{7,79}") +PROMPT_MAX = 20000 +VERSION_KEEP = 60.0 +_VERSIONS: dict[str, tuple[float, str | None]] = {} + + +def _version(path: str) -> str | None: + now = time.monotonic() + kept = _VERSIONS.get(path) + if kept and now - kept[0] < VERSION_KEEP: + return kept[1] + env = {k: v for k, v in os.environ.items() if not k.startswith("FORMENCODER_")} + try: + out = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=5, stdin=subprocess.DEVNULL, env=env) + lines = out.stdout.strip().splitlines() if out.returncode == 0 else [] + except (OSError, subprocess.SubprocessError): + lines = [] + found = lines[0].strip()[:80] if lines else None + _VERSIONS[path] = (now, found) + return found + + +def _program(kind: str) -> dict: + path = shutil.which(AGENTS[kind]) + return {"installed": path is not None, "path": path, "version": _version(path) if path else None, "signedIn": None, + "install": PROGRAMS[kind]["install"], "title": PROGRAMS[kind]["title"], "program": AGENTS[kind]} def _environment(base_url: str, token: str | None) -> dict: @@ -49,13 +82,14 @@ def _shell() -> list[str]: class Session: - def __init__(self, cols: int, rows: int, env: dict, cwd: str): + def __init__(self, cols: int, rows: int, env: dict, cwd: str, argv: list[str] | None = None): self.cols, self.rows = max(20, min(500, cols)), max(5, min(300, rows)) self.pid = None self.fd = None self.process = None self.winpty = None self.decoder = codecs.getincrementaldecoder("utf-8")(errors="replace") + command = argv or _shell() if POSIX: import pty @@ -65,18 +99,19 @@ def __init__(self, cols: int, rows: int, env: dict, cwd: str): os.chdir(cwd) except OSError: os.chdir(os.path.expanduser("~")) - os.execvpe(_shell()[0], _shell(), env) + try: + os.execvpe(command[0], command, env) + except OSError: + os._exit(127) self.pid, self.fd = pid, fd self.resize(self.cols, self.rows) return try: from winpty import PtyProcess - self.winpty = PtyProcess.spawn(_shell(), cwd=cwd, env=env, dimensions=(self.rows, self.cols)) + self.winpty = PtyProcess.spawn(command, cwd=cwd, env=env, dimensions=(self.rows, self.cols)) except Exception: - import subprocess - - self.process = subprocess.Popen(_shell(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, cwd=cwd) + self.process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, cwd=cwd) def resize(self, cols: int, rows: int) -> None: self.cols, self.rows = max(20, min(500, cols)), max(5, min(300, rows)) @@ -151,13 +186,21 @@ def status() -> dict: } +@router.get("/agents") +def agent_programs(request: Request) -> dict: + window_key.require(request) + return {"agents": {kind: _program(kind) for kind in PROGRAMS}} + + KEEP = 256_000 class Term: - def __init__(self, tid: str, title: str, cwd: str, cols: int, rows: int, base: str, owned: bool, trusted: bool = False) -> None: + def __init__(self, tid: str, title: str, cwd: str, cols: int, rows: int, base: str, owned: bool, trusted: bool = False, + kind: str = "shell", window: bool = False, argv: list[str] | None = None) -> None: self.id, self.title, self.cwd, self.base, self.owned = tid, title, cwd, base, owned self.trusted = trusted + self.kind, self.window, self.argv = kind, window, argv self.token: str | None = None self.opener = "ui" self.created = time.time() @@ -173,7 +216,7 @@ def _start(self, cols: int, rows: int) -> None: self.exited = False consent.revoke(self.token) self.token = consent.issue() if self.trusted else None - self.session = Session(cols, rows, _environment(self.base, self.token), self.cwd) + self.session = Session(cols, rows, _environment(self.base, self.token), self.cwd, self.argv) session = self.session def pump() -> None: @@ -203,6 +246,9 @@ def _ended(self, session: "Session") -> None: if session is not self.session: return self.exited = True + if self.window: + consent.revoke(self.token) + self.token = None for q in list(self.listeners): with contextlib.suppress(asyncio.QueueFull): q.put_nowait(None) @@ -222,6 +268,9 @@ def restart(self) -> None: old, self.session = self.session, None if old: old.close() + for q in list(self.listeners): + with contextlib.suppress(asyncio.QueueFull): + q.put_nowait({"type": "restart"}) self._feed("\r\n[formencoder] terminal restarted\r\n") self._start(cols, rows) @@ -231,9 +280,13 @@ def close(self) -> None: self.exited = True consent.revoke(self.token) self.token = None + for q in list(self.listeners): + with contextlib.suppress(asyncio.QueueFull): + q.put_nowait({"type": "closed"}) def row(self) -> dict: - return {"id": self.id, "title": self.title, "cwd": self.cwd, "created": self.created, "exited": self.exited, "owned": self.owned, "offset": self.offset, "opener": self.opener} + return {"id": self.id, "title": self.title, "cwd": self.cwd, "created": self.created, "exited": self.exited, "owned": self.owned, "offset": self.offset, "opener": self.opener, + "kind": self.kind if self.opener == "ui" else "agent", "alive": not self.exited} class Hub: @@ -245,15 +298,26 @@ def changed(self) -> None: from ..engine.host import host as engine_host engine_host.bus.publish({"type": "terminals", "sessions": self.listing()}, ("ui",)) + engine_host.bus.publish({"type": "terminalTabs", "tabs": self.tabs()}, ("ui",)) def listing(self) -> list[dict]: - return [t.row() for t in self.terms.values() if not t.owned] + return [t.row() for t in self.terms.values() if not t.owned and not t.window] + + def tabs(self) -> list[dict]: + return [t.row() for t in self.terms.values() if t.window] + + def listed(self, tid: str) -> Term: + term = self.get(tid) + if term.window: + raise KeyError(f"no terminal {tid!r}; open terminals: {', '.join(t['id'] for t in self.listing()) or 'none'}") + return term - def open(self, title: str | None, cwd: str | None, cols: int, rows: int, base: str, owned: bool = False, run: str | None = None, trusted: bool = False) -> Term: + def open(self, title: str | None, cwd: str | None, cols: int, rows: int, base: str, owned: bool = False, run: str | None = None, trusted: bool = False, + kind: str = "shell", window: bool = False, argv: list[str] | None = None) -> Term: self._n += 1 tid = f"t{self._n}" place = cwd or str(workspace.ensure()) - term = Term(tid, title or f"Terminal {self._n}", place, cols, rows, base, owned, trusted) + term = Term(tid, title or f"Terminal {self._n}", place, cols, rows, base, owned, trusted, kind, window, argv) self.terms[tid] = term if run: term.write(run + "\r") @@ -290,6 +354,44 @@ def sessions() -> dict: return {"sessions": hub.listing()} +@router.get("/tabs") +def tabs(request: Request) -> dict: + window_key.require(request) + return {"tabs": hub.tabs()} + + +@router.post("/tabs") +async def open_tab(request: Request) -> dict: + body = await request.json() if (await request.body()) else {} + if not isinstance(body, dict): + body = {} + kind = body.get("kind") or "shell" + prompt, resume = body.get("prompt") or None, body.get("resume") or None + if kind != "shell" and kind not in PROGRAMS: + raise HTTPException(422, {"code": "unknown_kind", "message": f"No tab kind called {kind}. Kinds: shell, {', '.join(PROGRAMS)}."}) + if prompt is not None and (kind == "shell" or not isinstance(prompt, str) or len(prompt) > PROMPT_MAX): + raise HTTPException(422, {"code": "bad_prompt", "message": f"A prompt is text of at most {PROMPT_MAX} characters for an agent tab."}) + if resume is not None and (kind != "claude" or not isinstance(resume, str) or not RESUME.fullmatch(resume)): + raise HTTPException(422, {"code": "bad_resume", "message": "resume is a Claude Code session id, for a claude tab only."}) + try: + cols, rows = int(body.get("cols") or 100), int(body.get("rows") or 30) + except (TypeError, ValueError): + cols, rows = 100, 30 + argv = None + if kind in PROGRAMS: + path = shutil.which(AGENTS[kind]) + if path is None: + raise HTTPException(404, {"code": "not_installed", "message": f"{PROGRAMS[kind]['title']} is not installed on this computer.", "install": PROGRAMS[kind]["install"]}) + argv = [path, *(["--resume", resume] if resume else []), *((["--", prompt] if prompt.startswith("-") else [prompt]) if prompt else [])] + title = body.get("title") if isinstance(body.get("title"), str) else None + cwd = body.get("cwd") if isinstance(body.get("cwd"), str) else None + try: + term = hub.open(title or (PROGRAMS[kind]["title"] if argv else None), cwd, cols, rows, _base(request.headers.get("host")), trusted=argv is not None, kind=kind, window=True, argv=argv) + except OSError as exc: + raise HTTPException(500, {"code": "failed", "message": f"The program could not start: {exc}"}) from None + return term.row() + + @router.post("/sessions") async def open_session(request: Request) -> dict: body = await request.json() if (await request.body()) else {} @@ -361,25 +463,44 @@ async def terminal(socket: WebSocket) -> None: except ValueError: cols, rows = 100, 30 attach = socket.query_params.get("session") + typed = socket.query_params.get("typed") == "1" if attach and attach in hub.terms: term = hub.terms[attach] if term.session: term.session.resize(cols, rows) + elif attach and typed: + await socket.send_bytes(json.dumps({"type": "gone", "id": attach}).encode("utf-8")) + await socket.close(code=4404) + return else: base = _base(socket.headers.get("host"), socket.query_params.get("engine")) term = hub.open(None, socket.query_params.get("cwd"), cols, rows, base, owned=True, trusted=True) queue: asyncio.Queue = asyncio.Queue(maxsize=4000) replay, _ = term.read(None) + if typed: + await socket.send_bytes(json.dumps({"type": "hello", "id": term.id, "kind": term.kind, "alive": not term.exited}).encode("utf-8")) if replay and attach: await socket.send_text(replay) + if typed and term.exited: + await socket.send_bytes(json.dumps({"type": "exit"}).encode("utf-8")) term.listeners.add(queue) async def send() -> None: while True: data = await queue.get() + if isinstance(data, dict): + if typed: + await socket.send_bytes(json.dumps(data).encode("utf-8")) + if data.get("type") == "closed": + await socket.close() + break + continue if data is None: with contextlib.suppress(Exception): - await socket.send_text(json.dumps({"exit": True})) + if typed: + await socket.send_bytes(json.dumps({"type": "exit"}).encode("utf-8")) + else: + await socket.send_text(json.dumps({"exit": True})) if term.owned: break continue @@ -392,6 +513,19 @@ async def send() -> None: try: while True: message = await socket.receive_text() + if typed: + try: + control = json.loads(message) + except ValueError: + control = None + if not isinstance(control, dict): + continue + if control.get("type") == "input" and isinstance(control.get("data"), str): + term.write(control["data"]) + elif control.get("type") == "resize" and term.session: + with contextlib.suppress(TypeError, ValueError): + term.session.resize(int(control.get("cols")), int(control.get("rows"))) + continue if message.startswith("\x00{"): try: control = json.loads(message[1:]) diff --git a/backend/tests/test_dock_engine.py b/backend/tests/test_dock_engine.py new file mode 100644 index 0000000..0520675 --- /dev/null +++ b/backend/tests/test_dock_engine.py @@ -0,0 +1,184 @@ +import asyncio +import json +import os +import time + +import pytest + +from conftest import CHANGING_TOOL, INAPP_HEADER, LOCAL_HEADER, MCP_PATH, window_ticket + +LOCAL = {LOCAL_HEADER: "1"} +POSIX_ONLY = pytest.mark.skipif(os.name == "nt", reason="the stand-ins are shell scripts") +REFUSED = {"detail": "Only the formencoder window can do this"} + + +@pytest.fixture +def stand_ins(tmp_path, monkeypatch): + folder = tmp_path / "bin" + folder.mkdir() + for name in ("claude", "codex", "cursor-agent"): + script = folder / name + script.write_text(f'#!/bin/sh\nif [ "$1" = "--version" ]; then echo "{name} 9.9.9"; exit 0; fi\n' + 'echo "stand-in args=$*"\necho "token-present=${FORMENCODER_AGENT_TOKEN:+yes}"\nread line\n') + script.chmod(0o755) + monkeypatch.setenv("PATH", f"{folder}{os.pathsep}{os.environ.get('PATH', '')}") + return folder + + +@pytest.fixture +def no_programs(tmp_path, monkeypatch): + monkeypatch.setenv("PATH", str(tmp_path)) + + +def changing_call(client, token): + name, args = CHANGING_TOOL + r = client.post(MCP_PATH, json={"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": name, "arguments": args, "clientInfo": {"name": "tab-test"}}}, headers={INAPP_HEADER: token}) + return r.json()["result"] + + +def printed(client, tid, needle, seconds=5.0): + end = time.monotonic() + seconds + text = "" + while time.monotonic() < end and needle not in text: + text = client.get(f"/api/terminal/sessions/{tid}/output").json()["text"] + time.sleep(0.05) + return text + + +def test_a_question_says_when_it_expires_and_every_window_hears_when_it_ends(): + from app.engine.bus import Bus + + async def run(): + bus = Bus() + one, two = bus.join("ui"), bus.join("ui") + before = time.time() + expired = await bus.ask_window({"type": "consent", "client": "mcp:x"}, timeout=0.05) + asked, same = one.queue.get_nowait(), two.queue.get_nowait() + ended = [one.queue.get_nowait(), two.queue.get_nowait()] + task = asyncio.create_task(bus.ask_window({"type": "consent", "client": "mcp:x"}, timeout=5)) + await asyncio.sleep(0.01) + again = one.queue.get_nowait() + two.queue.get_nowait() + assert bus.answer(again["requestId"], {"allow": True}) + reply = await task + return expired, asked, same, before, ended, again, reply, one.queue.get_nowait(), two.queue.get_nowait() + + expired, asked, same, before, ended, again, reply, told_one, told_two = asyncio.run(run()) + assert expired is None and same == asked + assert asked["id"] == str(asked["requestId"]) and asked["expiresIn"] == 0.05 and before <= asked["expiresAt"] <= time.time() + 0.05 + gone = {"type": "withdrawn", "requestId": asked["requestId"], "id": asked["id"], "of": "consent", "reason": "expired"} + assert ended == [gone, gone] + assert reply == {"allow": True} + answered = {"type": "withdrawn", "requestId": again["requestId"], "id": again["id"], "of": "consent", "reason": "answered"} + assert told_one == answered and told_two == answered + + +def test_a_question_that_has_its_own_id_keeps_it(): + from app.engine.bus import Bus + + async def run(): + bus = Bus() + window = bus.join("ui") + await bus.ask_window({"type": "extensions", "id": "some.extension"}, timeout=0.01) + return window.queue.get_nowait() + + assert asyncio.run(run())["id"] == "some.extension" + + +def test_the_agent_status_names_each_program_its_version_and_its_install_line(client, bare, stand_ins): + assert bare.get("/api/terminal/agents").status_code == 403 + agents = client.get("/api/terminal/agents").json()["agents"] + assert list(agents) == ["claude", "codex", "cursor"] + assert agents["codex"] == agents["codex"] | {"installed": True, "path": str(stand_ins / "codex"), "version": "codex 9.9.9", "signedIn": None, "title": "Codex", "program": "codex"} + assert agents["cursor"]["version"] == "cursor-agent 9.9.9" and agents["claude"]["version"] == "claude 9.9.9" + assert all(a["install"] for a in agents.values()) + + +def test_the_agent_status_says_what_is_missing(client, no_programs): + agents = client.get("/api/terminal/agents").json()["agents"] + for kind in ("claude", "codex", "cursor"): + assert agents[kind]["installed"] is False and agents[kind]["path"] is None and agents[kind]["version"] is None and agents[kind]["install"] + assert client.get("/api/terminal/status").json()["agents"] == {"claude": False, "codex": False, "cursor": False} + + +@POSIX_ONLY +@pytest.mark.parametrize("kind,title", [("claude", "Claude Code"), ("codex", "Codex"), ("cursor", "Cursor")]) +def test_an_agent_tab_runs_the_program_with_its_own_token_which_dies_with_the_tab(client, stand_ins, kind, title): + from app.agent import consent + from app.routers.terminal import hub + + row = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": kind, "cols": 80, "rows": 24}).json() + assert row == row | {"kind": kind, "title": title, "alive": True, "owned": False} + term = hub.terms[row["id"]] + token = term.token + assert consent.inapp(token) and all(token not in part for part in term.argv) + assert "token-present=yes" in printed(client, row["id"], "token-present") + assert not changing_call(client, token).get("isError") + assert [t["id"] for t in client.get("/api/terminal/tabs").json()["tabs"]] == [row["id"]] + assert row["id"] not in [t["id"] for t in hub.listing()] + with pytest.raises(KeyError): + hub.listed(row["id"]) + assert client.delete(f"/api/terminal/sessions/{row['id']}", headers=LOCAL).json() == {"closed": row["id"]} + assert not consent.inapp(token) + assert client.get("/api/terminal/tabs").json()["tabs"] == [] + + +@POSIX_ONLY +def test_a_prompt_and_a_resume_id_reach_the_program_as_arguments(client, stand_ins): + from app.routers.terminal import hub + + row = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "claude", "prompt": "make a small file", "resume": "0123abcd-4567"}).json() + assert hub.terms[row["id"]].argv == [str(stand_ins / "claude"), "--resume", "0123abcd-4567", "make a small file"] + assert "args=--resume 0123abcd-4567 make a small file" in printed(client, row["id"], "args=") + dashed = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "codex", "prompt": "-v"}).json() + assert hub.terms[dashed["id"]].argv == [str(stand_ins / "codex"), "--", "-v"] + for tid in (row["id"], dashed["id"]): + client.delete(f"/api/terminal/sessions/{tid}", headers=LOCAL) + + +@POSIX_ONLY +def test_a_plain_shell_tab_carries_no_token_and_stays_out_of_the_agent_list(client): + from app.routers.terminal import hub + + row = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "shell"}).json() + term = hub.terms[row["id"]] + assert row["kind"] == "shell" and term.token is None and term.window + assert row["id"] not in [t["id"] for t in client.get("/api/terminal/sessions").json()["sessions"]] + client.delete(f"/api/terminal/sessions/{row['id']}", headers=LOCAL) + + +def test_opening_a_tab_refuses_what_it_cannot_start(client, bare, no_programs): + assert bare.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "codex"}).json() == REFUSED + missing = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "codex"}) + assert missing.status_code == 404 and missing.json()["detail"] == missing.json()["detail"] | {"code": "not_installed", "install": "npm install -g @openai/codex"} + assert client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "vim"}).json()["detail"]["code"] == "unknown_kind" + assert client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "shell", "prompt": "x"}).status_code == 422 + assert client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "codex", "resume": "0123abcd-4567"}).status_code == 422 + + +@POSIX_ONLY +def test_the_typed_socket_keeps_control_apart_from_output(client, stand_ins): + from app.agent import consent + from app.routers.terminal import hub + + row = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "codex"}).json() + token = hub.terms[row["id"]].token + with client.websocket_connect(f"/api/terminal/ws?session={row['id']}&typed=1&cols=80&rows=24&ticket={window_ticket()}") as ws: + assert json.loads(ws.receive_bytes()) == {"type": "hello", "id": row["id"], "kind": "codex", "alive": True} + ws.send_text("not json") + ws.send_text(json.dumps({"type": "resize", "cols": 90, "rows": 30})) + ws.send_text(json.dumps({"type": "input", "data": "done\r"})) + text, control = "", None + while control is None: + frame = ws.receive() + if frame.get("bytes") is not None: + control = json.loads(frame["bytes"]) + else: + text += frame.get("text") or "" + assert control == {"type": "exit"} and '{"exit": true}' not in text + assert not consent.inapp(token) + assert client.get("/api/terminal/tabs").json()["tabs"][0]["alive"] is False + client.delete(f"/api/terminal/sessions/{row['id']}", headers=LOCAL) + assert json.loads(ws.receive_bytes()) == {"type": "closed"} + with client.websocket_connect(f"/api/terminal/ws?session=t0&typed=1&ticket={window_ticket()}") as ws: + assert json.loads(ws.receive_bytes()) == {"type": "gone", "id": "t0"} From ad13e477bf0f6e2bc950ad892e161d4059251853 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 15:38:32 -0500 Subject: [PATCH 18/30] chore(release): 0.9.0 Sets 0.9.0 at the version sites of the 0.8.4 release (README, backend, frontend package and lock, version.ts, the native and desktop Cargo files and their lock entries, pyproject, tauri.conf.json, the three demo bundles), adds the CHANGELOG entry, and lets the function manifest's own generator rewrite form-functions.json. Run: backend suite 246 passed, 3 failed (three cases of one test that fail the same way on main at 0.8.4 and are not touched here); the function manifest check and agents sync --check are in step. --- CHANGELOG.md | 21 +++++++++++++++++++++ README.md | 4 ++-- backend/app/__init__.py | 2 +- demo/assets/demo.js | 2 +- demos/broadcast/assets/broadcast.js | 2 +- demos/inspect/assets/inspect.js | 2 +- form-functions.json | 2 +- frontend/package-lock.json | 4 ++-- frontend/package.json | 2 +- frontend/src/version.ts | 2 +- native/Cargo.lock | 14 +++++++------- native/Cargo.toml | 2 +- native/fencoder-py/pyproject.toml | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 16 files changed, 44 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2fb953..f5079ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## v0.9.0 · 2026-11-19 + +The family update. Only the FormEncoder window can change things or answer for the person, an agent's permission is asked for in clearer words, encodes write to local files only, and there is a true-black theme. FormEncoder keeps its own Terminal panel in this release. + +- Only the FormEncoder window can change things through the engine, answer a permission or approval question, or drive its terminal. Changes from outside the app's window are refused. Outside agents still come in through MCP or the command line and are asked about in the window, as before. +- The permission question names the agent and says what it asked to do, lists the answers on offer and says when it expires. It can be answered "once", for that call only. Every open window is told when a question has ended, whether it was answered, ran out of time or was withdrawn. +- Allow Always and Full faith are protected. A change made to the saved agent permission outside the app is ignored, the permission goes back to Ask, and the Agents panel says so. After updating, an agent that was allowed before is asked once more. The protection keeps its secret in the system keychain (new dependency: keyring, MIT); on a computer without a keychain the saved choices stand as before. +- `FORMENCODER_AGENTS` can no longer switch the agent question off. `deny` still refuses every change from every agent, now including agents started in the Terminal panel, and reading still works. Any other value, `allow` included, leaves the person's own choice in charge, so an outside agent is asked about in the window. If a script of yours sets `FORMENCODER_AGENTS=allow`, remove it: it no longer does anything. An unattended run can still call the read-only tools. +- Agents can no longer change the FFmpeg folder, the camera raw decoders or the media cache folder, or turn off the numbering of output names. Those stay in Preferences in the window. +- The agent token a Terminal panel shell carries is now its own: it is replaced when the shell restarts and dropped when it closes. Terminals that agents open do not get one. +- The engine can start Claude Code, Codex and Cursor as tabs of their own, each with its own access that ends with the tab, and one call reports which of the three are installed, their versions and how to install a missing one. The Terminal panel itself looks and works as it did. +- Encode outputs are local files only. An output path or folder that is a network address or a stream (`tcp:`, `udp:`, `http:`, `rtmp:`, `ftp:`, `pipe:`, `file:` and the like) is refused when it is set and again when the job starts. Every other output path is made absolute before FFmpeg is called, so the queue shows the full path of an output that was given as a relative one. Inputs that are addresses are refused as well: FormEncoder reads local files. +- FFmpeg is downloaded from the formai-binaries release, with the earlier formcut-binaries address as the fallback, and every file is still checked against the record. When both fail, the error names both addresses. `FORMENCODER_FFMPEG_RELEASE` (a release folder URL) is documented and, when set, is the only address asked. +- New theme, AMOLED Black: a true-black window for OLED screens, with panes told apart by thin outlines. That makes sixteen themes. +- At start the desktop app waits at most 10 seconds, once the engine has given its address, for the engine to recognise the window as the app's own. If that does not happen, the app shows "The formencoder engine failed to start" and opens no window. How long the engine may take to start is unchanged. +- Running from source, reloading the page no longer makes the engine report a second window that never opened. +- `agents/manifest.json` lists what FormEncoder offers agents: 125 MCP tools (54 of them read-only, 71 that ask the person first) and 2 skills with 18 sub-skills. `./formencoder agents sync` writes it and `--check` fails when it is out of date. +- Encode as a Form function, merged after 0.8.4: `form-functions.json` lets a graph in NodeMode's hub run a FormEncoder preset on one file with no window open, and fail when the result does not verify. Its settings accept only listed values and bounded numbers, and name no file. `form-functions.json` is written again for this release and states 0.9.0. +- Documents brought in line with the app: AGENTS.md, the Agents wiki page and the skillset state the real tool counts (29 curated tools, 125 in the full profile), the demo pages say sixteen themes, formcompiler is named under nodemode-dev, and the wiki's Parity links open `docs/PARITY.md`. +- The version string inside the three browser demo bundles (`demo/assets/demo.js`, `demos/broadcast/assets/broadcast.js`, `demos/inspect/assets/inspect.js`) is bumped to 0.9.0 by hand, without a rebuild. + ## v0.8.4 · 2026-11-13 A start-up fix found by running the Linux AppImage. diff --git a/README.md b/README.md index c984beb..8b32c94 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@

- version 0.8.4 + version 0.9.0 Rust TypeScript macOS, Windows, Linux @@ -102,7 +102,7 @@ FormEncoder loads extensions made to the Form Extension Contract (API 1): FormPo ## Under the hood -Version 0.8.4 · Apache-2.0 · Rust encoding engine, Python service, TypeScript interface, Tauri 2 shell +Version 0.9.0 · Apache-2.0 · Rust encoding engine, Python service, TypeScript interface, Tauri 2 shell - **Engine:** seven `fencoder` Rust crates in `native/`, loaded by the Python service as the `fe_core` extension. - **FFmpeg:** a pinned LGPL build, run as a separate program and never linked. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index fa3ddd8..3e2f46a 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.8.4" +__version__ = "0.9.0" diff --git a/demo/assets/demo.js b/demo/assets/demo.js index d7351ef..95ead4a 100644 --- a/demo/assets/demo.js +++ b/demo/assets/demo.js @@ -10,7 +10,7 @@

- `),this.areas=Object.fromEntries(ne.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,r=>{r.preventDefault(),e.setPointerCapture(r.pointerId),n(e,`is-dragging`,!0);let i={x:r.clientX,y:r.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},a=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,i.l+e.clientX-i.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,i.r-(e.clientX-i.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,i.b-(e.clientY-i.y)))),this.applySizes()},o=()=>{n(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,a),e.removeEventListener(`pointerup`,o),this.save()};e.addEventListener(`pointermove`,a),e.addEventListener(`pointerup`,o)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,r=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${r}px`),n(this.el,`no-left`,!e),n(this.el,`no-right`,!t),n(this.el,`no-bottom`,!r);for(let e of te){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ne){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new re(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(T);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??w[e]??w.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(T),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(T,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(T)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(T)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??w[e]??w.Default,e),this.save()}resetWorkspace(){this.applyLayout(w[this.workspace]??w.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(T)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(T,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ne)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new re(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,n(this.el,`is-maximized`,!1),n(e.el,`is-max`,!1)):(this.maximized&&n(this.maximized.el,`is-max`,!1),this.maximized=e,n(this.el,`is-maximized`,!0),n(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&n(t.el,`is-focused`,!1),this.focused=e;let r=this.find(e);r&&n(r.el,`is-focused`,!0),this.onFocus?.(e)}},E={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},ae=`studio`,oe=`#f2545b`,se=`formencoder_ui_settings`,ce=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function le(){try{let e=localStorage.getItem(se);if(e){let t=JSON.parse(e);return{theme:t.theme&&E[t.theme]?t.theme:ae,accentColor:t.accentColor||`#f2545b`,intensity:ce(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:ae,accentColor:oe,intensity:1}}function ue(e){try{let t=localStorage.getItem(se),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(se,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function de(e=le()){let t=document.documentElement,n=E[e.theme]||E.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(ce(e.intensity))),t.style.setProperty(`--accent-tint`,pe(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,pe(e.accentColor,.1))}function fe(e){let t={...le(),theme:e};ue(t),de(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function pe(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var me=`0.8.4`;function he(e,t){let n=(e,t)=>e>>16-t*8&255,r=Array.from(e.keys()),i=[{lo:0,hi:r.length}],a=r,o=t=>{let r=0,i=-1;for(let o=0;o<3;o++){let s=255,c=0;for(let r=t.lo;rc&&(c=t)}c-s>i&&(i=c-s,r=o)}return{c:r,span:i}};for(;i.length{if(e.hi-e.lo<2)return;let i=o(e),a=i.span*Math.sqrt(e.hi-e.lo);a>r&&(r=a,t=n,s=i.c)}),t<0)break;let c=i[t],l=a.slice(c.lo,c.hi).sort((t,r)=>n(e[t],s)-n(e[r],s));for(let e=0;e>1);i.splice(t,1,{lo:c.lo,hi:u},{lo:u,hi:c.hi})}let s=new Uint8Array(768);return i.forEach((t,r)=>{let i=0,o=0,c=0,l=Math.max(1,t.hi-t.lo);for(let r=t.lo;r{for(a|=e<=8;)t.push(a&255),a>>>=8,o-=8};s(256);let c=e[0];for(let t=1;t1<0&&t.push(a&255),Uint8Array.from(t)}var ve=class{width;height;parts=[];constructor(e,t){this.width=e,this.height=t;let n=new Uint8Array(13),r=new DataView(n.buffer);n.set(new TextEncoder().encode(`GIF89a`),0),r.setUint16(6,e,!0),r.setUint16(8,t,!0),n[10]=0,n[11]=0,n[12]=0,this.parts.push(n),this.parts.push(Uint8Array.from([33,255,11,...new TextEncoder().encode(`NETSCAPE2.0`),3,1,0,0,0]))}addFrame(e,t){let n=this.width*this.height,r=Math.max(1,Math.floor(n/12e3)),i=[];for(let t=0;t{let r=e>>3<<10|t>>3<<5|n>>3,i=o.get(r);if(i!==void 0)return i;let s=e>>3<<3|4,c=t>>3<<3|4,l=n>>3<<3|4,u=0,d=1/0;for(let e=0;e<256;e++){let t=a[e*3]-s,n=a[e*3+1]-c,r=a[e*3+2]-l,i=t*t*2+n*n*4+r*r*3;i>8&255,0,0]));let l=new Uint8Array(10),u=new DataView(l.buffer);l[0]=44,u.setUint16(5,this.width,!0),u.setUint16(7,this.height,!0),l[9]=135,this.parts.push(l),this.parts.push(a),this.parts.push(Uint8Array.from([8]));let d=_e(c);for(let e=0;ee>0?-.691+10*Math.log10(e):-1/0;function Ce(e,t){if(!e.length)return-1/0;let n=(e.length-1)*t,r=Math.floor(n),i=Math.min(e.length-1,r+1);return e[r]+(e[i]-e[r])*(n-r)}function we(e,t){let n=[];for(let r=0;r+t<=e.length;r++){let i=0;for(let n=0;n=e.length)continue;let o=i-n,s=Math.abs(o)<1e-9?1:Math.sin(Math.PI*o)/(Math.PI*o),c=.5+.5*Math.cos(Math.PI*o/9);r+=e[a]*s*c}return r}function Ee(e){let t=0;for(let n of e)for(let e=0;et&&(t=r)}let n=t,r=t*.55;for(let t of e)for(let e=0;en&&(n=i)}return{sample:t,truePeak:n}}function De(e,t){let n=e=>e>0?20*Math.log10(e):-1/0,r=e[0]?.length??0,i=Ee(e),a=Math.round(t*.1),o=Math.floor(r/a),s=Se(e.length),c=new Float64Array(o);e.forEach((e,n)=>{if(!s[n])return;let r=xe(e,t);for(let e=0;eD(e)>-70),d=-1/0;if(u.length){let e=D(u.reduce((e,t)=>e+t,0)/u.length)-10,t=l.filter(t=>D(t)>-70&&D(t)>e);t.length&&(d=D(t.reduce((e,t)=>e+t,0)/t.length))}let f=we(c,30).filter(e=>D(e)>-70),p=0,m=-1/0;if(f.length){let e=D(f.reduce((e,t)=>e+t,0)/f.length)-20,t=f.map(D).filter(t=>t>e).sort((e,t)=>e-t);t.length&&(p=Ce(t,.95)-Ce(t,.1),m=t[t.length-1])}return{integrated:d,lra:p,samplePeak:n(i.sample),truePeak:n(i.truePeak),shortTermMax:m}}function Oe(e){return Number.isFinite(e)?e.toFixed(1):`-inf`}function O(e){return`${Oe(e.integrated)} LUFS, LRA ${e.lra.toFixed(1)} LU, peak ${Oe(e.truePeak)} dBTP`}function ke(e,t,n=-1){if(!Number.isFinite(e.integrated))return{gainDb:0,limited:!1};let r=t-e.integrated,i=n-e.truePeak;return Number.isFinite(i)&&r>i?{gainDb:i,limited:!0}:{gainDb:r,limited:!1}}function k(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Ae(e){let t=[],n=e;for(;n>0;)t.unshift(n&255),n=Math.floor(n/256);return Uint8Array.from(t)}function je(e){let t=1;for(;t<8&&e>=2**(7*t)-1;)t++;let n=new Uint8Array(t),r=e;for(let e=t-1;e>=0;e--)n[e]=r%256,r=Math.floor(r/256);return n[0]|=1<<8-t,n}function A(e,t){return k([Ae(e),je(t.length),t])}function j(e,t){let n=[],r=t;do n.unshift(r%256),r=Math.floor(r/256);while(r>0);return A(e,Uint8Array.from(n))}function Me(e,t){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!1),A(e,n)}function M(e,t){return A(e,new TextEncoder().encode(t))}function Ne(e){let t=new Uint8Array(19),n=new DataView(t.buffer);return t.set(new TextEncoder().encode(`OpusHead`),0),t[8]=1,t[9]=e.channels,n.setUint16(10,e.preSkip,!0),n.setUint32(12,e.sampleRate,!0),n.setInt16(16,0,!0),t[18]=0,t}function Pe(e){return Ne(e)}function Fe(e,t,n,r){let i=A(440786851,k([j(17030,1),j(17143,1),j(17138,4),j(17139,8),M(17026,`webm`),j(17031,4),j(17029,2)])),a=A(357149030,k([j(2807729,1e6),Me(17545,r),M(19840,`formencoder demo`),M(22337,`formencoder demo`)])),o=[];e&&o.push(A(174,k([j(215,1),j(29637,1),j(131,1),j(156,0),M(134,e.codec),A(224,k([j(176,e.width),j(186,e.height)]))]))),t&&o.push(A(174,k([j(215,2),j(29637,2),j(131,2),j(156,0),M(134,`A_OPUS`),j(22186,Math.round(t.preSkip/48e3*1e9)),j(22203,8e7),A(25506,Ne(t)),A(225,k([Me(181,t.sampleRate),j(159,t.channels)]))])));let s=A(374648427,k(o)),c=[...n].sort((e,t)=>e.timeMs-t.timeMs||e.track-t.track),l=[],u=[],d=a.length+s.length,f=[],p=0,m=!1,h=()=>{if(!m)return;let e=A(524531317,k([j(231,Math.round(p)),...f]));l.push(e),d+=e.length,f=[],m=!1};for(let e of c){let t=Math.round(e.timeMs),n=t-Math.round(p);(!m||e.track===1&&e.key&&n>0||n>3e4)&&(h(),p=t,m=!0,e.track===1&&e.key&&u.push({timeMs:t,offset:d}));let r=new Uint8Array(4);r[0]=128|e.track,new DataView(r.buffer).setInt16(1,t-Math.round(p),!1),r[3]=e.key?128:0,f.push(A(163,k([r,e.data])))}h();let g=u.length?A(475249515,k(u.map(e=>A(187,k([j(179,e.timeMs),A(183,k([j(247,1),j(241,e.offset)]))]))))):new Uint8Array,_=A(408125543,k([a,s,...l,g]));return new Blob([i,_],{type:`video/webm`})}var Ie=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t<<24;for(let e=0;e<8;e++)n=n&2147483648?n<<1^79764919:n<<1;e[t]=n>>>0}return e})();function Le(e){let t=0;for(let n=0;n>>24^e[n])&255])>>>0;return t>>>0}function Re(e,t,n,r,i,a=!1){let o=[];for(let t of e){let e=t.length;for(;e>=255;)o.push(255),e-=255;o.push(e)}let s=e.reduce((e,t)=>e+t.length,0),c=new Uint8Array(27+o.length+s),l=new DataView(c.buffer);c.set(new TextEncoder().encode(`OggS`),0),c[4]=0,c[5]=t|+!!a,l.setBigUint64(6,BigInt(n),!0),l.setUint32(14,r,!0),l.setUint32(18,i,!0),c[26]=o.length,c.set(o,27);let u=27+o.length;for(let t of e)c.set(t,u),u+=t.length;return l.setUint32(22,Le(c),!0),c}function ze(e,t,n,r){let i=1178947139,a=[],o=Pe({sampleRate:r,channels:t,preSkip:n}),s=new TextEncoder().encode(`formencoder demo`),c=new Uint8Array(12+s.length+4),l=new DataView(c.buffer);c.set(new TextEncoder().encode(`OpusTags`),0),l.setUint32(8,s.length,!0),c.set(s,12),l.setUint32(12+s.length,0,!0),a.push(Re([o],2,0,i,0)),a.push(Re([c],0,0,i,1));let u=2,d=n,f=[],p=e.length;return e.forEach((e,t)=>{f.push(e),d+=e.samples;let n=t===p-1;(f.length>=40||n)&&(a.push(Re(f.map(e=>e.data),n?4:0,d,i,u++)),f=[])}),new Blob(a,{type:`audio/ogg`})}function Be(e,t){let n=t===16?32767:8388607,r=Math.max(-1,Math.min(1,e));return Math.round(r<0?r*(n+1):r*n)}function Ve(e,t,n){let r=e[0]?.length??0,i=e.length,a=n/8,o=r*i*a,s=new ArrayBuffer(44+o),c=new DataView(s),l=(e,t)=>{for(let n=0;n>8&255),c.setUint8(u+2,i>>16&255)),u+=a}return new Blob([s],{type:`audio/wav`})}function He(e,t,n){let r=e[0]?.length??0,i=e.length,a=n/8,o=r*i*a,s=new ArrayBuffer(54+o),c=new DataView(s),l=(e,t)=>{for(let n=0;n>16&255),c.setUint8(d+1,i>>8&255),c.setUint8(d+2,i&255)),d+=a}return new Blob([s],{type:`audio/aiff`})}var Ue=[[`match-source-high`,`Match Source - High bitrate`,`Web Video`,`h264`,null,null,null,20],[`match-source-medium`,`Match Source - Medium bitrate`,`Web Video`,`h264`,null,null,null,10],[`match-source-adaptive-high`,`Match Source - Adaptive High Bitrate`,`Web Video`,`h264`,null,null,null,null],[`hevc-match-source-high`,`HEVC Match Source - High bitrate`,`Web Video`,`hevc`,null,null,null,14],[`hevc-4k-hdr10`,`HEVC 4K HDR10 (Rec. 2100 PQ)`,`Web Video`,`hevc`,3840,2160,null,40],[`av1-match-source`,`AV1 Match Source`,`Web Video`,`av1`,null,null,null,null],[`webm-vp9-1080p`,`WebM VP9 1080p`,`Web Video`,`webm`,1920,1080,null,null],[`webm-vp9-alpha`,`WebM VP9 with Alpha`,`Web Video`,`webm`,null,null,null,null],[`youtube-1080p`,`YouTube 1080p Full HD`,`Social Media`,`h264`,1920,1080,null,16],[`youtube-1440p`,`YouTube 1440p 2K QHD`,`Social Media`,`h264`,2560,1440,null,24],[`youtube-2160p`,`YouTube 2160p 4K UHD`,`Social Media`,`h264`,3840,2160,null,45],[`youtube-shorts`,`YouTube Shorts 1080x1920`,`Social Media`,`h264`,1080,1920,null,16],[`vimeo-1080p`,`Vimeo 1080p Full HD`,`Social Media`,`h264`,1920,1080,null,20],[`vimeo-2160p`,`Vimeo 2160p 4K UHD`,`Social Media`,`h264`,3840,2160,null,50],[`x-1080p`,`X (Twitter) 1080p`,`Social Media`,`h264`,1920,1080,null,8],[`instagram-reels`,`Instagram Reels and Stories 1080x1920`,`Social Media`,`h264`,1080,1920,30,10],[`instagram-feed-square`,`Instagram Feed 1080x1080`,`Social Media`,`h264`,1080,1080,30,8],[`tiktok`,`TikTok 1080x1920`,`Social Media`,`h264`,1080,1920,null,10],[`facebook-1080p`,`Facebook 1080p`,`Social Media`,`h264`,1920,1080,null,10],[`linkedin-1080p`,`LinkedIn 1080p`,`Social Media`,`h264`,1920,1080,30,8],[`apple-tv-4k`,`Apple TV 4K (HEVC)`,`Devices`,`hevc`,3840,2160,null,25],[`iphone-1080p`,`Apple iPhone and iPad 1080p`,`Devices`,`h264`,1920,1080,null,10],[`android-1080p`,`Android Phone and Tablet 1080p`,`Devices`,`h264`,1920,1080,null,10],[`android-720p`,`Android Phone 720p`,`Devices`,`h264`,1280,720,null,5],[`prores-proxy`,`Apple ProRes 422 Proxy`,`Mezzanine`,`prores`,null,null,null,null],[`prores-lt`,`Apple ProRes 422 LT`,`Mezzanine`,`prores`,null,null,null,null],[`prores-422`,`Apple ProRes 422`,`Mezzanine`,`prores`,null,null,null,null],[`prores-hq`,`Apple ProRes 422 HQ`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444`,`Apple ProRes 4444`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444-alpha`,`Apple ProRes 4444 with Alpha`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444xq`,`Apple ProRes 4444 XQ`,`Mezzanine`,`prores`,null,null,null,null],[`dnxhr-lb`,`DNxHR LB`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-sq`,`DNxHR SQ`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-hq`,`DNxHR HQ`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-hqx`,`DNxHR HQX 10-bit`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-444`,`DNxHR 444 10-bit`,`Mezzanine`,`quicktime`,null,null,null,null],[`cineform-high`,`GoPro CineForm YUV 10-bit`,`Mezzanine`,`cineform`,null,null,null,null],[`cineform-alpha`,`GoPro CineForm RGBA 12-bit with Alpha`,`Mezzanine`,`cineform`,null,null,null,null],[`animation-alpha`,`QuickTime Animation with Alpha`,`Mezzanine`,`quicktime`,null,null,null,null],[`uncompressed-10bit`,`Uncompressed 10-bit 4:2:2 (v210)`,`Mezzanine`,`quicktime`,null,null,null,null],[`xdcam-hd422-1080i50`,`XDCAM HD 422 1080i 25 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1920,1080,25,null],[`xdcam-hd422-1080i5994`,`XDCAM HD 422 1080i 29.97 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1920,1080,29.97,null],[`xdcam-hd422-720p50`,`XDCAM HD 422 720p 50 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1280,720,50,null],[`dnxhr-hq-mxf`,`DNxHR HQ MXF OP1a`,`Broadcast`,`dnxhr_mxf`,null,null,null,null],[`dnxhd-145-mxf`,`DNxHD 145 MXF OP1a 1080`,`Broadcast`,`dnxhr_mxf`,1920,1080,null,null],[`prores-hq-mxf`,`Apple ProRes 422 HQ MXF OP1a`,`Broadcast`,`prores_mxf`,null,null,null,null],[`jpeg2000-mxf`,`JPEG 2000 MXF OP1a`,`Broadcast`,`jpeg2000_mxf`,null,null,null,null],[`mpeg2-1080i`,`MPEG-2 1080i 29.97 Broadcast`,`Broadcast`,`mpeg2`,1920,1080,29.97,25],[`h264-broadcast-ebu`,`H.264 Broadcast, EBU R128 loudness`,`Broadcast`,`h264`,1920,1080,null,30],[`h264-broadcast-atsc`,`H.264 Broadcast, ATSC A/85 loudness`,`Broadcast`,`h264`,1920,1080,null,30],[`mpeg2-dvd-ntsc`,`NTSC DV Widescreen DVD`,`DVD`,`mpeg2_dvd`,720,480,29.97,6],[`bluray-mpeg2-1080i`,`Blu-ray MPEG-2 1080i 29.97`,`DVD`,`mpeg2_bluray`,1920,1080,29.97,25],[`bluray-h264-1080p24`,`Blu-ray H.264 1080p 23.976`,`DVD`,`h264_bluray`,1920,1080,23.976,25],[`as10-high-hd-1080i50`,`AS-10 HIGH_HD_2014 1080i 25`,`Broadcast`,`as10`,null,null,25,null],[`as10-high-hd-1080i5994`,`AS-10 HIGH_HD_2014 1080i 29.97`,`Broadcast`,`as10`,null,null,29.97,null],[`as11-mpeg2-1080i50`,`AS-11 OP1a MPEG-2 HD422 1080i 25`,`Broadcast`,`as11`,null,null,25,null],[`as11-d10-imx50-625`,`AS-11 D10 IMX 50 625 (UK DPP SD)`,`Broadcast`,`as11_d10`,null,null,null,null],[`p2-dvcprohd-1080i50`,`P2 DVCPRO HD 1080i 25`,`Broadcast`,`p2`,null,null,null,null],[`p2-dvcprohd-720p50`,`P2 DVCPRO HD 720p 50`,`Broadcast`,`p2`,null,null,null,null],[`dcp-2k-flat-24`,`DCP 2K Flat 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-2k-scope-24`,`DCP 2K Scope 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-2k-flat-24-interop`,`DCP 2K Flat 24 (Interop)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-4k-flat-24`,`DCP 4K Flat 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`mpeg2-dvd-pal`,`PAL DV Widescreen DVD`,`DVD`,`mpeg2_dvd`,720,576,25,6],[`png-sequence`,`PNG Sequence`,`Image Sequence`,`png`,null,null,null,null],[`png-sequence-alpha`,`PNG Sequence with Alpha`,`Image Sequence`,`png`,null,null,null,null],[`tiff-sequence-16`,`TIFF Sequence 16-bit`,`Image Sequence`,`tiff`,null,null,null,null],[`dpx-sequence-10`,`DPX Sequence 10-bit`,`Image Sequence`,`dpx`,null,null,null,null],[`exr-sequence-half`,`OpenEXR Sequence (half float)`,`Image Sequence`,`exr`,null,null,null,null],[`jpeg-sequence`,`JPEG Sequence`,`Image Sequence`,`jpeg`,null,null,null,null],[`targa-sequence`,`Targa Sequence`,`Image Sequence`,`targa`,null,null,null,null],[`png-still`,`PNG Still (first frame of the range)`,`Image`,`png`,null,null,null,null],[`jpeg-still`,`JPEG Still`,`Image`,`jpeg`,null,null,null,null],[`gif-480`,`Animated GIF 480 px`,`Animated GIF`,`gif`,null,null,15,null],[`gif-720`,`Animated GIF 720 px`,`Animated GIF`,`gif`,null,null,20,null],[`wav-48-24`,`Waveform Audio 48 kHz 24-bit`,`Audio Only`,`wav`,null,null,null,null],[`wav-48-16`,`Waveform Audio 48 kHz 16-bit`,`Audio Only`,`wav`,null,null,null,null],[`bwf-ebu`,`Broadcast WAV, EBU R128 loudness`,`Audio Only`,`bwf`,null,null,null,null],[`aiff-48-24`,`AIFF 48 kHz 24-bit`,`Audio Only`,`aiff`,null,null,null,null],[`mp3-320`,`MP3 320 kb/s`,`Audio Only`,`mp3`,null,null,null,null],[`mp3-podcast`,`MP3 Podcast, -16 LUFS`,`Audio Only`,`mp3`,null,null,null,null],[`aac-256`,`AAC Audio 256 kb/s`,`Audio Only`,`aac`,null,null,null,null],[`aac-streaming`,`AAC Streaming, -14 LUFS`,`Audio Only`,`aac`,null,null,null,null],[`flac-48-24`,`FLAC 48 kHz 24-bit`,`Audio Only`,`flac`,null,null,null,null],[`ogg-opus`,`Ogg Opus 160 kb/s`,`Audio Only`,`ogg`,null,null,null,null],[`ffv1-archive`,`FFV1 Lossless Archive (Matroska)`,`Archive`,`matroska`,null,null,null,null],[`proxy-prores`,`ProRes Proxy, quarter size (proxy)`,`Proxy`,`prores`,960,540,null,null],[`proxy-h264-540`,`H.264 Proxy 960x540`,`Proxy`,`h264`,960,540,null,3],[`proxy-h264-720`,`H.264 Proxy 1280x720 (formcut)`,`Proxy`,`h264`,1280,720,null,5],[`proxy-cineform`,`CineForm Proxy 1280x720`,`Proxy`,`cineform`,1280,720,null,null],[`family-formcut-mezzanine`,`formcut mezzanine (ProRes 422 HQ)`,`Form Family`,`prores`,null,null,null,null],[`family-formwav-audio`,`formwav session audio (WAV 48 kHz 24-bit)`,`Form Family`,`wav`,null,null,null,null],[`family-formvis-stills`,`formvis stills (PNG Sequence)`,`Form Family`,`png`,null,null,null,null]],We=new Set([`h264`,`hevc`,`av1`,`webm`,`mpeg2`,`mpeg2_dvd`,`mpeg2_bluray`,`h264_bluray`,`matroska`]);function Ge(e,t){return e===`webm-vp9-alpha`||e===`ffv1-archive`?null:We.has(t)?`webm`:t===`gif`?`gif`:t===`wav`||t===`bwf`?`wav`:t===`aiff`?`aiff`:t===`ogg`?`ogg`:e===`png-still`?`png`:e===`jpeg-still`?`jpeg`:null}function Ke(e){if(/EBU R128/.test(e))return-23;if(/ATSC A\/85/.test(e))return-24;let t=/(-\d+) LUFS/.exec(e);return t?Number(t[1]):null}var N=Ue.map(([e,t,n,r,i,a,o,s])=>({id:e,name:t,category:n,format:r,width:i,height:a,fps:o,mbps:s,target:Ge(e,r),lufs:Ke(t),bits:/-16\b|16-bit/.test(t)?16:24})),P=new Map(N.map(e=>[e.id,e])),F={webm:`WebM`,gif:`GIF`,wav:`WAV`,aiff:`AIFF`,ogg:`Ogg Opus`,png:`PNG`,jpeg:`JPEG`},I={webm:`webm`,gif:`gif`,wav:`wav`,aiff:`aiff`,ogg:`opus`,png:`png`,jpeg:`jpg`},L={webm:`video/webm`,gif:`image/gif`,wav:`audio/wav`,aiff:`audio/aiff`,ogg:`audio/ogg`,png:`image/png`,jpeg:`image/jpeg`},qe={h264:`H.264`,hevc:`HEVC`,av1:`AV1`,webm:`WebM`,prores:`ProRes`,quicktime:`QuickTime`,cineform:`CineForm`,mxf_op1a:`MXF OP1a`,dnxhr_mxf:`DNx MXF`,prores_mxf:`ProRes MXF`,jpeg2000_mxf:`J2K MXF`,mpeg2:`MPEG-2`,mpeg2_dvd:`DVD`,mpeg2_bluray:`Blu-ray`,h264_bluray:`Blu-ray`,as10:`AS-10`,as11:`AS-11`,as11_d10:`AS-11 D10`,p2:`P2`,dcp:`DCP`,png:`PNG`,tiff:`TIFF`,dpx:`DPX`,exr:`EXR`,jpeg:`JPEG`,targa:`Targa`,gif:`GIF`,wav:`WAV`,bwf:`BWF`,aiff:`AIFF`,mp3:`MP3`,aac:`AAC`,flac:`FLAC`,ogg:`Ogg`,matroska:`Matroska`},Je=new Set([`wav`,`aiff`,`ogg`]);function Ye(e){return e.width&&e.height?`${e.width}x${e.height}`:``}function Xe(e){return e.fps?`${Number(e.fps.toFixed(3))}`:``}function Ze(e){return e.mbps?`${e.mbps} Mb/s`:``}var Qe=0,$e=()=>`src${++Qe}`,R=48e3;function et(e,t,n,r=8e3){return new Promise((i,a)=>{let o=window.setTimeout(()=>{l(),a(Error(`timed out waiting for ${t}`))},r),s=()=>{l(),i()},c=()=>{l(),a(Error(`the browser cannot decode this file`))},l=()=>{window.clearTimeout(o),e.removeEventListener(t,s),e.removeEventListener(n,c)};e.addEventListener(t,s),e.addEventListener(n,c)})}async function tt(e){if(Number.isFinite(e.duration))return e.duration;e.currentTime=1e101,await et(e,`durationchange`,`error`,4e3).catch(()=>void 0);let t=Number.isFinite(e.duration)?e.duration:0;return e.currentTime=0,t}async function nt(e){let t=e.requestVideoFrameCallback?.bind(e);if(!t)return 30;let n=[];return new Promise(r=>{let i=()=>{e.pause(),e.currentTime=0;let t=[];for(let e=1;en[e-1]&&t.push(n[e]-n[e-1]);t.sort((e,t)=>e-t);let i=1/(t.length?t[t.length>>1]:1/30),a=[12,15,23.976,24,25,29.97,30,50,59.94,60].reduce((e,t)=>Math.abs(t-i){n.push(r.mediaTime),n.length>=14?i():t(a)};t(a),e.muted=!0,e.play().catch(()=>i()),window.setTimeout(()=>{n.length<14&&i()},1500)})}async function rt(e,t){let n=URL.createObjectURL(e),r=document.createElement(`video`);r.muted=!0,r.preload=`auto`,r.playsInline=!0,r.src=n;try{await et(r,`loadedmetadata`,`error`)}catch(e){throw URL.revokeObjectURL(n),e}let i=await tt(r),a=r.videoWidth>0&&r.videoHeight>0,o=a?t??await nt(r):0;a&&await it(r,0);let s=null;return{id:$e(),name:e.name,kind:a?`video`:`audio`,sample:!1,size:e.size,width:r.videoWidth,height:r.videoHeight,fps:o,duration:i,async frame(e){return await it(r,Math.max(0,Math.min(e,Math.max(0,i-.001)))),r},audio(){return s||=(async()=>{if(e.size>629145600)return null;try{return await new OfflineAudioContext(2,1,R).decodeAudioData(await e.arrayBuffer())}catch{return null}})(),s},dispose(){r.removeAttribute(`src`),r.load(),URL.revokeObjectURL(n)}}}async function it(e,t){if(Math.abs(e.currentTime-t)<1e-4&&e.readyState>=2)return;let n=et(e,`seeked`,`error`,6e3);e.currentTime=t,await n}var at=640,ot=360,z=24,B=8;function st(){let e=R*B,t=new AudioBuffer({length:e,numberOfChannels:2,sampleRate:R}),n=t.getChannelData(0),r=t.getChannelData(1),i=[261.63,329.63,392,523.25,392,329.63,293.66,349.23],a=12345,o=()=>(a=a*1664525+1013904223>>>0,a/4294967296-.5);for(let t=0;t{e.fillStyle=t,e.fillRect(n/o.length*r,0,n/o.length+1,34)}),e.strokeStyle=`rgba(255,255,255,0.12)`,e.lineWidth=1;for(let i=-(t*40)%40;i=0;r--){let i=t-r*.035,a=n/2+Math.sin(i*1.7)*190,o=190+Math.cos(i*2.3)*70;e.fillStyle=`rgba(242, 84, 91, ${.9-r*.09})`,e.beginPath(),e.arc(a,o,26-r*1.6,0,Math.PI*2),e.fill()}e.strokeStyle=`rgba(255,255,255,0.8)`,e.lineWidth=3,e.beginPath(),e.arc(s,c,48,t*3,t*3+Math.PI*1.3),e.stroke();let l=.5+.5*Math.sin(t*6);e.fillStyle=`rgba(0,0,0,0.45)`,e.fillRect(18,300,604,14),e.fillStyle=`#f2545b`,e.fillRect(18,300,t/B*604,14),e.fillStyle=`rgba(255,255,255,${.5+l*.4})`,e.fillRect(18+t/B*604-2,296,4,22);let u=Math.floor(t*z),d=Math.floor(u/z),f=u%z;e.fillStyle=`#fff`,e.font=`600 44px ui-monospace, Menlo, monospace`,e.textBaseline=`alphabetic`,e.fillText(`00:00:${String(d).padStart(2,`0`)}:${String(f).padStart(2,`0`)}`,20,96),e.font=`500 15px system-ui, sans-serif`,e.fillStyle=`rgba(255,255,255,0.8)`,e.fillText(`formencoder sample · generated in this page · 640x360 · 24 fps`,20,344)}function lt(){let e=document.createElement(`canvas`);e.width=at,e.height=ot;let t=e.getContext(`2d`,{willReadFrequently:!1}),n=null;return{id:$e(),name:`formencoder-sample`,kind:`video`,sample:!0,size:0,width:at,height:ot,fps:z,duration:B,async frame(n){return ct(t,Math.max(0,Math.min(n,B))),e},async audio(){return n||=st(),n},dispose(){n=null}}}var ut=1280;function dt(e){return{size:`preset`,fps:null,mbps:null,codec:`auto`,audio:!0,lufs:e.lufs,start:0,end:null}}var V=e=>Math.max(2,Math.round(e/2)*2);function H(e,t,n){let r=Math.max(0,Math.min(n.start,e.duration)),i=Math.max(r+.05,Math.min(n.end??e.duration,e.duration)),a=e.width||640,o=e.height||360,s=!1,c=t.target===`gif`?Number(/(\d+) px/.exec(t.name)?.[1]??0):0;typeof n.size==`number`?(a=n.size,o=e.height/e.width*n.size):n.size===`preset`&&t.width&&t.height?(a=t.width,o=t.height,s=!0):n.size===`preset`&&c&&(a=c,o=e.height/e.width*c);let l=!1,u=Math.max(a,o);if(u>1280){let e=ut/u;a*=e,o*=e,l=!0}let d=V(a),f=V(o),p=d,m=f;if(s&&e.width&&e.height){let t=Math.min(d/e.width,f/e.height);p=V(e.width*t),m=V(e.height*t)}let h=n.fps??t.fps??(e.fps||30),g=Math.max(1,Math.min(60,t.target===`gif`?Math.min(h,25):h)),_=n.mbps??0;_||=t.mbps&&t.width&&t.height?t.mbps*(d*f/(t.width*t.height))*(g/(t.fps||30)):t.mbps?t.mbps*.25:.09*d*f*g/1e6,_=Math.max(.15,Math.min(14,_));let v=Math.max(1,Math.floor((i-r)*g));return{width:d,height:f,innerWidth:p,innerHeight:m,fps:g,mbps:_,start:r,end:i,frames:v,capped:l}}function ft(){let e=[];return e.push(typeof VideoEncoder>`u`?`VideoEncoder missing`:`VideoEncoder ready`),e.push(typeof AudioEncoder>`u`?`AudioEncoder missing`:`AudioEncoder ready`),e.join(`, `)}function U(e){if(e.aborted)throw new DOMException(`stopped`,`AbortError`)}function pt(){return new Promise(e=>window.setTimeout(e,0))}function mt(e,t,n,r,i){e.fillStyle=`#000`,e.fillRect(0,0,t.width,t.height);let a=(t.width-t.innerWidth)/2,o=(t.height-t.innerHeight)/2;e.drawImage(n,0,0,r,i,a,o,t.innerWidth,t.innerHeight)}function ht(e,t){return e instanceof HTMLVideoElement?{w:e.videoWidth,h:e.videoHeight}:e instanceof HTMLCanvasElement?{w:e.width,h:e.height}:{w:t.width,h:t.height}}async function gt(e,t){let n=await e.source.audio();if(!n)return null;let r=Math.floor(t.start*n.sampleRate),i=Math.min(n.length,Math.ceil(t.end*n.sampleRate)),a=[];for(let e=0;e=0?`+`:``}${t.gainDb.toFixed(1)} dB${t.limited?`, held at -1 dBTP`:``})`}else r=`Loudness ${O(i)}`;return{channels:n.channels,rate:n.rate,note:r}}async function yt(e,t,n,r){if(typeof AudioEncoder>`u`)throw Error(`this browser has no AudioEncoder`);if(t!==48e3)throw Error(`audio at ${t} Hz needs resampling; the demo expects ${R} Hz`);let i={codec:`opus`,sampleRate:R,numberOfChannels:e.length,bitrate:n};if(!(await AudioEncoder.isConfigSupported(i)).supported)throw Error(`Opus encoding is not available in this browser`);let a=[],o=null,s=new AudioEncoder({output:e=>{let t=new Uint8Array(e.byteLength);e.copyTo(t),a.push({data:t,timeUs:e.timestamp,samples:Math.round((e.duration??2e4)/1e6*R)})},error:e=>{o=e}});s.configure(i);let c=e[0].length;for(let t=0;ti.set(e.subarray(t,t+n),r*960));let a=new AudioData({format:`f32-planar`,sampleRate:R,numberOfFrames:960,numberOfChannels:e.length,timestamp:Math.round(t/R*1e6),data:i});s.encode(a),a.close(),s.encodeQueueSize>12&&await pt()}if(await s.flush(),s.close(),o)throw o;return a}async function bt(e){if(typeof VideoEncoder>`u`)throw Error(`this browser has no WebCodecs VideoEncoder`);let{source:t,preset:n,settings:r}=e;if(t.kind!==`video`)throw Error(`this source has no picture`);let i=H(t,n,r),a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`),s=r.codec===`vp8`?[`vp8`]:r.codec===`vp9`?[`vp09.00.10.08`]:[`vp09.00.10.08`,`vp8`],c=``,l=null;for(let e of s){let t={codec:e,width:i.width,height:i.height,bitrate:Math.round(i.mbps*1e6),framerate:i.fps,latencyMode:`quality`,bitrateMode:`variable`};if((await VideoEncoder.isConfigSupported(t)).supported){c=e,l=t;break}}if(!l)throw Error(`neither VP9 nor VP8 encoding is available in this browser`);let u=[],d=null,f=new VideoEncoder({output:e=>{let t=new Uint8Array(e.byteLength);e.copyTo(t),u.push({track:1,timeMs:e.timestamp/1e3,key:e.type===`key`,data:t})},error:e=>{d=e}});f.configure(l);let p=performance.now(),m=Math.max(1,Math.round(i.fps*2)),h=0;for(let n=0;n6;)await pt();let u=performance.now();u-h>160&&(h=u,e.onPreview(a));let g=(u-p)/1e3;e.onProgress({fraction:(n+1)/i.frames*.92,frame:n+1,frames:i.frames,message:`${((n+1)/Math.max(g,.001)).toFixed(1)} fps`})}if(await f.flush(),f.close(),e.onPreview(a),d)throw d;let g=i.capped?`Frame size capped at ${ut} px in the browser demo`:``,_=null;if(r.audio){e.onProgress({fraction:.93,frame:i.frames,frames:i.frames,message:`Encoding audio`});let t=await vt(e,i);if(t)try{let n=await yt(t.channels,t.rate,128e3,e.signal);for(let e of n)u.push({track:2,timeMs:e.timeUs/1e3,key:!0,data:e.data});_={sampleRate:R,channels:t.channels.length,preSkip:312},g=[g,t.note].filter(Boolean).join(`. `)}catch(e){g=[g,`Audio left out: ${e.message}`].filter(Boolean).join(`. `)}}return e.onProgress({fraction:.98,frame:i.frames,frames:i.frames,message:`Writing WebM`}),{blob:Fe({codec:c===`vp8`?`V_VP8`:`V_VP9`,width:i.width,height:i.height},_,u,(i.end-i.start)*1e3),ext:I.webm,mime:L.webm,encoder:`WebCodecs ${c===`vp8`?`VP8`:`VP9`}${_?` + Opus`:``} · ${i.width}x${i.height} · ${i.fps} fps · ${i.mbps.toFixed(1)} Mb/s`,note:g}}async function xt(e){let{source:t,preset:n,settings:r}=e;if(t.kind!==`video`)throw Error(`this source has no picture`);let i=H(t,n,r),a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`,{willReadFrequently:!0}),s=new ve(i.width,i.height),c=Math.max(2,Math.round(100/i.fps));for(let n=0;n({data:e.data,samples:e.samples})),a.channels.length,312,a.rate),ext:I.ogg,mime:L.ogg,encoder:`WebCodecs Opus · ${a.channels.length} ch · 160 kb/s`,note:a.note}:{blob:t===`aiff`?He(a.channels,a.rate,r.bits):Ve(a.channels,a.rate,r.bits),ext:I[t],mime:L[t],encoder:`PCM ${r.bits}-bit · ${a.rate} Hz · ${a.channels.length} ch`,note:a.note}}async function Ct(e,t){let{source:n,preset:r,settings:i}=e;if(n.kind!==`video`)throw Error(`this source has no picture`);let a=H(n,r,i),o=document.createElement(`canvas`);o.width=a.width,o.height=a.height;let s=o.getContext(`2d`),c=await n.frame(a.start),l=ht(c,n);return mt(s,a,c,l.w,l.h),e.onPreview(o),{blob:await new Promise((e,n)=>o.toBlob(t=>t?e(t):n(Error(`the canvas could not be saved`)),L[t],.92)),ext:I[t],mime:L[t],encoder:`${t.toUpperCase()} still · ${a.width}x${a.height}`,note:``}}async function wt(e){let t=e.preset.target;if(!t)throw Error(`needs the desktop engine`);return t===`webm`?bt(e):t===`gif`?xt(e):Je.has(t)?St(e,t):Ct(e,t)}function Tt(e){return e==null||!Number.isFinite(e)?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function Et(e){if(e==null||!Number.isFinite(e)||e<0)return`--:--`;let t=Math.round(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n?`${n}:${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`:`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`}function Dt(e){return!e||!Number.isFinite(e)?``:e<60?`${e.toFixed(e<10?2:1)} s`:Et(e)}var Ot={ready:`Ready`,preparing:`Preparing`,encoding:`Encoding`,paused:`Paused`,done:`Done`,failed:`Failed`,stopped:`Stopped`,skipped:`Skipped`},W=new TextDecoder(`latin1`);async function G(e,t,n){let r=await e.slice(t,t+n).arrayBuffer();return new DataView(r)}var K=(e,t)=>W.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),kt={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},At={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},jt={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function Mt(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=K(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=K(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=K(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=K(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${kt[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=K(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=Mt(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:Nt(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Pt(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:jt[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function It(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await G(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function Vt(e){let t=await G(e,0,Math.min(e.size,64));if(t.byteLength<26||K(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Ht=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Ut=[44100,48e3,32e3];async function Wt(e){let t=await G(e,0,Math.min(e.size,65536)),n=0;if(K(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Ht[t.getUint8(r+2)>>4],o=Ut[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Gt(e){let t=[Ft,Rt,zt,Bt,Vt,Wt];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Kt=[{pack:`open-water`,file:`open-water-1280x720-30fps.mp4`,mime:`video/mp4`,kind:`video`,width:1280,height:720,fps:29.97,duration:8.008,bytes:6819433,outputs:[{preset:`match-source-medium`},{preset:`gif-480`},{preset:`png-still`}]},{pack:`coast-aerial`,file:`coast-aerial-1280x720-25fps.mp4`,mime:`video/mp4`,kind:`video`,width:1280,height:720,fps:25,duration:7,bytes:6637734,outputs:[{preset:`match-source-medium`},{preset:`gif-480`}]},{pack:`shoreline-vertical`,file:`shoreline-vertical-404x720-60fps.mp4`,mime:`video/mp4`,kind:`video`,width:404,height:720,fps:59.94,duration:7.858,bytes:4235966,outputs:[{preset:`match-source-medium`},{preset:`gif-480`,size:`source`}]},{pack:`on-the-sea-reading`,file:`on-the-sea-reading.mp3`,mime:`audio/mpeg`,kind:`audio`,width:0,height:0,fps:0,duration:21.133,bytes:211755,outputs:[{preset:`ogg-opus`,lufs:-16},{preset:`bwf-ebu`},{preset:`wav-48-24`}]}];function qt(){let e=window;return e.FE_MEDIA||={},e.FE_MEDIA}function Jt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}async function Yt(e){await Jt(e.pack);let t=qt(),n=t[e.file];if(delete t[e.file],!n)throw Error(`the media pack ${e.pack} holds no ${e.file}`);let r=atob(n),i=new Uint8Array(r.length);for(let e=0;ePromise.reject(Error(`the source is still loading`)),audio:()=>Promise.resolve(null),dispose:()=>void 0}}var Qt=0,q=new class{items=[];selectedItem=``;selectedOutput=``;running=!1;logs=[];listeners=new Map;abort=null;previews=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e)?.add(t)}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}log(e,t=!1){let n=new Date,r=[n.getHours(),n.getMinutes(),n.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`);this.logs.push({time:r,text:e,error:t}),this.logs.length>400&&this.logs.shift(),this.emit(`log`)}previewFor(e){return this.previews.get(e)}item(e){return this.items.find(t=>t.id===e)}outputOf(e){for(let t of this.items){let n=t.outputs.find(t=>t.id===e);if(n)return{item:t,output:n}}}select(e,t=``){(this.selectedItem!==e||this.selectedOutput!==t)&&(this.selectedItem=e,this.selectedOutput=t,this.emit(`select`))}makeOutput(e){let t=P.get(e);if(!t)throw Error(`unknown preset ${e}`);return{id:`out${++Qt}`,presetId:e,settings:dt(t),status:`ready`,progress:0,message:``,encoder:``,note:``,blob:null,mime:``,fileName:``,elapsed:0,fps:0,frame:0,frames:0,eta:0,speed:0}}stem(e){return e.source.name.replace(/\.[^.]+$/,``).replace(/[^A-Za-z0-9._-]+/g,`_`)||`source`}nameFor(e,t){let n=P.get(t.presetId),r=n?.target?I[n.target]:`out`;return`${this.stem(e)}_${t.presetId}.${r}`}addOutput(e,t){let n=this.item(e);if(!n)return;let r=this.makeOutput(t);return r.fileName=this.nameFor(n,r),n.outputs.push(r),n.collapsed=!1,this.log(`Added output ${P.get(t)?.name??t} to ${n.source.name}`),this.emit(`items`),r}async addSource(e,t){let n={id:e.id,source:e,probe:{container:``,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[]},loudness:null,loudnessState:`pending`,poster:null,outputs:[],collapsed:!1,loading:!1};this.items.push(n);for(let e of t){let t=this.makeOutput(e);t.fileName=this.nameFor(n,t),n.outputs.push(t)}return this.selectedItem=n.id,this.selectedOutput=``,this.log(`Added source ${e.name}`),this.emit(`items`),this.emit(`select`),n}async analyse(e,t){if(e.probe=t?await Gt(t):{container:`generated in this page (no file)`,duration:e.source.duration,size:0,bitrate:null,video:{codec:`canvas RGB`,profile:``,width:e.source.width,height:e.source.height,fps:e.source.fps,frames:Math.round(e.source.duration*e.source.fps),bitrate:null,pixels:`rgb24`},audio:[{codec:`PCM f32 (synthesised)`,sampleRate:48e3,channels:2,bitDepth:32,bitrate:null}],notes:[]},e.source.kind===`video`)try{let t=await e.source.frame(Math.min(1,e.source.duration/2)),n=document.createElement(`canvas`);n.width=640,n.height=Math.max(2,Math.round(640*e.source.height/e.source.width)),n.getContext(`2d`)?.drawImage(t,0,0,n.width,n.height),e.poster=n}catch(e){this.log(`No preview frame: ${e.message}`,!0)}this.emit(`items`),this.emit(`select`);try{let t=await e.source.audio();if(!t)e.loudnessState=`none`;else{e.probe.audio.length||e.probe.audio.push({codec:`decoded by the browser`,sampleRate:t.sampleRate,channels:t.numberOfChannels,bitDepth:null,bitrate:null}),await new Promise(e=>window.setTimeout(e,0));let n=[];for(let e=0;e{let r=this.addCuratedRow(t);e.push({item:r,index:n})}),this.selectedItem=e[0].item.id,this.emit(`select`);let t=0;for(let{item:n,index:r}of e){let e=Kt[r];try{let r=await Yt(e),i=await rt(r,e.fps||null);i.id=n.id,n.source.dispose(),n.source=i,n.loading=!1,this.emit(`items`),await this.analyse(n,r),t++}catch(t){this.log(`Could not load ${e.file}: ${t.message}`,!0),this.items=this.items.filter(e=>e.id!==n.id),this.selectedItem===n.id&&(this.selectedItem=this.items[0]?.id??``),this.emit(`items`),this.emit(`select`)}}t||(this.log(`The curated media did not load; adding the built-in sample instead`,!0),await this.addSample())}addCuratedRow(e){let t=Zt(e),n={id:t.id,source:t,probe:{container:``,duration:e.duration,size:e.bytes,bitrate:null,video:null,audio:[],notes:[]},loudness:null,loudnessState:`pending`,poster:null,outputs:[],collapsed:!1,loading:!0};this.items.push(n);for(let t of e.outputs){let e=this.makeOutput(t.preset);t.lufs!==void 0&&(e.settings.lufs=t.lufs),t.size&&(e.settings.size=t.size),e.fileName=this.nameFor(n,e),n.outputs.push(e)}return this.log(`Added source ${e.file}`),this.emit(`items`),n}async addSample(){let e=lt(),t=await this.addSource(e,[`match-source-medium`,`gif-480`,`bwf-ebu`]);await this.analyse(t,null)}removeSelected(){if(!this.running){if(this.selectedOutput){let e=this.outputOf(this.selectedOutput);e&&(e.item.outputs=e.item.outputs.filter(e=>e.id!==this.selectedOutput),this.selectedOutput=``)}else this.selectedItem&&=(this.item(this.selectedItem)?.source.dispose(),this.items=this.items.filter(e=>e.id!==this.selectedItem),this.items[0]?.id??``);this.emit(`items`),this.emit(`select`)}}resetOutput(e){e.status=`ready`,e.progress=0,e.message=``,e.blob=null,e.note=``,e.encoder=``,this.emit(`items`)}async start(){if(this.running)return;let e=[];for(let t of this.items)for(let n of t.outputs)(!t.loading&&n.status===`ready`||n.status===`failed`||n.status===`stopped`)&&e.push({item:t,out:n});if(!e.length)this.log(`Nothing to encode: every output is done`);else{this.running=!0,this.abort=new AbortController,this.emit(`run`),this.log(`Queue started: ${e.length} output${e.length===1?``:`s`}`);for(let{item:t,out:n}of e){if(this.abort.signal.aborted)break;await this.runOne(t,n,this.abort.signal)}this.running=!1,this.abort=null,this.log(`Queue finished`),this.emit(`run`)}}stop(){this.abort?.abort()}async runOne(e,t,n){let r=P.get(t.presetId);if(!r)return;if(!r.target){t.status=`skipped`,t.message=`Needs the desktop engine`,this.log(`Skipped ${t.fileName}: ${r.name} needs the desktop engine`),this.emit(`progress`,t);return}t.status=`preparing`,t.progress=0,t.message=`Preparing`,t.blob=null,t.note=``,this.emit(`progress`,t);let i=performance.now();this.log(`Encoding ${t.fileName} with ${r.name}`);try{let a=()=>{let e=this.previews.get(t.id);return e||(e=document.createElement(`canvas`),this.previews.set(t.id,e)),e},o=await wt({source:e.source,preset:r,settings:t.settings,signal:n,onProgress:n=>{let r=(performance.now()-i)/1e3;t.status=`encoding`,t.progress=n.fraction,t.frame=n.frame,t.frames=n.frames,t.elapsed=r,t.eta=n.fraction>.02?r/n.fraction*(1-n.fraction):0,t.fps=r>0?n.frame/r:0,t.speed=r>0&&e.source.fps?n.frame/e.source.fps/r:0,t.message=n.message,this.emit(`progress`,t)},onPreview:e=>{let n=a();(n.width!==e.width||n.height!==e.height)&&(n.width=e.width,n.height=e.height),n.getContext(`2d`)?.drawImage(e,0,0),this.emit(`progress`,t)}});t.blob=o.blob,t.mime=o.mime,t.fileName=t.fileName.replace(/\.[^.]+$/,`.${o.ext}`),t.encoder=o.encoder,t.note=o.note,t.status=`done`,t.progress=1,t.elapsed=(performance.now()-i)/1e3,t.eta=0,t.message=Tt(o.blob.size),this.log(`Done ${t.fileName}: ${o.encoder}${o.note?`. `+o.note:``}`)}catch(e){let n=e;n.name===`AbortError`?(t.status=`stopped`,t.message=`Stopped`,this.log(`Stopped ${t.fileName}`)):(t.status=`failed`,t.message=n.message,this.log(`Failed ${t.fileName}: ${n.message}`,!0))}this.emit(`progress`,t),this.emit(`items`)}},$t=new WeakMap;function J(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout($t.get(a)),$t.set(a,window.setTimeout(()=>a.remove(),r));return}let o=s(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();$t.set(o,window.setTimeout(()=>o.remove(),r))}var en=null,tn,nn,rn=``;function an(){let e=new _(`Preview`,760);return tn=s(`
`),nn=s(`

`),e.body.appendChild(tn),e.body.appendChild(nn),e.button(`Save`,`ghost`,()=>{rn&&on(rn)}),e.button(`Close`,`primary`,()=>e.close()),e.onClose=()=>{tn.replaceChildren(),rn=``},e}function on(e){let t=q.outputOf(e);if(!t?.output.blob){J(`This output has not been encoded yet`);return}let n=URL.createObjectURL(t.output.blob),r=document.createElement(`a`);r.href=n,r.download=t.output.fileName,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>URL.revokeObjectURL(n),4e3)}function sn(e){let n=q.outputOf(e);if(!n?.output.blob){J(`This output has not been encoded yet`);return}en??=an();let{output:r}=n,i=URL.createObjectURL(n.output.blob),a;r.mime.startsWith(`video/`)?(a=s(``),a.src=i):r.mime.startsWith(`audio/`)?(a=s(``),a.src=i):(a=s(``),a.src=i),tn.replaceChildren(a),rn=e,en.setTitle(r.fileName),t(nn,[r.encoder,r.note].filter(Boolean).join(`. `)),en.open(c(en.scrim,`.cv-btn-primary`))}var cn=class{id=`encoding`;title=`Encoding`;el;list;constructor(){this.el=s(`
+
`),this.areas=Object.fromEntries(ne.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,r=>{r.preventDefault(),e.setPointerCapture(r.pointerId),n(e,`is-dragging`,!0);let i={x:r.clientX,y:r.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},a=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,i.l+e.clientX-i.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,i.r-(e.clientX-i.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,i.b-(e.clientY-i.y)))),this.applySizes()},o=()=>{n(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,a),e.removeEventListener(`pointerup`,o),this.save()};e.addEventListener(`pointermove`,a),e.addEventListener(`pointerup`,o)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,r=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${r}px`),n(this.el,`no-left`,!e),n(this.el,`no-right`,!t),n(this.el,`no-bottom`,!r);for(let e of te){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ne){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new re(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(T);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??w[e]??w.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(T),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(T,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(T)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(T)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??w[e]??w.Default,e),this.save()}resetWorkspace(){this.applyLayout(w[this.workspace]??w.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(T)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(T,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ne)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new re(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,n(this.el,`is-maximized`,!1),n(e.el,`is-max`,!1)):(this.maximized&&n(this.maximized.el,`is-max`,!1),this.maximized=e,n(this.el,`is-maximized`,!0),n(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&n(t.el,`is-focused`,!1),this.focused=e;let r=this.find(e);r&&n(r.el,`is-focused`,!0),this.onFocus?.(e)}},E={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},ae=`studio`,oe=`#f2545b`,se=`formencoder_ui_settings`,ce=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function le(){try{let e=localStorage.getItem(se);if(e){let t=JSON.parse(e);return{theme:t.theme&&E[t.theme]?t.theme:ae,accentColor:t.accentColor||`#f2545b`,intensity:ce(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:ae,accentColor:oe,intensity:1}}function ue(e){try{let t=localStorage.getItem(se),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(se,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function de(e=le()){let t=document.documentElement,n=E[e.theme]||E.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(ce(e.intensity))),t.style.setProperty(`--accent-tint`,pe(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,pe(e.accentColor,.1))}function fe(e){let t={...le(),theme:e};ue(t),de(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function pe(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var me=`0.9.0`;function he(e,t){let n=(e,t)=>e>>16-t*8&255,r=Array.from(e.keys()),i=[{lo:0,hi:r.length}],a=r,o=t=>{let r=0,i=-1;for(let o=0;o<3;o++){let s=255,c=0;for(let r=t.lo;rc&&(c=t)}c-s>i&&(i=c-s,r=o)}return{c:r,span:i}};for(;i.length{if(e.hi-e.lo<2)return;let i=o(e),a=i.span*Math.sqrt(e.hi-e.lo);a>r&&(r=a,t=n,s=i.c)}),t<0)break;let c=i[t],l=a.slice(c.lo,c.hi).sort((t,r)=>n(e[t],s)-n(e[r],s));for(let e=0;e>1);i.splice(t,1,{lo:c.lo,hi:u},{lo:u,hi:c.hi})}let s=new Uint8Array(768);return i.forEach((t,r)=>{let i=0,o=0,c=0,l=Math.max(1,t.hi-t.lo);for(let r=t.lo;r{for(a|=e<=8;)t.push(a&255),a>>>=8,o-=8};s(256);let c=e[0];for(let t=1;t1<0&&t.push(a&255),Uint8Array.from(t)}var ve=class{width;height;parts=[];constructor(e,t){this.width=e,this.height=t;let n=new Uint8Array(13),r=new DataView(n.buffer);n.set(new TextEncoder().encode(`GIF89a`),0),r.setUint16(6,e,!0),r.setUint16(8,t,!0),n[10]=0,n[11]=0,n[12]=0,this.parts.push(n),this.parts.push(Uint8Array.from([33,255,11,...new TextEncoder().encode(`NETSCAPE2.0`),3,1,0,0,0]))}addFrame(e,t){let n=this.width*this.height,r=Math.max(1,Math.floor(n/12e3)),i=[];for(let t=0;t{let r=e>>3<<10|t>>3<<5|n>>3,i=o.get(r);if(i!==void 0)return i;let s=e>>3<<3|4,c=t>>3<<3|4,l=n>>3<<3|4,u=0,d=1/0;for(let e=0;e<256;e++){let t=a[e*3]-s,n=a[e*3+1]-c,r=a[e*3+2]-l,i=t*t*2+n*n*4+r*r*3;i>8&255,0,0]));let l=new Uint8Array(10),u=new DataView(l.buffer);l[0]=44,u.setUint16(5,this.width,!0),u.setUint16(7,this.height,!0),l[9]=135,this.parts.push(l),this.parts.push(a),this.parts.push(Uint8Array.from([8]));let d=_e(c);for(let e=0;ee>0?-.691+10*Math.log10(e):-1/0;function Ce(e,t){if(!e.length)return-1/0;let n=(e.length-1)*t,r=Math.floor(n),i=Math.min(e.length-1,r+1);return e[r]+(e[i]-e[r])*(n-r)}function we(e,t){let n=[];for(let r=0;r+t<=e.length;r++){let i=0;for(let n=0;n=e.length)continue;let o=i-n,s=Math.abs(o)<1e-9?1:Math.sin(Math.PI*o)/(Math.PI*o),c=.5+.5*Math.cos(Math.PI*o/9);r+=e[a]*s*c}return r}function Ee(e){let t=0;for(let n of e)for(let e=0;et&&(t=r)}let n=t,r=t*.55;for(let t of e)for(let e=0;en&&(n=i)}return{sample:t,truePeak:n}}function De(e,t){let n=e=>e>0?20*Math.log10(e):-1/0,r=e[0]?.length??0,i=Ee(e),a=Math.round(t*.1),o=Math.floor(r/a),s=Se(e.length),c=new Float64Array(o);e.forEach((e,n)=>{if(!s[n])return;let r=xe(e,t);for(let e=0;eD(e)>-70),d=-1/0;if(u.length){let e=D(u.reduce((e,t)=>e+t,0)/u.length)-10,t=l.filter(t=>D(t)>-70&&D(t)>e);t.length&&(d=D(t.reduce((e,t)=>e+t,0)/t.length))}let f=we(c,30).filter(e=>D(e)>-70),p=0,m=-1/0;if(f.length){let e=D(f.reduce((e,t)=>e+t,0)/f.length)-20,t=f.map(D).filter(t=>t>e).sort((e,t)=>e-t);t.length&&(p=Ce(t,.95)-Ce(t,.1),m=t[t.length-1])}return{integrated:d,lra:p,samplePeak:n(i.sample),truePeak:n(i.truePeak),shortTermMax:m}}function Oe(e){return Number.isFinite(e)?e.toFixed(1):`-inf`}function O(e){return`${Oe(e.integrated)} LUFS, LRA ${e.lra.toFixed(1)} LU, peak ${Oe(e.truePeak)} dBTP`}function ke(e,t,n=-1){if(!Number.isFinite(e.integrated))return{gainDb:0,limited:!1};let r=t-e.integrated,i=n-e.truePeak;return Number.isFinite(i)&&r>i?{gainDb:i,limited:!0}:{gainDb:r,limited:!1}}function k(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Ae(e){let t=[],n=e;for(;n>0;)t.unshift(n&255),n=Math.floor(n/256);return Uint8Array.from(t)}function je(e){let t=1;for(;t<8&&e>=2**(7*t)-1;)t++;let n=new Uint8Array(t),r=e;for(let e=t-1;e>=0;e--)n[e]=r%256,r=Math.floor(r/256);return n[0]|=1<<8-t,n}function A(e,t){return k([Ae(e),je(t.length),t])}function j(e,t){let n=[],r=t;do n.unshift(r%256),r=Math.floor(r/256);while(r>0);return A(e,Uint8Array.from(n))}function Me(e,t){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!1),A(e,n)}function M(e,t){return A(e,new TextEncoder().encode(t))}function Ne(e){let t=new Uint8Array(19),n=new DataView(t.buffer);return t.set(new TextEncoder().encode(`OpusHead`),0),t[8]=1,t[9]=e.channels,n.setUint16(10,e.preSkip,!0),n.setUint32(12,e.sampleRate,!0),n.setInt16(16,0,!0),t[18]=0,t}function Pe(e){return Ne(e)}function Fe(e,t,n,r){let i=A(440786851,k([j(17030,1),j(17143,1),j(17138,4),j(17139,8),M(17026,`webm`),j(17031,4),j(17029,2)])),a=A(357149030,k([j(2807729,1e6),Me(17545,r),M(19840,`formencoder demo`),M(22337,`formencoder demo`)])),o=[];e&&o.push(A(174,k([j(215,1),j(29637,1),j(131,1),j(156,0),M(134,e.codec),A(224,k([j(176,e.width),j(186,e.height)]))]))),t&&o.push(A(174,k([j(215,2),j(29637,2),j(131,2),j(156,0),M(134,`A_OPUS`),j(22186,Math.round(t.preSkip/48e3*1e9)),j(22203,8e7),A(25506,Ne(t)),A(225,k([Me(181,t.sampleRate),j(159,t.channels)]))])));let s=A(374648427,k(o)),c=[...n].sort((e,t)=>e.timeMs-t.timeMs||e.track-t.track),l=[],u=[],d=a.length+s.length,f=[],p=0,m=!1,h=()=>{if(!m)return;let e=A(524531317,k([j(231,Math.round(p)),...f]));l.push(e),d+=e.length,f=[],m=!1};for(let e of c){let t=Math.round(e.timeMs),n=t-Math.round(p);(!m||e.track===1&&e.key&&n>0||n>3e4)&&(h(),p=t,m=!0,e.track===1&&e.key&&u.push({timeMs:t,offset:d}));let r=new Uint8Array(4);r[0]=128|e.track,new DataView(r.buffer).setInt16(1,t-Math.round(p),!1),r[3]=e.key?128:0,f.push(A(163,k([r,e.data])))}h();let g=u.length?A(475249515,k(u.map(e=>A(187,k([j(179,e.timeMs),A(183,k([j(247,1),j(241,e.offset)]))]))))):new Uint8Array,_=A(408125543,k([a,s,...l,g]));return new Blob([i,_],{type:`video/webm`})}var Ie=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t<<24;for(let e=0;e<8;e++)n=n&2147483648?n<<1^79764919:n<<1;e[t]=n>>>0}return e})();function Le(e){let t=0;for(let n=0;n>>24^e[n])&255])>>>0;return t>>>0}function Re(e,t,n,r,i,a=!1){let o=[];for(let t of e){let e=t.length;for(;e>=255;)o.push(255),e-=255;o.push(e)}let s=e.reduce((e,t)=>e+t.length,0),c=new Uint8Array(27+o.length+s),l=new DataView(c.buffer);c.set(new TextEncoder().encode(`OggS`),0),c[4]=0,c[5]=t|+!!a,l.setBigUint64(6,BigInt(n),!0),l.setUint32(14,r,!0),l.setUint32(18,i,!0),c[26]=o.length,c.set(o,27);let u=27+o.length;for(let t of e)c.set(t,u),u+=t.length;return l.setUint32(22,Le(c),!0),c}function ze(e,t,n,r){let i=1178947139,a=[],o=Pe({sampleRate:r,channels:t,preSkip:n}),s=new TextEncoder().encode(`formencoder demo`),c=new Uint8Array(12+s.length+4),l=new DataView(c.buffer);c.set(new TextEncoder().encode(`OpusTags`),0),l.setUint32(8,s.length,!0),c.set(s,12),l.setUint32(12+s.length,0,!0),a.push(Re([o],2,0,i,0)),a.push(Re([c],0,0,i,1));let u=2,d=n,f=[],p=e.length;return e.forEach((e,t)=>{f.push(e),d+=e.samples;let n=t===p-1;(f.length>=40||n)&&(a.push(Re(f.map(e=>e.data),n?4:0,d,i,u++)),f=[])}),new Blob(a,{type:`audio/ogg`})}function Be(e,t){let n=t===16?32767:8388607,r=Math.max(-1,Math.min(1,e));return Math.round(r<0?r*(n+1):r*n)}function Ve(e,t,n){let r=e[0]?.length??0,i=e.length,a=n/8,o=r*i*a,s=new ArrayBuffer(44+o),c=new DataView(s),l=(e,t)=>{for(let n=0;n>8&255),c.setUint8(u+2,i>>16&255)),u+=a}return new Blob([s],{type:`audio/wav`})}function He(e,t,n){let r=e[0]?.length??0,i=e.length,a=n/8,o=r*i*a,s=new ArrayBuffer(54+o),c=new DataView(s),l=(e,t)=>{for(let n=0;n>16&255),c.setUint8(d+1,i>>8&255),c.setUint8(d+2,i&255)),d+=a}return new Blob([s],{type:`audio/aiff`})}var Ue=[[`match-source-high`,`Match Source - High bitrate`,`Web Video`,`h264`,null,null,null,20],[`match-source-medium`,`Match Source - Medium bitrate`,`Web Video`,`h264`,null,null,null,10],[`match-source-adaptive-high`,`Match Source - Adaptive High Bitrate`,`Web Video`,`h264`,null,null,null,null],[`hevc-match-source-high`,`HEVC Match Source - High bitrate`,`Web Video`,`hevc`,null,null,null,14],[`hevc-4k-hdr10`,`HEVC 4K HDR10 (Rec. 2100 PQ)`,`Web Video`,`hevc`,3840,2160,null,40],[`av1-match-source`,`AV1 Match Source`,`Web Video`,`av1`,null,null,null,null],[`webm-vp9-1080p`,`WebM VP9 1080p`,`Web Video`,`webm`,1920,1080,null,null],[`webm-vp9-alpha`,`WebM VP9 with Alpha`,`Web Video`,`webm`,null,null,null,null],[`youtube-1080p`,`YouTube 1080p Full HD`,`Social Media`,`h264`,1920,1080,null,16],[`youtube-1440p`,`YouTube 1440p 2K QHD`,`Social Media`,`h264`,2560,1440,null,24],[`youtube-2160p`,`YouTube 2160p 4K UHD`,`Social Media`,`h264`,3840,2160,null,45],[`youtube-shorts`,`YouTube Shorts 1080x1920`,`Social Media`,`h264`,1080,1920,null,16],[`vimeo-1080p`,`Vimeo 1080p Full HD`,`Social Media`,`h264`,1920,1080,null,20],[`vimeo-2160p`,`Vimeo 2160p 4K UHD`,`Social Media`,`h264`,3840,2160,null,50],[`x-1080p`,`X (Twitter) 1080p`,`Social Media`,`h264`,1920,1080,null,8],[`instagram-reels`,`Instagram Reels and Stories 1080x1920`,`Social Media`,`h264`,1080,1920,30,10],[`instagram-feed-square`,`Instagram Feed 1080x1080`,`Social Media`,`h264`,1080,1080,30,8],[`tiktok`,`TikTok 1080x1920`,`Social Media`,`h264`,1080,1920,null,10],[`facebook-1080p`,`Facebook 1080p`,`Social Media`,`h264`,1920,1080,null,10],[`linkedin-1080p`,`LinkedIn 1080p`,`Social Media`,`h264`,1920,1080,30,8],[`apple-tv-4k`,`Apple TV 4K (HEVC)`,`Devices`,`hevc`,3840,2160,null,25],[`iphone-1080p`,`Apple iPhone and iPad 1080p`,`Devices`,`h264`,1920,1080,null,10],[`android-1080p`,`Android Phone and Tablet 1080p`,`Devices`,`h264`,1920,1080,null,10],[`android-720p`,`Android Phone 720p`,`Devices`,`h264`,1280,720,null,5],[`prores-proxy`,`Apple ProRes 422 Proxy`,`Mezzanine`,`prores`,null,null,null,null],[`prores-lt`,`Apple ProRes 422 LT`,`Mezzanine`,`prores`,null,null,null,null],[`prores-422`,`Apple ProRes 422`,`Mezzanine`,`prores`,null,null,null,null],[`prores-hq`,`Apple ProRes 422 HQ`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444`,`Apple ProRes 4444`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444-alpha`,`Apple ProRes 4444 with Alpha`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444xq`,`Apple ProRes 4444 XQ`,`Mezzanine`,`prores`,null,null,null,null],[`dnxhr-lb`,`DNxHR LB`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-sq`,`DNxHR SQ`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-hq`,`DNxHR HQ`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-hqx`,`DNxHR HQX 10-bit`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-444`,`DNxHR 444 10-bit`,`Mezzanine`,`quicktime`,null,null,null,null],[`cineform-high`,`GoPro CineForm YUV 10-bit`,`Mezzanine`,`cineform`,null,null,null,null],[`cineform-alpha`,`GoPro CineForm RGBA 12-bit with Alpha`,`Mezzanine`,`cineform`,null,null,null,null],[`animation-alpha`,`QuickTime Animation with Alpha`,`Mezzanine`,`quicktime`,null,null,null,null],[`uncompressed-10bit`,`Uncompressed 10-bit 4:2:2 (v210)`,`Mezzanine`,`quicktime`,null,null,null,null],[`xdcam-hd422-1080i50`,`XDCAM HD 422 1080i 25 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1920,1080,25,null],[`xdcam-hd422-1080i5994`,`XDCAM HD 422 1080i 29.97 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1920,1080,29.97,null],[`xdcam-hd422-720p50`,`XDCAM HD 422 720p 50 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1280,720,50,null],[`dnxhr-hq-mxf`,`DNxHR HQ MXF OP1a`,`Broadcast`,`dnxhr_mxf`,null,null,null,null],[`dnxhd-145-mxf`,`DNxHD 145 MXF OP1a 1080`,`Broadcast`,`dnxhr_mxf`,1920,1080,null,null],[`prores-hq-mxf`,`Apple ProRes 422 HQ MXF OP1a`,`Broadcast`,`prores_mxf`,null,null,null,null],[`jpeg2000-mxf`,`JPEG 2000 MXF OP1a`,`Broadcast`,`jpeg2000_mxf`,null,null,null,null],[`mpeg2-1080i`,`MPEG-2 1080i 29.97 Broadcast`,`Broadcast`,`mpeg2`,1920,1080,29.97,25],[`h264-broadcast-ebu`,`H.264 Broadcast, EBU R128 loudness`,`Broadcast`,`h264`,1920,1080,null,30],[`h264-broadcast-atsc`,`H.264 Broadcast, ATSC A/85 loudness`,`Broadcast`,`h264`,1920,1080,null,30],[`mpeg2-dvd-ntsc`,`NTSC DV Widescreen DVD`,`DVD`,`mpeg2_dvd`,720,480,29.97,6],[`bluray-mpeg2-1080i`,`Blu-ray MPEG-2 1080i 29.97`,`DVD`,`mpeg2_bluray`,1920,1080,29.97,25],[`bluray-h264-1080p24`,`Blu-ray H.264 1080p 23.976`,`DVD`,`h264_bluray`,1920,1080,23.976,25],[`as10-high-hd-1080i50`,`AS-10 HIGH_HD_2014 1080i 25`,`Broadcast`,`as10`,null,null,25,null],[`as10-high-hd-1080i5994`,`AS-10 HIGH_HD_2014 1080i 29.97`,`Broadcast`,`as10`,null,null,29.97,null],[`as11-mpeg2-1080i50`,`AS-11 OP1a MPEG-2 HD422 1080i 25`,`Broadcast`,`as11`,null,null,25,null],[`as11-d10-imx50-625`,`AS-11 D10 IMX 50 625 (UK DPP SD)`,`Broadcast`,`as11_d10`,null,null,null,null],[`p2-dvcprohd-1080i50`,`P2 DVCPRO HD 1080i 25`,`Broadcast`,`p2`,null,null,null,null],[`p2-dvcprohd-720p50`,`P2 DVCPRO HD 720p 50`,`Broadcast`,`p2`,null,null,null,null],[`dcp-2k-flat-24`,`DCP 2K Flat 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-2k-scope-24`,`DCP 2K Scope 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-2k-flat-24-interop`,`DCP 2K Flat 24 (Interop)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-4k-flat-24`,`DCP 4K Flat 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`mpeg2-dvd-pal`,`PAL DV Widescreen DVD`,`DVD`,`mpeg2_dvd`,720,576,25,6],[`png-sequence`,`PNG Sequence`,`Image Sequence`,`png`,null,null,null,null],[`png-sequence-alpha`,`PNG Sequence with Alpha`,`Image Sequence`,`png`,null,null,null,null],[`tiff-sequence-16`,`TIFF Sequence 16-bit`,`Image Sequence`,`tiff`,null,null,null,null],[`dpx-sequence-10`,`DPX Sequence 10-bit`,`Image Sequence`,`dpx`,null,null,null,null],[`exr-sequence-half`,`OpenEXR Sequence (half float)`,`Image Sequence`,`exr`,null,null,null,null],[`jpeg-sequence`,`JPEG Sequence`,`Image Sequence`,`jpeg`,null,null,null,null],[`targa-sequence`,`Targa Sequence`,`Image Sequence`,`targa`,null,null,null,null],[`png-still`,`PNG Still (first frame of the range)`,`Image`,`png`,null,null,null,null],[`jpeg-still`,`JPEG Still`,`Image`,`jpeg`,null,null,null,null],[`gif-480`,`Animated GIF 480 px`,`Animated GIF`,`gif`,null,null,15,null],[`gif-720`,`Animated GIF 720 px`,`Animated GIF`,`gif`,null,null,20,null],[`wav-48-24`,`Waveform Audio 48 kHz 24-bit`,`Audio Only`,`wav`,null,null,null,null],[`wav-48-16`,`Waveform Audio 48 kHz 16-bit`,`Audio Only`,`wav`,null,null,null,null],[`bwf-ebu`,`Broadcast WAV, EBU R128 loudness`,`Audio Only`,`bwf`,null,null,null,null],[`aiff-48-24`,`AIFF 48 kHz 24-bit`,`Audio Only`,`aiff`,null,null,null,null],[`mp3-320`,`MP3 320 kb/s`,`Audio Only`,`mp3`,null,null,null,null],[`mp3-podcast`,`MP3 Podcast, -16 LUFS`,`Audio Only`,`mp3`,null,null,null,null],[`aac-256`,`AAC Audio 256 kb/s`,`Audio Only`,`aac`,null,null,null,null],[`aac-streaming`,`AAC Streaming, -14 LUFS`,`Audio Only`,`aac`,null,null,null,null],[`flac-48-24`,`FLAC 48 kHz 24-bit`,`Audio Only`,`flac`,null,null,null,null],[`ogg-opus`,`Ogg Opus 160 kb/s`,`Audio Only`,`ogg`,null,null,null,null],[`ffv1-archive`,`FFV1 Lossless Archive (Matroska)`,`Archive`,`matroska`,null,null,null,null],[`proxy-prores`,`ProRes Proxy, quarter size (proxy)`,`Proxy`,`prores`,960,540,null,null],[`proxy-h264-540`,`H.264 Proxy 960x540`,`Proxy`,`h264`,960,540,null,3],[`proxy-h264-720`,`H.264 Proxy 1280x720 (formcut)`,`Proxy`,`h264`,1280,720,null,5],[`proxy-cineform`,`CineForm Proxy 1280x720`,`Proxy`,`cineform`,1280,720,null,null],[`family-formcut-mezzanine`,`formcut mezzanine (ProRes 422 HQ)`,`Form Family`,`prores`,null,null,null,null],[`family-formwav-audio`,`formwav session audio (WAV 48 kHz 24-bit)`,`Form Family`,`wav`,null,null,null,null],[`family-formvis-stills`,`formvis stills (PNG Sequence)`,`Form Family`,`png`,null,null,null,null]],We=new Set([`h264`,`hevc`,`av1`,`webm`,`mpeg2`,`mpeg2_dvd`,`mpeg2_bluray`,`h264_bluray`,`matroska`]);function Ge(e,t){return e===`webm-vp9-alpha`||e===`ffv1-archive`?null:We.has(t)?`webm`:t===`gif`?`gif`:t===`wav`||t===`bwf`?`wav`:t===`aiff`?`aiff`:t===`ogg`?`ogg`:e===`png-still`?`png`:e===`jpeg-still`?`jpeg`:null}function Ke(e){if(/EBU R128/.test(e))return-23;if(/ATSC A\/85/.test(e))return-24;let t=/(-\d+) LUFS/.exec(e);return t?Number(t[1]):null}var N=Ue.map(([e,t,n,r,i,a,o,s])=>({id:e,name:t,category:n,format:r,width:i,height:a,fps:o,mbps:s,target:Ge(e,r),lufs:Ke(t),bits:/-16\b|16-bit/.test(t)?16:24})),P=new Map(N.map(e=>[e.id,e])),F={webm:`WebM`,gif:`GIF`,wav:`WAV`,aiff:`AIFF`,ogg:`Ogg Opus`,png:`PNG`,jpeg:`JPEG`},I={webm:`webm`,gif:`gif`,wav:`wav`,aiff:`aiff`,ogg:`opus`,png:`png`,jpeg:`jpg`},L={webm:`video/webm`,gif:`image/gif`,wav:`audio/wav`,aiff:`audio/aiff`,ogg:`audio/ogg`,png:`image/png`,jpeg:`image/jpeg`},qe={h264:`H.264`,hevc:`HEVC`,av1:`AV1`,webm:`WebM`,prores:`ProRes`,quicktime:`QuickTime`,cineform:`CineForm`,mxf_op1a:`MXF OP1a`,dnxhr_mxf:`DNx MXF`,prores_mxf:`ProRes MXF`,jpeg2000_mxf:`J2K MXF`,mpeg2:`MPEG-2`,mpeg2_dvd:`DVD`,mpeg2_bluray:`Blu-ray`,h264_bluray:`Blu-ray`,as10:`AS-10`,as11:`AS-11`,as11_d10:`AS-11 D10`,p2:`P2`,dcp:`DCP`,png:`PNG`,tiff:`TIFF`,dpx:`DPX`,exr:`EXR`,jpeg:`JPEG`,targa:`Targa`,gif:`GIF`,wav:`WAV`,bwf:`BWF`,aiff:`AIFF`,mp3:`MP3`,aac:`AAC`,flac:`FLAC`,ogg:`Ogg`,matroska:`Matroska`},Je=new Set([`wav`,`aiff`,`ogg`]);function Ye(e){return e.width&&e.height?`${e.width}x${e.height}`:``}function Xe(e){return e.fps?`${Number(e.fps.toFixed(3))}`:``}function Ze(e){return e.mbps?`${e.mbps} Mb/s`:``}var Qe=0,$e=()=>`src${++Qe}`,R=48e3;function et(e,t,n,r=8e3){return new Promise((i,a)=>{let o=window.setTimeout(()=>{l(),a(Error(`timed out waiting for ${t}`))},r),s=()=>{l(),i()},c=()=>{l(),a(Error(`the browser cannot decode this file`))},l=()=>{window.clearTimeout(o),e.removeEventListener(t,s),e.removeEventListener(n,c)};e.addEventListener(t,s),e.addEventListener(n,c)})}async function tt(e){if(Number.isFinite(e.duration))return e.duration;e.currentTime=1e101,await et(e,`durationchange`,`error`,4e3).catch(()=>void 0);let t=Number.isFinite(e.duration)?e.duration:0;return e.currentTime=0,t}async function nt(e){let t=e.requestVideoFrameCallback?.bind(e);if(!t)return 30;let n=[];return new Promise(r=>{let i=()=>{e.pause(),e.currentTime=0;let t=[];for(let e=1;en[e-1]&&t.push(n[e]-n[e-1]);t.sort((e,t)=>e-t);let i=1/(t.length?t[t.length>>1]:1/30),a=[12,15,23.976,24,25,29.97,30,50,59.94,60].reduce((e,t)=>Math.abs(t-i){n.push(r.mediaTime),n.length>=14?i():t(a)};t(a),e.muted=!0,e.play().catch(()=>i()),window.setTimeout(()=>{n.length<14&&i()},1500)})}async function rt(e,t){let n=URL.createObjectURL(e),r=document.createElement(`video`);r.muted=!0,r.preload=`auto`,r.playsInline=!0,r.src=n;try{await et(r,`loadedmetadata`,`error`)}catch(e){throw URL.revokeObjectURL(n),e}let i=await tt(r),a=r.videoWidth>0&&r.videoHeight>0,o=a?t??await nt(r):0;a&&await it(r,0);let s=null;return{id:$e(),name:e.name,kind:a?`video`:`audio`,sample:!1,size:e.size,width:r.videoWidth,height:r.videoHeight,fps:o,duration:i,async frame(e){return await it(r,Math.max(0,Math.min(e,Math.max(0,i-.001)))),r},audio(){return s||=(async()=>{if(e.size>629145600)return null;try{return await new OfflineAudioContext(2,1,R).decodeAudioData(await e.arrayBuffer())}catch{return null}})(),s},dispose(){r.removeAttribute(`src`),r.load(),URL.revokeObjectURL(n)}}}async function it(e,t){if(Math.abs(e.currentTime-t)<1e-4&&e.readyState>=2)return;let n=et(e,`seeked`,`error`,6e3);e.currentTime=t,await n}var at=640,ot=360,z=24,B=8;function st(){let e=R*B,t=new AudioBuffer({length:e,numberOfChannels:2,sampleRate:R}),n=t.getChannelData(0),r=t.getChannelData(1),i=[261.63,329.63,392,523.25,392,329.63,293.66,349.23],a=12345,o=()=>(a=a*1664525+1013904223>>>0,a/4294967296-.5);for(let t=0;t{e.fillStyle=t,e.fillRect(n/o.length*r,0,n/o.length+1,34)}),e.strokeStyle=`rgba(255,255,255,0.12)`,e.lineWidth=1;for(let i=-(t*40)%40;i=0;r--){let i=t-r*.035,a=n/2+Math.sin(i*1.7)*190,o=190+Math.cos(i*2.3)*70;e.fillStyle=`rgba(242, 84, 91, ${.9-r*.09})`,e.beginPath(),e.arc(a,o,26-r*1.6,0,Math.PI*2),e.fill()}e.strokeStyle=`rgba(255,255,255,0.8)`,e.lineWidth=3,e.beginPath(),e.arc(s,c,48,t*3,t*3+Math.PI*1.3),e.stroke();let l=.5+.5*Math.sin(t*6);e.fillStyle=`rgba(0,0,0,0.45)`,e.fillRect(18,300,604,14),e.fillStyle=`#f2545b`,e.fillRect(18,300,t/B*604,14),e.fillStyle=`rgba(255,255,255,${.5+l*.4})`,e.fillRect(18+t/B*604-2,296,4,22);let u=Math.floor(t*z),d=Math.floor(u/z),f=u%z;e.fillStyle=`#fff`,e.font=`600 44px ui-monospace, Menlo, monospace`,e.textBaseline=`alphabetic`,e.fillText(`00:00:${String(d).padStart(2,`0`)}:${String(f).padStart(2,`0`)}`,20,96),e.font=`500 15px system-ui, sans-serif`,e.fillStyle=`rgba(255,255,255,0.8)`,e.fillText(`formencoder sample · generated in this page · 640x360 · 24 fps`,20,344)}function lt(){let e=document.createElement(`canvas`);e.width=at,e.height=ot;let t=e.getContext(`2d`,{willReadFrequently:!1}),n=null;return{id:$e(),name:`formencoder-sample`,kind:`video`,sample:!0,size:0,width:at,height:ot,fps:z,duration:B,async frame(n){return ct(t,Math.max(0,Math.min(n,B))),e},async audio(){return n||=st(),n},dispose(){n=null}}}var ut=1280;function dt(e){return{size:`preset`,fps:null,mbps:null,codec:`auto`,audio:!0,lufs:e.lufs,start:0,end:null}}var V=e=>Math.max(2,Math.round(e/2)*2);function H(e,t,n){let r=Math.max(0,Math.min(n.start,e.duration)),i=Math.max(r+.05,Math.min(n.end??e.duration,e.duration)),a=e.width||640,o=e.height||360,s=!1,c=t.target===`gif`?Number(/(\d+) px/.exec(t.name)?.[1]??0):0;typeof n.size==`number`?(a=n.size,o=e.height/e.width*n.size):n.size===`preset`&&t.width&&t.height?(a=t.width,o=t.height,s=!0):n.size===`preset`&&c&&(a=c,o=e.height/e.width*c);let l=!1,u=Math.max(a,o);if(u>1280){let e=ut/u;a*=e,o*=e,l=!0}let d=V(a),f=V(o),p=d,m=f;if(s&&e.width&&e.height){let t=Math.min(d/e.width,f/e.height);p=V(e.width*t),m=V(e.height*t)}let h=n.fps??t.fps??(e.fps||30),g=Math.max(1,Math.min(60,t.target===`gif`?Math.min(h,25):h)),_=n.mbps??0;_||=t.mbps&&t.width&&t.height?t.mbps*(d*f/(t.width*t.height))*(g/(t.fps||30)):t.mbps?t.mbps*.25:.09*d*f*g/1e6,_=Math.max(.15,Math.min(14,_));let v=Math.max(1,Math.floor((i-r)*g));return{width:d,height:f,innerWidth:p,innerHeight:m,fps:g,mbps:_,start:r,end:i,frames:v,capped:l}}function ft(){let e=[];return e.push(typeof VideoEncoder>`u`?`VideoEncoder missing`:`VideoEncoder ready`),e.push(typeof AudioEncoder>`u`?`AudioEncoder missing`:`AudioEncoder ready`),e.join(`, `)}function U(e){if(e.aborted)throw new DOMException(`stopped`,`AbortError`)}function pt(){return new Promise(e=>window.setTimeout(e,0))}function mt(e,t,n,r,i){e.fillStyle=`#000`,e.fillRect(0,0,t.width,t.height);let a=(t.width-t.innerWidth)/2,o=(t.height-t.innerHeight)/2;e.drawImage(n,0,0,r,i,a,o,t.innerWidth,t.innerHeight)}function ht(e,t){return e instanceof HTMLVideoElement?{w:e.videoWidth,h:e.videoHeight}:e instanceof HTMLCanvasElement?{w:e.width,h:e.height}:{w:t.width,h:t.height}}async function gt(e,t){let n=await e.source.audio();if(!n)return null;let r=Math.floor(t.start*n.sampleRate),i=Math.min(n.length,Math.ceil(t.end*n.sampleRate)),a=[];for(let e=0;e=0?`+`:``}${t.gainDb.toFixed(1)} dB${t.limited?`, held at -1 dBTP`:``})`}else r=`Loudness ${O(i)}`;return{channels:n.channels,rate:n.rate,note:r}}async function yt(e,t,n,r){if(typeof AudioEncoder>`u`)throw Error(`this browser has no AudioEncoder`);if(t!==48e3)throw Error(`audio at ${t} Hz needs resampling; the demo expects ${R} Hz`);let i={codec:`opus`,sampleRate:R,numberOfChannels:e.length,bitrate:n};if(!(await AudioEncoder.isConfigSupported(i)).supported)throw Error(`Opus encoding is not available in this browser`);let a=[],o=null,s=new AudioEncoder({output:e=>{let t=new Uint8Array(e.byteLength);e.copyTo(t),a.push({data:t,timeUs:e.timestamp,samples:Math.round((e.duration??2e4)/1e6*R)})},error:e=>{o=e}});s.configure(i);let c=e[0].length;for(let t=0;ti.set(e.subarray(t,t+n),r*960));let a=new AudioData({format:`f32-planar`,sampleRate:R,numberOfFrames:960,numberOfChannels:e.length,timestamp:Math.round(t/R*1e6),data:i});s.encode(a),a.close(),s.encodeQueueSize>12&&await pt()}if(await s.flush(),s.close(),o)throw o;return a}async function bt(e){if(typeof VideoEncoder>`u`)throw Error(`this browser has no WebCodecs VideoEncoder`);let{source:t,preset:n,settings:r}=e;if(t.kind!==`video`)throw Error(`this source has no picture`);let i=H(t,n,r),a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`),s=r.codec===`vp8`?[`vp8`]:r.codec===`vp9`?[`vp09.00.10.08`]:[`vp09.00.10.08`,`vp8`],c=``,l=null;for(let e of s){let t={codec:e,width:i.width,height:i.height,bitrate:Math.round(i.mbps*1e6),framerate:i.fps,latencyMode:`quality`,bitrateMode:`variable`};if((await VideoEncoder.isConfigSupported(t)).supported){c=e,l=t;break}}if(!l)throw Error(`neither VP9 nor VP8 encoding is available in this browser`);let u=[],d=null,f=new VideoEncoder({output:e=>{let t=new Uint8Array(e.byteLength);e.copyTo(t),u.push({track:1,timeMs:e.timestamp/1e3,key:e.type===`key`,data:t})},error:e=>{d=e}});f.configure(l);let p=performance.now(),m=Math.max(1,Math.round(i.fps*2)),h=0;for(let n=0;n6;)await pt();let u=performance.now();u-h>160&&(h=u,e.onPreview(a));let g=(u-p)/1e3;e.onProgress({fraction:(n+1)/i.frames*.92,frame:n+1,frames:i.frames,message:`${((n+1)/Math.max(g,.001)).toFixed(1)} fps`})}if(await f.flush(),f.close(),e.onPreview(a),d)throw d;let g=i.capped?`Frame size capped at ${ut} px in the browser demo`:``,_=null;if(r.audio){e.onProgress({fraction:.93,frame:i.frames,frames:i.frames,message:`Encoding audio`});let t=await vt(e,i);if(t)try{let n=await yt(t.channels,t.rate,128e3,e.signal);for(let e of n)u.push({track:2,timeMs:e.timeUs/1e3,key:!0,data:e.data});_={sampleRate:R,channels:t.channels.length,preSkip:312},g=[g,t.note].filter(Boolean).join(`. `)}catch(e){g=[g,`Audio left out: ${e.message}`].filter(Boolean).join(`. `)}}return e.onProgress({fraction:.98,frame:i.frames,frames:i.frames,message:`Writing WebM`}),{blob:Fe({codec:c===`vp8`?`V_VP8`:`V_VP9`,width:i.width,height:i.height},_,u,(i.end-i.start)*1e3),ext:I.webm,mime:L.webm,encoder:`WebCodecs ${c===`vp8`?`VP8`:`VP9`}${_?` + Opus`:``} · ${i.width}x${i.height} · ${i.fps} fps · ${i.mbps.toFixed(1)} Mb/s`,note:g}}async function xt(e){let{source:t,preset:n,settings:r}=e;if(t.kind!==`video`)throw Error(`this source has no picture`);let i=H(t,n,r),a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`,{willReadFrequently:!0}),s=new ve(i.width,i.height),c=Math.max(2,Math.round(100/i.fps));for(let n=0;n({data:e.data,samples:e.samples})),a.channels.length,312,a.rate),ext:I.ogg,mime:L.ogg,encoder:`WebCodecs Opus · ${a.channels.length} ch · 160 kb/s`,note:a.note}:{blob:t===`aiff`?He(a.channels,a.rate,r.bits):Ve(a.channels,a.rate,r.bits),ext:I[t],mime:L[t],encoder:`PCM ${r.bits}-bit · ${a.rate} Hz · ${a.channels.length} ch`,note:a.note}}async function Ct(e,t){let{source:n,preset:r,settings:i}=e;if(n.kind!==`video`)throw Error(`this source has no picture`);let a=H(n,r,i),o=document.createElement(`canvas`);o.width=a.width,o.height=a.height;let s=o.getContext(`2d`),c=await n.frame(a.start),l=ht(c,n);return mt(s,a,c,l.w,l.h),e.onPreview(o),{blob:await new Promise((e,n)=>o.toBlob(t=>t?e(t):n(Error(`the canvas could not be saved`)),L[t],.92)),ext:I[t],mime:L[t],encoder:`${t.toUpperCase()} still · ${a.width}x${a.height}`,note:``}}async function wt(e){let t=e.preset.target;if(!t)throw Error(`needs the desktop engine`);return t===`webm`?bt(e):t===`gif`?xt(e):Je.has(t)?St(e,t):Ct(e,t)}function Tt(e){return e==null||!Number.isFinite(e)?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function Et(e){if(e==null||!Number.isFinite(e)||e<0)return`--:--`;let t=Math.round(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n?`${n}:${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`:`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`}function Dt(e){return!e||!Number.isFinite(e)?``:e<60?`${e.toFixed(e<10?2:1)} s`:Et(e)}var Ot={ready:`Ready`,preparing:`Preparing`,encoding:`Encoding`,paused:`Paused`,done:`Done`,failed:`Failed`,stopped:`Stopped`,skipped:`Skipped`},W=new TextDecoder(`latin1`);async function G(e,t,n){let r=await e.slice(t,t+n).arrayBuffer();return new DataView(r)}var K=(e,t)=>W.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),kt={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},At={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},jt={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function Mt(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=K(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=K(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=K(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=K(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${kt[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=K(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=Mt(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:Nt(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Pt(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:jt[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function It(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await G(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function Vt(e){let t=await G(e,0,Math.min(e.size,64));if(t.byteLength<26||K(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Ht=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Ut=[44100,48e3,32e3];async function Wt(e){let t=await G(e,0,Math.min(e.size,65536)),n=0;if(K(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Ht[t.getUint8(r+2)>>4],o=Ut[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Gt(e){let t=[Ft,Rt,zt,Bt,Vt,Wt];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Kt=[{pack:`open-water`,file:`open-water-1280x720-30fps.mp4`,mime:`video/mp4`,kind:`video`,width:1280,height:720,fps:29.97,duration:8.008,bytes:6819433,outputs:[{preset:`match-source-medium`},{preset:`gif-480`},{preset:`png-still`}]},{pack:`coast-aerial`,file:`coast-aerial-1280x720-25fps.mp4`,mime:`video/mp4`,kind:`video`,width:1280,height:720,fps:25,duration:7,bytes:6637734,outputs:[{preset:`match-source-medium`},{preset:`gif-480`}]},{pack:`shoreline-vertical`,file:`shoreline-vertical-404x720-60fps.mp4`,mime:`video/mp4`,kind:`video`,width:404,height:720,fps:59.94,duration:7.858,bytes:4235966,outputs:[{preset:`match-source-medium`},{preset:`gif-480`,size:`source`}]},{pack:`on-the-sea-reading`,file:`on-the-sea-reading.mp3`,mime:`audio/mpeg`,kind:`audio`,width:0,height:0,fps:0,duration:21.133,bytes:211755,outputs:[{preset:`ogg-opus`,lufs:-16},{preset:`bwf-ebu`},{preset:`wav-48-24`}]}];function qt(){let e=window;return e.FE_MEDIA||={},e.FE_MEDIA}function Jt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}async function Yt(e){await Jt(e.pack);let t=qt(),n=t[e.file];if(delete t[e.file],!n)throw Error(`the media pack ${e.pack} holds no ${e.file}`);let r=atob(n),i=new Uint8Array(r.length);for(let e=0;ePromise.reject(Error(`the source is still loading`)),audio:()=>Promise.resolve(null),dispose:()=>void 0}}var Qt=0,q=new class{items=[];selectedItem=``;selectedOutput=``;running=!1;logs=[];listeners=new Map;abort=null;previews=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e)?.add(t)}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}log(e,t=!1){let n=new Date,r=[n.getHours(),n.getMinutes(),n.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`);this.logs.push({time:r,text:e,error:t}),this.logs.length>400&&this.logs.shift(),this.emit(`log`)}previewFor(e){return this.previews.get(e)}item(e){return this.items.find(t=>t.id===e)}outputOf(e){for(let t of this.items){let n=t.outputs.find(t=>t.id===e);if(n)return{item:t,output:n}}}select(e,t=``){(this.selectedItem!==e||this.selectedOutput!==t)&&(this.selectedItem=e,this.selectedOutput=t,this.emit(`select`))}makeOutput(e){let t=P.get(e);if(!t)throw Error(`unknown preset ${e}`);return{id:`out${++Qt}`,presetId:e,settings:dt(t),status:`ready`,progress:0,message:``,encoder:``,note:``,blob:null,mime:``,fileName:``,elapsed:0,fps:0,frame:0,frames:0,eta:0,speed:0}}stem(e){return e.source.name.replace(/\.[^.]+$/,``).replace(/[^A-Za-z0-9._-]+/g,`_`)||`source`}nameFor(e,t){let n=P.get(t.presetId),r=n?.target?I[n.target]:`out`;return`${this.stem(e)}_${t.presetId}.${r}`}addOutput(e,t){let n=this.item(e);if(!n)return;let r=this.makeOutput(t);return r.fileName=this.nameFor(n,r),n.outputs.push(r),n.collapsed=!1,this.log(`Added output ${P.get(t)?.name??t} to ${n.source.name}`),this.emit(`items`),r}async addSource(e,t){let n={id:e.id,source:e,probe:{container:``,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[]},loudness:null,loudnessState:`pending`,poster:null,outputs:[],collapsed:!1,loading:!1};this.items.push(n);for(let e of t){let t=this.makeOutput(e);t.fileName=this.nameFor(n,t),n.outputs.push(t)}return this.selectedItem=n.id,this.selectedOutput=``,this.log(`Added source ${e.name}`),this.emit(`items`),this.emit(`select`),n}async analyse(e,t){if(e.probe=t?await Gt(t):{container:`generated in this page (no file)`,duration:e.source.duration,size:0,bitrate:null,video:{codec:`canvas RGB`,profile:``,width:e.source.width,height:e.source.height,fps:e.source.fps,frames:Math.round(e.source.duration*e.source.fps),bitrate:null,pixels:`rgb24`},audio:[{codec:`PCM f32 (synthesised)`,sampleRate:48e3,channels:2,bitDepth:32,bitrate:null}],notes:[]},e.source.kind===`video`)try{let t=await e.source.frame(Math.min(1,e.source.duration/2)),n=document.createElement(`canvas`);n.width=640,n.height=Math.max(2,Math.round(640*e.source.height/e.source.width)),n.getContext(`2d`)?.drawImage(t,0,0,n.width,n.height),e.poster=n}catch(e){this.log(`No preview frame: ${e.message}`,!0)}this.emit(`items`),this.emit(`select`);try{let t=await e.source.audio();if(!t)e.loudnessState=`none`;else{e.probe.audio.length||e.probe.audio.push({codec:`decoded by the browser`,sampleRate:t.sampleRate,channels:t.numberOfChannels,bitDepth:null,bitrate:null}),await new Promise(e=>window.setTimeout(e,0));let n=[];for(let e=0;e{let r=this.addCuratedRow(t);e.push({item:r,index:n})}),this.selectedItem=e[0].item.id,this.emit(`select`);let t=0;for(let{item:n,index:r}of e){let e=Kt[r];try{let r=await Yt(e),i=await rt(r,e.fps||null);i.id=n.id,n.source.dispose(),n.source=i,n.loading=!1,this.emit(`items`),await this.analyse(n,r),t++}catch(t){this.log(`Could not load ${e.file}: ${t.message}`,!0),this.items=this.items.filter(e=>e.id!==n.id),this.selectedItem===n.id&&(this.selectedItem=this.items[0]?.id??``),this.emit(`items`),this.emit(`select`)}}t||(this.log(`The curated media did not load; adding the built-in sample instead`,!0),await this.addSample())}addCuratedRow(e){let t=Zt(e),n={id:t.id,source:t,probe:{container:``,duration:e.duration,size:e.bytes,bitrate:null,video:null,audio:[],notes:[]},loudness:null,loudnessState:`pending`,poster:null,outputs:[],collapsed:!1,loading:!0};this.items.push(n);for(let t of e.outputs){let e=this.makeOutput(t.preset);t.lufs!==void 0&&(e.settings.lufs=t.lufs),t.size&&(e.settings.size=t.size),e.fileName=this.nameFor(n,e),n.outputs.push(e)}return this.log(`Added source ${e.file}`),this.emit(`items`),n}async addSample(){let e=lt(),t=await this.addSource(e,[`match-source-medium`,`gif-480`,`bwf-ebu`]);await this.analyse(t,null)}removeSelected(){if(!this.running){if(this.selectedOutput){let e=this.outputOf(this.selectedOutput);e&&(e.item.outputs=e.item.outputs.filter(e=>e.id!==this.selectedOutput),this.selectedOutput=``)}else this.selectedItem&&=(this.item(this.selectedItem)?.source.dispose(),this.items=this.items.filter(e=>e.id!==this.selectedItem),this.items[0]?.id??``);this.emit(`items`),this.emit(`select`)}}resetOutput(e){e.status=`ready`,e.progress=0,e.message=``,e.blob=null,e.note=``,e.encoder=``,this.emit(`items`)}async start(){if(this.running)return;let e=[];for(let t of this.items)for(let n of t.outputs)(!t.loading&&n.status===`ready`||n.status===`failed`||n.status===`stopped`)&&e.push({item:t,out:n});if(!e.length)this.log(`Nothing to encode: every output is done`);else{this.running=!0,this.abort=new AbortController,this.emit(`run`),this.log(`Queue started: ${e.length} output${e.length===1?``:`s`}`);for(let{item:t,out:n}of e){if(this.abort.signal.aborted)break;await this.runOne(t,n,this.abort.signal)}this.running=!1,this.abort=null,this.log(`Queue finished`),this.emit(`run`)}}stop(){this.abort?.abort()}async runOne(e,t,n){let r=P.get(t.presetId);if(!r)return;if(!r.target){t.status=`skipped`,t.message=`Needs the desktop engine`,this.log(`Skipped ${t.fileName}: ${r.name} needs the desktop engine`),this.emit(`progress`,t);return}t.status=`preparing`,t.progress=0,t.message=`Preparing`,t.blob=null,t.note=``,this.emit(`progress`,t);let i=performance.now();this.log(`Encoding ${t.fileName} with ${r.name}`);try{let a=()=>{let e=this.previews.get(t.id);return e||(e=document.createElement(`canvas`),this.previews.set(t.id,e)),e},o=await wt({source:e.source,preset:r,settings:t.settings,signal:n,onProgress:n=>{let r=(performance.now()-i)/1e3;t.status=`encoding`,t.progress=n.fraction,t.frame=n.frame,t.frames=n.frames,t.elapsed=r,t.eta=n.fraction>.02?r/n.fraction*(1-n.fraction):0,t.fps=r>0?n.frame/r:0,t.speed=r>0&&e.source.fps?n.frame/e.source.fps/r:0,t.message=n.message,this.emit(`progress`,t)},onPreview:e=>{let n=a();(n.width!==e.width||n.height!==e.height)&&(n.width=e.width,n.height=e.height),n.getContext(`2d`)?.drawImage(e,0,0),this.emit(`progress`,t)}});t.blob=o.blob,t.mime=o.mime,t.fileName=t.fileName.replace(/\.[^.]+$/,`.${o.ext}`),t.encoder=o.encoder,t.note=o.note,t.status=`done`,t.progress=1,t.elapsed=(performance.now()-i)/1e3,t.eta=0,t.message=Tt(o.blob.size),this.log(`Done ${t.fileName}: ${o.encoder}${o.note?`. `+o.note:``}`)}catch(e){let n=e;n.name===`AbortError`?(t.status=`stopped`,t.message=`Stopped`,this.log(`Stopped ${t.fileName}`)):(t.status=`failed`,t.message=n.message,this.log(`Failed ${t.fileName}: ${n.message}`,!0))}this.emit(`progress`,t),this.emit(`items`)}},$t=new WeakMap;function J(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout($t.get(a)),$t.set(a,window.setTimeout(()=>a.remove(),r));return}let o=s(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();$t.set(o,window.setTimeout(()=>o.remove(),r))}var en=null,tn,nn,rn=``;function an(){let e=new _(`Preview`,760);return tn=s(`
`),nn=s(`

`),e.body.appendChild(tn),e.body.appendChild(nn),e.button(`Save`,`ghost`,()=>{rn&&on(rn)}),e.button(`Close`,`primary`,()=>e.close()),e.onClose=()=>{tn.replaceChildren(),rn=``},e}function on(e){let t=q.outputOf(e);if(!t?.output.blob){J(`This output has not been encoded yet`);return}let n=URL.createObjectURL(t.output.blob),r=document.createElement(`a`);r.href=n,r.download=t.output.fileName,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>URL.revokeObjectURL(n),4e3)}function sn(e){let n=q.outputOf(e);if(!n?.output.blob){J(`This output has not been encoded yet`);return}en??=an();let{output:r}=n,i=URL.createObjectURL(n.output.blob),a;r.mime.startsWith(`video/`)?(a=s(``),a.src=i):r.mime.startsWith(`audio/`)?(a=s(``),a.src=i):(a=s(``),a.src=i),tn.replaceChildren(a),rn=e,en.setTitle(r.fileName),t(nn,[r.encoder,r.note].filter(Boolean).join(`. `)),en.open(c(en.scrim,`.cv-btn-primary`))}var cn=class{id=`encoding`;title=`Encoding`;el;list;constructor(){this.el=s(`
${h(`film`,26)}Nothing has run yet. Press Start in the Queue.
diff --git a/demos/broadcast/assets/broadcast.js b/demos/broadcast/assets/broadcast.js index 0cb88f4..f1b7e61 100644 --- a/demos/broadcast/assets/broadcast.js +++ b/demos/broadcast/assets/broadcast.js @@ -10,7 +10,7 @@
-
`),this.areas=Object.fromEntries(ot.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,n=>{n.preventDefault(),e.setPointerCapture(n.pointerId),k(e,`is-dragging`,!0);let r={x:n.clientX,y:n.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},i=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,r.l+e.clientX-r.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,r.r-(e.clientX-r.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,r.b-(e.clientY-r.y)))),this.applySizes()},a=()=>{k(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,i),e.removeEventListener(`pointerup`,a),this.save()};e.addEventListener(`pointermove`,i),e.addEventListener(`pointerup`,a)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,n=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${n}px`),k(this.el,`no-left`,!e),k(this.el,`no-right`,!t),k(this.el,`no-bottom`,!n);for(let e of at){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ot){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new st(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(R);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??L[e]??L.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(R),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(R,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(R)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(R)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??L[e]??L.Default,e),this.save()}resetWorkspace(){this.applyLayout(L[this.workspace]??L.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(R)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(R,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ot)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new st(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,k(this.el,`is-maximized`,!1),k(e.el,`is-max`,!1)):(this.maximized&&k(this.maximized.el,`is-max`,!1),this.maximized=e,k(this.el,`is-maximized`,!0),k(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&k(t.el,`is-focused`,!1),this.focused=e;let n=this.find(e);n&&k(n.el,`is-focused`,!0),this.onFocus?.(e)}},lt={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},ut=`studio`,dt=`#f2545b`,ft=`formencoder_ui_settings`,pt=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function mt(){try{let e=localStorage.getItem(ft);if(e){let t=JSON.parse(e);return{theme:t.theme&<[t.theme]?t.theme:ut,accentColor:t.accentColor||`#f2545b`,intensity:pt(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:ut,accentColor:dt,intensity:1}}function ht(e){try{let t=localStorage.getItem(ft),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(ft,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function gt(e=mt()){let t=document.documentElement,n=lt[e.theme]||lt.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(pt(e.intensity))),t.style.setProperty(`--accent-tint`,vt(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,vt(e.accentColor,.1))}function _t(e){let t={...mt(),theme:e};ht(t),gt(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function vt(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var yt=new WeakMap;function bt(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout(yt.get(a)),yt.set(a,window.setTimeout(()=>a.remove(),r));return}let o=A(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();yt.set(o,window.setTimeout(()=>o.remove(),r))}var xt=`0.8.4`;function St(e){let t=.7071752369554196,n=Math.tan(Math.PI*1681.974450955533/e),r=10**(3.999843853973347/20),i=r**.4996667741545416,a=1+n/t+n*n;return{b0:(r+i*n/t+n*n)/a,b1:2*(n*n-r)/a,b2:(r-i*n/t+n*n)/a,a1:2*(n*n-1)/a,a2:(1-n/t+n*n)/a}}function Ct(e){let t=.5003270373238773,n=Math.tan(Math.PI*38.13547087602444/e),r=1+n/t+n*n;return{b0:1,b1:-2,b2:1,a1:2*(n*n-1)/r,a2:(1-n/t+n*n)/r}}function wt(e,t){let n=St(t),r=Ct(t),i=new Float64Array(e.length),a=0,o=0,s=0,c=0;for(let t=0;te>0?-.691+10*Math.log10(e):-1/0,Et=e=>e>0?20*Math.log10(e):-1/0;function Dt(e,t,n){let r=0;for(let i=-7;i<=8;i++){let a=t+i;if(a<0||a>=e.length)continue;let o=i-n,s=Math.abs(o)<1e-9?1:Math.sin(Math.PI*o)/(Math.PI*o);r+=e[a]*s*(.5+.5*Math.cos(Math.PI*o/9))}return r}function Ot(e){let t=0;for(let n of e)for(let e=0;et&&(t=r)}let n=t,r=t*.5;for(let t of e)for(let e=0;en&&(n=i)}return{sample:t,truePeak:n}}function kt(e,t){let n=(e.length-1)*t,r=Math.floor(n),i=Math.min(e.length-1,r+1);return e[r]+(e[i]-e[r])*(n-r)}function At(e,t){let n=new Float32Array(e.length).fill(NaN),r=0;for(let i=0;i=t&&(r-=e[i-t]),i>=t-1&&(n[i]=Tt(r/t));return n}function z(e,t){let n=e[0]?.length??0,r=Math.round(t*.1),i=Math.floor(n/r),a=new Float64Array(i);for(let n of e){let e=wt(n,t);for(let t=0;t10**((e+.691)/10),l=Array.from(o).filter(e=>Number.isFinite(e)&&e>-70),u=-1/0;if(l.length){let e=Tt(l.reduce((e,t)=>e+c(t),0)/l.length)-10,t=l.filter(t=>t>e);t.length&&(u=Tt(t.reduce((e,t)=>e+c(t),0)/t.length))}let d=Array.from(s).filter(e=>Number.isFinite(e)&&e>-70),f=0;if(d.length){let e=Tt(d.reduce((e,t)=>e+c(t),0)/d.length)-20,t=d.filter(t=>t>e).sort((e,t)=>e-t);t.length&&(f=kt(t,.95)-kt(t,.1))}let p=Ot(e),m=e=>e.reduce((e,t)=>Number.isFinite(t)&&t>e?t:e,-1/0);return{integrated:u,lra:f,samplePeak:Et(p.sample),truePeak:Et(p.truePeak),momentary:o,short:s,momentaryMax:m(o),shortMax:m(s),step:.1,duration:n/t}}function B(e,t=1){let n=Number(e.toFixed(t));return`${n>0?`+`:``}${n.toFixed(t)}`}function V(e,t=1){return Number.isFinite(e)?e.toFixed(t):`-inf`}function jt(){let e=window;return e.FE_MEDIA||={},e.FE_MEDIA}function Mt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}async function Nt(e){await Mt(e.pack);let t=jt(),n=t[e.file];if(delete t[e.file],!n)throw Error(`the media pack ${e.pack} holds no ${e.file}`);let r=atob(n),i=new Uint8Array(r.length);for(let e=0;ePt.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),Ft={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},It={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},Lt={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function Rt(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=U(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=U(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=U(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=U(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${Ft[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=U(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=Rt(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:zt(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Bt(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:Lt[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function Ht(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await H(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function qt(e){let t=await H(e,0,Math.min(e.size,64));if(t.byteLength<26||U(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Jt=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Yt=[44100,48e3,32e3];async function Xt(e){let t=await H(e,0,Math.min(e.size,65536)),n=0;if(U(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Jt[t.getUint8(r+2)>>4],o=Yt[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Zt(e){let t=[Vt,Wt,Gt,Kt,qt,Xt];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Qt=`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAACa7klEQVR42u39aZgt2XUdBq59Iu6Uw5vrvRoeUKhCASBATCIBkBRFgDMJUpIhCqJEUaREkZJMWa22P8ndn9WDZXf7k9vdbbcttU1qFkXZ1mdJptykKFIkAYKYUShUFQo1z1Wv6s053ykizu4fMe1zzj5xb76qfPWymIEvka8yb94bN26cffZee+21gKPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODpu6kFHl2Dp63F0rQ7XwTf4u6Mb/vfJ+yblGtBRQDjUC54ii5s7/pvFdz4KAG/O90fKvwm4j+6+O6OiKJrrIP9trSVrLRljGAAuXQKAS0eL/5YOAudw7lz7+RljuP78ACBJEuffL7zQY+BpFgFACwh8FAAO3+4uF725G3cb3A30ej1++umnCwCF98Ea8TfGey4DIKm+G++5l7mmLH7Ob/AO6e+W9BquM0f+m16n19hP+l4vWFt9FdV3uZCt9zh57sl9992XZFlGeAF4AS9Y8RgtQBwFgFt40RMAc/78eTMcDu3TTz+dVR8mAVgFcGY4XL/j9Okz5/v90dnV0cpbjUnX0jQ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dq8GVP/ZYPaMkbmsVKBOxb3m2rR4/cRcEUdi5YWPA4duzwdgX63ZBDgJX4eyxa6ggm/2RfI77eja8G/GbolfAQmdp7zogX/+24hHB2vbxDoSt9vtH5fxKtdBKS9lvOmJbRIDkor8qADwNFxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx614/P8BURHlBMXY6sIAAAAASUVORK5CYII=`,$t=`1 + `),this.areas=Object.fromEntries(ot.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,n=>{n.preventDefault(),e.setPointerCapture(n.pointerId),k(e,`is-dragging`,!0);let r={x:n.clientX,y:n.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},i=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,r.l+e.clientX-r.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,r.r-(e.clientX-r.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,r.b-(e.clientY-r.y)))),this.applySizes()},a=()=>{k(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,i),e.removeEventListener(`pointerup`,a),this.save()};e.addEventListener(`pointermove`,i),e.addEventListener(`pointerup`,a)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,n=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${n}px`),k(this.el,`no-left`,!e),k(this.el,`no-right`,!t),k(this.el,`no-bottom`,!n);for(let e of at){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ot){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new st(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(R);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??L[e]??L.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(R),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(R,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(R)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(R)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??L[e]??L.Default,e),this.save()}resetWorkspace(){this.applyLayout(L[this.workspace]??L.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(R)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(R,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ot)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new st(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,k(this.el,`is-maximized`,!1),k(e.el,`is-max`,!1)):(this.maximized&&k(this.maximized.el,`is-max`,!1),this.maximized=e,k(this.el,`is-maximized`,!0),k(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&k(t.el,`is-focused`,!1),this.focused=e;let n=this.find(e);n&&k(n.el,`is-focused`,!0),this.onFocus?.(e)}},lt={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},ut=`studio`,dt=`#f2545b`,ft=`formencoder_ui_settings`,pt=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function mt(){try{let e=localStorage.getItem(ft);if(e){let t=JSON.parse(e);return{theme:t.theme&<[t.theme]?t.theme:ut,accentColor:t.accentColor||`#f2545b`,intensity:pt(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:ut,accentColor:dt,intensity:1}}function ht(e){try{let t=localStorage.getItem(ft),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(ft,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function gt(e=mt()){let t=document.documentElement,n=lt[e.theme]||lt.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(pt(e.intensity))),t.style.setProperty(`--accent-tint`,vt(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,vt(e.accentColor,.1))}function _t(e){let t={...mt(),theme:e};ht(t),gt(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function vt(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var yt=new WeakMap;function bt(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout(yt.get(a)),yt.set(a,window.setTimeout(()=>a.remove(),r));return}let o=A(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();yt.set(o,window.setTimeout(()=>o.remove(),r))}var xt=`0.9.0`;function St(e){let t=.7071752369554196,n=Math.tan(Math.PI*1681.974450955533/e),r=10**(3.999843853973347/20),i=r**.4996667741545416,a=1+n/t+n*n;return{b0:(r+i*n/t+n*n)/a,b1:2*(n*n-r)/a,b2:(r-i*n/t+n*n)/a,a1:2*(n*n-1)/a,a2:(1-n/t+n*n)/a}}function Ct(e){let t=.5003270373238773,n=Math.tan(Math.PI*38.13547087602444/e),r=1+n/t+n*n;return{b0:1,b1:-2,b2:1,a1:2*(n*n-1)/r,a2:(1-n/t+n*n)/r}}function wt(e,t){let n=St(t),r=Ct(t),i=new Float64Array(e.length),a=0,o=0,s=0,c=0;for(let t=0;te>0?-.691+10*Math.log10(e):-1/0,Et=e=>e>0?20*Math.log10(e):-1/0;function Dt(e,t,n){let r=0;for(let i=-7;i<=8;i++){let a=t+i;if(a<0||a>=e.length)continue;let o=i-n,s=Math.abs(o)<1e-9?1:Math.sin(Math.PI*o)/(Math.PI*o);r+=e[a]*s*(.5+.5*Math.cos(Math.PI*o/9))}return r}function Ot(e){let t=0;for(let n of e)for(let e=0;et&&(t=r)}let n=t,r=t*.5;for(let t of e)for(let e=0;en&&(n=i)}return{sample:t,truePeak:n}}function kt(e,t){let n=(e.length-1)*t,r=Math.floor(n),i=Math.min(e.length-1,r+1);return e[r]+(e[i]-e[r])*(n-r)}function At(e,t){let n=new Float32Array(e.length).fill(NaN),r=0;for(let i=0;i=t&&(r-=e[i-t]),i>=t-1&&(n[i]=Tt(r/t));return n}function z(e,t){let n=e[0]?.length??0,r=Math.round(t*.1),i=Math.floor(n/r),a=new Float64Array(i);for(let n of e){let e=wt(n,t);for(let t=0;t10**((e+.691)/10),l=Array.from(o).filter(e=>Number.isFinite(e)&&e>-70),u=-1/0;if(l.length){let e=Tt(l.reduce((e,t)=>e+c(t),0)/l.length)-10,t=l.filter(t=>t>e);t.length&&(u=Tt(t.reduce((e,t)=>e+c(t),0)/t.length))}let d=Array.from(s).filter(e=>Number.isFinite(e)&&e>-70),f=0;if(d.length){let e=Tt(d.reduce((e,t)=>e+c(t),0)/d.length)-20,t=d.filter(t=>t>e).sort((e,t)=>e-t);t.length&&(f=kt(t,.95)-kt(t,.1))}let p=Ot(e),m=e=>e.reduce((e,t)=>Number.isFinite(t)&&t>e?t:e,-1/0);return{integrated:u,lra:f,samplePeak:Et(p.sample),truePeak:Et(p.truePeak),momentary:o,short:s,momentaryMax:m(o),shortMax:m(s),step:.1,duration:n/t}}function B(e,t=1){let n=Number(e.toFixed(t));return`${n>0?`+`:``}${n.toFixed(t)}`}function V(e,t=1){return Number.isFinite(e)?e.toFixed(t):`-inf`}function jt(){let e=window;return e.FE_MEDIA||={},e.FE_MEDIA}function Mt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}async function Nt(e){await Mt(e.pack);let t=jt(),n=t[e.file];if(delete t[e.file],!n)throw Error(`the media pack ${e.pack} holds no ${e.file}`);let r=atob(n),i=new Uint8Array(r.length);for(let e=0;ePt.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),Ft={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},It={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},Lt={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function Rt(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=U(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=U(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=U(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=U(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${Ft[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=U(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=Rt(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:zt(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Bt(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:Lt[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function Ht(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await H(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function qt(e){let t=await H(e,0,Math.min(e.size,64));if(t.byteLength<26||U(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Jt=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Yt=[44100,48e3,32e3];async function Xt(e){let t=await H(e,0,Math.min(e.size,65536)),n=0;if(U(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Jt[t.getUint8(r+2)>>4],o=Yt[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Zt(e){let t=[Vt,Wt,Gt,Kt,qt,Xt];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Qt=`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAACa7klEQVR42u39aZgt2XUdBq59Iu6Uw5vrvRoeUKhCASBATCIBkBRFgDMJUpIhCqJEUaREkZJMWa22P8ndn9WDZXf7k9vdbbcttU1qFkXZ1mdJptykKFIkAYKYUShUFQo1z1Wv6s053ykizu4fMe1zzj5xb76qfPWymIEvka8yb94bN26cffZee+21gKPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+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7VMrvVlnwmXCykos89/4t6/tcsfG6ZXd9HNKbVWYBmsioXyakYqHLwCB/XwePxMsQ6uclJQhEZtuOFv4+C5UF8N7SRP2uAGAjnBL5JVP2zPt3pvxcpvdFZOEfqJLv79cAoJUFUMoDGRQSz5Uo9RZ7ogQRf/GbjsVPtziYym/SINLhHx64mdqOr1wJCrmXzvtfVknzcRjS/TdLAMCChSi5BL4AadqR6ieRlN8sWPS079G63z9pf5ebIC03PtQpBxwLAloW4M+X+KVAoezqfubgL/Il7JCPAsAbGQxICQpaWt9V72tfvIRWFi/p2kH7rJlv5G+WI8e/Nt5PVxp/M4IOd5QEVskO/GAgvxdK8HjTLHq8yetW6qjRu75MpL6PPc9BX78bpdq8GVP/ZYPaMkbmsVKBOxb3m2rR4/cRcEUdi5YWPA4duzwdgX63ZBDgJX4eyxa6ggm/2RfI77eja8G/GbolfAQmdp7zogX/+24hHB2vbxDoSt9vtH5fxKtdBKS9lvOmJbRIDkor8qADwNFxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx614/P8BURHlBMXY6sIAAAAASUVORK5CYII=`,$t=`1 00:00:00,340 --> 00:00:03,850 She was fastened by a light chain to one of the seats on deck, diff --git a/demos/inspect/assets/inspect.js b/demos/inspect/assets/inspect.js index 6f6916a..1c5dea9 100644 --- a/demos/inspect/assets/inspect.js +++ b/demos/inspect/assets/inspect.js @@ -10,7 +10,7 @@
- `),this.areas=Object.fromEntries(ae.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,r=>{r.preventDefault(),e.setPointerCapture(r.pointerId),n(e,`is-dragging`,!0);let i={x:r.clientX,y:r.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},a=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,i.l+e.clientX-i.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,i.r-(e.clientX-i.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,i.b-(e.clientY-i.y)))),this.applySizes()},o=()=>{n(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,a),e.removeEventListener(`pointerup`,o),this.save()};e.addEventListener(`pointermove`,a),e.addEventListener(`pointerup`,o)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,r=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${r}px`),n(this.el,`no-left`,!e),n(this.el,`no-right`,!t),n(this.el,`no-bottom`,!r);for(let e of ie){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ae){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new oe(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(C);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??S[e]??S.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(C),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(C,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(C)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(C)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??S[e]??S.Default,e),this.save()}resetWorkspace(){this.applyLayout(S[this.workspace]??S.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(C)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(C,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ae)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new oe(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,n(this.el,`is-maximized`,!1),n(e.el,`is-max`,!1)):(this.maximized&&n(this.maximized.el,`is-max`,!1),this.maximized=e,n(this.el,`is-maximized`,!0),n(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&n(t.el,`is-focused`,!1),this.focused=e;let r=this.find(e);r&&n(r.el,`is-focused`,!0),this.onFocus?.(e)}},ce={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},le=`studio`,ue=`#f2545b`,de=`formencoder_ui_settings`,fe=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function pe(){try{let e=localStorage.getItem(de);if(e){let t=JSON.parse(e);return{theme:t.theme&&ce[t.theme]?t.theme:le,accentColor:t.accentColor||`#f2545b`,intensity:fe(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:le,accentColor:ue,intensity:1}}function me(e){try{let t=localStorage.getItem(de),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(de,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function he(e=pe()){let t=document.documentElement,n=ce[e.theme]||ce.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(fe(e.intensity))),t.style.setProperty(`--accent-tint`,_e(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,_e(e.accentColor,.1))}function ge(e){let t={...pe(),theme:e};me(t),he(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function _e(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var ve=`0.8.4`,ye=new WeakMap;function w(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout(ye.get(a)),ye.set(a,window.setTimeout(()=>a.remove(),r));return}let o=s(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();ye.set(o,window.setTimeout(()=>o.remove(),r))}var be=new TextDecoder(`latin1`);async function T(e,t,n){let r=await e.slice(t,t+n).arrayBuffer();return new DataView(r)}var E=(e,t)=>be.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),xe={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},Se={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},Ce={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function we(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=E(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=E(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=E(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=E(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${xe[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=E(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=we(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:Te(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Ee(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:Ce[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function Oe(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await T(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function Ne(e){let t=await T(e,0,Math.min(e.size,64));if(t.byteLength<26||E(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Pe=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Fe=[44100,48e3,32e3];async function Ie(e){let t=await T(e,0,Math.min(e.size,65536)),n=0;if(E(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Pe[t.getUint8(r+2)>>4],o=Fe[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Le(e){let t=[De,Ae,je,Me,Ne,Ie];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Re=0,ze=()=>`src${++Re}`,D=48e3;function Be(e,t,n,r=8e3){return new Promise((i,a)=>{let o=window.setTimeout(()=>{l(),a(Error(`timed out waiting for ${t}`))},r),s=()=>{l(),i()},c=()=>{l(),a(Error(`the browser cannot decode this file`))},l=()=>{window.clearTimeout(o),e.removeEventListener(t,s),e.removeEventListener(n,c)};e.addEventListener(t,s),e.addEventListener(n,c)})}async function Ve(e){if(Number.isFinite(e.duration))return e.duration;e.currentTime=1e101,await Be(e,`durationchange`,`error`,4e3).catch(()=>void 0);let t=Number.isFinite(e.duration)?e.duration:0;return e.currentTime=0,t}async function He(e){let t=e.requestVideoFrameCallback?.bind(e);if(!t)return 30;let n=[];return new Promise(r=>{let i=()=>{e.pause(),e.currentTime=0;let t=[];for(let e=1;en[e-1]&&t.push(n[e]-n[e-1]);t.sort((e,t)=>e-t);let i=1/(t.length?t[t.length>>1]:1/30),a=[12,15,23.976,24,25,29.97,30,50,59.94,60].reduce((e,t)=>Math.abs(t-i){n.push(r.mediaTime),n.length>=14?i():t(a)};t(a),e.muted=!0,e.play().catch(()=>i()),window.setTimeout(()=>{n.length<14&&i()},1500)})}async function Ue(e,t){let n=URL.createObjectURL(e),r=document.createElement(`video`);r.muted=!0,r.preload=`auto`,r.playsInline=!0,r.src=n;try{await Be(r,`loadedmetadata`,`error`)}catch(e){throw URL.revokeObjectURL(n),e}let i=await Ve(r),a=r.videoWidth>0&&r.videoHeight>0,o=a?t??await He(r):0;a&&await We(r,0);let s=null;return{id:ze(),name:e.name,kind:a?`video`:`audio`,sample:!1,size:e.size,width:r.videoWidth,height:r.videoHeight,fps:o,duration:i,async frame(e){return await We(r,Math.max(0,Math.min(e,Math.max(0,i-.001)))),r},audio(){return s||=(async()=>{if(e.size>629145600)return null;try{return await new OfflineAudioContext(2,1,D).decodeAudioData(await e.arrayBuffer())}catch{return null}})(),s},dispose(){r.removeAttribute(`src`),r.load(),URL.revokeObjectURL(n)}}}async function We(e,t){if(Math.abs(e.currentTime-t)<1e-4&&e.readyState>=2)return;let n=Be(e,`seeked`,`error`,6e3);e.currentTime=t,await n}function O(e){return e==null||!Number.isFinite(e)?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function Ge(e){if(e==null||!Number.isFinite(e)||e<0)return`--:--`;let t=Math.round(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n?`${n}:${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`:`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`}function k(e){return!e||!Number.isFinite(e)?``:e<60?`${e.toFixed(e<10?2:1)} s`:Ge(e)}function Ke(e){return Math.abs(e-29.97)<.02||Math.abs(e-59.94)<.03}function qe(e,t){let n=Math.max(1,Math.round(t)),r=Ke(t)?Math.round(n/15):0,i=Math.max(0,Math.floor(e));if(r){let e=Math.round(t*600),a=n*60-r,o=Math.floor(i/e),s=i%e;i+=r*9*o+(s>r?r*Math.floor((s-r)/a):0)}let a=i%n,o=Math.floor(i/n),s=e=>String(e).padStart(2,`0`);return`${s(Math.floor(o/3600))}:${s(Math.floor(o/60)%60)}:${s(o%60)}${r?`;`:`:`}${s(a)}`}function A(e){let t=[[23.976,`23.976`],[24,`24`],[25,`25`],[29.97,`29.97`],[30,`30`],[50,`50`],[59.94,`59.94`],[60,`60`]].find(([t])=>Math.abs(t-e)<.02);return t?t[1]:String(Number(e.toFixed(3)))}function j(e,t){if(!e||!t)return``;let n=e/t,r=[[16/9,`16:9`],[2,`2:1`],[9/16,`9:16`],[4/3,`4:3`],[1,`1:1`],[3/4,`3:4`],[21/9,`21:9`]].find(([e])=>Math.abs(e-n)/e<.01);return r?r[1]:n.toFixed(2)}function Je(e,t,n,r){return{id:e,name:t,role:n,form:r,parent:``,origin:`included`,label:``,state:`loading`,progress:0,message:``,blob:null,size:0,source:null,probe:null,gif:null,seq:null,frameBlobs:null,names:[],thumb:``,md5:``,md5State:`idle`,width:0,height:0,fps:0,frames:0,duration:0,offset:0,expect:null,checks:null,url:``}}var M=e=>e.replace(/\.[^.]+$/,``).replace(/_%0\dd$/,``),N=e=>(e.form===`video`||e.form===`sequence`)&&!!e.source&&e.state!==`loading`,P=new class{items=[];slotA=``;slotB=``;view=`compare`;zoom=`fit`;frame=0;markIn=null;markOut=null;working=``;logs=[];listeners=new Map;seq=0;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e)?.add(t)}emit(e){for(let t of this.listeners.get(e)??[])t()}log(e,t=!1){let n=new Date,r=[n.getHours(),n.getMinutes(),n.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`);this.logs.push({time:r,text:e,error:t}),this.logs.length>400&&this.logs.shift(),this.emit(`log`)}nextId(){return this.seq+=1,`m${this.seq}`}get(e){return this.items.find(t=>t.id===e)}a(){return this.get(this.slotA)}b(){return this.get(this.slotB)}master(){let e=this.a();return e&&e.fps>0?e:this.b()}sources(){return this.items.filter(e=>e.role===`source`)}outputs(){return this.items.filter(e=>e.role!==`source`)}add(e){return this.items.push(e),this.emit(`items`),e}make(e,t,n){return Je(this.nextId(),e,t,n)}setSlots(e,t){(e!==this.slotA||t!==this.slotB)&&(this.slotA=e,this.slotB=t,this.emit(`slots`))}setView(e){e!==this.view&&(this.view=e,this.emit(`view`))}setZoom(e){e!==this.zoom&&(this.zoom=e,this.emit(`view`))}setFrame(e){let t=this.master(),n=t?Math.max(0,t.frames-1):0,r=Math.max(0,Math.min(n,Math.round(e)));r!==this.frame&&(this.frame=r,this.emit(`frame`))}setMarks(e,t){this.markIn=e,this.markOut=t,this.emit(`marks`)}},Ye=e=>e?`${(e/1e6).toFixed(2)} Mb/s`:``;function Xe(e){return e.form===`sequence`?`Image sequence`:e.form===`animation`?`Animated GIF`:e.form===`archive`?`Numbered frames (ZIP)`:e.role===`proxy`?`Video, proxy`:`Video`}function Ze(e,t){let n=[],r=(e,t,r)=>{r&&n.push({key:e,label:t,value:r})};r(`kind`,`Kind`,Xe(e));let i=e.probe;if(e.form===`sequence`&&e.seq)r(`container`,`Container`,`Numbered ${e.seq.ext.slice(1).toUpperCase()} files`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.duration)),r(`vcodec`,`Video`,e.seq.ext.slice(1).toUpperCase()===`JPG`?`JPEG, intra only`:e.seq.ext.slice(1).toUpperCase()),r(`frame`,`Frame`,`${e.width}x${e.height}`),r(`shape`,`Shape`,j(e.width,e.height)),r(`rate`,`Rate`,`${A(e.fps)} fps (set when added)`),r(`frames`,`Frames`,`${e.seq.count}, ${String(e.seq.first).padStart(e.seq.digits,`0`)} to ${String(e.seq.last).padStart(e.seq.digits,`0`)}${e.seq.gaps.length?`, ${e.seq.gaps.length} missing`:`, no gaps`}`),r(`audio`,`Audio`,`None`);else if(e.form===`animation`&&e.gif)r(`container`,`Container`,`GIF89a`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.gif.duration)),r(`vcodec`,`Video`,`GIF, 256 colours`),r(`frame`,`Frame`,`${e.gif.width}x${e.gif.height}`),r(`shape`,`Shape`,j(e.gif.width,e.gif.height)),r(`rate`,`Rate`,e.gif.duration?`${A(e.gif.frames/e.gif.duration)} fps`:``),r(`frames`,`Frames`,String(e.gif.frames)),r(`audio`,`Audio`,`None`),r(`loop`,`Loop`,e.gif.loops?`Forever`:`Once`);else if(e.form===`archive`)r(`container`,`Container`,`ZIP, stored`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.duration)),r(`vcodec`,`Video`,e.seq?.ext.slice(1).toUpperCase()??``),r(`frame`,`Frame`,e.width?`${e.width}x${e.height}`:``),r(`shape`,`Shape`,j(e.width,e.height)),r(`rate`,`Rate`,e.fps?`${A(e.fps)} fps`:``),e.seq&&r(`frames`,`Frames`,`${e.seq.count}, ${String(e.seq.first).padStart(e.seq.digits,`0`)} to ${String(e.seq.last).padStart(e.seq.digits,`0`)}${e.seq.gaps.length?`, ${e.seq.gaps.length} missing`:`, no gaps`}`),r(`audio`,`Audio`,`None`);else if(i){r(`container`,`Container`,i.container),r(`size`,`Size`,O(i.size)),r(`duration`,`Duration`,k(i.duration??e.duration)),r(`bitrate`,`Bit rate`,Ye(i.bitrate)),i.video&&(r(`vcodec`,`Video`,[i.video.codec,i.video.profile].filter(Boolean).join(` `)),r(`frame`,`Frame`,`${i.video.width}x${i.video.height}`),r(`shape`,`Shape`,j(i.video.width,i.video.height)),r(`rate`,`Rate`,i.video.fps?`${A(i.video.fps)} fps`:``),r(`frames`,`Frames`,i.video.frames?String(i.video.frames):``),r(`vbit`,`Video rate`,Ye(i.video.bitrate)));let n=i.audio[0];r(`audio`,`Audio`,n?[n.codec,n.sampleRate?`${n.sampleRate} Hz`:``,n.channels?`${n.channels} ch`:``].filter(Boolean).join(`, `):`None`),r(`loud`,`Loudness`,t)}return r(`md5`,`MD5`,e.md5?`${e.md5.slice(0,12)}...`:e.md5State===`running`?`Reading`:``),n}var F=(e,t,n)=>Math.abs(e-t)<=n;function Qe(e){let t=e.expect,n=[];if(!t)return n;if(e.form===`archive`&&e.seq){let r=e.width===t.width&&e.height===t.height;return n.push({label:`Frame count`,want:String(t.frames),got:String(e.seq.count),ok:e.seq.count===t.frames}),n.push({label:`Numbers`,want:`1 to ${t.frames}`,got:`${e.seq.first} to ${e.seq.last}`,ok:e.seq.first===1&&e.seq.last===t.frames&&e.seq.gaps.length===0}),n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${e.width}x${e.height}`,ok:r}),n}if(e.form===`animation`&&e.gif)return n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${e.gif.width}x${e.gif.height}`,ok:e.gif.width===t.width&&e.gif.height===t.height}),n.push({label:`Frame rate`,want:`${A(t.fps)}`,got:e.gif.duration?`${A(e.gif.frames/e.gif.duration)}`:``,ok:e.gif.duration>0&&F(e.gif.frames/e.gif.duration,t.fps,1.6)}),n.push({label:`Duration`,want:`${t.duration.toFixed(2)} s`,got:`${e.gif.duration.toFixed(2)} s`,ok:F(e.gif.duration,t.duration,Math.max(.1,1/t.fps))}),n;let r=e.probe?.video;if(!r)return n;n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${r.width}x${r.height}`,ok:r.width===t.width&&r.height===t.height}),n.push({label:`Frame rate`,want:A(t.fps),got:r.fps?A(r.fps):``,ok:!!r.fps&&F(r.fps,t.fps,.05)});let i=e.probe?.duration??e.duration;n.push({label:`Duration`,want:`${t.duration.toFixed(2)} s`,got:`${i.toFixed(2)} s`,ok:F(i,t.duration,Math.max(.06,1.5/t.fps))}),n.push({label:`Video codec`,want:t.codec,got:r.codec,ok:r.codec.toLowerCase().replace(/\W/g,``).includes(t.codec.toLowerCase().replace(/\W/g,``))});let a=(e.probe?.audio.length??0)>0;return n.push({label:`Audio`,want:t.audio?`present`:`none`,got:a?`present`:`none`,ok:a===t.audio}),r.frames&&t.frames&&n.push({label:`Frames`,want:String(t.frames),got:String(r.frames),ok:Math.abs(r.frames-t.frames)<=1}),n}function $e(e,t){let n=e.probe?.video,r=t.probe?.video;if(!n||!r)return[];let i=(e.probe?.audio.length??0)>0,a=(t.probe?.audio.length??0)>0,o=n.frames??Math.round((e.probe?.duration??e.duration)*(n.fps??e.fps)),s=r.frames??Math.round((t.probe?.duration??t.duration)*(r.fps??t.fps));return[{label:`Same frame rate`,want:r.fps?A(r.fps):``,got:n.fps?A(n.fps):``,ok:!!n.fps&&!!r.fps&&F(n.fps,r.fps,.05)},{label:`Same frame count`,want:String(s),got:String(o),ok:!!o&&Math.abs(o-s)<=1},{label:`Same duration`,want:`${(t.probe?.duration??t.duration).toFixed(2)} s`,got:`${(e.probe?.duration??e.duration).toFixed(2)} s`,ok:F(e.probe?.duration??e.duration,t.probe?.duration??t.duration,.08)},{label:`Same shape`,want:j(r.width,r.height),got:j(n.width,n.height),ok:j(r.width,r.height)===j(n.width,n.height)},{label:`Same audio`,want:a?`present`:`none`,got:i?`present`:`none`,ok:i===a}]}function et(){let e=P.sources().filter(e=>e.state!==`loading`&&e.fps>0);if(e.length<2)return[];let t=[...new Set(e.map(e=>A(e.fps)))],n=[...new Set(e.map(e=>j(e.width,e.height)))],r=[];return r.push(`${e.length} sources, ${t.length} frame rate${t.length===1?``:`s`} (${t.join(`, `)})`),r.push(`${n.length} frame shape${n.length===1?``:`s`} (${n.join(`, `)})`),r}async function tt(e){let t=new Uint8Array(await e.arrayBuffer()),n=String.fromCharCode(...t.subarray(0,6));if(n!==`GIF89a`&&n!==`GIF87a`)return null;let r=new DataView(t.buffer),i=r.getUint16(6,!0),a=r.getUint16(8,!0),o=13+(t[10]&128?3*2**((t[10]&7)+1):0),s=0,c=0,l=!1,u=()=>{for(;o>>0;var it=class{a=1732584193;b=-271733879;c=-1732584194;d=271733878;tail=new Uint8Array(64);fill=0;total=0;w=new Int32Array(16);update(e){this.total+=e.length;let t=0;if(this.fill){let n=Math.min(64-this.fill,e.length);this.tail.set(e.subarray(0,n),this.fill),this.fill+=n,t=n,this.fill===64&&(this.block(this.tail,0),this.fill=0)}for(;t+64<=e.length;t+=64)this.block(e,t);t>4)*4+(e&3)],l=r+t+rt[e]+n[s]|0,u=i+(l<>>32-c)|0;r=o,o=a,a=i,i=u}this.a=this.a+r|0,this.b=this.b+i|0,this.c=this.c+a|0,this.d=this.d+o|0}hex(){let e=this.total*8,t=new Uint8Array((this.fill<56?56:120)-this.fill+8);t[0]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,e>>>0,!0),n.setUint32(t.length-4,Math.floor(e/4294967296),!0),this.update(t);let r=new Uint8Array(16),i=new DataView(r.buffer);return i.setInt32(0,this.a,!0),i.setInt32(4,this.b,!0),i.setInt32(8,this.c,!0),i.setInt32(12,this.d,!0),Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``)}},I=2097152;function at(){return new Promise(e=>window.setTimeout(e,0))}async function L(e,t){let n=new it;for(let r=0;rvoid 0).then(async()=>{let e=await r.frame(t);return n(e,e instanceof HTMLVideoElement?e.videoWidth:e.width,e instanceof HTMLVideoElement?e.videoHeight:e.height)});return ot.set(e.id,i),i}async function st(e,t){return(await fetch(`data:${t};base64,${e}`)).blob()}function ct(){let e=window;return e.INSPECT_MEDIA||={},e.INSPECT_MEDIA}function lt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}var ut=/^(.*?)(\d+)(\.[A-Za-z0-9]+)$/;function dt(e){let t=new Map;for(let n of e){let e=ut.exec(n.name);if(!e)continue;let r=`${e[1]}|${e[2].length}|${e[3].toLowerCase()}`;t.has(r)||t.set(r,[]),t.get(r)?.push({...n,n:Number(e[2])})}let n=null,r=``;for(let[e,i]of t)(!n||i.length>n.length)&&(n=i,r=e);if(!n||n.length<2)return null;n.sort((e,t)=>e.n-t.n);let[i,a,o]=r.split(`|`),s=new Set(n.map(e=>e.n)),c=n[0].n,l=n[n.length-1].n,u=[];for(let e=c;e<=l;e++)s.has(e)||u.push(e);return{files:n,info:{pattern:`${i}%0${a}d${o}`,first:c,last:l,count:n.length,gaps:u,digits:Number(a),ext:o}}}var ft=0;async function pt(e,t){let n=dt(e);if(!n)throw Error(`these files are not a numbered image sequence`);let r=await Promise.all(n.files.map(e=>createImageBitmap(e.blob))),i=r[0].width,a=r[0].height,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`),c=r.length/t;return{source:{id:`seq${++ft}`,name:n.info.pattern,kind:`video`,sample:!1,size:n.files.reduce((e,t)=>e+t.blob.size,0),width:i,height:a,fps:t,duration:c,async frame(e){let n=Math.max(0,Math.min(r.length-1,Math.floor(e*t+1e-6)));return s.clearRect(0,0,i,a),s.drawImage(r[n],0,0,i,a),o},audio:()=>Promise.resolve(null),dispose:()=>void 0},info:n.info,names:n.files.map(e=>e.name),width:i,height:a}}var mt=3e4/1001,ht=[{pack:`autumn-stream`,file:`autumn-stream.mp4`,role:`source`,form:`video`,parent:``,label:`Camera original, trimmed`,width:1280,height:720,fps:mt,duration:8.008,frames:240,size:6525912,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`waterfall`,file:`waterfall.mp4`,role:`source`,form:`video`,parent:``,label:`Camera original, trimmed`,width:1280,height:640,fps:24e3/1001,duration:6.006,frames:144,size:2898071,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`river-vertical`,file:`river-vertical.mp4`,role:`source`,form:`video`,parent:``,label:`Phone original, vertical`,width:404,height:720,fps:60,duration:6.15,frames:369,size:1501308,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`clouds-sequence`,file:`clouds_%04d.jpg`,role:`source`,form:`sequence`,parent:``,label:`Numbered stills, 24 fps`,width:960,height:540,fps:24,duration:1.5,frames:36,size:17e5,codec:`JPEG`,audio:!1,offset:0,type:`image/jpeg`},{pack:`autumn-stream_high`,file:`autumn-stream_high.mp4`,role:`output`,form:`video`,parent:`autumn-stream.mp4`,label:`Match Source, high: H.264 3.5 Mb/s`,width:1280,height:720,fps:mt,duration:3.003,frames:90,size:1514869,codec:`H.264`,audio:!0,offset:2.002,type:`video/mp4`},{pack:`autumn-stream_low`,file:`autumn-stream_low.mp4`,role:`output`,form:`video`,parent:`autumn-stream.mp4`,label:`Match Source, low: H.264 0.45 Mb/s`,width:1280,height:720,fps:mt,duration:3.003,frames:90,size:220648,codec:`H.264`,audio:!0,offset:2.002,type:`video/mp4`},{pack:`autumn-stream_Proxy`,file:`autumn-stream_Proxy.mp4`,role:`proxy`,form:`video`,parent:`autumn-stream.mp4`,label:`H.264 Proxy 960x540`,width:960,height:540,fps:mt,duration:8.008,frames:240,size:2922345,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`autumn-stream_480`,file:`autumn-stream_480.gif`,role:`output`,form:`animation`,parent:`autumn-stream.mp4`,label:`Animated GIF 480 px`,width:480,height:270,fps:15,duration:3,frames:45,size:892598,codec:`GIF`,audio:!1,offset:2.002,type:`image/gif`}],gt={markIn:60,markOut:149};function _t(){let e=new Map;for(let t of ht){let n=P.make(t.file,t.role,t.form);n.label=t.label,n.width=t.width,n.height=t.height,n.fps=t.fps,n.duration=t.duration,n.frames=t.frames,n.size=t.size,n.offset=t.offset,n.origin=`included`,t.role!==`source`&&(n.expect={width:t.width,height:t.height,fps:t.fps,duration:t.duration,frames:t.frames,codec:t.codec,audio:t.audio},n.parent=e.get(t.parent)?.id??``),e.set(t.file,n),P.items.push(n)}return e}async function vt(e){return R(e,e.form===`sequence`?e.duration/2:Math.min(e.duration/2,2.5),(e,t,n)=>{let r=document.createElement(`canvas`);return r.width=240,r.height=Math.max(2,Math.round(240*n/t)),r.getContext(`2d`)?.drawImage(e,0,0,r.width,r.height),r.toDataURL(`image/jpeg`,.72)})}async function yt(e,t){await lt(e.pack);let n=ct(),r=e.form===`sequence`?e.pack:e.file,i=n[r];if(delete n[r],!i)throw Error(`the pack ${e.pack} holds no ${e.file}`);if(e.form===`sequence`){let n=await Promise.all(Object.entries(i).map(async([e,t])=>({name:e,blob:await st(t,`image/jpeg`)}))),r=await pt(n,e.fps);t.source=r.source,t.seq=r.info,t.names=r.names,t.size=r.source.size,t.width=r.width,t.height=r.height,t.frames=r.info.count,t.duration=r.info.count/e.fps,t.frameBlobs=n.sort((e,t)=>e.name.localeCompare(t.name)).map(e=>e.blob)}else{let n=await st(i,e.type);if(t.blob=n,t.size=n.size,e.form===`animation`)t.gif=await tt(n),t.url=URL.createObjectURL(n);else{let r=new File([n],e.file,{type:e.type}),i=await Le(r);t.probe=i;let a=i.video?.fps&&Number.isFinite(i.video.fps)?i.video.fps:e.fps;t.source=await Ue(r,a),t.fps=a,t.width=i.video?.width??e.width,t.height=i.video?.height??e.height,t.duration=i.duration??t.source.duration,t.frames=i.video?.frames??Math.round(t.duration*a)}}t.state=`ready`}async function bt(e){if(e.source)try{e.thumb=await vt(e)}catch(t){P.log(`No thumbnail for ${e.name}: ${t.message}`,!0)}}function z(e){if(!e.expect)return;let t=Qe(e),n=P.get(e.parent);e.checks=e.role===`proxy`&&n?.probe?[...t,...$e(e,n)]:t}async function xt(){for(let e of P.items){if(!e.blob&&!e.frameBlobs||e.md5State===`done`)continue;e.md5State=`running`,P.emit(`items`);let t=performance.now();try{e.md5=e.blob?await L(e.blob):await L(new Blob(e.frameBlobs)),e.md5State=`done`,P.log(`MD5 ${e.md5} ${e.name} (${((performance.now()-t)/1e3).toFixed(1)} s)`)}catch(t){e.md5State=`idle`,P.log(`MD5 failed for ${e.name}: ${t.message}`,!0)}P.emit(`items`)}}async function St(){let e=_t();P.emit(`items`);let t=e.get(`autumn-stream.mp4`),n=e.get(`autumn-stream_low.mp4`);P.setSlots(t.id,n.id);let r=[`autumn-stream.mp4`,`autumn-stream_low.mp4`,`autumn-stream_high.mp4`,`waterfall.mp4`,`river-vertical.mp4`,`clouds_%04d.jpg`,`autumn-stream_Proxy.mp4`,`autumn-stream_480.gif`],i=0;for(let n of r){let r=ht.find(e=>e.file===n),a=e.get(n);try{await yt(r,a),i+=1,z(a),P.emit(`items`),a===t&&P.setFrame(gt.markIn+24),bt(a).then(()=>P.emit(`items`)),P.log(`Loaded ${a.name}`)}catch(e){a.state=`failed`,a.message=e.message,P.log(`Could not load ${n}: ${a.message}`,!0),P.emit(`items`)}}for(let e of P.items)e.role===`proxy`&&z(e);P.emit(`items`),i||P.log(`No curated media loaded`,!0),xt()}function B(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>URL.revokeObjectURL(n),4e3)}function Ct(e,t=`image/png`,n){return new Promise((r,i)=>e.toBlob(e=>e?r(e):i(Error(`the canvas could not be saved`)),t,n))}var wt=new Map,Tt=`md5`,Et=!1,Dt=!1,Ot={size:`Size`,md5:`MD5`,bit:`Bit for bit`};function kt(e){return e.blob?e.blob:e.frameBlobs?new Blob(e.frameBlobs):null}async function At(e,t,n){let r=kt(e);if(!r)return;let i={mode:t,srcMd5:``,copyMd5:``,ok:!1,detail:``,progress:0,running:!0,flipped:n};wt.set(e.id,i),P.emit(`items`);let a=new it,o=[],s=Math.floor(r.size*.37);for(let e=0;e=e&&s{i.progress=.5+e*.5,P.emit(`items`)}),i.ok=i.copyMd5===i.srcMd5,i.detail=i.ok?`Copy read back from storage matches`:`${i.srcMd5.slice(0,8)} against ${i.copyMd5.slice(0,8)}`;else{let e=-1;for(let t=0;te.md5).map(e=>`${e.md5} ${e.name}`).join(` + `),this.areas=Object.fromEntries(ae.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,r=>{r.preventDefault(),e.setPointerCapture(r.pointerId),n(e,`is-dragging`,!0);let i={x:r.clientX,y:r.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},a=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,i.l+e.clientX-i.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,i.r-(e.clientX-i.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,i.b-(e.clientY-i.y)))),this.applySizes()},o=()=>{n(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,a),e.removeEventListener(`pointerup`,o),this.save()};e.addEventListener(`pointermove`,a),e.addEventListener(`pointerup`,o)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,r=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${r}px`),n(this.el,`no-left`,!e),n(this.el,`no-right`,!t),n(this.el,`no-bottom`,!r);for(let e of ie){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ae){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new oe(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(C);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??S[e]??S.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(C),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(C,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(C)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(C)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??S[e]??S.Default,e),this.save()}resetWorkspace(){this.applyLayout(S[this.workspace]??S.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(C)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(C,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ae)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new oe(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,n(this.el,`is-maximized`,!1),n(e.el,`is-max`,!1)):(this.maximized&&n(this.maximized.el,`is-max`,!1),this.maximized=e,n(this.el,`is-maximized`,!0),n(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&n(t.el,`is-focused`,!1),this.focused=e;let r=this.find(e);r&&n(r.el,`is-focused`,!0),this.onFocus?.(e)}},ce={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},le=`studio`,ue=`#f2545b`,de=`formencoder_ui_settings`,fe=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function pe(){try{let e=localStorage.getItem(de);if(e){let t=JSON.parse(e);return{theme:t.theme&&ce[t.theme]?t.theme:le,accentColor:t.accentColor||`#f2545b`,intensity:fe(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:le,accentColor:ue,intensity:1}}function me(e){try{let t=localStorage.getItem(de),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(de,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function he(e=pe()){let t=document.documentElement,n=ce[e.theme]||ce.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(fe(e.intensity))),t.style.setProperty(`--accent-tint`,_e(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,_e(e.accentColor,.1))}function ge(e){let t={...pe(),theme:e};me(t),he(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function _e(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var ve=`0.9.0`,ye=new WeakMap;function w(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout(ye.get(a)),ye.set(a,window.setTimeout(()=>a.remove(),r));return}let o=s(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();ye.set(o,window.setTimeout(()=>o.remove(),r))}var be=new TextDecoder(`latin1`);async function T(e,t,n){let r=await e.slice(t,t+n).arrayBuffer();return new DataView(r)}var E=(e,t)=>be.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),xe={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},Se={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},Ce={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function we(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=E(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=E(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=E(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=E(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${xe[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=E(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=we(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:Te(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Ee(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:Ce[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function Oe(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await T(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function Ne(e){let t=await T(e,0,Math.min(e.size,64));if(t.byteLength<26||E(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Pe=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Fe=[44100,48e3,32e3];async function Ie(e){let t=await T(e,0,Math.min(e.size,65536)),n=0;if(E(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Pe[t.getUint8(r+2)>>4],o=Fe[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Le(e){let t=[De,Ae,je,Me,Ne,Ie];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Re=0,ze=()=>`src${++Re}`,D=48e3;function Be(e,t,n,r=8e3){return new Promise((i,a)=>{let o=window.setTimeout(()=>{l(),a(Error(`timed out waiting for ${t}`))},r),s=()=>{l(),i()},c=()=>{l(),a(Error(`the browser cannot decode this file`))},l=()=>{window.clearTimeout(o),e.removeEventListener(t,s),e.removeEventListener(n,c)};e.addEventListener(t,s),e.addEventListener(n,c)})}async function Ve(e){if(Number.isFinite(e.duration))return e.duration;e.currentTime=1e101,await Be(e,`durationchange`,`error`,4e3).catch(()=>void 0);let t=Number.isFinite(e.duration)?e.duration:0;return e.currentTime=0,t}async function He(e){let t=e.requestVideoFrameCallback?.bind(e);if(!t)return 30;let n=[];return new Promise(r=>{let i=()=>{e.pause(),e.currentTime=0;let t=[];for(let e=1;en[e-1]&&t.push(n[e]-n[e-1]);t.sort((e,t)=>e-t);let i=1/(t.length?t[t.length>>1]:1/30),a=[12,15,23.976,24,25,29.97,30,50,59.94,60].reduce((e,t)=>Math.abs(t-i){n.push(r.mediaTime),n.length>=14?i():t(a)};t(a),e.muted=!0,e.play().catch(()=>i()),window.setTimeout(()=>{n.length<14&&i()},1500)})}async function Ue(e,t){let n=URL.createObjectURL(e),r=document.createElement(`video`);r.muted=!0,r.preload=`auto`,r.playsInline=!0,r.src=n;try{await Be(r,`loadedmetadata`,`error`)}catch(e){throw URL.revokeObjectURL(n),e}let i=await Ve(r),a=r.videoWidth>0&&r.videoHeight>0,o=a?t??await He(r):0;a&&await We(r,0);let s=null;return{id:ze(),name:e.name,kind:a?`video`:`audio`,sample:!1,size:e.size,width:r.videoWidth,height:r.videoHeight,fps:o,duration:i,async frame(e){return await We(r,Math.max(0,Math.min(e,Math.max(0,i-.001)))),r},audio(){return s||=(async()=>{if(e.size>629145600)return null;try{return await new OfflineAudioContext(2,1,D).decodeAudioData(await e.arrayBuffer())}catch{return null}})(),s},dispose(){r.removeAttribute(`src`),r.load(),URL.revokeObjectURL(n)}}}async function We(e,t){if(Math.abs(e.currentTime-t)<1e-4&&e.readyState>=2)return;let n=Be(e,`seeked`,`error`,6e3);e.currentTime=t,await n}function O(e){return e==null||!Number.isFinite(e)?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function Ge(e){if(e==null||!Number.isFinite(e)||e<0)return`--:--`;let t=Math.round(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n?`${n}:${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`:`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`}function k(e){return!e||!Number.isFinite(e)?``:e<60?`${e.toFixed(e<10?2:1)} s`:Ge(e)}function Ke(e){return Math.abs(e-29.97)<.02||Math.abs(e-59.94)<.03}function qe(e,t){let n=Math.max(1,Math.round(t)),r=Ke(t)?Math.round(n/15):0,i=Math.max(0,Math.floor(e));if(r){let e=Math.round(t*600),a=n*60-r,o=Math.floor(i/e),s=i%e;i+=r*9*o+(s>r?r*Math.floor((s-r)/a):0)}let a=i%n,o=Math.floor(i/n),s=e=>String(e).padStart(2,`0`);return`${s(Math.floor(o/3600))}:${s(Math.floor(o/60)%60)}:${s(o%60)}${r?`;`:`:`}${s(a)}`}function A(e){let t=[[23.976,`23.976`],[24,`24`],[25,`25`],[29.97,`29.97`],[30,`30`],[50,`50`],[59.94,`59.94`],[60,`60`]].find(([t])=>Math.abs(t-e)<.02);return t?t[1]:String(Number(e.toFixed(3)))}function j(e,t){if(!e||!t)return``;let n=e/t,r=[[16/9,`16:9`],[2,`2:1`],[9/16,`9:16`],[4/3,`4:3`],[1,`1:1`],[3/4,`3:4`],[21/9,`21:9`]].find(([e])=>Math.abs(e-n)/e<.01);return r?r[1]:n.toFixed(2)}function Je(e,t,n,r){return{id:e,name:t,role:n,form:r,parent:``,origin:`included`,label:``,state:`loading`,progress:0,message:``,blob:null,size:0,source:null,probe:null,gif:null,seq:null,frameBlobs:null,names:[],thumb:``,md5:``,md5State:`idle`,width:0,height:0,fps:0,frames:0,duration:0,offset:0,expect:null,checks:null,url:``}}var M=e=>e.replace(/\.[^.]+$/,``).replace(/_%0\dd$/,``),N=e=>(e.form===`video`||e.form===`sequence`)&&!!e.source&&e.state!==`loading`,P=new class{items=[];slotA=``;slotB=``;view=`compare`;zoom=`fit`;frame=0;markIn=null;markOut=null;working=``;logs=[];listeners=new Map;seq=0;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e)?.add(t)}emit(e){for(let t of this.listeners.get(e)??[])t()}log(e,t=!1){let n=new Date,r=[n.getHours(),n.getMinutes(),n.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`);this.logs.push({time:r,text:e,error:t}),this.logs.length>400&&this.logs.shift(),this.emit(`log`)}nextId(){return this.seq+=1,`m${this.seq}`}get(e){return this.items.find(t=>t.id===e)}a(){return this.get(this.slotA)}b(){return this.get(this.slotB)}master(){let e=this.a();return e&&e.fps>0?e:this.b()}sources(){return this.items.filter(e=>e.role===`source`)}outputs(){return this.items.filter(e=>e.role!==`source`)}add(e){return this.items.push(e),this.emit(`items`),e}make(e,t,n){return Je(this.nextId(),e,t,n)}setSlots(e,t){(e!==this.slotA||t!==this.slotB)&&(this.slotA=e,this.slotB=t,this.emit(`slots`))}setView(e){e!==this.view&&(this.view=e,this.emit(`view`))}setZoom(e){e!==this.zoom&&(this.zoom=e,this.emit(`view`))}setFrame(e){let t=this.master(),n=t?Math.max(0,t.frames-1):0,r=Math.max(0,Math.min(n,Math.round(e)));r!==this.frame&&(this.frame=r,this.emit(`frame`))}setMarks(e,t){this.markIn=e,this.markOut=t,this.emit(`marks`)}},Ye=e=>e?`${(e/1e6).toFixed(2)} Mb/s`:``;function Xe(e){return e.form===`sequence`?`Image sequence`:e.form===`animation`?`Animated GIF`:e.form===`archive`?`Numbered frames (ZIP)`:e.role===`proxy`?`Video, proxy`:`Video`}function Ze(e,t){let n=[],r=(e,t,r)=>{r&&n.push({key:e,label:t,value:r})};r(`kind`,`Kind`,Xe(e));let i=e.probe;if(e.form===`sequence`&&e.seq)r(`container`,`Container`,`Numbered ${e.seq.ext.slice(1).toUpperCase()} files`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.duration)),r(`vcodec`,`Video`,e.seq.ext.slice(1).toUpperCase()===`JPG`?`JPEG, intra only`:e.seq.ext.slice(1).toUpperCase()),r(`frame`,`Frame`,`${e.width}x${e.height}`),r(`shape`,`Shape`,j(e.width,e.height)),r(`rate`,`Rate`,`${A(e.fps)} fps (set when added)`),r(`frames`,`Frames`,`${e.seq.count}, ${String(e.seq.first).padStart(e.seq.digits,`0`)} to ${String(e.seq.last).padStart(e.seq.digits,`0`)}${e.seq.gaps.length?`, ${e.seq.gaps.length} missing`:`, no gaps`}`),r(`audio`,`Audio`,`None`);else if(e.form===`animation`&&e.gif)r(`container`,`Container`,`GIF89a`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.gif.duration)),r(`vcodec`,`Video`,`GIF, 256 colours`),r(`frame`,`Frame`,`${e.gif.width}x${e.gif.height}`),r(`shape`,`Shape`,j(e.gif.width,e.gif.height)),r(`rate`,`Rate`,e.gif.duration?`${A(e.gif.frames/e.gif.duration)} fps`:``),r(`frames`,`Frames`,String(e.gif.frames)),r(`audio`,`Audio`,`None`),r(`loop`,`Loop`,e.gif.loops?`Forever`:`Once`);else if(e.form===`archive`)r(`container`,`Container`,`ZIP, stored`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.duration)),r(`vcodec`,`Video`,e.seq?.ext.slice(1).toUpperCase()??``),r(`frame`,`Frame`,e.width?`${e.width}x${e.height}`:``),r(`shape`,`Shape`,j(e.width,e.height)),r(`rate`,`Rate`,e.fps?`${A(e.fps)} fps`:``),e.seq&&r(`frames`,`Frames`,`${e.seq.count}, ${String(e.seq.first).padStart(e.seq.digits,`0`)} to ${String(e.seq.last).padStart(e.seq.digits,`0`)}${e.seq.gaps.length?`, ${e.seq.gaps.length} missing`:`, no gaps`}`),r(`audio`,`Audio`,`None`);else if(i){r(`container`,`Container`,i.container),r(`size`,`Size`,O(i.size)),r(`duration`,`Duration`,k(i.duration??e.duration)),r(`bitrate`,`Bit rate`,Ye(i.bitrate)),i.video&&(r(`vcodec`,`Video`,[i.video.codec,i.video.profile].filter(Boolean).join(` `)),r(`frame`,`Frame`,`${i.video.width}x${i.video.height}`),r(`shape`,`Shape`,j(i.video.width,i.video.height)),r(`rate`,`Rate`,i.video.fps?`${A(i.video.fps)} fps`:``),r(`frames`,`Frames`,i.video.frames?String(i.video.frames):``),r(`vbit`,`Video rate`,Ye(i.video.bitrate)));let n=i.audio[0];r(`audio`,`Audio`,n?[n.codec,n.sampleRate?`${n.sampleRate} Hz`:``,n.channels?`${n.channels} ch`:``].filter(Boolean).join(`, `):`None`),r(`loud`,`Loudness`,t)}return r(`md5`,`MD5`,e.md5?`${e.md5.slice(0,12)}...`:e.md5State===`running`?`Reading`:``),n}var F=(e,t,n)=>Math.abs(e-t)<=n;function Qe(e){let t=e.expect,n=[];if(!t)return n;if(e.form===`archive`&&e.seq){let r=e.width===t.width&&e.height===t.height;return n.push({label:`Frame count`,want:String(t.frames),got:String(e.seq.count),ok:e.seq.count===t.frames}),n.push({label:`Numbers`,want:`1 to ${t.frames}`,got:`${e.seq.first} to ${e.seq.last}`,ok:e.seq.first===1&&e.seq.last===t.frames&&e.seq.gaps.length===0}),n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${e.width}x${e.height}`,ok:r}),n}if(e.form===`animation`&&e.gif)return n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${e.gif.width}x${e.gif.height}`,ok:e.gif.width===t.width&&e.gif.height===t.height}),n.push({label:`Frame rate`,want:`${A(t.fps)}`,got:e.gif.duration?`${A(e.gif.frames/e.gif.duration)}`:``,ok:e.gif.duration>0&&F(e.gif.frames/e.gif.duration,t.fps,1.6)}),n.push({label:`Duration`,want:`${t.duration.toFixed(2)} s`,got:`${e.gif.duration.toFixed(2)} s`,ok:F(e.gif.duration,t.duration,Math.max(.1,1/t.fps))}),n;let r=e.probe?.video;if(!r)return n;n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${r.width}x${r.height}`,ok:r.width===t.width&&r.height===t.height}),n.push({label:`Frame rate`,want:A(t.fps),got:r.fps?A(r.fps):``,ok:!!r.fps&&F(r.fps,t.fps,.05)});let i=e.probe?.duration??e.duration;n.push({label:`Duration`,want:`${t.duration.toFixed(2)} s`,got:`${i.toFixed(2)} s`,ok:F(i,t.duration,Math.max(.06,1.5/t.fps))}),n.push({label:`Video codec`,want:t.codec,got:r.codec,ok:r.codec.toLowerCase().replace(/\W/g,``).includes(t.codec.toLowerCase().replace(/\W/g,``))});let a=(e.probe?.audio.length??0)>0;return n.push({label:`Audio`,want:t.audio?`present`:`none`,got:a?`present`:`none`,ok:a===t.audio}),r.frames&&t.frames&&n.push({label:`Frames`,want:String(t.frames),got:String(r.frames),ok:Math.abs(r.frames-t.frames)<=1}),n}function $e(e,t){let n=e.probe?.video,r=t.probe?.video;if(!n||!r)return[];let i=(e.probe?.audio.length??0)>0,a=(t.probe?.audio.length??0)>0,o=n.frames??Math.round((e.probe?.duration??e.duration)*(n.fps??e.fps)),s=r.frames??Math.round((t.probe?.duration??t.duration)*(r.fps??t.fps));return[{label:`Same frame rate`,want:r.fps?A(r.fps):``,got:n.fps?A(n.fps):``,ok:!!n.fps&&!!r.fps&&F(n.fps,r.fps,.05)},{label:`Same frame count`,want:String(s),got:String(o),ok:!!o&&Math.abs(o-s)<=1},{label:`Same duration`,want:`${(t.probe?.duration??t.duration).toFixed(2)} s`,got:`${(e.probe?.duration??e.duration).toFixed(2)} s`,ok:F(e.probe?.duration??e.duration,t.probe?.duration??t.duration,.08)},{label:`Same shape`,want:j(r.width,r.height),got:j(n.width,n.height),ok:j(r.width,r.height)===j(n.width,n.height)},{label:`Same audio`,want:a?`present`:`none`,got:i?`present`:`none`,ok:i===a}]}function et(){let e=P.sources().filter(e=>e.state!==`loading`&&e.fps>0);if(e.length<2)return[];let t=[...new Set(e.map(e=>A(e.fps)))],n=[...new Set(e.map(e=>j(e.width,e.height)))],r=[];return r.push(`${e.length} sources, ${t.length} frame rate${t.length===1?``:`s`} (${t.join(`, `)})`),r.push(`${n.length} frame shape${n.length===1?``:`s`} (${n.join(`, `)})`),r}async function tt(e){let t=new Uint8Array(await e.arrayBuffer()),n=String.fromCharCode(...t.subarray(0,6));if(n!==`GIF89a`&&n!==`GIF87a`)return null;let r=new DataView(t.buffer),i=r.getUint16(6,!0),a=r.getUint16(8,!0),o=13+(t[10]&128?3*2**((t[10]&7)+1):0),s=0,c=0,l=!1,u=()=>{for(;o>>0;var it=class{a=1732584193;b=-271733879;c=-1732584194;d=271733878;tail=new Uint8Array(64);fill=0;total=0;w=new Int32Array(16);update(e){this.total+=e.length;let t=0;if(this.fill){let n=Math.min(64-this.fill,e.length);this.tail.set(e.subarray(0,n),this.fill),this.fill+=n,t=n,this.fill===64&&(this.block(this.tail,0),this.fill=0)}for(;t+64<=e.length;t+=64)this.block(e,t);t>4)*4+(e&3)],l=r+t+rt[e]+n[s]|0,u=i+(l<>>32-c)|0;r=o,o=a,a=i,i=u}this.a=this.a+r|0,this.b=this.b+i|0,this.c=this.c+a|0,this.d=this.d+o|0}hex(){let e=this.total*8,t=new Uint8Array((this.fill<56?56:120)-this.fill+8);t[0]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,e>>>0,!0),n.setUint32(t.length-4,Math.floor(e/4294967296),!0),this.update(t);let r=new Uint8Array(16),i=new DataView(r.buffer);return i.setInt32(0,this.a,!0),i.setInt32(4,this.b,!0),i.setInt32(8,this.c,!0),i.setInt32(12,this.d,!0),Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``)}},I=2097152;function at(){return new Promise(e=>window.setTimeout(e,0))}async function L(e,t){let n=new it;for(let r=0;rvoid 0).then(async()=>{let e=await r.frame(t);return n(e,e instanceof HTMLVideoElement?e.videoWidth:e.width,e instanceof HTMLVideoElement?e.videoHeight:e.height)});return ot.set(e.id,i),i}async function st(e,t){return(await fetch(`data:${t};base64,${e}`)).blob()}function ct(){let e=window;return e.INSPECT_MEDIA||={},e.INSPECT_MEDIA}function lt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}var ut=/^(.*?)(\d+)(\.[A-Za-z0-9]+)$/;function dt(e){let t=new Map;for(let n of e){let e=ut.exec(n.name);if(!e)continue;let r=`${e[1]}|${e[2].length}|${e[3].toLowerCase()}`;t.has(r)||t.set(r,[]),t.get(r)?.push({...n,n:Number(e[2])})}let n=null,r=``;for(let[e,i]of t)(!n||i.length>n.length)&&(n=i,r=e);if(!n||n.length<2)return null;n.sort((e,t)=>e.n-t.n);let[i,a,o]=r.split(`|`),s=new Set(n.map(e=>e.n)),c=n[0].n,l=n[n.length-1].n,u=[];for(let e=c;e<=l;e++)s.has(e)||u.push(e);return{files:n,info:{pattern:`${i}%0${a}d${o}`,first:c,last:l,count:n.length,gaps:u,digits:Number(a),ext:o}}}var ft=0;async function pt(e,t){let n=dt(e);if(!n)throw Error(`these files are not a numbered image sequence`);let r=await Promise.all(n.files.map(e=>createImageBitmap(e.blob))),i=r[0].width,a=r[0].height,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`),c=r.length/t;return{source:{id:`seq${++ft}`,name:n.info.pattern,kind:`video`,sample:!1,size:n.files.reduce((e,t)=>e+t.blob.size,0),width:i,height:a,fps:t,duration:c,async frame(e){let n=Math.max(0,Math.min(r.length-1,Math.floor(e*t+1e-6)));return s.clearRect(0,0,i,a),s.drawImage(r[n],0,0,i,a),o},audio:()=>Promise.resolve(null),dispose:()=>void 0},info:n.info,names:n.files.map(e=>e.name),width:i,height:a}}var mt=3e4/1001,ht=[{pack:`autumn-stream`,file:`autumn-stream.mp4`,role:`source`,form:`video`,parent:``,label:`Camera original, trimmed`,width:1280,height:720,fps:mt,duration:8.008,frames:240,size:6525912,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`waterfall`,file:`waterfall.mp4`,role:`source`,form:`video`,parent:``,label:`Camera original, trimmed`,width:1280,height:640,fps:24e3/1001,duration:6.006,frames:144,size:2898071,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`river-vertical`,file:`river-vertical.mp4`,role:`source`,form:`video`,parent:``,label:`Phone original, vertical`,width:404,height:720,fps:60,duration:6.15,frames:369,size:1501308,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`clouds-sequence`,file:`clouds_%04d.jpg`,role:`source`,form:`sequence`,parent:``,label:`Numbered stills, 24 fps`,width:960,height:540,fps:24,duration:1.5,frames:36,size:17e5,codec:`JPEG`,audio:!1,offset:0,type:`image/jpeg`},{pack:`autumn-stream_high`,file:`autumn-stream_high.mp4`,role:`output`,form:`video`,parent:`autumn-stream.mp4`,label:`Match Source, high: H.264 3.5 Mb/s`,width:1280,height:720,fps:mt,duration:3.003,frames:90,size:1514869,codec:`H.264`,audio:!0,offset:2.002,type:`video/mp4`},{pack:`autumn-stream_low`,file:`autumn-stream_low.mp4`,role:`output`,form:`video`,parent:`autumn-stream.mp4`,label:`Match Source, low: H.264 0.45 Mb/s`,width:1280,height:720,fps:mt,duration:3.003,frames:90,size:220648,codec:`H.264`,audio:!0,offset:2.002,type:`video/mp4`},{pack:`autumn-stream_Proxy`,file:`autumn-stream_Proxy.mp4`,role:`proxy`,form:`video`,parent:`autumn-stream.mp4`,label:`H.264 Proxy 960x540`,width:960,height:540,fps:mt,duration:8.008,frames:240,size:2922345,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`autumn-stream_480`,file:`autumn-stream_480.gif`,role:`output`,form:`animation`,parent:`autumn-stream.mp4`,label:`Animated GIF 480 px`,width:480,height:270,fps:15,duration:3,frames:45,size:892598,codec:`GIF`,audio:!1,offset:2.002,type:`image/gif`}],gt={markIn:60,markOut:149};function _t(){let e=new Map;for(let t of ht){let n=P.make(t.file,t.role,t.form);n.label=t.label,n.width=t.width,n.height=t.height,n.fps=t.fps,n.duration=t.duration,n.frames=t.frames,n.size=t.size,n.offset=t.offset,n.origin=`included`,t.role!==`source`&&(n.expect={width:t.width,height:t.height,fps:t.fps,duration:t.duration,frames:t.frames,codec:t.codec,audio:t.audio},n.parent=e.get(t.parent)?.id??``),e.set(t.file,n),P.items.push(n)}return e}async function vt(e){return R(e,e.form===`sequence`?e.duration/2:Math.min(e.duration/2,2.5),(e,t,n)=>{let r=document.createElement(`canvas`);return r.width=240,r.height=Math.max(2,Math.round(240*n/t)),r.getContext(`2d`)?.drawImage(e,0,0,r.width,r.height),r.toDataURL(`image/jpeg`,.72)})}async function yt(e,t){await lt(e.pack);let n=ct(),r=e.form===`sequence`?e.pack:e.file,i=n[r];if(delete n[r],!i)throw Error(`the pack ${e.pack} holds no ${e.file}`);if(e.form===`sequence`){let n=await Promise.all(Object.entries(i).map(async([e,t])=>({name:e,blob:await st(t,`image/jpeg`)}))),r=await pt(n,e.fps);t.source=r.source,t.seq=r.info,t.names=r.names,t.size=r.source.size,t.width=r.width,t.height=r.height,t.frames=r.info.count,t.duration=r.info.count/e.fps,t.frameBlobs=n.sort((e,t)=>e.name.localeCompare(t.name)).map(e=>e.blob)}else{let n=await st(i,e.type);if(t.blob=n,t.size=n.size,e.form===`animation`)t.gif=await tt(n),t.url=URL.createObjectURL(n);else{let r=new File([n],e.file,{type:e.type}),i=await Le(r);t.probe=i;let a=i.video?.fps&&Number.isFinite(i.video.fps)?i.video.fps:e.fps;t.source=await Ue(r,a),t.fps=a,t.width=i.video?.width??e.width,t.height=i.video?.height??e.height,t.duration=i.duration??t.source.duration,t.frames=i.video?.frames??Math.round(t.duration*a)}}t.state=`ready`}async function bt(e){if(e.source)try{e.thumb=await vt(e)}catch(t){P.log(`No thumbnail for ${e.name}: ${t.message}`,!0)}}function z(e){if(!e.expect)return;let t=Qe(e),n=P.get(e.parent);e.checks=e.role===`proxy`&&n?.probe?[...t,...$e(e,n)]:t}async function xt(){for(let e of P.items){if(!e.blob&&!e.frameBlobs||e.md5State===`done`)continue;e.md5State=`running`,P.emit(`items`);let t=performance.now();try{e.md5=e.blob?await L(e.blob):await L(new Blob(e.frameBlobs)),e.md5State=`done`,P.log(`MD5 ${e.md5} ${e.name} (${((performance.now()-t)/1e3).toFixed(1)} s)`)}catch(t){e.md5State=`idle`,P.log(`MD5 failed for ${e.name}: ${t.message}`,!0)}P.emit(`items`)}}async function St(){let e=_t();P.emit(`items`);let t=e.get(`autumn-stream.mp4`),n=e.get(`autumn-stream_low.mp4`);P.setSlots(t.id,n.id);let r=[`autumn-stream.mp4`,`autumn-stream_low.mp4`,`autumn-stream_high.mp4`,`waterfall.mp4`,`river-vertical.mp4`,`clouds_%04d.jpg`,`autumn-stream_Proxy.mp4`,`autumn-stream_480.gif`],i=0;for(let n of r){let r=ht.find(e=>e.file===n),a=e.get(n);try{await yt(r,a),i+=1,z(a),P.emit(`items`),a===t&&P.setFrame(gt.markIn+24),bt(a).then(()=>P.emit(`items`)),P.log(`Loaded ${a.name}`)}catch(e){a.state=`failed`,a.message=e.message,P.log(`Could not load ${n}: ${a.message}`,!0),P.emit(`items`)}}for(let e of P.items)e.role===`proxy`&&z(e);P.emit(`items`),i||P.log(`No curated media loaded`,!0),xt()}function B(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>URL.revokeObjectURL(n),4e3)}function Ct(e,t=`image/png`,n){return new Promise((r,i)=>e.toBlob(e=>e?r(e):i(Error(`the canvas could not be saved`)),t,n))}var wt=new Map,Tt=`md5`,Et=!1,Dt=!1,Ot={size:`Size`,md5:`MD5`,bit:`Bit for bit`};function kt(e){return e.blob?e.blob:e.frameBlobs?new Blob(e.frameBlobs):null}async function At(e,t,n){let r=kt(e);if(!r)return;let i={mode:t,srcMd5:``,copyMd5:``,ok:!1,detail:``,progress:0,running:!0,flipped:n};wt.set(e.id,i),P.emit(`items`);let a=new it,o=[],s=Math.floor(r.size*.37);for(let e=0;e=e&&s{i.progress=.5+e*.5,P.emit(`items`)}),i.ok=i.copyMd5===i.srcMd5,i.detail=i.ok?`Copy read back from storage matches`:`${i.srcMd5.slice(0,8)} against ${i.copyMd5.slice(0,8)}`;else{let e=-1;for(let t=0;te.md5).map(e=>`${e.md5} ${e.name}`).join(` `)+` `}async function Nt(e){let n=await e.text(),r=[];for(let e of n.split(/\r?\n/)){let t=/^([a-fA-F0-9]{32})\s+\*?(.+?)\s*$/.exec(e);if(!t)continue;let n=P.items.find(e=>e.name===t[2]);n?n.md5?n.md5===t[1].toLowerCase()?r.push([`ok`,t[2],`OK`]):r.push([`bad`,t[2],`FAILED, listed ${t[1].slice(0,8)}, file ${n.md5.slice(0,8)}`]):r.push([`missing`,t[2],`not read yet`]):r.push([`missing`,t[2],`no file of that name is loaded`])}let i=new v(`Check ${e.name}`,560),a=s(`
`);r.length||a.appendChild(s(`

No MD5 lines were found. Each line is a 32 character hash, two spaces and a file name.

`));for(let[e,n,i]of r){let r=s(`
`);t(c(r,`.ins-report-name`),n),t(c(r,`.ins-report-text`),i),a.appendChild(r)}i.body.appendChild(a);let o=r.filter(e=>e[0]!==`ok`).length;P.log(`Checked ${e.name}: ${r.length-o} of ${r.length} match`,o>0),i.button(`Close`,`primary`,()=>i.close()),i.open()}var Pt=class{id=`checksums`;title=`Ingest and Checksums`;el;list;constructor(){this.el=s(`
diff --git a/form-functions.json b/form-functions.json index 3bf084c..b64a8f1 100644 --- a/form-functions.json +++ b/form-functions.json @@ -2,7 +2,7 @@ "format": "form-functions", "format_version": 1, "app": "formencoder", - "app_version": "0.8.0", + "app_version": "0.9.0", "functions": [ { "id": "encode", diff --git a/frontend/package-lock.json b/frontend/package-lock.json index d25fa2f..0e13edd 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formencoder", - "version": "0.8.4", + "version": "0.9.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formencoder", - "version": "0.8.4", + "version": "0.9.0", "license": "Apache-2.0", "dependencies": { "@fontsource/inter": "5.3.0", diff --git a/frontend/package.json b/frontend/package.json index bc4eff2..5340036 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formencoder", "private": true, - "version": "0.8.4", + "version": "0.9.0", "description": "formencoder · the media encoder of the form family", "license": "Apache-2.0", "type": "module", diff --git a/frontend/src/version.ts b/frontend/src/version.ts index 73f389f..b336f57 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.8.4'; +export const VERSION = '0.9.0'; diff --git a/native/Cargo.lock b/native/Cargo.lock index 4d4af21..c5ed463 100644 --- a/native/Cargo.lock +++ b/native/Cargo.lock @@ -157,7 +157,7 @@ dependencies = [ [[package]] name = "fencoder-commands" -version = "0.8.4" +version = "0.9.0" dependencies = [ "fencoder-core", "fencoder-engine", @@ -170,7 +170,7 @@ dependencies = [ [[package]] name = "fencoder-core" -version = "0.8.4" +version = "0.9.0" dependencies = [ "ab_glyph", "chrono", @@ -183,7 +183,7 @@ dependencies = [ [[package]] name = "fencoder-engine" -version = "0.8.4" +version = "0.9.0" dependencies = [ "fencoder-core", "fencoder-io", @@ -194,7 +194,7 @@ dependencies = [ [[package]] name = "fencoder-io" -version = "0.8.4" +version = "0.9.0" dependencies = [ "chrono", "fencoder-core", @@ -207,7 +207,7 @@ dependencies = [ [[package]] name = "fencoder-plan" -version = "0.8.4" +version = "0.9.0" dependencies = [ "chrono", "fencoder-core", @@ -218,7 +218,7 @@ dependencies = [ [[package]] name = "fencoder-py" -version = "0.8.4" +version = "0.9.0" dependencies = [ "fencoder-commands", "fencoder-core", @@ -232,7 +232,7 @@ dependencies = [ [[package]] name = "fencoder-run" -version = "0.8.4" +version = "0.9.0" dependencies = [ "fencoder-core", "fencoder-io", diff --git a/native/Cargo.toml b/native/Cargo.toml index b485adf..77cae2f 100644 --- a/native/Cargo.toml +++ b/native/Cargo.toml @@ -11,7 +11,7 @@ members = [ ] [workspace.package] -version = "0.8.4" +version = "0.9.0" edition = "2024" rust-version = "1.95" license = "Apache-2.0" diff --git a/native/fencoder-py/pyproject.toml b/native/fencoder-py/pyproject.toml index 7704988..4196a0c 100644 --- a/native/fencoder-py/pyproject.toml +++ b/native/fencoder-py/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "fe-core" -version = "0.8.4" +version = "0.9.0" description = "formencoder's own encoding engine for the formencoder engine service" license = { text = "Apache-2.0" } requires-python = ">=3.10" diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index c207e57..b87538c 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -893,7 +893,7 @@ dependencies = [ [[package]] name = "formencoder" -version = "0.8.4" +version = "0.9.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index ee5a977..c1ea6b7 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formencoder" -version = "0.8.4" +version = "0.9.0" description = "formencoder desktop shell" authors = ["NodeAgentc, Inc."] license = "Apache-2.0" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index a050e87..b301fef 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormEncoder", - "version": "0.8.4", + "version": "0.9.0", "identifier": "dev.formai.formencoder", "build": { "frontendDist": "../frontend/dist" From 4a62c9819a05ec00aaf5c98e55c753db8b7dd678 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:08 -0500 Subject: [PATCH 19/30] feat(dock): the family's shared dock module 2.1.0 is in the tree, unchanged The 15 files of frontend/src/dock are copied byte for byte from FormVis at 8bbdf61b. Nothing uses them yet. --- frontend/src/dock/CONTRACT.md | 61 +++ frontend/src/dock/MANIFEST.json | 20 + frontend/src/dock/adapter.ts | 158 ++++++++ frontend/src/dock/chat.ts | 340 ++++++++++++++++ frontend/src/dock/consent.ts | 149 +++++++ frontend/src/dock/dock.css | 131 ++++++ frontend/src/dock/dock.ts | 683 ++++++++++++++++++++++++++++++++ frontend/src/dock/dom.ts | 27 ++ frontend/src/dock/icons.ts | 21 + frontend/src/dock/keys.ts | 35 ++ frontend/src/dock/placement.ts | 166 ++++++++ frontend/src/dock/state.ts | 45 +++ frontend/src/dock/strings.ts | 114 ++++++ frontend/src/dock/terminal.ts | 88 ++++ frontend/src/dock/tour.ts | 182 +++++++++ 15 files changed, 2220 insertions(+) create mode 100644 frontend/src/dock/CONTRACT.md create mode 100644 frontend/src/dock/MANIFEST.json create mode 100644 frontend/src/dock/adapter.ts create mode 100644 frontend/src/dock/chat.ts create mode 100644 frontend/src/dock/consent.ts create mode 100644 frontend/src/dock/dock.css create mode 100644 frontend/src/dock/dock.ts create mode 100644 frontend/src/dock/dom.ts create mode 100644 frontend/src/dock/icons.ts create mode 100644 frontend/src/dock/keys.ts create mode 100644 frontend/src/dock/placement.ts create mode 100644 frontend/src/dock/state.ts create mode 100644 frontend/src/dock/strings.ts create mode 100644 frontend/src/dock/terminal.ts create mode 100644 frontend/src/dock/tour.ts diff --git a/frontend/src/dock/CONTRACT.md b/frontend/src/dock/CONTRACT.md new file mode 100644 index 0000000..be1995e --- /dev/null +++ b/frontend/src/dock/CONTRACT.md @@ -0,0 +1,61 @@ +# The dock's engine contract + +Module version 2.1.0. This file travels with the shared dock folder and is the same in every app. + +The dock's frontend never talks to an engine. It calls the functions of `DockAdapter` (adapter.ts), and each app's adapter turns them into its engine's routes, sockets or event streams. This file says what an engine has to provide so that an adapter can deliver each function, in words that do not depend on the engine's language. Paths, header names and transports are each app's own. Where a clause says "the adapter", the engine may do the work instead; where it says "the engine", the adapter cannot make it up. + +Sixteen clauses. An engine that lacks one says so in its app's port notes and the adapter leaves the matching member out; the module then hides what depends on it. + +## Who may call + +1. **The caller.** Every route and stream acts for a caller the app identifies by its own means (a window key, a session cookie). Terminal tabs and the Chat conversation belong to that caller, and a list returns only theirs. An agent's credential is never accepted for these routes: the dock is the person's. +2. **Stream authentication is the app's.** A stream may need a one-time ticket, a first message carrying a key, or a cookie. The adapter hides this: `terminal.channel(id)` and `chat.subscribe(handlers)` may take an asynchronous step before the stream opens. A ticket is bought with the caller's own credential, is spent once and expires within a minute. + +## Terminals + +3. **The record.** `{ id, title, alive, kind }` and optionally `tip`. `id` is opaque and safe in a URL path. `kind` is one of `shell`, `claude`, `codex`, `cursor`, `agent` (a read-only tab showing an agent's commands). `title` is shown as given and is not translated. `alive: false` means the program has ended and the tab is shown struck through. `tip` is the tab's tooltip (a working folder, for example). Extra fields are ignored. `terminal.list()` returns the caller's tabs, oldest first. +4. **Open.** `terminal.open(kind, { cols, rows, prompt?, resume? })` returns the record. `cols` and `rows` are integers the engine clamps without failing. `prompt` is a first message for Claude Code: the engine may type it into a Claude Code tab that is already running and return that tab, so the module accepts an id it already has. `resume` is a Claude Code session id and always makes a new tab. The prompt may be a program argument; a token never is. +5. **Restart.** `terminal.restart(id)` keeps the id, starts the program again and clears the screen. The engine either keeps the stream open across the restart or ends it; the module opens a new channel when the old one has closed. An engine with no restart leaves the function out and the button is not shown. +6. **Close.** `terminal.close(id)` kills the program, is safe to repeat, and succeeds for an id that is already gone. +7. **The channel, engine to window.** `onData` delivers the program's output as text or as bytes, undecoded by the engine; a character may be split across two deliveries when bytes are used. On every attach the engine first replays its scrollback (how much is its choice), and reports `onExit` at once if the program has already ended. `onExit` is an event and nothing is printed for it. The engine sends something on every attach (an empty replay counts if the adapter reports it), because a channel that closes before any data is how the module decides that the engine did not answer. +8. **The channel, window to engine.** `send(text)` is what the person typed, as the terminal emulator encodes it; `resize(cols, rows)` follows every change of size. How these travel (JSON frames, binary frames, separate requests) is between the adapter and the engine. The engine ignores what it does not understand. +9. **The channel, the rest.** Several attachments to one tab are allowed and each gets the replay. For a reader that cannot keep up the engine drops output or closes the stream, never blocks the program. No keep-alive is required. `onClose` after the first data means "closed", whatever the reason. `close()` ends the attachment, not the program. + +## Agent programs + +10. **Status.** `agentStatus()` answers for the programs the app offers, in one request: `{ claude?, codex?, cursor? }`, each `{ installed, version, install, signedIn }`. `version` is a string or null. `install` is a command line a person can paste, never a sentence, and may be empty. `signedIn` is true, false, or null when the engine cannot tell; the module has a wording for each. A program that is left out is one the app does not offer, and the module says nothing about it. `null` for the whole answer means the engine was not reachable. The call must be cheap enough to make whenever the dock opens (cache the program's own version call); the module never makes it while the dock is closed. +11. **Launching an agent program.** The program learns the app's MCP address and a token made for that tab from its environment or from a file only the caller's user can read (mode 0600), never from its command line. A plain shell tab gets no token. The token is good only while its tab is open. The engine sets the working folder and removes its own secrets from the child's environment. + +## Chat + +12. **Chat events.** The adapter either gives its own pane (`chat.pane(host)`) and then this clause does not apply, or it gives `status`, `send`, `subscribe` and what it has of `start`, `stop`, `answer`, `modes`, `renderText`. After `subscribe`, the adapter calls `open()`, replays the conversation from its start as events, then sends `state`. Events are those of `DockChatEvent`: `state { running, state, session, mode? }` where `state` is exactly `busy` while a turn runs and any other word otherwise, and `session` is a Claude Code session id usable with resume, or null; `user { text, note? }`; `block { id, kind }` before any `delta { id, text }` for that id; `tool { id, name, summary }` then `tool_result { id, text, error }` (text may be empty); `permission { id, tool, summary }` and `permission_done { id, allowed }` only from engines that ask, which then implement `answer`; `result { ok, text, meta? }` at the end of every turn, also after `stop`; `notice { text }`; `reset` when the conversation was cleared or replaced; `meter { text, high? }` for a usage line. Ids are unique within a conversation. `send` while busy is refused with a message. `start(mode, fresh)` with `fresh` clears the conversation and the session; an engine without modes gets `null` and has no `modes`. `status()` answers `{ installed, version, signedIn, install, running, state, session }`, optionally `mode`, `lead` (a sentence to show in the empty Chat in place of the app's) and `refused` (see clause 13); null means not reachable. + +## Refusals and availability + +13. **A refusal is not an outage.** The adapter tells the module which it is, through `errors.kind(error)`: `refused` (the engine answered and said no to this caller: the message is shown as it is, and nothing suggests restarting anything), `unreachable` (no answer), `notInstalled` (the program is missing: the install line is shown), `oldEngine` (the route does not exist in this engine), `busy`. Engines use fixed codes for these rather than English text the adapter has to read. `chat.status()` may carry `refused` with the sentence to show. +14. **Availability.** The app can answer cheaply which tabs this caller may use here (`tabs()` is read at mount and on `dock.refresh()`), so a server that allows the dock only to its owner, or an operating system without a PTY, offers fewer tabs or none. `firstRun()` returning false means "not now" for the first-run guide. + +## Outside agents + +15. **Consent is optional and has two kinds.** An app that gates outside agents by a credential given on its own sign-in page provides neither `consent` nor `storedChoice`, and the module shows no dialog and no Outside agents entry. An app that asks in the window provides `consent`: each request is `{ id, agent, what, offers, always, expires?, escape?, notes? }`. `id` names one waiting call. `agent` is the program's name as the engine knows it, or empty. `what` completes "It asked to ...". `offers` lists the answers the engine can honour, from `deny`, `once`, `always`; the module shows no other. `always` says what a standing yes would cover: `agent` (this program only) or `all` (every outside agent). `expires` is when the engine stops waiting (milliseconds since the epoch). `escape: 'deny'` makes Escape a refusal; otherwise Escape leaves the request unanswered. An answer is for the request with that id and for no other. The engine must be able to say that a request is gone (its caller hung up, its time ran out, another window answered), and the adapter then calls `withdraw(id)`; after a reload of the window the adapter asks the engine which requests are still waiting and shows them again. Only the window can answer. `storedChoice` is the standing setting `ask`, `allowed` or `blocked`, kept by the engine and sealed against changes made outside the app (`changedOutside` reports a broken seal). `blocked` refuses every agent at once, with or without a window, the app's own Chat and agent tabs included. + +## Versions + +16. **A number, not a missing route.** The engine reports the contract version it implements (this file's module version) where its adapter can read it, so "this engine is too old" is decided by comparing numbers. An adapter maps an older engine onto `oldEngine` errors and onto a smaller `tabs()` set. + +## Module 2.1.0: what an adapter may now say + +Nothing an engine provides changed in 2.1.0: the sixteen clauses read as they did, and an engine that meets them for 2.0 meets them for 2.1. An adapter written for 2.0.1 compiles and behaves as before; every item here is used only by an adapter that asks for it. The one type that widened is `dock.sendChat(text)`, which now resolves to a boolean (false when nothing was sent). + +- **The app's own Chat pane is told what happens to it.** `pane(host)` is still called once, and the object it returns may have `shown()` (the dock is open and Chat is the tab in front), `hidden(why)` with `'tab'` (another tab was chosen or the Chat tab was closed) or `'dock'` (the dock was closed or its host hid it), `closed()` (the Chat tab's cross; the host element is kept and the next show is `shown()` again), `busy()` and `askTarget` (the element the guide's "how to ask" step points at). `send(text)` may answer `false`, or a promise of it, when the text was not taken. The host is `.ft-chat.is-own`, an absolutely placed box that fills the stage with `overflow: auto`; a pane that scrolls by itself fills it (`position: absolute; inset: 0` or `height: 100%`) and manages its own overflow. +- **The ask line beside an own pane**, `chat.ask`. Absent or `'none'`: no ask line on any tab. `'line'`: the module's line on every tab; on Chat the text goes to the pane's `send`, elsewhere it opens Claude Code with the text as `prompt` (clause 4). `{ send(text, tab) }`: the module's line on every tab and every submit goes to that function with the kind of the tab in front. `{ element }`: the app's own element is placed in the slot. The slot is `form.ft-dock-ask`, the same box on every tab; the root has `has-ask-line` while it shows. A busy pane or an answer of `false` leaves the text in the line. +- **First run.** The guide counts the steps it can show. A legacy reader (`placement.storage.legacy.read`) may return `seen: true` with the layout it moves, and `jsonLegacy(keys, true)` from state.ts says it for old keys that hold JSON; without that a moved layout is not taken as seen. +- **Focus at load.** When the dock is restored open before the app has revealed its window, the dock focuses once at the first `class`, `style` or `hidden` change on one of its ancestors that leaves it shown. An app that reveals itself another way (removing a cover, swapping a stylesheet) calls `dock.focus()` after its reveal. +- **Keys in capture-phase listeners.** The module stops keys at its roots in the bubble phase. An app listener in the capture phase starts with `if (dock.keeps(event)) return;`. +- **Notes of a question** (`ConsentRequest.notes`, clause 15) are shown one element each, so each is one whole sentence, already in the person's language or matchable by the app's page translator. +- **Names.** The classes, attributes and tokens an app may rely on are `DOCK_PUBLIC` in adapter.ts and nowhere else; 2.1.0 added the classes `has-ask-line`, `ft-dock-ask`, `ft-dock-ask-own`, `ft-dock-head`, `ft-dock-tab`, `ft-dock-stage`, `ft-icon`, `is-on`, `is-own` and the tokens `--dock-stage-pad`, `--dock-ask-ctl-h`, `--dock-tab-accent`, each token defaulting to the value 2.0 had written. +- **Type check.** Before a module version is cut, and as a step of every port, the folder is compiled with `noUnusedLocals`, `noUnusedParameters`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, `noImplicitOverride` and `noImplicitReturns` on. + +## The manifest + +`MANIFEST.json` in this folder lists the module version and the SHA-256 of every other file here, this one included. The source app (FormVis) writes it; every other app only checks it: read the file names and hashes from the manifest, hash each file's bytes, and fail naming any file that differs, is missing or is extra. The check is small enough to write in any language an app's tools use. diff --git a/frontend/src/dock/MANIFEST.json b/frontend/src/dock/MANIFEST.json new file mode 100644 index 0000000..fdeee27 --- /dev/null +++ b/frontend/src/dock/MANIFEST.json @@ -0,0 +1,20 @@ +{ + "module": "dock", + "version": "2.1.0", + "files": { + "CONTRACT.md": "3fa57822b0024100bd4f5db5e06525f774539c4595493da171f1bd14871d2e05", + "adapter.ts": "fe8e9212273a49ffefa37baac056bab5d499581ae78f995ab691ac9867d5fd6a", + "chat.ts": "91fef36e0ee61a1681194fe441458cd766660277718b0ba854e2960fddc5ca1b", + "consent.ts": "83873a14cb337ea679f0f372c4865428ab8cf136cecce8f8c7ab159a656c777b", + "dock.css": "7fbb58622379689a0fcf980e726a4f452ccf8d3acb394e9b6cf04f7a0c8d77d7", + "dock.ts": "d3ff0afa24c06afd6f80ba478e4b4f8e90f5a150ec9f9f96a3d4b14179b6849f", + "dom.ts": "dc2adf64e70e600f28eaa2d84eed0b4ad7deadb6e200cd489ee7abb583269e62", + "icons.ts": "a8b146eb3772621e4b4349ad143da14170d28ed3dd68aad41748dbaeb8e99988", + "keys.ts": "1adfc7daefa35b0e6eb8957250dca3926ded1c59fd51db7d60da6346caf0d561", + "placement.ts": "0f7e03ef0b720af07995111f30dcb5ed124529d44cf5cb67ae4bfb1f96c7f880", + "state.ts": "bef508e8343737f67adfbd7ae8cb8efb446968dfd4e7e0aff37da11f996955d7", + "strings.ts": "b1ad5ff88bd46e3631b12fc831fc919329ad051ba38c99927c1d5aed9eea5de8", + "terminal.ts": "8bf886a7ad4dc69323e803acc13641a66e1d8614e9b85a6a60977fa30d8a56fc", + "tour.ts": "9b72d54ece42fd15b84054e21264453207c5e73261d387110a9abf91d29586aa" + } +} diff --git a/frontend/src/dock/adapter.ts b/frontend/src/dock/adapter.ts new file mode 100644 index 0000000..59476b9 --- /dev/null +++ b/frontend/src/dock/adapter.ts @@ -0,0 +1,158 @@ +import type { DockLegacy } from './state'; +import type { StringKey } from './strings'; + +export type { DockLegacy, DockSide, DockState, DockStore } from './state'; +export type DockKind = 'shell' | 'claude' | 'codex' | 'cursor' | 'chat'; +export type DockProgram = 'claude' | 'codex' | 'cursor'; +export type PtyKind = 'shell' | 'claude' | 'codex' | 'cursor' | 'agent'; +export type ChatMode = 'ask' | 'auto-edits' | 'plan'; + +export interface DockTerminal { id: string; title: string; alive: boolean; kind: PtyKind; tip?: string } +export interface DockChannel { + send(data: string): void; + resize(cols: number, rows: number): void; + onData(handler: (data: string | Uint8Array) => void): void; + onExit(handler: () => void): void; + onClose?(handler: () => void): void; + close(): void; +} +export interface DockOpen { cols: number; rows: number; prompt?: string; resume?: string } +export interface DockProgramStatus { installed: boolean; version: string | null; install: string; signedIn: boolean | null } +export type DockAgentStatus = Partial>; +export interface DockChatStatus { + installed: boolean; + version: string | null; + signedIn: boolean | null; + install: string; + running: boolean; + state: string; + session: string | null; + mode?: ChatMode; + lead?: string; + refused?: string; +} +export interface DockChatHandlers { open(): void; event(event: DockChatEvent): void; close(): void } +export interface DockChatEngine { + status(): Promise; + send(text: string): Promise; + subscribe(handlers: DockChatHandlers): () => void; + start?(mode: ChatMode | null, fresh: boolean): Promise; + stop?(): Promise; + answer?(id: string, allow: boolean): Promise; + modes?: ChatMode[]; + renderText?(node: HTMLElement, text: string): void; +} +export type DockSent = boolean | void | Promise; +export type DockPaneHidden = 'tab' | 'dock'; +export interface DockOwnChat { + send?(text: string): DockSent; + focus?(): void; + shown?(): void; + hidden?(why: DockPaneHidden): void; + closed?(): void; + busy?(): boolean; + askTarget?: HTMLElement; +} +export interface DockOwnAsk { send?(text: string, tab: DockKind | null): DockSent; element?: HTMLElement } +export interface DockChatPane { pane(host: HTMLElement): DockOwnChat | void; ask?: 'none' | 'line' | DockOwnAsk } +export type DockChatEvent = + | { type: 'state'; running: boolean; state: string; session: string | null; mode?: ChatMode } + | { type: 'user'; text: string; note?: string } + | { type: 'reset' } + | { type: 'meter'; text: string; high?: boolean } + | { type: 'block'; id: string; kind: 'text' | 'thinking' } + | { type: 'delta'; id: string; text: string } + | { type: 'tool'; id: string; name: string; summary: string } + | { type: 'tool_result'; id: string; text: string; error: boolean } + | { type: 'permission'; id: string; tool: string; summary: string } + | { type: 'permission_done'; id: string; allowed: boolean } + | { type: 'result'; ok: boolean; text: string; meta?: string } + | { type: 'notice'; text: string }; + +export interface DockSizes { + minHeight: number; + minWidth: number; + defaultHeight: number; + defaultWidth: number; + maxHeightShare: number; + maxWidthShare: number; + keepHeight?: number; + keepWidth?: number; + maxHeight?(): number; + maxWidth?(): number; +} +export type DockErrorKind = 'refused' | 'unreachable' | 'notInstalled' | 'oldEngine' | 'busy'; +export interface DockWords { app: string; noun: string; lead: string; example: string; start?: string } +export interface DockAppTab { id: string; label: string; icon: string; mount(host: HTMLElement): void | (() => void) } +export interface DockTabs { builtin: DockKind[]; own?: DockAppTab[] } +export interface DockStorage { key: string; legacy?: DockLegacy | string[] } +export type DockPlacement = + | { mode: 'own'; storage: DockStorage; sizes: DockSizes; canDockRight?(): boolean } + | { mode: 'hosted'; request(open: boolean): void }; + +export interface DockAdapter { + words: DockWords; + strings?: Partial>; + placement: DockPlacement; + passKey?(event: KeyboardEvent): boolean; + isDockChord?(event: KeyboardEvent): boolean; + chordLabel?(): string; + tabs(): DockTabs; + classes: { iconButton: string; button: string; primaryButton: string; input: string; select: string; note: string }; + t(key: string, english: string): string; + onTheme(handler: () => void): void; + keyHeaders(): Record; + errors: { message(err: unknown): string | null; kind?(err: unknown): DockErrorKind | null }; + firstRun?(): boolean; + terminal: { + list(): Promise; + open(kind: Exclude, options: DockOpen): Promise; + restart?(id: string): Promise; + close(id: string): Promise; + channel(id: string): DockChannel | Promise; + scrollback?: number; + }; + agentStatus(): Promise; + chat?: DockChatEngine | DockChatPane; + consent?: { + subscribe(add: (request: ConsentRequest) => void, withdraw: (id: string) => void): void; + answer(id: string, choice: ConsentChoice): Promise; + }; + storedChoice?: { + get(): Promise; + set(value: StoredChoice): Promise; + }; + openSettings?(): void; +} + +export const DOCK_PUBLIC = { + classes: ['ft-dock', 'ft-consent', 'ft-tour', 'ft-term', 'ft-chat', 'ft-dock-pane', 'ft-notranslate', 'is-hosted', 'has-own-chat', 'has-no-ask', 'has-ask-line', 'ft-dock-ask', 'ft-dock-ask-own', 'ft-dock-head', 'ft-dock-tab', 'ft-dock-stage', 'ft-icon', 'is-on', 'is-own'], + rootAttributes: ['data-ft-dock', 'data-ft-dock-side', 'data-ft-dock-h', 'data-ft-dock-w'], + rootProperties: ['--ft-dock-size', '--ft-dock-wsize'], + tokens: [ + '--dock-bg', '--dock-bar-bg', '--dock-raised', '--dock-hover', '--dock-input-bg', '--dock-border', '--dock-edge', '--dock-divider', '--dock-tab-border', '--dock-outline', '--dock-scrim', + '--dock-text', '--dock-text-dim', '--dock-text-muted', '--dock-tab-text', '--dock-accent', '--dock-accent-line', '--dock-accent-ink', '--dock-danger', '--dock-danger-text', + '--dock-space-1', '--dock-space-2', '--dock-space-3', '--dock-space-4', '--dock-radius-xs', '--dock-radius-sm', '--dock-radius', '--dock-radius-md', '--dock-tab-radius', + '--dock-head-h', '--dock-tab-h', '--dock-ibtn', '--dock-ask-h', '--dock-chat-bar-h', '--dock-ctl-h', '--dock-icon', '--dock-icon-sm', '--dock-icon-xs', '--dock-icon-note', '--dock-icon-send', + '--dock-stage-pad', '--dock-ask-ctl-h', '--dock-tab-accent', + '--dock-fs-xs', '--dock-fs-sm', '--dock-fs-md', '--dock-font-mono', + '--dock-term-bg', '--dock-term-fg', '--dock-term-cursor', '--dock-term-selection', '--dock-term-font-size', '--dock-term-line-height', '--dock-term-contrast', + ], + layers: ['--z-raised', '--z-overlay'], +} as const; + +export type ConsentChoice = 'deny' | 'once' | 'always'; +export type ConsentScope = 'agent' | 'all'; +export type StoredChoice = 'ask' | 'allowed' | 'blocked'; +export interface ConsentRequest { + id: string; + agent: string; + what: string; + offers: ConsentChoice[]; + always: ConsentScope; + expires?: number; + escape?: 'deny'; + notes?: string[]; +} +export interface StoredChoiceState { value: StoredChoice; changedOutside: boolean } +export type ConsentHost = Pick; diff --git a/frontend/src/dock/chat.ts b/frontend/src/dock/chat.ts new file mode 100644 index 0000000..64d02ae --- /dev/null +++ b/frontend/src/dock/chat.ts @@ -0,0 +1,340 @@ +import type { ChatMode, DockAdapter, DockChatEngine, DockChatEvent, DockChatPane, DockChatStatus, DockOwnChat, DockPaneHidden } from './adapter'; +import { el, q, setClass, setDisabled, setHidden, setText } from './dom'; +import { dockIcon as icon } from './icons'; +import { lead as appLead, strings, type Say, type StringKey } from './strings'; + +const MODES: [ChatMode, StringKey][] = [['ask', 'modeAsk'], ['auto-edits', 'modeAuto'], ['plan', 'modePlan']]; + +function toolName(name: string): string { + return name.replace(/^mcp__/, '').replace(/__/g, ' '); +} + +export type ChatHost = Omit & { chat: DockChatEngine }; + +export interface DockChatView { + readonly root: HTMLElement; + load(): Promise; + release(): void; + isBusy(): boolean; + send(text: string): Promise; + focus?(): void; + visible?(on: boolean, why: DockPaneHidden): void; + askTarget?(): HTMLElement | undefined; +} + +export class OwnChat implements DockChatView { + readonly root: HTMLElement; + private readonly own: DockOwnChat; + private on = false; + + constructor(pane: DockChatPane) { + this.root = el(''); + this.own = pane.pane(this.root) ?? {}; + } + + load(): Promise { return Promise.resolve(); } + release(): void { this.own.closed?.(); } + isBusy(): boolean { return this.own.busy?.() === true; } + async send(text: string): Promise { + if (!this.own.send || this.isBusy()) return false; + return (await this.own.send(text)) !== false; + } + focus(): void { this.own.focus?.(); } + askTarget(): HTMLElement | undefined { return this.own.askTarget; } + visible(on: boolean, why: DockPaneHidden): void { + if (on === this.on) return; + this.on = on; + if (on) this.own.shown?.(); else this.own.hidden?.(why); + } +} + +export class ChatPane implements DockChatView { + private readonly s: Say; + readonly root: HTMLElement; + onFail: (err: unknown) => void = () => undefined; + onHandoff: (session: string) => void = () => undefined; + onBash: () => void = () => undefined; + private readonly log: HTMLElement; + private readonly empty: HTMLElement; + private readonly emptyText: HTMLElement; + private readonly install: HTMLElement; + private readonly statusEl: HTMLElement; + private readonly mode: HTMLSelectElement; + private readonly stopBtn: HTMLButtonElement; + private readonly blocks = new Map(); + private readonly tools = new Map(); + private readonly asks = new Map(); + private live: { off(): void } | null = null; + private info: DockChatStatus | null = null; + private state = 'idle'; + private running = false; + private offline = false; + private wanted = false; + private session: string | null = null; + + constructor(private readonly a: ChatHost) { + const s = strings(a); + const c = a.classes; + this.s = s; + this.root = el(``); + this.log = q(this.root, '.ft-chat-log'); + this.empty = q(this.root, '.ft-chat-empty'); + this.emptyText = q(this.root, '.ft-chat-empty-text'); + this.install = q(this.root, '.ft-chat-install'); + this.statusEl = q(this.root, '.ft-chat-status'); + this.mode = q(this.root, '.ft-chat-mode'); + this.stopBtn = q(this.root, '.ft-chat-stop'); + const offered = a.chat.modes ?? []; + for (const [value, key] of MODES) { + if (!offered.includes(value)) continue; + const o = document.createElement('option'); + o.value = value; + o.textContent = s(key); + this.mode.append(o); + } + setHidden(this.mode, offered.length === 0); + setHidden(this.stopBtn, !a.chat.stop); + q(this.root, '.ft-chat-new').addEventListener('click', () => void this.begin(true)); + q(this.root, '.ft-chat-handoff').addEventListener('click', () => void this.handoff()); + q(this.root, '.ft-chat-copy').addEventListener('click', () => { void navigator.clipboard?.writeText(this.info?.install ?? '').catch(() => undefined); }); + this.stopBtn.addEventListener('click', () => { void a.chat.stop?.().catch(() => undefined); }); + this.mode.addEventListener('change', () => { if (this.running) void this.begin(false); }); + } + + private get meter(): HTMLElement { return q(this.root, '.ft-chat-meter'); } + + isBusy(): boolean { return this.state === 'busy'; } + + async load(): Promise { + this.wanted = true; + this.connect(); + await this.refresh(); + } + + release(): void { + this.wanted = false; + const live = this.live; + this.live = null; + live?.off(); + } + + async send(text: string): Promise { + if (!text || this.state === 'busy') return false; + if (!this.running && !(await this.begin(false))) return false; + let went = true; + try { await this.a.chat.send(text); } catch (err) { + went = false; + this.note('note', this.a.errors.message(err) ?? this.s('sendFailed')); + } + this.paint(); + return went; + } + + private async refresh(): Promise { + this.info = await this.a.chat.status(); + this.offline = this.info === null; + if (this.info) { + this.running = this.info.running; + this.state = this.info.state; + this.session = this.info.session ?? this.session; + if (this.info.mode && this.mode.value !== this.info.mode && this.info.running) this.mode.value = this.info.mode; + } + this.paint(); + this.root.classList.add('is-loaded'); + } + + private paint(): void { + const s = this.s; + const i = this.info; + let status: string; + let lead: string; + if (this.offline || !i) { + status = this.a.words.start ? s('offlineStart') : s('offline'); + lead = status; + } else if (i.refused !== undefined) { + status = i.refused || s('refused'); + lead = status; + } else if (!i.installed) { + status = s('missing'); + lead = s('notInstalled'); + } else { + const parts = [`Claude Code ${i.version ?? ''}`.trim()]; + if (i.signedIn === true) parts.push(s('signedIn')); + else if (i.signedIn === false) parts.push(s('notSignedIn')); + parts.push(this.running ? (this.state === 'busy' ? s('working') : s('ready')) : s('idle')); + status = parts.join(' · '); + lead = i.lead ?? appLead(this.a); + } + setText(this.statusEl, status); + this.statusEl.title = status; + setText(this.emptyText, lead); + const missing = !!i && !i.installed; + setHidden(this.install, !missing); + if (missing) setText(q(this.install, '.ft-chat-install-cmd'), i.install); + const usable = !!i && i.installed && !this.offline; + setDisabled(this.stopBtn, !this.running); + setDisabled(this.mode, !usable); + setClass(this.root, 'is-busy', this.state === 'busy'); + } + + private connect(): void { + if (this.live) return; + const live = { off: (): void => undefined }; + this.live = live; + live.off = this.a.chat.subscribe({ + open: () => { if (this.live === live) this.wipe(); }, + event: (ev) => { if (this.live === live) this.onEvent(ev); }, + close: () => { + if (this.live !== live) return; + this.live = null; + if (this.wanted) window.setTimeout(() => { if (this.wanted && !this.live) { this.connect(); void this.refresh(); } }, 2000); + }, + }); + } + + private wipe(): void { + this.log.replaceChildren(this.empty); + setHidden(this.empty, false); + this.blocks.clear(); + this.tools.clear(); + this.asks.clear(); + } + + private async begin(fresh: boolean): Promise { + try { + await this.a.chat.start?.(this.a.chat.modes?.length ? this.mode.value as ChatMode : null, fresh); + if (fresh) this.wipe(); + return true; + } catch (err) { + this.note('note', this.a.errors.message(err) ?? this.s('notStarted')); + return false; + } + } + + private async handoff(): Promise { + const st = await this.a.chat.status(); + const session = st?.session ?? this.session; + if (!session) { this.onFail(new Error(this.s('handoffFirst'))); return; } + if ((st?.state ?? this.state) === 'busy') { this.onFail(new Error(this.s('handoffBusy'))); return; } + this.onHandoff(session); + } + + private add(cls: string): HTMLElement { + const node = el(/is-note|is-error|ft-chat-ask/.test(cls) ? `
` : `
`); + setHidden(this.empty, true); + const stick = this.log.scrollHeight - this.log.scrollTop - this.log.clientHeight < 40; + this.log.append(node); + if (stick) this.log.scrollTop = this.log.scrollHeight; + return node; + } + + private note(kind: 'user' | 'note' | 'error', text: string): void { + setText(this.add(`ft-chat-msg is-${kind}`), text); + } + + private grow(node: HTMLElement): void { + if (this.log.scrollHeight - this.log.scrollTop - this.log.clientHeight < 80 + node.clientHeight) this.log.scrollTop = this.log.scrollHeight; + } + + private onEvent(ev: DockChatEvent): void { + switch (ev.type) { + case 'state': + this.running = ev.running; + this.state = ev.state; + this.session = ev.session ?? this.session; + if (ev.running && ev.mode && this.mode.value !== ev.mode) this.mode.value = ev.mode; + this.paint(); + break; + case 'user': { + const node = this.add('ft-chat-msg is-user'); + setText(node, ev.text); + if (ev.note) { const note = el(''); setText(note, ev.note); node.append(note); } + break; + } + case 'reset': this.wipe(); break; + case 'meter': + setText(this.meter, ev.text); + setClass(this.meter, 'is-high', ev.high === true); + break; + case 'block': + if (!this.blocks.has(ev.id)) { + const node = this.add(`ft-chat-msg is-${ev.kind === 'thinking' ? 'thinking' : 'assistant'}`); + const text = document.createTextNode(''); + node.append(text); + this.blocks.set(ev.id, { node, text, raw: '' }); + } + break; + case 'delta': { + const block = this.blocks.get(ev.id); + if (!block) break; + block.raw += ev.text; + const render = this.a.chat.renderText; + if (render && block.node.classList.contains('is-assistant')) render(block.node, block.raw); else block.text.appendData(ev.text); + this.grow(block.node); + break; + } + case 'tool': this.tool(ev.id, ev.name, ev.summary); break; + case 'tool_result': { + const card = this.tools.get(ev.id); + if (!card) break; + const chip = q(card, '.ft-chat-tool'); + const out = q(card, '.ft-chat-tool-out'); + setText(out, ev.text); + setHidden(out, ev.text === '' || !ev.error); + setClass(chip, 'is-running', false); + setClass(chip, 'is-done', !ev.error); + setClass(chip, 'is-error', ev.error); + break; + } + case 'permission': this.question(ev.id, ev.tool, ev.summary); break; + case 'permission_done': { + const card = this.asks.get(ev.id); + if (!card) break; + card.classList.add('is-done'); + setText(q(card, '.ft-chat-ask-state'), ev.allowed ? this.s('allowed') : this.s('declined')); + break; + } + case 'result': + if (!ev.ok) this.note('error', ev.text || this.s('stoppedError')); + if (ev.meta) setText(this.add('ft-chat-msg is-meta'), ev.meta); + break; + case 'notice': this.note('note', ev.text); break; + } + } + + private tool(id: string, name: string, summary: string): void { + if (this.tools.has(id)) return; + const card = this.add('ft-chat-tool-card'); + const chip = el(`
${icon('terminal', 11)}
`); + const out = el(''); + setText(q(chip, '.ft-chat-tool-name'), toolName(name)); + setText(q(chip, '.ft-chat-tool-input'), summary); + chip.title = summary; + const toggle = (): void => { if (out.textContent) setHidden(out, !out.hidden); }; + chip.addEventListener('click', toggle); + chip.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle(); } }); + card.append(chip, out); + this.tools.set(id, card); + if (name === 'Bash') this.onBash(); + } + + private question(id: string, tool: string, summary: string): void { + if (this.asks.has(id)) return; + const c = this.a.classes; + const card = this.add('ft-chat-ask'); + card.append(el('
'), el(''), + el(`
`)); + setText(q(card, '.ft-chat-ask-text'), this.s('asksToUse', { tool: toolName(tool) })); + setText(q(card, '.ft-chat-ask-sum'), summary); + q(card, '.ft-chat-allow').addEventListener('click', () => { void this.a.chat.answer?.(id, true).catch(() => undefined); }); + q(card, '.ft-chat-deny').addEventListener('click', () => { void this.a.chat.answer?.(id, false).catch(() => undefined); }); + this.asks.set(id, card); + } +} diff --git a/frontend/src/dock/consent.ts b/frontend/src/dock/consent.ts new file mode 100644 index 0000000..652b41d --- /dev/null +++ b/frontend/src/dock/consent.ts @@ -0,0 +1,149 @@ +import type { ConsentChoice, ConsentHost, ConsentRequest } from './adapter'; +import { el, q, setClass, setHidden, setText } from './dom'; +import { fill, strings, type Say } from './strings'; + +const CHOICES: ConsentChoice[] = ['deny', 'once', 'always']; + +export class Consent { + private root: HTMLDialogElement | null = null; + private readonly s: Say; + private readonly queue: ConsentRequest[] = []; + private busy = false; + private opening = false; + private ours = false; + private timer = 0; + onChange: (open: boolean) => void = () => undefined; + private readonly onKey = (e: KeyboardEvent): void => { + const at = e.target as Node; + if (this.root && (this.root.contains(at) || at === document.body || at === document.documentElement)) e.stopPropagation(); + }; + + constructor(private readonly a: ConsentHost) { + this.s = strings(a); + a.consent?.subscribe((request) => this.add(request), (id) => this.withdraw(id)); + } + + get waiting(): number { return this.queue.length; } + + isOpen(): boolean { return this.root?.open === true; } + + private build(): HTMLDialogElement { + if (this.root) return this.root; + const s = this.s; + const c = this.a.classes; + const root = el(` + + `); + for (const b of root.querySelectorAll('.ft-consent-btn')) b.addEventListener('click', () => void this.pick(b.dataset.choice as ConsentChoice)); + root.addEventListener('cancel', (e) => { e.preventDefault(); this.escape(); }); + root.addEventListener('close', () => this.closed()); + document.body.append(root); + this.root = root; + return root; + } + + private add(request: ConsentRequest): void { + if (this.queue.some((r) => r.id === request.id)) return; + this.queue.push(request); + this.watch(); + void this.render(); + } + + withdraw(id: string): void { + const at = this.queue.findIndex((r) => r.id === id); + if (at < 0) return; + this.queue.splice(at, 1); + this.watch(); + void this.render(); + } + + private watch(): void { + window.clearTimeout(this.timer); + const now = Date.now(); + for (const r of this.queue.filter((x) => x.expires !== undefined && x.expires <= now)) this.queue.splice(this.queue.indexOf(r), 1); + const next = Math.min(...this.queue.map((r) => r.expires ?? Infinity)); + if (Number.isFinite(next)) this.timer = window.setTimeout(() => { this.watch(); void this.render(); }, Math.max(50, next - now)); + } + + private async render(): Promise { + const r = this.queue[0]; + if (!r) { this.shut(); return; } + const d = this.build(); + const s = this.s; + setText(q(d, '.ft-consent-title'), r.agent ? fill(s('consentTitle'), { agent: r.agent }) : s('consentTitleUnnamed')); + setText(q(d, '.ft-consent-what'), fill(s('consentWhat'), { what: r.what })); + const notes = q(d, '.ft-consent-notes'); + const lines = r.notes ?? []; + for (let i = 0; i < Math.max(lines.length, notes.children.length); i += 1) { + const line = (notes.children[i] as HTMLElement | undefined) ?? notes.appendChild(el('')); + setText(line, lines[i] ?? ''); + setHidden(line, i >= lines.length); + } + setHidden(notes, !lines.length); + const count = q(d, '.ft-consent-count'); + setText(count, fill(s('consentCount'), { n: 1, total: this.queue.length })); + setClass(count, 'is-one', this.queue.length < 2); + for (const choice of CHOICES) setHidden(q(d, `.ft-consent-${choice}`), !r.offers.includes(choice)); + setText(q(d, '.ft-consent-always'), r.always === 'all' ? s('consentAlwaysAll') : r.agent ? fill(s('consentAlways'), { agent: r.agent }) : s('consentAlwaysUnnamed')); + if (d.open || this.opening) return; + this.opening = true; + let changed = false; + try { changed = (await this.a.storedChoice?.get())?.changedOutside === true; } catch { changed = false; } + this.opening = false; + if (!this.queue.length || d.open) return; + setHidden(q(d, '.ft-consent-notice'), !changed); + window.addEventListener('keydown', this.onKey, true); + d.showModal(); + this.onChange(true); + } + + private shut(): void { + const d = this.root; + if (!d?.open) return; + this.ours = true; + d.close(); + } + + private closed(): void { + const ours = this.ours; + this.ours = false; + if (this.root?.open) return; + window.removeEventListener('keydown', this.onKey, true); + this.onChange(false); + if (ours || this.busy || !this.queue.length) return; + this.queue.shift(); + this.watch(); + void this.render(); + } + + private async pick(choice: ConsentChoice): Promise { + const r = this.queue[0]; + if (this.busy || !r || !r.offers.includes(choice)) return; + this.busy = true; + try { await this.a.consent?.answer(r.id, choice); } catch { this.busy = false; } finally { this.busy = false; } + const at = this.queue.indexOf(r); + if (at >= 0) this.queue.splice(at, 1); + this.watch(); + void this.render(); + } + + private escape(): void { + const r = this.queue[0]; + if (!r || this.busy) return; + if (r.escape === 'deny' && r.offers.includes('deny')) { void this.pick('deny'); return; } + this.queue.shift(); + this.watch(); + void this.render(); + } +} diff --git a/frontend/src/dock/dock.css b/frontend/src/dock/dock.css new file mode 100644 index 0000000..69eff56 --- /dev/null +++ b/frontend/src/dock/dock.css @@ -0,0 +1,131 @@ +.ft-dock [hidden], .ft-consent [hidden], .ft-tour [hidden] { display: none; } +.ft-dock.has-no-ask .ft-dock-ask { display: none; } +.ft-dock-pane { position: absolute; inset: 0; overflow: auto; background: var(--dock-bg); user-select: text; -webkit-user-select: text; } +.ft-icon { display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; } +.ft-icon svg { width: 100%; height: 100%; } +.ft-icon, .ft-icon-15, .ft-icon-16 { width: var(--dock-icon, 15px); height: var(--dock-icon, 15px); } +.ft-icon-14 { width: var(--dock-icon-send, 14px); height: var(--dock-icon-send, 14px); } +.ft-icon-13, .ft-dock-tab-icon { width: var(--dock-icon-sm, 13px); height: var(--dock-icon-sm, 13px); } +.ft-icon-12 { width: var(--dock-icon-note, 12px); height: var(--dock-icon-note, 12px); } +.ft-icon-11 { width: var(--dock-icon-xs, 11px); height: var(--dock-icon-xs, 11px); } + +.ft-dock { position: relative; display: flex; flex-direction: column; min-height: 0; overflow: hidden; min-width: 0; background: var(--dock-bg); border-top: 1px solid var(--dock-edge, var(--dock-border)); color: var(--dock-text); user-select: none; -webkit-user-select: none; } +:root:not([data-ft-dock="open"]) .ft-dock:not(.is-hosted) { visibility: hidden; border-top-width: 0; border-left-width: 0; } +.ft-dock.is-hosted { height: 100%; border-top-width: 0; } +.ft-dock.is-hosted .ft-dock-grip, .ft-dock.is-hosted .ft-dock-side, .ft-dock.is-hosted .ft-dock-hide { display: none; } +.ft-dock-grip.is-dragging { background: var(--dock-accent-line); } +:root[data-ft-dock-side="right"] .ft-dock { border-top: 0; border-left: 1px solid var(--dock-edge, var(--dock-border)); } +:root[data-ft-dock-side="right"] .ft-dock-grip { top: 0; bottom: 0; right: auto; width: 6px; height: auto; cursor: ew-resize; } +.ft-dock-side > span { display: inline-grid; place-items: center; } +:root[data-ft-dock-side="right"] .ft-dock-side-right, :root:not([data-ft-dock-side="right"]) .ft-dock-side-bottom { display: none; } +.ft-dock-grip { position: absolute; top: 0; left: 0; right: 0; height: 6px; cursor: ns-resize; z-index: var(--z-raised); touch-action: none; } +.ft-dock-grip:hover { background: var(--dock-accent-line); } +.ft-dock-head { flex: none; display: flex; align-items: center; gap: var(--dock-space-2); height: var(--dock-head-h); padding: 0 var(--dock-space-2); background: var(--dock-bar-bg); border-bottom: 1px solid var(--dock-divider, var(--dock-border)); min-width: 0; } +.ft-dock-tabs { display: flex; align-items: center; gap: 2px; min-width: 0; overflow-x: auto; scrollbar-width: none; } +.ft-dock-spacer { flex: 1; } +.ft-dock-tab { display: inline-flex; align-items: center; flex: none; gap: 6px; height: var(--dock-tab-h, 26px); padding: 0 6px 0 9px; border: 1px solid transparent; border-radius: var(--dock-tab-radius, 6px); background: transparent; color: var(--dock-tab-text, var(--dock-text-dim)); font: inherit; font-size: var(--dock-fs-sm); cursor: pointer; white-space: nowrap; } +.ft-dock-tab:hover { color: var(--dock-text); } +.ft-dock-tab.is-on { border-color: var(--dock-tab-border); background: var(--dock-raised); color: var(--dock-text); } +.ft-dock-tab.is-claude > .ft-icon, .ft-dock-tab.is-chat > .ft-icon, .ft-dock-tab.is-codex > .ft-icon, .ft-dock-tab.is-cursor > .ft-icon { color: var(--dock-tab-accent, var(--dock-accent)); } +.ft-dock-head .ft-dock-ibtn[hidden] { display: none; } +.ft-dock-menu { position: absolute; top: calc(var(--dock-head-h) + var(--dock-space-1)); right: var(--dock-space-2); z-index: var(--z-raised); display: flex; flex-direction: column; gap: var(--dock-space-2); width: min(340px, calc(100% - 16px)); padding: var(--dock-space-2) var(--dock-space-3); border: 1px solid var(--dock-border); border-radius: var(--dock-radius-md); background: var(--dock-bar-bg); color: var(--dock-text); font-size: var(--dock-fs-sm); user-select: text; -webkit-user-select: text; } +.ft-dock-menu[hidden], .ft-dock-menu-go[hidden], .ft-dock-menu-cmd[hidden] { display: none; } +.ft-dock-menu-row { display: flex; flex-direction: column; align-items: flex-start; gap: var(--dock-space-1); } +.ft-dock-menu-go { display: inline-flex; align-items: center; gap: 6px; } +.ft-dock-menu-how { margin: 0; line-height: 1.4; } +.ft-dock-menu-cmd { padding: var(--dock-space-1) var(--dock-space-2); border-radius: var(--dock-radius-sm); background: var(--dock-input-bg); font-family: var(--dock-font-mono); font-size: var(--dock-fs-xs); overflow-wrap: anywhere; } +.ft-dock-tab.is-agent .ft-dock-tab-title { color: var(--dock-accent-ink); } +.ft-dock-tab.is-ended .ft-dock-tab-title { text-decoration: line-through; color: var(--dock-text-muted); } +.ft-dock-tab-x { display: inline-grid; place-items: center; width: 16px; height: 16px; border-radius: var(--dock-radius-xs); color: var(--dock-text-muted); } +.ft-dock-tab-x:hover { background: var(--dock-hover); color: var(--dock-text); } +.ft-dock-head .ft-dock-ibtn { width: var(--dock-ibtn, 26px); height: var(--dock-ibtn, 26px); min-width: 0; min-height: 0; padding: 0; flex: none; } +.ft-dock-head .ft-dock-ibtn:disabled { opacity: 0.4; cursor: default; } +.ft-dock-stage { position: relative; flex: 1; min-height: 0; padding: var(--dock-stage-pad, var(--dock-space-1) var(--dock-space-2) 0); overflow: hidden; background: var(--dock-bg); } +.ft-term { height: 100%; user-select: text; -webkit-user-select: text; } +.ft-term[hidden] { display: none; } +.ft-term .xterm { height: 100%; } +.ft-term .xterm .xterm-viewport { scrollbar-width: none !important; -ms-overflow-style: none !important; background-color: transparent !important; } +.ft-term .xterm .xterm-viewport::-webkit-scrollbar { display: none !important; width: 0 !important; height: 0 !important; } +.ft-term .xterm .scrollbar, .ft-term .xterm .xterm-scrollable-element > .scrollbar, .ft-term .xterm .xterm-scrollable-element > .shadow { display: none !important; } + +.ft-dock-empty { position: absolute; inset: 0; display: grid; place-items: center; margin: 0; padding: 0 var(--dock-space-4); text-align: center; } +.ft-dock-empty[hidden], .ft-dock-note[hidden], .ft-dock-note-cmd[hidden], .ft-dock-note-copy[hidden] { display: none; } +.ft-dock-note { position: absolute; left: var(--dock-space-2); right: var(--dock-space-2); bottom: var(--dock-space-2); z-index: var(--z-raised); display: flex; align-items: center; gap: var(--dock-space-2); padding: var(--dock-space-2) var(--dock-space-3); border: 1px solid var(--dock-accent-line); border-radius: var(--dock-radius-md); background: var(--dock-bar-bg); color: var(--dock-text); font-size: var(--dock-fs-sm); line-height: 1.4; user-select: text; -webkit-user-select: text; } +.ft-dock-note-text { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; } +.ft-dock-note-cmd { flex: 0 1 auto; max-width: 50%; padding: var(--dock-space-1) var(--dock-space-2); border-radius: var(--dock-radius-sm); background: var(--dock-input-bg); font-family: var(--dock-font-mono); font-size: var(--dock-fs-xs); overflow-wrap: anywhere; } +.ft-dock-note .ft-dock-ibtn { width: 24px; height: 24px; flex: none; } +.ft-dock-ask { flex: none; display: flex; align-items: center; gap: var(--dock-space-2); height: var(--dock-ask-h, 40px); padding: 0 var(--dock-space-2); background: var(--dock-bar-bg); border-top: 1px solid var(--dock-divider, var(--dock-border)); } +.ft-dock-ask-mark { display: inline-grid; place-items: center; color: var(--dock-accent); } +.ft-dock-ask-input { flex: 1; height: var(--dock-ask-ctl-h, 28px); user-select: text; -webkit-user-select: text; } +.ft-dock-ask .ft-dock-ibtn { width: var(--dock-ask-ctl-h, 28px); height: var(--dock-ask-ctl-h, 28px); flex: none; } + +.ft-chat { position: absolute; inset: 0; display: grid; grid-template-rows: var(--dock-chat-bar-h, 36px) minmax(0, 1fr); background: var(--dock-bg); } +.ft-chat.is-own { display: block; overflow: auto; } +.ft-chat[hidden], .ft-chat.is-own[hidden], .ft-chat-mode[hidden], .ft-chat-stop[hidden] { display: none; } +.ft-dock.has-own-chat .ft-dock-ask { display: none; } +.ft-dock.has-own-chat.has-ask-line .ft-dock-ask { display: flex; } +.ft-dock-ask.has-element > .ft-dock-ask-mark, .ft-dock-ask.has-element > .ft-dock-ask-input, .ft-dock-ask.has-element > .ft-dock-ask-send { display: none; } +.ft-dock-ask-own { flex: 1 1 auto; display: flex; align-items: center; min-width: 0; height: 100%; } +.ft-chat-meter { margin: 0; flex: none; white-space: nowrap; } +.ft-chat-meter:empty { display: none; } +.ft-chat-meter.is-high { color: var(--dock-accent); } +.ft-chat-msg-note { display: block; margin-top: 2px; color: var(--dock-text-muted); font-size: var(--dock-fs-xs); } +.ft-chat-msg.is-meta { color: var(--dock-text-muted); font-size: var(--dock-fs-xs); } +.ft-chat-bar { display: flex; align-items: center; gap: var(--dock-space-2); padding: 0 var(--dock-space-3); border-bottom: 1px solid var(--dock-border); min-width: 0; } +.ft-chat-status { margin: 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ft-chat-bar .ft-chat-btn, .ft-chat-bar .ft-chat-mode { flex: none; width: auto; height: var(--dock-ctl-h, 26px); min-height: var(--dock-ctl-h, 26px); padding: 0 var(--dock-space-3); font-size: var(--dock-fs-sm); white-space: nowrap; } +.ft-chat:not(.is-loaded) .ft-chat-log { visibility: hidden; } +.ft-chat-log { overflow-y: auto; display: flex; flex-direction: column; gap: var(--dock-space-2); padding: var(--dock-space-2) var(--dock-space-3) var(--dock-space-3); font-size: var(--dock-fs-sm); user-select: text; -webkit-user-select: text; } +.ft-chat-empty { margin: auto 0; max-width: 64ch; display: flex; flex-direction: column; gap: var(--dock-space-2); } +.ft-chat-empty[hidden], .ft-chat-install[hidden], .ft-chat-tool-out[hidden] { display: none; } +.ft-chat-empty p { margin: 0; line-height: 1.45; } +.ft-chat-install { display: flex; align-items: center; gap: var(--dock-space-2); } +.ft-chat-install code { flex: 1; min-width: 0; padding: var(--dock-space-1) var(--dock-space-2); border-radius: var(--dock-radius-sm); background: var(--dock-input-bg); font-family: var(--dock-font-mono); font-size: var(--dock-fs-xs); overflow-wrap: anywhere; } +.ft-chat-msg { max-width: 82ch; white-space: pre-wrap; line-height: 1.45; overflow-wrap: anywhere; } +.ft-chat-msg.is-user { align-self: flex-end; padding: 6px 10px; border-radius: 8px; background: var(--dock-raised); color: var(--dock-text); } +.ft-chat-msg.is-assistant { align-self: flex-start; color: var(--dock-text); } +.ft-chat-msg.is-thinking, .ft-chat-msg.is-note { color: var(--dock-text-muted); font-size: var(--dock-fs-xs); } +.ft-chat-msg.is-thinking { font-style: italic; } +.ft-chat-msg.is-error { color: var(--dock-danger-text); } +.ft-chat-tool-card { display: flex; flex-direction: column; gap: 4px; align-self: flex-start; max-width: 100%; } +.ft-chat-tool { display: inline-flex; align-items: center; align-self: flex-start; gap: 6px; max-width: 100%; padding: 2px 8px; border: 1px solid var(--dock-border); border-radius: 6px; color: var(--dock-text-muted); font-family: var(--dock-font-mono); font-size: var(--dock-fs-xs); cursor: pointer; } +.ft-chat-tool-mark { display: inline-grid; place-items: center; } +.ft-chat-tool-name { color: var(--dock-text); } +.ft-chat-tool-input { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.ft-chat-tool.is-running .ft-chat-tool-mark { color: var(--dock-accent); } +.ft-chat-tool.is-error { border-color: var(--dock-danger); } +.ft-chat-tool.is-error .ft-chat-tool-mark { color: var(--dock-danger); } +.ft-chat-tool-out { margin: 0; max-height: 120px; overflow: auto; font-family: var(--dock-font-mono); font-size: var(--dock-fs-xs); white-space: pre-wrap; overflow-wrap: anywhere; color: var(--dock-text-muted); } +.ft-chat-ask { display: flex; flex-direction: column; gap: var(--dock-space-1); align-self: flex-start; max-width: 82ch; padding: var(--dock-space-2) var(--dock-space-3); border: 1px solid var(--dock-accent-line); border-radius: var(--dock-radius); background: var(--dock-bar-bg); } +.ft-chat-ask-sum { font-family: var(--dock-font-mono); font-size: var(--dock-fs-xs); white-space: pre-wrap; overflow-wrap: anywhere; color: var(--dock-text-dim); } +.ft-chat-ask-row { display: flex; align-items: center; gap: var(--dock-space-2); } +.ft-chat-ask.is-done .ft-chat-allow, .ft-chat-ask.is-done .ft-chat-deny { display: none; } +.ft-chat-ask-state { color: var(--dock-text-muted); } + +.ft-consent { margin: auto; padding: 0; border: 0; max-width: none; max-height: none; overflow: visible; background: transparent; color: var(--dock-text); } +.ft-consent::backdrop { background: var(--dock-scrim, rgba(0, 0, 0, 0.5)); } +.ft-consent-count.is-one { visibility: hidden; } +.ft-consent-notes { margin: 0; color: var(--dock-text-dim); font-size: var(--dock-fs-sm); line-height: 1.45; white-space: pre-line; overflow-wrap: anywhere; } +.ft-consent-note { display: block; } +.ft-consent-notes[hidden], .ft-consent-note[hidden], .ft-consent-btn[hidden] { display: none; } +.ft-consent-box { display: flex; flex-direction: column; gap: var(--dock-space-2); width: min(440px, calc(100vw - 32px)); padding: var(--dock-space-4); border: 1px solid var(--dock-outline, var(--dock-border)); border-radius: var(--dock-radius-md); background: var(--dock-bg); color: var(--dock-text); box-shadow: 0 18px 48px rgba(0, 0, 0, 0.45); user-select: text; -webkit-user-select: text; } +.ft-consent-title { margin: 0; font-size: var(--dock-fs-md, 15px); font-weight: 600; line-height: 1.35; } +.ft-consent-count, .ft-consent-notice { margin: 0; color: var(--dock-text-dim); font-size: var(--dock-fs-sm); } +.ft-consent-notice[hidden] { display: none; } +.ft-consent-what { margin: 0; color: var(--dock-text); font-size: var(--dock-fs-sm); line-height: 1.45; overflow-wrap: anywhere; } +.ft-consent-buttons { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: var(--dock-space-2); margin-top: var(--dock-space-2); } +.ft-consent-buttons > .ft-consent-btn { min-width: 0; max-width: 100%; overflow: hidden; text-overflow: ellipsis; } + +.ft-tour { position: fixed; inset: 0; z-index: var(--z-overlay); pointer-events: none; contain: strict; } +.ft-tour[hidden] { display: none; } +.ft-tour-ring { position: fixed; left: 0; top: 0; width: 0; height: 0; border: 2px solid var(--dock-accent); border-radius: var(--dock-radius-md); box-shadow: 0 0 0 9999px var(--dock-scrim, rgba(0, 0, 0, 0.5)); pointer-events: none; } +.ft-tour-card { position: fixed; left: 0; top: 0; display: flex; flex-direction: column; gap: var(--dock-space-2); width: min(320px, calc(100vw - 16px)); padding: var(--dock-space-3) var(--dock-space-4); border: 1px solid var(--dock-outline, var(--dock-border)); border-radius: var(--dock-radius-md); background: var(--dock-bg); color: var(--dock-text); box-shadow: 0 12px 36px rgba(0, 0, 0, 0.45); pointer-events: auto; user-select: text; -webkit-user-select: text; outline: none; } +.ft-tour-count { margin: 0; color: var(--dock-text-dim); font-size: var(--dock-fs-xs); } +.ft-tour-title { margin: 0; font-size: var(--dock-fs-md, 15px); font-weight: 600; } +.ft-tour-body { margin: 0; font-size: var(--dock-fs-sm); line-height: 1.45; } +.ft-tour-cmd { display: flex; align-items: center; gap: var(--dock-space-2); } +.ft-tour-cmd[hidden] { display: none; } +.ft-tour-cmd code { flex: 1; padding: var(--dock-space-1) var(--dock-space-2); border-radius: var(--dock-radius-sm); background: var(--dock-input-bg); font-family: var(--dock-font-mono); font-size: var(--dock-fs-xs); overflow-wrap: anywhere; } +.ft-tour-nav { display: flex; align-items: center; justify-content: flex-end; gap: var(--dock-space-2); } +.ft-tour-x { margin-right: auto; } +.ft-tour-back[hidden] { visibility: hidden; display: inline-flex; } diff --git a/frontend/src/dock/dock.ts b/frontend/src/dock/dock.ts new file mode 100644 index 0000000..84312cd --- /dev/null +++ b/frontend/src/dock/dock.ts @@ -0,0 +1,683 @@ +import type { DockAdapter, DockAgentStatus, DockAppTab, DockChannel, DockKind, DockOwnAsk, DockPaneHidden, DockTerminal, PtyKind } from './adapter'; +import { ChatPane, OwnChat, type DockChatView } from './chat'; +import { Consent } from './consent'; +import { el, q, setClass, setDisabled, setHidden, setText } from './dom'; +import { dockIcon as icon } from './icons'; +import { chordLabel, contain, isChord, keeps, leaves } from './keys'; +import { placementFor, type Placement } from './placement'; +import type { DockSide } from './state'; +import type { DockTerm } from './terminal'; +import { strings, type Say } from './strings'; +import { Tour, type TourStep } from './tour'; + +export type { DockAdapter, DockKind } from './adapter'; + +const PROGRAMS = ['codex', 'cursor'] as const; +type Program = typeof PROGRAMS[number]; + +interface Tab { + id: string; + term: DockTerm | null; + host: HTMLElement; + tab: HTMLElement; + channel: DockChannel | null; + kind: PtyKind; + seen: boolean; + closed: boolean; +} + +export class Dock { + private readonly s: Say; + readonly root: HTMLElement; + private readonly tabsEl: HTMLElement; + private readonly stage: HTMLElement; + private readonly empty: HTMLElement; + private readonly note: HTMLElement; + private readonly noteText: HTMLElement; + private readonly noteCmd: HTMLElement; + private readonly noteCopy: HTMLButtonElement; + private readonly ask: HTMLInputElement; + private readonly restartBtn: HTMLButtonElement; + private readonly tabs = new Map(); + private readonly owned = new Map void) | undefined }>(); + private chat: DockChatView | null = null; + private readonly ownAsk: DockOwnAsk | null; + private chatTab: HTMLElement | null = null; + private active: string | null = null; + private started = false; + private pending: Promise | null = null; + private emulator: Promise | null = null; + private asked: Promise | null = null; + private mounted = false; + private revealing = false; + private readonly place: Placement; + onTab: () => void = () => undefined; + onChange: () => void = () => undefined; + onResize: () => void = () => undefined; + readonly consent: Consent | null; + private readonly tour: Tour; + + constructor(private readonly a: DockAdapter, parts: { consent?: Consent } = {}) { + const s = strings(a); + const c = a.classes; + const ib = `${c.iconButton} ft-dock-ibtn`; + this.s = s; + this.root = el(`
+ +
+
+ + + + + + + + + + +
+ +
+
+
+ ${icon('agent', 15)} + + +
+
`); + this.tabsEl = q(this.root, '.ft-dock-tabs'); + this.stage = q(this.root, '.ft-dock-stage'); + this.empty = q(this.root, '.ft-dock-empty'); + this.note = q(this.root, '.ft-dock-note'); + this.noteText = q(this.root, '.ft-dock-note-text'); + this.noteCmd = q(this.root, '.ft-dock-note-cmd'); + this.noteCopy = q(this.root, '.ft-dock-note-copy'); + this.ask = q(this.root, '.ft-dock-ask-input'); + this.restartBtn = q(this.root, '.ft-dock-restart'); + this.place = placementFor(a); + q(this.root, '.ft-dock-new').addEventListener('click', () => void this.open()); + q(this.root, '.ft-dock-claude').addEventListener('click', () => void this.claude()); + q(this.root, '.ft-dock-chat').addEventListener('click', () => void this.showChat()); + q(this.root, '.ft-dock-hide').addEventListener('click', () => this.toggle(false)); + q(this.root, '.ft-dock-side').addEventListener('click', () => { this.setSide(this.side() === 'right' ? 'bottom' : 'right'); this.focus(); }); + for (const kind of PROGRAMS) { + q(this.root, `.ft-dock-${kind}`).addEventListener('click', () => void this.program(kind)); + q(this.root, `.ft-dock-menu-row[data-kind="${kind}"] .ft-dock-menu-go`).addEventListener('click', () => { this.menu(false); void this.program(kind); }); + } + q(this.root, '.ft-dock-more').addEventListener('click', () => { this.menu(q(this.root, '.ft-dock-menu').hidden === true); }); + q(this.root, '.ft-dock-menu-settings').addEventListener('click', () => { this.menu(false); a.openSettings?.(); }); + setHidden(q(this.root, '.ft-dock-menu-settings'), !a.openSettings); + q(this.root, '.ft-dock-menu-tour').addEventListener('click', () => { this.menu(false); void this.guide(); }); + this.consent = parts.consent ?? (a.consent ? new Consent(a) : null); + this.tour = new Tour(a); + this.restartBtn.addEventListener('click', () => void this.restart()); + q(this.root, '.ft-dock-ask').addEventListener('submit', (e) => { e.preventDefault(); void this.send(); }); + q(this.root, '.ft-dock-note-x').addEventListener('click', () => this.dismiss()); + this.noteCopy.addEventListener('click', () => { void navigator.clipboard?.writeText(this.noteCmd.textContent ?? '').catch(() => undefined); }); + contain(this.root, a); + setClass(this.root, 'has-own-chat', !!a.chat && 'pane' in a.chat); + const ask = a.chat && 'pane' in a.chat ? a.chat.ask : undefined; + this.ownAsk = !ask || ask === 'none' ? null : ask === 'line' ? {} : ask; + if (this.ownAsk?.element) { + const slot = q(this.root, '.ft-dock-ask'); + const box = el('
'); + box.appendChild(this.ownAsk.element); + slot.classList.add('has-element'); + slot.appendChild(box); + } + } + + mount(host: HTMLElement, before: Node | null = null): void { + if (this.mounted) return; + this.mounted = true; + const a = this.a; + host.insertBefore(this.root, before); + this.place.start(this.root, q(this.root, '.ft-dock-grip'), { + changed: () => { this.labelSide(); this.onChange(); this.fitActive(); }, + resizing: () => { this.onResize(); }, + settled: () => { this.keep(); window.dispatchEvent(new Event('resize')); this.focus(); }, + }); + this.labelSide(); + this.refresh(); + document.addEventListener('pointerdown', (e) => { if (!(e.target as Element).closest?.('.ft-dock-menu, .ft-dock-more')) this.menu(false); }, true); + new ResizeObserver(() => this.fitActive()).observe(this.stage); + document.addEventListener('keydown', (e) => { + if (!isChord(a, e)) return; + e.preventDefault(); + e.stopPropagation(); + if (!e.repeat) this.toggle(); + }, true); + a.onTheme(() => this.retheme()); + new MutationObserver(() => this.retheme()).observe(document.documentElement, { attributes: true, attributeFilter: ['style', 'class', 'data-theme'] }); + if (this.isOpen()) void this.ensure(); + } + + isOpen(): boolean { return this.place.isOpen(); } + + keeps(event: Event): boolean { return keeps(this.a, event); } + + shown(): void { + this.place.shown(true); + this.tell('dock'); + void this.ensure(); + this.onTab(); + } + + hidden(): void { + this.place.shown(false); + this.tell('dock'); + this.tour.end(false); + this.onTab(); + } + + private tell(why: DockPaneHidden): void { + this.chat?.visible?.(this.isOpen() && this.active === 'chat' && this.chatTab !== null, why); + } + + toggle(on = !this.isOpen(), seed: DockKind | 'none' = 'shell'): void { + const p = this.a.placement; + if (p.mode === 'hosted') { p.request(on); return; } + this.place.setOpen(on); + this.tell('dock'); + this.keep(); + this.onChange(); + window.dispatchEvent(new Event('resize')); + if (on && !this.place.seen() && !this.tour.isRunning() && this.a.firstRun?.() !== false) void this.guide(); + if (!on) this.tour.end(false); + if (on) void this.ensure(seed); + this.onTab(); + } + + async newTerminal(): Promise { + if (!this.isOpen()) this.toggle(true); + else await this.open(); + } + + activeKind(): DockKind | null { + if (this.active === 'chat') return 'chat'; + const kind = this.active ? this.tabs.get(this.active)?.kind : undefined; + return kind && kind !== 'agent' ? kind : null; + } + + isShowing(kind: DockKind): boolean { return this.isOpen() && this.activeKind() === kind; } + + async show(kind: DockKind): Promise { + if (!this.isOpen()) this.toggle(true, 'none'); + await this.ensure('none'); + if (kind === 'chat') { await this.showChat(); return; } + const own = [...this.tabs.values()].find((x) => x.kind === kind); + if (own) this.select(own.id); + else if (kind === 'claude') await this.claude(); + else if (kind === 'codex' || kind === 'cursor') await this.program(kind); + else await this.open(); + } + + private async programs(): Promise { + const status = await this.agents(); + for (const kind of PROGRAMS) { + const st = status?.[kind]; + const offered = this.offers(kind); + const found = offered && !!st?.installed; + const row = q(this.root, `.ft-dock-menu-row[data-kind="${kind}"]`); + setHidden(row, !offered || !st); + setHidden(q(this.root, `.ft-dock-${kind}`), !found); + setHidden(q(row, '.ft-dock-menu-go'), !found); + setText(q(row, '.ft-dock-menu-how'), this.s(found ? 'programReady' : 'programMissing', { program: this.s(kind) })); + setText(q(row, '.ft-dock-menu-cmd'), found ? '' : st?.install ?? ''); + setHidden(q(row, '.ft-dock-menu-cmd'), found || !st?.install); + } + } + + private offers(kind: DockKind): boolean { + return this.a.tabs().builtin.includes(kind) && (kind !== 'chat' || !!this.a.chat); + } + + activeTab(): string | null { return this.active; } + + refresh(): void { + setHidden(q(this.root, '.ft-dock-new'), !this.offers('shell')); + setHidden(q(this.root, '.ft-dock-chat'), !this.offers('chat')); + setHidden(q(this.root, '.ft-dock-claude'), !this.offers('claude')); + setHidden(this.restartBtn, !this.a.terminal.restart); + setClass(this.root, 'has-no-ask', !this.offers('claude') && !this.offers('chat')); + setClass(this.root, 'has-ask-line', this.ownAsk !== null && (this.offers('claude') || this.offers('chat'))); + const want = new Map((this.a.tabs().own ?? []).map((spec) => [spec.id, spec])); + for (const [id, o] of [...this.owned]) { + if (want.has(id)) continue; + o.off?.(); + o.tab.remove(); + o.host.remove(); + this.owned.delete(id); + if (this.active !== `own:${id}`) continue; + this.active = null; + const next = [...this.tabs.keys()].pop() ?? (this.chatTab ? 'chat' : undefined); + if (next) this.select(next); else { setHidden(this.empty, false); this.onTab(); } + } + for (const spec of want.values()) { + if (this.owned.has(spec.id)) continue; + const tab = el(''); + q(tab, '.ft-dock-tab-icon').innerHTML = spec.icon; + setText(q(tab, '.ft-dock-tab-title'), spec.label); + const host = el(''); + tab.addEventListener('click', () => this.select(`own:${spec.id}`)); + this.tabsEl.appendChild(tab); + this.stage.appendChild(host); + this.owned.set(spec.id, { spec, tab, host, mounted: false, off: undefined }); + setHidden(this.empty, true); + } + if (this.started) void this.programs(); + } + + private menu(open: boolean): void { + const m = q(this.root, '.ft-dock-menu'); + if (m.hidden === !open) return; + if (open) void this.programs(); + setHidden(m, !open); + q(this.root, '.ft-dock-more').setAttribute('aria-expanded', String(open)); + } + + async program(kind: Program): Promise { + const size = this.size(); + try { + const info = await this.a.terminal.open(kind, { cols: size.cols, rows: size.rows }); + if (!this.isOpen()) this.toggle(true, 'none'); + await this.attach(info, true); + this.dismiss(); + return true; + } catch (err) { + const kind = this.a.errors.kind?.(err); + if (kind === 'oldEngine' || kind === 'notInstalled') { void this.programs(); this.menu(true); } + else this.warn(err); + return false; + } + } + + async toggleKind(kind: DockKind): Promise { + if (this.isShowing(kind)) this.toggle(false); + else await this.show(kind); + } + + async sync(): Promise { + if (!this.started) return; + for (const info of await this.list()) if (info.kind === 'agent') this.adopt(info); + } + + private keep(): void { this.place.keep(this.activeKind()); } + + async guide(): Promise { + if (!this.isOpen()) { + const first = !this.place.seen(); + this.toggle(true, 'none'); + if (first) return; + } + await this.showChat(); + const claude = (await this.agents())?.claude ?? null; + const middle: TourStep = !claude?.installed ? { target: '.ft-dock-claude', title: 'tourMissingTitle', body: 'tourMissingBody', cmd: claude?.install || 'npm install -g @anthropic-ai/claude-code' } + : claude.signedIn === false ? { target: '.ft-dock-claude', title: 'tourSignInTitle', body: 'tourSignInBody' } + : claude.signedIn === true ? { target: '.ft-dock-claude', title: 'tourReadyTitle', body: 'tourReadyBody' } + : { target: '.ft-dock-claude', title: 'tourInstalledTitle', body: 'tourInstalledBody' }; + const steps: TourStep[] = [ + { target: '.ft-dock', title: 'tourPanelTitle', body: 'tourPanelBody' }, + { target: this.ownAsk?.element ? '.ft-dock-ask' : this.ownAsk ? '.ft-dock-ask-input' : this.chat?.askTarget?.() ?? '.ft-dock-ask-input', title: 'tourChatTitle', body: 'tourChatBody' }, + middle, + ...(this.consent ? [{ target: '.ft-dock-more', title: 'tourAskTitle', body: 'tourAskBody' } as TourStep] : []), + { target: '.ft-dock-side', title: 'tourSideTitle', body: 'tourSideBody' }, + ]; + this.tour.start(steps, () => this.place.markSeen()); + } + + side(): DockSide { return this.place.side(); } + + storedSide(): DockSide { return this.place.storedSide(); } + + setSide(side: DockSide): void { + if (side === this.place.storedSide() && side === this.side()) return; + this.place.setSide(side); + this.labelSide(); + this.keep(); + this.onChange(); + window.dispatchEvent(new Event('resize')); + } + + private labelSide(): void { + const right = this.side() === 'right'; + const label = right ? this.s('toBottom') : this.s('toRight'); + const btn = q(this.root, '.ft-dock-side'); + if (btn.title !== label) { btn.title = label; btn.setAttribute('aria-label', label); } + q(this.root, '.ft-dock-grip').setAttribute('aria-orientation', right ? 'vertical' : 'horizontal'); + setHidden(btn, !this.place.canRight()); + } + + private retheme(): void { + for (const x of this.tabs.values()) x.term?.retheme(); + this.fitActive(); + } + + private load(): Promise { + this.emulator ??= import('./terminal'); + return this.emulator; + } + + private agents(): Promise { + if (!this.asked) { + this.asked = this.a.agentStatus().catch(() => null); + void this.asked.then(() => window.setTimeout(() => { this.asked = null; }, 1500)); + } + return this.asked; + } + + private async list(): Promise { + try { return await this.a.terminal.list(); } catch { return []; } + } + + private ensure(seed: DockKind | 'none' = 'shell'): Promise { + this.pending ??= this.boot(seed).finally(() => { this.pending = null; }); + return this.pending; + } + + private async boot(seed: DockKind | 'none'): Promise { + if (!this.started) { + this.started = true; + const listed = await this.list(); + for (const info of listed) this.adopt(info); + } + const shown = !!this.chatTab || [...this.tabs.values()].some((x) => x.kind !== 'agent'); + if (!shown && seed === 'shell') { + const first = this.owned.keys().next(); + if (this.offers('chat') && (this.place.savedTab() === 'chat' || !this.offers('shell'))) await this.showChat(); + else if (this.offers('shell')) await this.open(); + else if (!first.done) this.select(`own:${first.value}`); + } + setHidden(this.empty, !!this.chatTab || this.tabs.size > 0); + void this.programs(); + this.fitActive(); + this.focus(); + this.awaitReveal(); + this.onTab(); + } + + private awaitReveal(): void { + const root = this.root; + const hiddenNow = (): boolean => root.getClientRects().length === 0 || getComputedStyle(root).visibility === 'hidden'; + const lost = document.activeElement; + if (this.revealing || !this.isOpen() || root.contains(lost) || !hiddenNow()) return; + this.revealing = true; + const watch = new MutationObserver(() => { + const moved = document.activeElement !== lost || !this.isOpen(); + if (!moved && hiddenNow()) return; + watch.disconnect(); + this.revealing = false; + if (!moved) this.focus(); + }); + for (let node: Node | null = root.parentNode; node instanceof Element; node = node.parentNode) watch.observe(node, { attributes: true, attributeFilter: ['class', 'style', 'hidden'] }); + } + + focus(): void { + if (this.active === 'chat' && this.ownAsk && !this.ownAsk.element) this.ask.focus({ preventScroll: true }); + else if (this.active === 'chat' && this.chat?.focus) this.chat.focus(); + else if (this.active === 'chat') this.ask.focus({ preventScroll: true }); + else if (this.active) this.tabs.get(this.active)?.term?.focus(); + } + + async sendChat(text: string): Promise { + await this.show('chat'); + return this.chat ? this.chat.send(text) : false; + } + + async showChat(): Promise { + const c = this.a.chat; + if (!c) return; + if (!this.chat) { + if ('pane' in c) this.chat = new OwnChat(c); + else { + const chat = new ChatPane({ ...this.a, chat: c }); + chat.onFail = (err) => this.warn(err); + chat.onHandoff = (session) => void this.claude(undefined, session); + chat.onBash = () => void this.sync(); + this.chat = chat; + } + this.stage.appendChild(this.chat.root); + } + if (!this.chatTab) { + const tab = el(``); + tab.addEventListener('click', (e) => { + if ((e.target as HTMLElement).closest('.ft-dock-tab-x')) this.closeChat(); + else this.select('chat'); + }); + this.tabsEl.prepend(tab); + this.chatTab = tab; + } + setHidden(this.empty, true); + this.select('chat'); + await this.chat.load(); + } + + private closeChat(): void { + this.chatTab?.remove(); + this.chatTab = null; + this.tell('tab'); + this.chat?.release(); + if (this.chat) setHidden(this.chat.root, true); + if (this.active === 'chat') { + this.active = null; + const next = [...this.tabs.keys()].pop(); + if (next) this.select(next); + else { setHidden(this.empty, false); this.syncAsk(); setDisabled(this.restartBtn, true); this.onTab(); } + } + } + + private syncAsk(): void { + const chat = this.active === 'chat'; + const text = chat ? this.s('chatPlaceholder') : this.s('askPlaceholder'); + if (this.ask.placeholder !== text) this.ask.placeholder = text; + } + + private async send(): Promise { + const text = this.ask.value.trim(); + if (!text) return; + const chat = this.chat; + if (this.ownAsk && (this.ownAsk.send || (this.active === 'chat' && chat))) { + const route = this.ownAsk.send; + if (!route && chat?.isBusy()) return; + this.ask.value = ''; + const went = route ? (await route(text, this.activeKind())) !== false : chat ? await chat.send(text) : false; + if (!went && !this.ask.value) this.ask.value = text; + return; + } + if (this.active === 'chat' && this.chat) { + if (this.chat.isBusy()) return; + this.ask.value = ''; + await this.chat.send(text); + return; + } + this.ask.value = ''; + const ok = await this.claude(text); + if (!ok && !this.ask.value) this.ask.value = text; + } + + private say(text: string, cmd = ''): void { + setText(this.noteText, text); + setText(this.noteCmd, cmd); + setHidden(this.noteCmd, cmd === ''); + setHidden(this.noteCopy, cmd === ''); + setHidden(this.note, false); + } + + private dismiss(): void { setHidden(this.note, true); } + + private warn(err: unknown): void { + const kind = this.a.errors.kind?.(err); + const said = this.a.errors.message(err) ?? (err instanceof Error ? err.message : ''); + if (kind === 'unreachable') this.say(this.a.words.start ? this.s('offlineStart') : this.s('offline')); + else if (kind === 'refused') this.say(said || this.s('refused')); + else this.say(said || this.s('failed')); + } + + private async fail(err: unknown, what: 'shell' | 'claude'): Promise { + const kind = this.a.errors.kind?.(err); + if (what === 'shell' || kind === 'refused' || kind === 'unreachable') { this.warn(err); return; } + const status = (await this.agents())?.claude; + if (status && !status.installed) { + this.say(this.s('notInstalled'), status.install); + return; + } + if (kind === 'oldEngine') this.say(this.s('oldEngine')); + else this.say(`${this.s('notStarted')} ${err instanceof Error ? err.message : ''}`.trim()); + } + + private ended(x: Tab, on: boolean): void { + setClass(x.tab, 'is-ended', on); + if (x.kind === 'agent') return; + const tip = on ? this.s('endedTab') : x.tab.dataset.tip ?? ''; + if (x.tab.title !== tip) x.tab.title = tip; + } + + private adopt(info: DockTerminal): void { + if (this.tabs.has(info.id)) return; + void this.attach(info, this.active === null || info.kind !== 'agent'); + } + + private async open(): Promise { + try { + const info = await this.a.terminal.open('shell', { cols: 100, rows: 24 }); + await this.attach(info, true); + this.dismiss(); + } catch (err) { await this.fail(err, 'shell'); } + } + + async claude(prompt?: string, resume?: string): Promise { + const size = this.size(); + try { + const info = await this.a.terminal.open('claude', { cols: size.cols, rows: size.rows, ...(prompt ? { prompt } : {}), ...(resume ? { resume } : {}) }); + if (!this.isOpen()) this.toggle(true, 'none'); + if (this.tabs.has(info.id)) this.select(info.id); + else await this.attach(info, true); + this.dismiss(); + return true; + } catch (err) { + await this.fail(err, 'claude'); + return false; + } + } + + private size(): { cols: number; rows: number } { + const tab = this.active ? this.tabs.get(this.active) : null; + return tab?.term ? { cols: tab.term.cols(), rows: tab.term.rows() } : { cols: 100, rows: 20 }; + } + + private async attach(info: DockTerminal, show: boolean): Promise { + if (this.tabs.has(info.id)) { if (show) this.select(info.id); return; } + const kind: PtyKind = ['claude', 'agent', 'codex', 'cursor'].includes(info.kind) ? info.kind : 'shell'; + const agent = kind === 'agent'; + const mark = kind === 'claude' ? 'agent' : kind === 'codex' || kind === 'cursor' ? kind : 'terminal'; + const host = el(''); + const tab = el(``); + setText(q(tab, '.ft-dock-tab-title'), info.title); + if (agent) tab.title = this.s('agentTab'); + tab.addEventListener('click', (e) => { + if ((e.target as HTMLElement).closest('.ft-dock-tab-x')) void this.close(info.id); + else this.select(info.id); + }); + this.stage.appendChild(host); + this.tabsEl.appendChild(tab); + if (info.tip) tab.dataset.tip = info.tip; + const entry: Tab = { id: info.id, term: null, host, tab, channel: null, kind, seen: false, closed: false }; + this.tabs.set(info.id, entry); + setHidden(this.empty, true); + this.ended(entry, !info.alive); + if (show) this.select(info.id, false); + const { createTerm } = await this.load(); + if (entry.closed) return; + const term = createTerm({ agent, scrollback: this.a.terminal.scrollback, leaves: (e) => leaves(this.a, e) }); + entry.term = term; + term.open(host); + term.onInput((data) => entry.channel?.send(data)); + if (this.active === info.id) { this.fitActive(); if (show && !agent) term.focus(); } + await this.connect(entry); + } + + private async connect(entry: Tab): Promise { + const silent = (): void => { if (!entry.seen && !entry.closed) this.say(this.s('noAnswer')); }; + let channel: DockChannel; + try { channel = await this.a.terminal.channel(entry.id); } catch { silent(); return; } + if (entry.closed) { channel.close(); return; } + entry.channel = channel; + channel.onData((data) => { entry.seen = true; entry.term?.write(data); }); + channel.onExit(() => { entry.seen = true; this.ended(entry, true); }); + channel.onClose?.(() => { if (entry.channel === channel) entry.channel = null; silent(); }); + this.sendSize(entry); + } + + private sendSize(x: Tab): void { + if (x.term) x.channel?.resize(x.term.cols(), x.term.rows()); + } + + private fitActive(): void { + const x = this.active ? this.tabs.get(this.active) : null; + if (!x?.term || x.host.hidden || this.stage.clientHeight < 20) return; + if (x.term.fit()) this.sendSize(x); + } + + private select(id: string, focus = true): void { + this.active = id; + for (const [tid, x] of this.tabs) { + const on = tid === id; + setHidden(x.host, !on); + x.tab.classList.toggle('is-on', on); + x.tab.setAttribute('aria-selected', String(on)); + } + if (this.chat) setHidden(this.chat.root, id !== 'chat'); + if (this.chatTab) { + this.chatTab.classList.toggle('is-on', id === 'chat'); + this.chatTab.setAttribute('aria-selected', String(id === 'chat')); + } + for (const [oid, o] of this.owned) { + const on = `own:${oid}` === id; + if (on && !o.mounted) { o.mounted = true; const off = o.spec.mount(o.host); o.off = typeof off === 'function' ? off : undefined; } + setHidden(o.host, !on); + setClass(o.tab, 'is-on', on); + o.tab.setAttribute('aria-selected', String(on)); + } + this.syncAsk(); + setDisabled(this.restartBtn, !this.tabs.has(id) || this.tabs.get(id)?.kind === 'agent'); + this.fitActive(); + if (focus) this.focus(); + this.keep(); + this.tell('tab'); + this.onTab(); + } + + private async restart(): Promise { + const x = this.active ? this.tabs.get(this.active) : null; + if (!x || x.kind === 'agent' || !this.a.terminal.restart) return; + try { await this.a.terminal.restart(x.id); } catch (err) { this.warn(err); return; } + this.ended(x, false); + if (!x.channel) { x.term?.reset(); x.seen = false; await this.connect(x); } + this.sendSize(x); + x.term?.focus(); + } + + private async close(id: string): Promise { + const x = this.tabs.get(id); + if (!x) return; + x.closed = true; + x.channel?.close(); + x.term?.dispose(); + x.host.remove(); + x.tab.remove(); + this.tabs.delete(id); + await this.a.terminal.close(id).catch(() => undefined); + if (this.active === id) { + this.active = null; + const next = [...this.tabs.keys()].pop() ?? (this.chatTab ? 'chat' : undefined); + if (next) this.select(next); + else { setDisabled(this.restartBtn, true); this.syncAsk(); this.onTab(); } + } + setHidden(this.empty, this.tabs.size > 0 || !!this.chatTab); + } +} diff --git a/frontend/src/dock/dom.ts b/frontend/src/dock/dom.ts new file mode 100644 index 0000000..d18d06a --- /dev/null +++ b/frontend/src/dock/dom.ts @@ -0,0 +1,27 @@ +export function el(html: string): T { + const t = document.createElement('template'); + t.innerHTML = html.trim(); + return document.adoptNode(t.content.firstElementChild as T); +} + +export function q(root: ParentNode, sel: string): T { + const n = root.querySelector(sel); + if (!n) throw new Error(`missing element: ${sel}`); + return n as T; +} + +export function setText(node: Element | null, text: string): void { + if (node && node.textContent !== text) node.textContent = text; +} + +export function setClass(node: Element | null, cls: string, on: boolean): void { + if (!node) return; + if (node.classList.contains(cls) !== on) node.classList.toggle(cls, on); +} + +export function setHidden(node: HTMLElement, hidden: boolean): void { if (node.hidden !== hidden) node.hidden = hidden; } +export function setDisabled(node: HTMLButtonElement | HTMLInputElement | HTMLSelectElement, disabled: boolean): void { if (node.disabled !== disabled) node.disabled = disabled; } + +export function cssToken(name: string, fallback: string): string { + return getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback; +} diff --git a/frontend/src/dock/icons.ts b/frontend/src/dock/icons.ts new file mode 100644 index 0000000..eccfac8 --- /dev/null +++ b/frontend/src/dock/icons.ts @@ -0,0 +1,21 @@ +const ICONS: Record = { + plus: ``, + close: ``, + refresh: ``, + send: ``, + agent: ``, + agentChat: ``, + terminal: ``, + codex: ``, + cursor: ``, + dockRight: ``, + dockBottom: ``, + menu: ``, +}; + +export type DockIcon = keyof typeof ICONS; + +export function dockIcon(name: string, size = 16): string { + const svg = ICONS[name] ?? ICONS.terminal; + return ``; +} diff --git a/frontend/src/dock/keys.ts b/frontend/src/dock/keys.ts new file mode 100644 index 0000000..d8f8e51 --- /dev/null +++ b/frontend/src/dock/keys.ts @@ -0,0 +1,35 @@ +import type { DockAdapter } from './adapter'; + +export type DockKeys = Pick; + +export function onMac(): boolean { + return /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent); +} + +export function isChord(a: DockKeys, e: KeyboardEvent): boolean { + if (a.isDockChord) return a.isDockChord(e); + if (e.code !== 'KeyJ' || e.shiftKey || e.altKey) return false; + return onMac() ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey; +} + +export function chordLabel(a: DockKeys): string { + return a.chordLabel ? a.chordLabel() : onMac() ? 'Cmd+J' : 'Ctrl+J'; +} + +export function leaves(a: DockKeys, e: KeyboardEvent): boolean { + return isChord(a, e) || a.passKey?.(e) === true; +} + +export function contain(node: HTMLElement, a: DockKeys): void { + const stop = (e: Event): void => { if (!leaves(a, e as KeyboardEvent)) e.stopPropagation(); }; + for (const type of ['keydown', 'keypress', 'keyup']) node.addEventListener(type, stop); +} + +export function ownsEvent(e: Event): boolean { + const at = e.target; + return at instanceof Element && at.closest('.ft-dock, .ft-consent, .ft-tour') !== null; +} + +export function keeps(a: DockKeys, e: Event): boolean { + return ownsEvent(e) && !(e instanceof KeyboardEvent && leaves(a, e)); +} diff --git a/frontend/src/dock/placement.ts b/frontend/src/dock/placement.ts new file mode 100644 index 0000000..d23caba --- /dev/null +++ b/frontend/src/dock/placement.ts @@ -0,0 +1,166 @@ +import type { DockAdapter, DockSizes, DockStorage } from './adapter'; +import { moveLegacy, readSeen, readState, type DockSide, type DockState } from './state'; + +export interface PlacementHooks { changed(): void; resizing(): void; settled(): void } + +export interface Placement { + readonly hosted: boolean; + start(root: HTMLElement, grip: HTMLElement, hooks: PlacementHooks): void; + isOpen(): boolean; + setOpen(on: boolean): void; + side(): DockSide; + storedSide(): DockSide; + canRight(): boolean; + setSide(side: DockSide): void; + keep(tab: string | null): void; + savedTab(): string; + seen(): boolean; + markSeen(): void; + shown(on: boolean): void; +} + +const store = (): Storage | null => { try { return window.localStorage; } catch { return null; } }; + +class OwnPlacement implements Placement { + readonly hosted = false; + private state: DockState; + private hooks: PlacementHooks | null = null; + + constructor(private readonly keyed: DockStorage, private readonly z: DockSizes, private readonly right: (() => boolean) | undefined) { + const s = store(); + const defaults = { h: z.defaultHeight, w: z.defaultWidth }; + if (s) moveLegacy(s, keyed.key, keyed.legacy, defaults); + this.state = s ? readState(s, keyed.key, keyed.legacy, defaults) : { open: false, side: 'bottom', h: defaults.h, w: defaults.w, tab: '' }; + } + + start(_root: HTMLElement, grip: HTMLElement, hooks: PlacementHooks): void { + this.hooks = hooks; + this.state.open = this.isOpen(); + this.apply(); + window.addEventListener('resize', () => { if (this.apply()) hooks.changed(); }); + this.drag(grip); + } + + isOpen(): boolean { + const at = document.documentElement.getAttribute('data-ft-dock'); + return at === null ? this.state.open : at === 'open'; + } + + setOpen(on: boolean): void { + this.state.open = on; + this.apply(); + } + + storedSide(): DockSide { return this.state.side; } + + side(): DockSide { return this.state.side === 'right' && this.canRight() ? 'right' : 'bottom'; } + + canRight(): boolean { + if (this.right && !this.right()) return false; + return this.z.keepWidth === undefined && !this.z.maxWidth ? true : this.maxWidth() >= this.z.minWidth; + } + + setSide(side: DockSide): void { + this.state.side = side; + this.apply(); + } + + keep(tab: string | null): void { + const s = store(); + if (!s) return; + if (tab) this.state.tab = tab; + const seen = readSeen(s, this.keyed.key); + try { s.setItem(this.keyed.key, JSON.stringify(seen ? { ...this.state, seen } : this.state)); } catch { return; } + } + + savedTab(): string { return this.state.tab; } + + seen(): boolean { + const s = store(); + return s ? readSeen(s, this.keyed.key) : true; + } + + markSeen(): void { + const s = store(); + if (!s) return; + try { s.setItem(this.keyed.key, JSON.stringify({ ...this.state, seen: true })); } catch { return; } + } + + shown(): void { return; } + + private maxWidth(): number { + return Math.min(window.innerWidth * this.z.maxWidthShare, window.innerWidth - (this.z.keepWidth ?? 0), this.z.maxWidth ? this.z.maxWidth() : Infinity); + } + + private maxHeight(): number { + return Math.min(window.innerHeight * this.z.maxHeightShare, window.innerHeight - (this.z.keepHeight ?? 0), this.z.maxHeight ? this.z.maxHeight() : Infinity); + } + + private width(w: number): number { return Math.round(Math.max(this.z.minWidth, Math.min(this.maxWidth(), w))); } + + private height(h: number): number { return Math.round(Math.max(this.z.minHeight, Math.min(this.maxHeight(), h))); } + + private apply(): boolean { + const html = document.documentElement; + const want: Array<[string, string]> = [ + ['data-ft-dock', this.state.open ? 'open' : 'closed'], ['data-ft-dock-side', this.side()], + ['data-ft-dock-h', String(this.height(this.state.h))], ['data-ft-dock-w', String(this.width(this.state.w))], + ]; + let changed = false; + for (const [name, value] of want) if (html.getAttribute(name) !== value) { html.setAttribute(name, value); changed = true; } + const sizes: Array<[string, string]> = [['--ft-dock-size', `${this.height(this.state.h)}px`], ['--ft-dock-wsize', `${this.width(this.state.w)}px`]]; + for (const [name, value] of sizes) if (html.style.getPropertyValue(name) !== value) html.style.setProperty(name, value); + return changed; + } + + private drag(grip: HTMLElement): void { + grip.addEventListener('pointerdown', (e) => { + if (e.button !== 0) return; + e.preventDefault(); + grip.setPointerCapture(e.pointerId); + grip.classList.add('is-dragging'); + const right = this.side() === 'right'; + const from = right ? this.width(this.state.w) : this.height(this.state.h); + const at = right ? e.clientX : e.clientY; + const move = (ev: PointerEvent): void => { + const size = from + at - (right ? ev.clientX : ev.clientY); + if (right) this.state.w = this.width(size); else this.state.h = this.height(size); + if (this.apply()) this.hooks?.resizing(); + }; + const up = (): void => { + grip.removeEventListener('pointermove', move); + grip.removeEventListener('pointerup', up); + grip.removeEventListener('pointercancel', up); + grip.classList.remove('is-dragging'); + this.hooks?.settled(); + }; + grip.addEventListener('pointermove', move); + grip.addEventListener('pointerup', up); + grip.addEventListener('pointercancel', up); + }); + } +} + +class HostedPlacement implements Placement { + readonly hosted = true; + private on = false; + private tab = ''; + + start(root: HTMLElement): void { root.classList.add('is-hosted'); } + isOpen(): boolean { return this.on; } + setOpen(): void { return; } + side(): DockSide { return 'bottom'; } + storedSide(): DockSide { return 'bottom'; } + canRight(): boolean { return false; } + setSide(): void { return; } + keep(tab: string | null): void { if (tab) this.tab = tab; } + savedTab(): string { return this.tab; } + seen(): boolean { return true; } + markSeen(): void { return; } + shown(on: boolean): void { this.on = on; } +} + +export function placementFor(a: Pick): Placement { + const p = a.placement; + return p.mode === 'hosted' ? new HostedPlacement() : new OwnPlacement(p.storage, p.sizes, p.canDockRight); +} diff --git a/frontend/src/dock/state.ts b/frontend/src/dock/state.ts new file mode 100644 index 0000000..6fc4b41 --- /dev/null +++ b/frontend/src/dock/state.ts @@ -0,0 +1,45 @@ +export type DockSide = 'bottom' | 'right'; +export interface DockState { open: boolean; side: DockSide; h: number; w: number; tab: string } +export interface DockStore { getItem(key: string): string | null; setItem(key: string, value: string): void; removeItem(key: string): void } + +export interface DockLegacy { keys: string[]; read(store: DockStore): (Partial & { seen?: boolean }) | null } + +export function jsonLegacy(keys: string[], seen = false): DockLegacy { + return { + keys, + read: (store) => { + for (const k of keys) { + try { const v = store.getItem(k); const s: unknown = v ? JSON.parse(v) : null; if (s && typeof s === 'object') return { ...(s as Partial), seen }; } catch { continue; } + } + return null; + }, + }; +} + +export function readState(store: DockStore, key: string, from: DockLegacy | string[] | undefined, defaults: { h: number; w: number }): DockState { + const legacy = Array.isArray(from) ? jsonLegacy(from) : from; + const own = (): Partial | null => { + try { const v = store.getItem(key); const s: unknown = v ? JSON.parse(v) : null; return s && typeof s === 'object' ? s as Partial : null; } catch { return null; } + }; + const old = (): Partial | null => { try { return legacy ? legacy.read(store) : null; } catch { return null; } }; + const s = own() ?? old() ?? {}; + return { + open: s.open === true, side: s.side === 'right' ? 'right' : 'bottom', + h: typeof s.h === 'number' ? s.h : defaults.h, w: typeof s.w === 'number' ? s.w : defaults.w, tab: typeof s.tab === 'string' ? s.tab : '', + }; +} + +export function readSeen(store: DockStore, key: string): boolean { + try { const v = store.getItem(key); return v ? (JSON.parse(v) as { seen?: unknown }).seen === true : false; } catch { return false; } +} + +export function moveLegacy(store: DockStore, key: string, from: DockLegacy | string[] | undefined, defaults: { h: number; w: number }): boolean { + const legacy = Array.isArray(from) ? jsonLegacy(from) : from; + try { + if (!legacy || store.getItem(key) !== null || !legacy.keys.some((k) => store.getItem(k) !== null)) return false; + const state = readState(store, key, legacy, defaults); + store.setItem(key, JSON.stringify(legacy.read(store)?.seen === true ? { ...state, seen: true } : state)); + for (const k of legacy.keys) store.removeItem(k); + return true; + } catch { return false; } +} diff --git a/frontend/src/dock/strings.ts b/frontend/src/dock/strings.ts new file mode 100644 index 0000000..5de91b9 --- /dev/null +++ b/frontend/src/dock/strings.ts @@ -0,0 +1,114 @@ +import type { DockAdapter } from './adapter'; + +export const STRINGS = { + terminal: 'Terminal', + resize: 'Resize the terminal', + terminals: 'Terminals', + newTerminal: 'New Terminal', + chatAbout: 'Chat with Claude about your {noun}', + chatWith: 'Chat with Claude', + claudeCode: 'Claude Code', + restart: 'Restart this tab', + hide: 'Hide Terminal', + codex: 'Codex', + cursor: 'Cursor', + moreAgents: 'More agents', + programMissing: '{program} is not on this computer yet: install it with the command below, then sign in once in a terminal.', + programReady: '{program} is installed. Start it in a new tab.', + toRight: 'Move the terminal to the right', + toBottom: 'Move the terminal to the bottom', + hideTitle: 'Hide Terminal ({chord}); programs keep running', + empty: 'No terminal is open. Start a shell with the plus button, Claude Code with the agent button, or Chat with the speech bubble.', + copy: 'Copy', + dismiss: 'Dismiss', + askPlaceholder: 'Ask Claude Code to work on your {noun}', + askLabel: 'Ask Claude Code', + send: 'Send to Claude Code', + chat: 'Chat', + closeChat: 'Close the Chat tab', + chatPlaceholder: 'Ask Claude about your {noun} (Enter to send)', + failed: 'The request failed.', + notInstalled: 'Claude Code is not installed. Install it with the command below, then sign in once by running claude in a terminal.', + oldEngine: 'This copy of the {app} engine cannot run Claude Code in a tab yet. Restart the engine, then try again.', + notStarted: 'Claude Code could not be started.', + closeTab: 'Close this tab', + agentTab: "Claude's commands, read only", + endedTab: 'This program has ended. Restart this tab to run it again.', + noAnswer: 'The engine did not answer on this terminal. Restart the engine, then close this tab and open it again.', + modeLabel: 'Permission mode', + stop: 'Stop', + handoffTitle: 'Continue this conversation in a Claude Code terminal tab', + handoff: 'Continue in Claude Code', + newChat: 'New Chat', + modeAsk: 'Ask', + modeAuto: 'Auto-accept edits', + modePlan: 'Plan', + sendFailed: 'The message could not be sent.', + offline: 'The {app} engine is not reachable.', + offlineStart: 'The {app} engine is not reachable. Start it with {start}.', + refused: 'This is not allowed for you here.', + missing: 'Claude Code is not installed', + signedIn: 'signed in', + notSignedIn: 'not signed in: run claude in a terminal and sign in with /login', + working: 'working', + ready: 'ready', + idle: 'not started', + handoffFirst: 'Start a conversation here first; then it can continue in Claude Code', + handoffBusy: 'Wait for Claude to finish, or press Stop, before moving the conversation', + allowed: 'Allowed', + declined: 'Declined', + stoppedError: 'Claude Code stopped with an error.', + allow: 'Allow', + deny: 'Deny', + asksToUse: 'Claude Code asks to use {tool}', + consentTitle: 'Allow an agent calling itself {agent} to make changes in {app}?', + consentTitleUnnamed: 'Allow an outside agent to make changes in {app}?', + consentWhat: 'It asked to {what}.', + consentCount: 'Request {n} of {total}', + consentDeny: 'Deny', + consentOnce: 'Allow once', + consentAlways: 'Always allow any agent named {agent}', + consentAlwaysUnnamed: 'Always allow this agent', + consentAlwaysAll: 'Always allow all outside agents', + consentChanged: 'The Outside agents setting was changed outside {app}, so {app} asks again.', + outsideAgents: 'Outside agents', + showAround: 'Show me around', + tourCount: 'Step {n} of {total}', + tourBack: 'Back', + tourNext: 'Next', + tourDone: 'Done', + tourClose: 'Close the guide', + tourPanelTitle: 'This is your helper panel', + tourPanelBody: 'This panel is where you talk to Claude, an assistant that can work on your {noun} for you. It stays out of the way until you open it.', + tourChatTitle: 'Ask for something in plain words', + tourChatBody: 'Type what you want in this line, for example "{example}", and press Enter. Claude does it in {app}.', + tourInstalledTitle: 'Claude Code is installed', + tourInstalledBody: 'Claude Code is installed. The robot button here opens it; the first time, it may ask you to sign in.', + tourMissingTitle: 'Claude Code is not on this computer yet', + tourMissingBody: 'For the bigger jobs, {app} uses a free program called Claude Code. To add it, copy the line below, open your computer\'s command window, paste it and press Enter.', + tourSignInTitle: 'Sign in to Claude Code once', + tourSignInBody: 'Claude Code is installed but not signed in. Press the robot button here: a window opens where you type /login and follow the steps. You only do this once.', + tourReadyTitle: 'Claude Code is ready', + tourReadyBody: 'Claude Code is installed and signed in. The robot button here opens it when you want it to take on a bigger job.', + tourAskTitle: 'You decide what other programs may change', + tourAskBody: 'If another AI program on this computer wants to change your {noun}, {app} asks you first in a box in the middle of the window. Choose Deny, Allow once or Always allow. You can change your answer later under Outside agents in the menu here.', + tourSideTitle: 'Put the panel where you like it', + tourSideBody: 'This button moves the panel to the right side of the window, and back to the bottom. Drag its edge to make it bigger or smaller.', +} as const; + +export type StringKey = keyof typeof STRINGS; +export type Say = (key: StringKey, vars?: Record) => string; +export const SENTENCES: readonly string[] = Object.values(STRINGS); + +export function fill(text: string, vars: Record): string { + return text.replace(/\{(\w+)\}/g, (m, name: string) => { const v = vars[name]; return v === undefined ? m : String(v); }); +} + +export function strings(a: Pick): Say { + const words = { app: a.words.app, noun: a.words.noun, example: a.words.example, start: a.words.start ?? '' }; + return (key, vars) => fill(a.t(key, a.strings?.[key] ?? STRINGS[key]), { ...words, ...vars }); +} + +export function lead(a: Pick): string { + return fill(a.t('lead', a.words.lead), { app: a.words.app, noun: a.words.noun, example: a.words.example }); +} diff --git a/frontend/src/dock/terminal.ts b/frontend/src/dock/terminal.ts new file mode 100644 index 0000000..a934d2b --- /dev/null +++ b/frontend/src/dock/terminal.ts @@ -0,0 +1,88 @@ +import { FitAddon } from '@xterm/addon-fit'; +import { Terminal } from '@xterm/xterm'; +import '@xterm/xterm/css/xterm.css'; +import { cssToken as token } from './dom'; + +export interface DockTermOptions { agent: boolean; scrollback?: number | undefined; leaves(event: KeyboardEvent): boolean } + +export interface DockTerm { + cols(): number; + rows(): number; + open(host: HTMLElement): void; + fit(): boolean; + focus(): void; + write(data: string | Uint8Array): void; + reset(): void; + retheme(): void; + onInput(handler: (data: string) => void): void; + dispose(): void; +} + +function number(name: string, fallback: number): number { + const n = parseFloat(token(name, String(fallback))); + return n > 0 ? n : fallback; +} + +function colour(probe: HTMLElement | null, name: string, fallback: string): string { + const raw = token(name, ''); + if (!raw) return fallback; + if (!probe || /^#[0-9a-f]{3,8}$/i.test(raw)) return raw; + probe.style.color = raw; + const seen = probe.style.color ? getComputedStyle(probe).color : ''; + probe.style.removeProperty('color'); + return /^rgba?\(/.test(seen) ? seen : raw; +} + +function theme(probe: HTMLElement | null): { background: string; foreground: string; cursor: string; cursorAccent: string; selectionBackground: string } { + const background = colour(probe, '--dock-term-bg', '#111111'); + return { + background, + foreground: colour(probe, '--dock-term-fg', '#f7f7f7'), + cursor: colour(probe, '--dock-term-cursor', '#f97316'), + cursorAccent: background, + selectionBackground: colour(probe, '--dock-term-selection', '#f9731633'), + }; +} + +export function createTerm(o: DockTermOptions): DockTerm { + const term = new Terminal({ + fontFamily: token('--dock-font-mono', 'monospace'), fontSize: number('--dock-term-font-size', 13), lineHeight: number('--dock-term-line-height', 1.25), + cursorBlink: !o.agent, disableStdin: o.agent, scrollback: o.scrollback ?? 5000, minimumContrastRatio: number('--dock-term-contrast', 1), + theme: theme(null), overviewRuler: { width: 0 }, + }); + const fit = new FitAddon(); + let probe: HTMLElement | null = null; + let look = ''; + term.loadAddon(fit); + term.attachCustomKeyEventHandler((e) => !o.leaves(e)); + const retheme = (): void => { + const now = theme(probe); + const size = number('--dock-term-font-size', 13); + const next = JSON.stringify([now, size]); + if (next === look) return; + look = next; + term.options.theme = now; + if (term.options.fontSize !== size) term.options.fontSize = size; + }; + return { + cols: () => term.cols, + rows: () => term.rows, + open: (host) => { + probe = host; + term.open(host); + retheme(); + if (o.agent) term.write('\x1b[?25l'); + }, + fit: () => { + const before = `${term.cols}x${term.rows}`; + fit.fit(); + return `${term.cols}x${term.rows}` !== before; + }, + focus: () => term.focus(), + write: (data) => term.write(data), + reset: () => term.reset(), + retheme, + onInput: (handler) => { term.onData(handler); }, + dispose: () => term.dispose(), + }; +} diff --git a/frontend/src/dock/tour.ts b/frontend/src/dock/tour.ts new file mode 100644 index 0000000..94eb988 --- /dev/null +++ b/frontend/src/dock/tour.ts @@ -0,0 +1,182 @@ +import type { DockAdapter } from './adapter'; +import { el, q, setHidden, setText } from './dom'; +import { contain } from './keys'; +import { strings, type Say, type StringKey } from './strings'; + +export interface TourStep { target: string | HTMLElement; title: StringKey; body: StringKey; cmd?: string } + +const find = (target: string | HTMLElement): Element | null => (typeof target === 'string' ? document.querySelector(target) : target); + +const GAP = 12; +const EDGE = 8; +const PAD = 4; + +const shown = (node: Element | null): node is HTMLElement => { + if (!(node instanceof HTMLElement) || !node.isConnected) return false; + const r = node.getBoundingClientRect(); + return r.width > 0 && r.height > 0; +}; + +export class Tour { + private root: HTMLElement | null = null; + private ring!: HTMLElement; + private card!: HTMLElement; + private count!: HTMLElement; + private title!: HTMLElement; + private body!: HTMLElement; + private cmdRow!: HTMLElement; + private cmd!: HTMLElement; + private back!: HTMLButtonElement; + private next!: HTMLButtonElement; + private readonly s: Say; + private steps: TourStep[] = []; + private at = -1; + private target: HTMLElement | null = null; + private returnTo: HTMLElement | null = null; + private done: (() => void) | null = null; + private readonly watch = new ResizeObserver(() => this.place()); + private readonly onMove = (): void => this.place(); + private readonly onKey = (e: KeyboardEvent): void => { + if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.end(true); } + }; + + constructor(private readonly a: DockAdapter) { + this.s = strings(a); + } + + isRunning(): boolean { return this.at >= 0; } + + start(steps: TourStep[], done: () => void): void { + if (this.isRunning()) this.end(false); + this.build(); + this.steps = steps; + this.done = done; + this.at = -1; + if (!this.go(0, 1)) { this.done = null; return; } + const active = document.activeElement; + this.returnTo = active instanceof HTMLElement && active !== document.body ? active : null; + window.addEventListener('resize', this.onMove); + window.addEventListener('scroll', this.onMove, true); + document.addEventListener('keydown', this.onKey, true); + setHidden(this.root as HTMLElement, false); + this.place(); + this.card.focus({ preventScroll: true }); + } + + private build(): void { + if (this.root) return; + const s = this.s; + const c = this.a.classes; + this.root = el(``); + this.ring = q(this.root, '.ft-tour-ring'); + this.card = q(this.root, '.ft-tour-card'); + this.count = q(this.root, '.ft-tour-count'); + this.title = q(this.root, '.ft-tour-title'); + this.body = q(this.root, '.ft-tour-body'); + this.cmdRow = q(this.root, '.ft-tour-cmd'); + this.cmd = q(this.cmdRow, 'code'); + this.back = q(this.root, '.ft-tour-back'); + this.next = q(this.root, '.ft-tour-next'); + contain(this.card, this.a); + q(this.root, '.ft-tour-copy').addEventListener('click', () => { void navigator.clipboard?.writeText(this.cmd.textContent ?? '').catch(() => undefined); }); + q(this.root, '.ft-tour-x').addEventListener('click', () => this.end(true)); + this.back.addEventListener('click', () => { this.go(this.at - 1, -1); this.place(); }); + this.next.addEventListener('click', () => { + if (!this.go(this.at + 1, 1)) { this.end(true); return; } + this.place(); + }); + document.body.append(this.root); + } + + private go(from: number, dir: 1 | -1): boolean { + for (let i = from; i >= 0 && i < this.steps.length; i += dir) { + const at = this.steps[i]; + const node = at ? find(at.target) : null; + if (!shown(node)) continue; + this.at = i; + this.watch.disconnect(); + this.target = node; + this.watch.observe(node); + this.fill(); + return true; + } + return false; + } + + private fill(): void { + const step = this.steps[this.at]; + if (!step) return; + const before = this.steps.slice(0, this.at).filter((x) => shown(find(x.target))).length; + const after = this.steps.slice(this.at + 1).filter((x) => shown(find(x.target))).length; + setText(this.count, this.s('tourCount').replace('{n}', String(before + 1)).replace('{total}', String(before + 1 + after))); + setText(this.title, this.s(step.title)); + setText(this.body, this.s(step.body)); + setText(this.cmd, step.cmd ?? ''); + setHidden(this.cmdRow, !step.cmd); + const first = before === 0; + const last = after === 0; + setHidden(this.back, first); + setText(this.next, last ? this.s('tourDone') : this.s('tourNext')); + } + + private place(): void { + if (!this.isRunning() || !this.root) return; + if (!shown(this.target)) { + if (!this.go(this.at + 1, 1) && !this.go(this.at - 1, -1)) { this.end(true); return; } + } + const r = (this.target as HTMLElement).getBoundingClientRect(); + const vw = window.innerWidth, vh = window.innerHeight; + const box = { left: Math.max(0, r.left - PAD), top: Math.max(0, r.top - PAD), right: Math.min(vw, r.right + PAD), bottom: Math.min(vh, r.bottom + PAD) }; + this.put(this.ring, box.left, box.top, box.right - box.left, box.bottom - box.top); + const cw = this.card.offsetWidth || 320, ch = this.card.offsetHeight || 160; + const clampX = (x: number): number => Math.min(Math.max(EDGE, x), vw - cw - EDGE); + const clampY = (y: number): number => Math.min(Math.max(EDGE, y), vh - ch - EDGE); + const midX = clampX((box.left + box.right) / 2 - cw / 2), midY = clampY((box.top + box.bottom) / 2 - ch / 2); + const spots: Array<[boolean, number, number]> = [ + [box.bottom + GAP + ch <= vh - EDGE, midX, box.bottom + GAP], + [box.top - GAP - ch >= EDGE, midX, box.top - GAP - ch], + [box.left - GAP - cw >= EDGE, box.left - GAP - cw, midY], + [box.right + GAP + cw <= vw - EDGE, box.right + GAP, midY], + ]; + const spot = spots.find((x) => x[0]); + this.put(this.card, spot ? spot[1] : clampX(box.left + EDGE), spot ? spot[2] : clampY(box.top + EDGE), 0, 0); + } + + private put(node: HTMLElement, x: number, y: number, w: number, h: number): void { + const st = node.style; + const tx = `translate(${Math.round(x)}px, ${Math.round(y)}px)`; + if (st.transform !== tx) st.transform = tx; + if (w > 0 && st.width !== `${Math.round(w)}px`) st.width = `${Math.round(w)}px`; + if (h > 0 && st.height !== `${Math.round(h)}px`) st.height = `${Math.round(h)}px`; + } + + end(finished: boolean): void { + if (!this.isRunning()) return; + this.at = -1; + this.target = null; + this.watch.disconnect(); + window.removeEventListener('resize', this.onMove); + window.removeEventListener('scroll', this.onMove, true); + document.removeEventListener('keydown', this.onKey, true); + if (this.root) setHidden(this.root, true); + const back = this.returnTo; + this.returnTo = null; + if (back?.isConnected) back.focus({ preventScroll: true }); + const done = this.done; + this.done = null; + if (finished) done?.(); + } +} From de0fb09c4002f66553c57d050da4d663b577cd8b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:08 -0500 Subject: [PATCH 20/30] feat(dock): the Terminal panel is the family's shared dock, with tabs for shells, Claude Code, Codex and Cursor The panel keeps its place in the panel framework (any group, floating, per workspace) and now holds the shared module in hosted placement. Shells are plain tabs with no agent access; Claude Code, Codex and Cursor run as tabs of their own; the ask line opens Claude Code with what was typed. The permission question is the module's dialog: Deny, Allow once, Always allow that agent; Escape refuses as before. A window that connects while a question is waiting is sent it again. The old panel file, its styles and the app's own consent dialog are removed. --- backend/app/engine/bus.py | 7 + backend/app/routers/live.py | 4 + frontend/src/app/app.ts | 31 +--- frontend/src/dock-adapter.ts | 238 ++++++++++++++++++++++++++++ frontend/src/panels/agents.ts | 2 +- frontend/src/panels/terminal.ts | 163 ------------------- frontend/src/styles/base.css | 10 -- frontend/src/styles/dock-tokens.css | 61 +++++++ frontend/src/ui/keys.ts | 2 +- 9 files changed, 315 insertions(+), 203 deletions(-) create mode 100644 frontend/src/dock-adapter.ts delete mode 100644 frontend/src/panels/terminal.ts create mode 100644 frontend/src/styles/dock-tokens.css diff --git a/backend/app/engine/bus.py b/backend/app/engine/bus.py index 07d3c62..4b4110b 100644 --- a/backend/app/engine/bus.py +++ b/backend/app/engine/bus.py @@ -20,6 +20,10 @@ def __init__(self) -> None: self.clients: set[Client] = set() self._ids = itertools.count(1) self._replies: dict[int, asyncio.Future] = {} + self._asking: dict[int, dict] = {} + + def waiting(self) -> list[dict]: + return list(self._asking.values()) def bind(self, loop: asyncio.AbstractEventLoop) -> None: self.loop = loop @@ -67,6 +71,8 @@ async def ask_window(self, message: dict, timeout: float, first: bool = False) - fut: asyncio.Future = asyncio.get_running_loop().create_future() self._replies[rid] = fut payload = {"id": str(rid), **message, "requestId": rid, "expiresIn": timeout, "expiresAt": time.time() + timeout} + if not first: + self._asking[rid] = payload for w in windows: try: w.queue.put_nowait(payload) @@ -82,6 +88,7 @@ async def ask_window(self, message: dict, timeout: float, first: bool = False) - return None finally: self._replies.pop(rid, None) + self._asking.pop(rid, None) self._deliver({"type": "withdrawn", "requestId": rid, "id": str(rid), "of": message.get("type"), "reason": reason}, ("ui",)) def answer(self, rid: int, value: dict) -> bool: diff --git a/backend/app/routers/live.py b/backend/app/routers/live.py index 85d9699..3e20043 100644 --- a/backend/app/routers/live.py +++ b/backend/app/routers/live.py @@ -35,6 +35,10 @@ async def slow(message: dict) -> None: sender = asyncio.create_task(pump()) put({"type": "hello", "version": __version__, "revision": host.revision, "running": host.running, "core": host.available, "error": host.error, "client": client.id}) + if window: + for waiting in host.bus.waiting(): + if waiting.get("type") == "consent": + put(waiting) tasks: set[asyncio.Task] = set() try: while True: diff --git a/frontend/src/app/app.ts b/frontend/src/app/app.ts index ebffa38..540521a 100644 --- a/frontend/src/app/app.ts +++ b/frontend/src/app/app.ts @@ -11,7 +11,7 @@ import { LogPanel } from '../panels/log'; import { MediaPanel } from '../panels/media'; import { PresetsPanel } from '../panels/presets'; import { QueuePanel } from '../panels/queue'; -import { TerminalPanel } from '../panels/terminal'; +import { TerminalPanel } from '../dock-adapter'; import { WatchPanel } from '../panels/watch'; import { Dialog, promptName } from '../ui/dialogs'; import { demoMenuEntries, openDemo } from '../ui/demos'; @@ -44,7 +44,6 @@ class App { private status!: HTMLElement; private wsSelect!: HTMLSelectElement; private revealed = false; - private consent: Dialog | null = null; private approval: { id: number; dialog: Dialog } | null = null; private readonly answered = new Set(); @@ -158,7 +157,7 @@ class App { } private registerPanels(): void { - this.terminal = new TerminalPanel(ctx); + this.terminal = new TerminalPanel(ctx, { show: () => this.dock.show('terminal'), close: () => this.dock.close('terminal'), settings: () => this.dock.show('agents') }); this.queue = new QueuePanel(ctx); this.dock.register('queue', 'Queue', () => this.queue); this.dock.register('encoding', 'Encoding', () => new EncodingPanel(ctx)); @@ -247,7 +246,6 @@ class App { private bindEngine(): void { ctx.client.events.on('toast', (ev) => toast(String(ev.text ?? ev.message ?? ''), ev.kind === 'error' ? 'error' : ev.kind === 'ok' ? 'ok' : 'info')); - ctx.client.events.on('consent', (ev) => this.askConsent(ev)); ctx.client.events.on('approvals', (ev) => this.approvals((ev.pending as Approval[] | undefined) ?? [])); ctx.client.events.on('open', () => void ctx.client.call<{ pending: Approval[] }>('agents.approvals').then((s) => this.approvals(s.pending)).catch(() => undefined)); ctx.client.events.on('notify', (ev) => this.notify(ev)); @@ -370,7 +368,7 @@ class App { decided.dialog.close(); decided.dialog.scrim.remove(); } - if (this.approval || this.consent?.isOpen) return; + if (this.approval || this.terminal.dock.consent?.isOpen()) return; const next = pending.find((r) => !this.answered.has(r.id)); if (!next) return; const d = new Dialog('Allow this agent action?', 500); @@ -395,29 +393,6 @@ class App { d.open(); } - private askConsent(ev: ServerEvent): void { - const rid = ev.requestId; - const who = String(ev.client ?? 'An agent').replace(/^mcp:/, ''); - this.consent?.close(); - const d = new Dialog('Allow an agent to change the queue?', 460); - d.scrim.dataset.automationId = 'consent'; - d.body.appendChild(el(`

${escapeHtml(who)} wants to use formencoder's tools (${escapeHtml(String(ev.detail ?? 'edit'))}). Queue changes are undoable. Agents you start from the Terminal panel never ask.

`)); - let answered = false; - const answer = (allow: boolean, remember: string): void => { - if (answered) return; - answered = true; - ctx.client.reply(rid, { allow, remember }); - d.close(); - d.scrim.remove(); - }; - d.onClose = () => answer(false, 'none'); - d.button('Don’t Allow', 'ghost', () => answer(false, 'none')); - d.button('Allow Always', '', () => answer(true, 'always')); - d.button('Allow', 'primary', () => answer(true, 'session')); - this.consent = d; - d.open(); - } - private automation(): void { const elements = (): Array<{ id: string; tag: string; text: string; visible: boolean; rect: number[] }> => Array.from(document.querySelectorAll('[data-automation-id]')).map((n) => { diff --git a/frontend/src/dock-adapter.ts b/frontend/src/dock-adapter.ts new file mode 100644 index 0000000..d55bfe2 --- /dev/null +++ b/frontend/src/dock-adapter.ts @@ -0,0 +1,238 @@ +import type { Ctx } from './app/ctx'; +import type { ConsentChoice, ConsentRequest, DockAdapter, DockAgentStatus, DockChannel, DockErrorKind, DockProgram, DockProgramStatus, DockTerminal, PtyKind, StoredChoiceState } from './dock/adapter'; +import { Dock } from './dock/dock'; +import { api, LOCAL_HEADERS, RpcFailure, windowTicket, wsUrl, type ServerEvent } from './engine/client'; +import type { Panel } from './ui/dock'; +import './dock/dock.css'; +import './styles/dock-tokens.css'; + +type Kind = Exclude; +interface Row { id: string; title: string; cwd?: string; kind?: string; alive?: boolean; exited?: boolean } +interface Program { installed: boolean; version: string | null; signedIn: boolean | null; install: string } +interface Refusal { code?: string; message?: string } + +export interface PanelHost { + show(): void; + close(): void; + settings(): void; +} + +const KINDS: PtyKind[] = ['shell', 'claude', 'codex', 'cursor', 'agent']; +const PROGRAMS: DockProgram[] = ['claude', 'codex', 'cursor']; +const NOTES = ['Changes to the queue can be undone.', 'Claude Code, Codex and Cursor tabs you start in the Terminal panel do not ask.']; + +function detail(err: unknown): Refusal | string | null { + if (!(err instanceof RpcFailure)) return null; + try { + const body = JSON.parse(err.message) as { detail?: unknown }; + if (typeof body.detail === 'string') return body.detail; + if (body.detail && typeof body.detail === 'object') return body.detail as Refusal; + } catch { + return err.message; + } + return err.message; +} + +function errorKind(err: unknown): DockErrorKind | null { + if (err instanceof TypeError) return 'unreachable'; + if (!(err instanceof RpcFailure)) return null; + const said = detail(err); + if (typeof said === 'object' && said?.code === 'not_installed') return 'notInstalled'; + if (err.code === 403) return 'refused'; + if (err.code === 502 || err.code === 503 || err.code === 504) return 'unreachable'; + if ((err.code === 404 || err.code === 405) && typeof said === 'string' && /^(Not Found|Method Not Allowed)$/i.test(said)) return 'oldEngine'; + return null; +} + +function record(row: Row): DockTerminal { + const kind = KINDS.includes(row.kind as PtyKind) ? row.kind as PtyKind : 'shell'; + const alive = row.alive ?? row.exited !== true; + return row.cwd ? { id: row.id, title: row.title, alive, kind, tip: row.cwd } : { id: row.id, title: row.title, alive, kind }; +} + +function channel(id: string): DockChannel { + let data = (_chunk: string | Uint8Array): void => undefined; + let exit = (): void => undefined; + let lost = (): void => undefined; + let socket: WebSocket | null = null; + let shut = false; + let size = { cols: 100, rows: 30 }; + const send = (message: unknown): void => { + if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message)); + }; + const control = (text: string): void => { + let message: { type?: string }; + try { + message = JSON.parse(text) as { type?: string }; + } catch { + return; + } + if (message.type === 'hello') { + data(''); + send({ type: 'resize', cols: size.cols, rows: size.rows }); + } else if (message.type === 'exit') exit(); + else if (message.type === 'restart') data('\x1bc'); + }; + const connect = async (): Promise => { + const ticket = await windowTicket(); + if (shut) return; + const made = new WebSocket(wsUrl(`/api/terminal/ws?session=${encodeURIComponent(id)}&typed=1&cols=${size.cols}&rows=${size.rows}&ticket=${encodeURIComponent(ticket)}`)); + made.binaryType = 'arraybuffer'; + socket = made; + made.addEventListener('message', (event) => { + if (typeof event.data === 'string') data(event.data); + else control(new TextDecoder().decode(event.data as ArrayBuffer)); + }); + made.addEventListener('close', () => { + if (socket === made) socket = null; + if (!shut) lost(); + }); + }; + void connect(); + return { + send: (chunk) => send({ type: 'input', data: chunk }), + resize: (cols, rows) => { + size = { cols, rows }; + send({ type: 'resize', cols, rows }); + }, + onData: (handler) => { data = handler; }, + onExit: (handler) => { exit = handler; }, + onClose: (handler) => { lost = handler; }, + close: () => { + shut = true; + socket?.close(); + }, + }; +} + +function program(value: Program | undefined): DockProgramStatus | undefined { + return value ? { installed: value.installed, version: value.version, install: value.install, signedIn: value.signedIn } : undefined; +} + +function question(ev: ServerEvent): ConsentRequest { + const answers = Array.isArray(ev.answers) ? ev.answers as unknown[] : ['deny', 'once', 'always']; + const offers = (['deny', 'once', 'always'] as ConsentChoice[]).filter((choice) => answers.includes(choice)); + const request: ConsentRequest = { + id: String(ev.id ?? ev.requestId), + agent: typeof ev.agent === 'string' ? ev.agent : String(ev.client ?? '').replace(/^mcp:/, ''), + what: typeof ev.what === 'string' && ev.what ? ev.what : 'make changes', + offers, + always: ev.alwaysScope === 'all' ? 'all' : 'agent', + escape: 'deny', + notes: NOTES, + }; + if (typeof ev.expiresAt === 'number') request.expires = Math.round(ev.expiresAt * 1000); + return request; +} + +function adapterFor(ctx: Ctx, host: PanelHost): DockAdapter { + return { + words: { + app: 'formencoder', + noun: 'queue', + example: 'make a YouTube file from this clip', + start: './formencoder boot', + lead: "Ask Claude Code to add files to the queue, pick presets and start encodes. It works through formencoder's own tools.", + }, + strings: { + empty: 'No terminal is open. Start a shell with the plus button, or Claude Code with the agent button.', + agentTab: 'A terminal an outside agent opened, read only', + tourPanelBody: 'This panel holds your terminals and Claude Code, an assistant that can work on your {noun} for you. Close it from its tab and open it again from the Window menu.', + tourChatBody: 'Type what you want in this line, for example "{example}", and press Enter. Claude Code opens in a new tab and does it in {app}.', + tourAskBody: 'If another AI program on this computer wants to change your {noun}, {app} asks you first in a box in the middle of the window. Choose Deny, Allow once or Always allow. Outside agents in the menu here opens the Agents panel, where the allowed agents are listed and can be forgotten.', + }, + placement: { mode: 'hosted', request: (open) => { if (open) host.show(); else host.close(); } }, + isDockChord: () => false, + chordLabel: () => '', + tabs: () => ({ builtin: ['shell', 'claude', 'codex', 'cursor'] }), + classes: { iconButton: 'cv-icon-btn', button: 'cv-btn', primaryButton: 'cv-btn-primary', input: 'cv-input', select: 'fx-select', note: 'cv-note' }, + t: (_key, english) => english, + onTheme: (handler) => { document.addEventListener('nm:ui-settings-changed', handler); }, + keyHeaders: () => ({ ...LOCAL_HEADERS }), + errors: { + message: (err) => { + const said = detail(err); + return typeof said === 'string' ? said : said?.message ?? null; + }, + kind: errorKind, + }, + terminal: { + list: async () => { + const [own, outside] = await Promise.all([api<{ tabs: Row[] }>('/api/terminal/tabs'), api<{ sessions: Row[] }>('/api/terminal/sessions')]); + return [...own.tabs, ...outside.sessions.filter((row) => row.kind === 'agent')].map(record); + }, + open: async (kind: Kind, o) => record(await api('/api/terminal/tabs', { + method: 'POST', + body: JSON.stringify({ kind, cols: o.cols, rows: o.rows, ...(o.prompt ? { prompt: o.prompt } : {}), ...(o.resume ? { resume: o.resume } : {}) }), + })), + restart: async (id) => { await api(`/api/terminal/sessions/${encodeURIComponent(id)}/restart`, { method: 'POST', body: '{}' }); }, + close: async (id) => { + try { + await api(`/api/terminal/sessions/${encodeURIComponent(id)}`, { method: 'DELETE' }); + } catch (err) { + if (!(err instanceof RpcFailure) || err.code !== 404) throw err; + } + }, + channel, + scrollback: 8000, + }, + agentStatus: async (): Promise => { + const status = await api<{ agents: Partial> }>('/api/terminal/agents'); + const out: DockAgentStatus = {}; + for (const kind of PROGRAMS) { + const found = program(status.agents[kind]); + if (found) out[kind] = found; + } + return out; + }, + consent: { + subscribe: (add, withdraw) => { + ctx.client.events.on('consent', (ev) => add(question(ev))); + ctx.client.events.on('event', (ev) => { + if (ev.type === 'withdrawn' && ev.of === 'consent') withdraw(String(ev.id ?? ev.requestId)); + }); + }, + answer: async (id, choice) => { + ctx.client.reply(Number(id), { allow: choice !== 'deny', remember: choice === 'deny' ? 'none' : choice }); + }, + }, + storedChoice: { + get: async (): Promise => { + const status = await api<{ consent: { policy: string; sealBroken?: boolean } }>('/api/agents/status'); + return { value: status.consent.policy === 'deny' ? 'blocked' : 'ask', changedOutside: status.consent.sealBroken === true }; + }, + set: async () => { throw new Error('formencoder keeps one answer per agent; forget them in the Agents panel.'); }, + }, + openSettings: () => host.settings(), + }; +} + +export class TerminalPanel implements Panel { + readonly id = 'terminal'; + readonly title = 'Terminal'; + readonly el: HTMLElement; + readonly dock: Dock; + + constructor(ctx: Ctx, private readonly host: PanelHost) { + this.el = document.createElement('div'); + this.el.className = 'fe-dock-host'; + this.dock = new Dock(adapterFor(ctx, host)); + this.dock.mount(this.el); + this.dock.root.querySelector('.ft-dock-stage')?.setAttribute('data-automation-id', 'terminal.screen'); + ctx.client.events.on('terminals', () => void this.dock.sync()); + } + + shown(): void { + this.dock.shown(); + this.dock.focus(); + } + + hidden(): void { + this.dock.hidden(); + } + + launch(kind: 'shell' | DockProgram): void { + this.host.show(); + void this.dock.show(kind); + } +} diff --git a/frontend/src/panels/agents.ts b/frontend/src/panels/agents.ts index e42b9da..c0e3ec3 100644 --- a/frontend/src/panels/agents.ts +++ b/frontend/src/panels/agents.ts @@ -101,7 +101,7 @@ export class AgentsPanel implements Panel { setText(q(this.el, '.fx-agents-ws'), s.workspace.path); for (const b of Array.from(this.el.querySelectorAll('[data-install]'))) setClass(b, 'is-missing', !s.clients[b.dataset.install as string]); const allowed = [...s.consent.always.map((c) => `${c} (always)`), ...s.consent.session.filter((c) => !s.consent.always.includes(c)).map((c) => `${c} (this session)`)]; - setText(q(this.el, '.fx-agents-allowed'), allowed.length ? allowed.join(', ') : `Policy: ${s.consent.policy}. Agents from the Terminal panel are always trusted; others ask once.`); + setText(q(this.el, '.fx-agents-allowed'), allowed.length ? allowed.join(', ') : `Policy: ${s.consent.policy}. Claude Code, Codex and Cursor tabs started in the Terminal panel are trusted; every other agent asks.`); setClass(q(this.el, '.fx-agents-seal'), 'is-shown', s.consent.sealBroken === true); if (!this.feed.length) this.feed = s.activity.filter((a) => a.source !== 'ui'); this.renderFeed(); diff --git a/frontend/src/panels/terminal.ts b/frontend/src/panels/terminal.ts deleted file mode 100644 index 975a5e5..0000000 --- a/frontend/src/panels/terminal.ts +++ /dev/null @@ -1,163 +0,0 @@ -import type { Ctx } from '../app/ctx'; -import { api, windowTicket, wsUrl } from '../engine/client'; -import type { Panel } from '../ui/dock'; -import { el, q, setClass, setText } from '../ui/dom'; -import { icon } from '../ui/icons'; - -interface TermStatus { - available: boolean; - pty: boolean; - shell: string; - cwd: string; - agents: Record; -} - -type XTerm = import('@xterm/xterm').Terminal; -type Fit = import('@xterm/addon-fit').FitAddon; - -export class TerminalPanel implements Panel { - readonly id = 'terminal'; - readonly title = 'Terminal'; - readonly el: HTMLElement; - private readonly host: HTMLElement; - private term: XTerm | null = null; - private fit: Fit | null = null; - private ws: WebSocket | null = null; - private started = false; - private status: TermStatus | null = null; - - constructor(private readonly ctx: Ctx) { - this.el = el(`
-
- ${icon('terminal', 14)}Agent terminal - - - - - - -
-
-
Agents started here are trusted and already know formencoder: CLAUDE.md, AGENTS.md, the formencoder MCP server and the formencoder-harness skill are in this folder.
-
`); - this.host = q(this.el, '.fx-term-host'); - for (const b of Array.from(this.el.querySelectorAll('[data-launch]'))) { - b.dataset.automationId = `terminal.launch.${b.dataset.launch}`; - b.addEventListener('click', () => this.launch(b.dataset.launch as string)); - } - q(this.el, '[data-act="restart"]').addEventListener('click', () => this.restart()); - } - - shown(): void { - if (!this.started) { - this.started = true; - void this.start(); - } else this.resized(); - this.term?.focus(); - } - - resized(): void { - if (!this.fit || this.el.hidden) return; - try { - this.fit.fit(); - } catch { - return; - } - this.sendSize(); - } - - private css(name: string, fb: string): string { - return getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fb; - } - - private async start(): Promise { - try { - this.status = await api('/api/terminal/status'); - setText(q(this.el, '.fx-term-cwd'), this.status.cwd); - for (const b of Array.from(this.el.querySelectorAll('[data-launch]'))) { - const on = !!this.status.agents[b.dataset.launch as string]; - setClass(b, 'is-missing', !on); - b.title = on ? b.title : `${b.textContent?.trim()} is not installed on this computer`; - } - } catch { - this.status = null; - } - const [{ Terminal }, { FitAddon }] = await Promise.all([import('@xterm/xterm'), import('@xterm/addon-fit')]); - await import('@xterm/xterm/css/xterm.css'); - const term = new Terminal({ - fontFamily: this.css('--font-mono', 'JetBrains Mono, ui-monospace, monospace'), - fontSize: 12.5, - lineHeight: 1.15, - cursorBlink: true, - allowProposedApi: false, - scrollback: 8000, - theme: { - background: this.css('--bg-primary', '#111111'), - foreground: this.css('--text-primary', '#f7f7f7'), - cursor: this.css('--accent-color', '#f2545b'), - selectionBackground: 'rgba(242,84,91,0.3)', - }, - }); - const fit = new FitAddon(); - term.loadAddon(fit); - term.open(this.host); - this.term = term; - this.fit = fit; - try { - fit.fit(); - } catch { - this.term.resize(100, 30); - } - term.onData((d) => this.ws?.readyState === WebSocket.OPEN && this.ws.send(d)); - term.onResize(() => this.sendSize()); - new ResizeObserver(() => this.resized()).observe(this.host); - this.connect(); - } - - private async connect(launch?: string): Promise { - const t = this.term; - if (!t) return; - const ticket = await windowTicket(); - const ws = new WebSocket(wsUrl(`/api/terminal/ws?cols=${t.cols}&rows=${t.rows}&ticket=${encodeURIComponent(ticket)}${launch ? `&launch=${launch}` : ''}`)); - this.ws = ws; - ws.onmessage = (ev) => { - const s = String(ev.data); - if (s === '{"exit": true}') { - t.write('\r\n\x1b[2m[shell exited, press Restart for a new one]\x1b[0m\r\n'); - return; - } - t.write(s); - }; - ws.onclose = () => { - if (this.ws === ws) this.ws = null; - }; - } - - private sendSize(): void { - const t = this.term; - if (t && this.ws?.readyState === WebSocket.OPEN) this.ws.send(`\u0000${JSON.stringify({ resize: [t.cols, t.rows] })}`); - } - - restart(launch?: string): void { - this.ws?.close(); - this.term?.reset(); - this.connect(launch); - this.term?.focus(); - } - - launch(agent: string): void { - this.ctx.ui.emit('showPanel', 'terminal'); - if (!this.started) { - this.started = true; - void this.start().then(() => this.launch(agent)); - return; - } - if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(`\u0000${JSON.stringify({ launch: agent })}`); - else this.restart(agent); - this.term?.focus(); - } - - write(text: string): void { - if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(text); - } -} diff --git a/frontend/src/styles/base.css b/frontend/src/styles/base.css index c5ea9a7..a0d68a3 100644 --- a/frontend/src/styles/base.css +++ b/frontend/src/styles/base.css @@ -155,16 +155,6 @@ body.theme-light .cv-menu, body.theme-light .cv-dialog, body.theme-light .cv-toa .fx-color::-webkit-color-swatch-wrapper { padding: 0; } .fx-color::-webkit-color-swatch { border: 0; border-radius: 3px; } -.fx-term { flex: 1; min-height: 0; display: grid; grid-template-rows: 34px minmax(0, 1fr) auto; background: var(--bg-primary); } -.fx-term-bar { display: flex; align-items: center; gap: 6px; padding: 0 8px; background: var(--surface-0); border-bottom: 1px solid var(--line-0); overflow: hidden; white-space: nowrap; } -.fx-term-title { display: inline-flex; align-items: center; gap: 6px; margin-right: 4px; color: var(--text-primary); font-size: var(--fs-12); font-weight: 500; } -.fx-agent-btn { display: inline-flex; align-items: center; gap: 5px; height: 24px; flex: none; padding: 0 9px; border: 1px solid var(--line-2); border-radius: 6px; background: var(--surface-1); color: var(--text-secondary); font: inherit; font-size: var(--fs-11); cursor: pointer; } -.fx-agent-btn:hover { border-color: var(--accent-line); background: var(--accent-soft); color: var(--text-primary); } -.fx-agent-btn.is-missing { opacity: 0.5; } -.fx-term-cwd { min-width: 0; overflow: hidden; color: var(--text-muted); font-family: var(--font-mono); font-size: var(--fs-10); text-overflow: ellipsis; } -.fx-term-host { min-height: 0; padding: 4px 0 0 8px; overflow: hidden; } -.fx-term-host .xterm { height: 100%; } -.fx-term-hint { padding: 5px 10px; border-top: 1px solid var(--line-0); color: var(--text-muted); font-size: var(--fs-10); line-height: 1.4; } .fx-agents { flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: auto; } .fx-agents-sec { display: flex; flex-direction: column; gap: 8px; padding: 10px 12px; border-bottom: 1px solid var(--line-0); color: var(--text-secondary); font-size: var(--fs-12); } diff --git a/frontend/src/styles/dock-tokens.css b/frontend/src/styles/dock-tokens.css new file mode 100644 index 0000000..211b6cc --- /dev/null +++ b/frontend/src/styles/dock-tokens.css @@ -0,0 +1,61 @@ +:root { + --z-overlay: var(--z-modal); + --dock-bg: var(--bg-primary); + --dock-bar-bg: var(--surface-0); + --dock-raised: var(--surface-raised); + --dock-hover: var(--bg-hover); + --dock-input-bg: var(--bg-input); + --dock-border: var(--line-0); + --dock-edge: var(--line-0); + --dock-divider: var(--line-0); + --dock-tab-border: var(--line-2); + --dock-outline: var(--accent-line); + --dock-scrim: var(--bg-scrim); + --dock-text: var(--text-primary); + --dock-text-dim: var(--text-secondary); + --dock-text-muted: var(--text-muted); + --dock-tab-text: var(--text-secondary); + --dock-accent: var(--accent-color); + --dock-accent-line: var(--accent-line); + --dock-accent-ink: var(--accent-ink); + --dock-danger: var(--danger); + --dock-danger-text: var(--danger-text); + --dock-space-1: var(--space-1); + --dock-space-2: var(--space-2); + --dock-space-3: var(--space-3); + --dock-space-4: var(--space-4); + --dock-radius-xs: var(--radius-xs); + --dock-radius-sm: var(--radius-sm); + --dock-radius: var(--radius); + --dock-radius-md: var(--radius-md); + --dock-tab-radius: var(--radius); + --dock-head-h: 34px; + --dock-tab-h: 24px; + --dock-ibtn: 26px; + --dock-ask-h: 40px; + --dock-chat-bar-h: 28px; + --dock-ctl-h: var(--ctl-md); + --dock-icon: 14px; + --dock-icon-sm: 12px; + --dock-icon-xs: 10px; + --dock-icon-note: 12px; + --dock-icon-send: 14px; + --dock-stage-pad: 4px 0 0 8px; + --dock-ask-ctl-h: var(--ctl-md); + --dock-tab-accent: var(--accent-color); + --dock-fs-xs: var(--fs-11); + --dock-fs-sm: var(--fs-12); + --dock-fs-md: var(--fs-13); + --dock-font-mono: var(--font-mono); + --dock-term-bg: var(--bg-primary); + --dock-term-fg: var(--text-primary); + --dock-term-cursor: var(--accent-color); + --dock-term-selection: var(--accent-soft); + --dock-term-font-size: 12.5px; + --dock-term-line-height: 1.15; + --dock-term-contrast: 1; +} + +.fe-dock-host { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; background: var(--bg-primary); } +.fe-dock-host[hidden] { display: none; } +.fe-dock-host > .ft-dock { flex: 1; } diff --git a/frontend/src/ui/keys.ts b/frontend/src/ui/keys.ts index f20d7f9..1d7446c 100644 --- a/frontend/src/ui/keys.ts +++ b/frontend/src/ui/keys.ts @@ -47,7 +47,7 @@ export class Keys { private down(e: KeyboardEvent): void { const t = e.target as HTMLElement; if (t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement || t?.isContentEditable) return; - if (t?.closest?.('.fx-term-host, .xterm')) return; + if (t?.closest?.('.ft-dock, .ft-consent, .ft-tour')) return; if (anyDialogOpen() || document.querySelector('.cv-menu:not([hidden])') || document.querySelector('.fx-palette-scrim:not([hidden])')) return; const combo = comboOf(e); if (!combo) return; From 9c09be03d40a701e653f4737afbf2ef030b74982 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:08 -0500 Subject: [PATCH 21/30] feat(agents): a question is withdrawn when its caller goes away, tabs use the MCP entry formencoder_tab, and the sync checks the dock folder An agent that hangs up while the person is being asked no longer leaves its question on screen: the engine notices within a second and tells every window. The agent workspace's Claude Code, Codex and Cursor configs name their MCP entry formencoder_tab, apart from the entry an outside agent installs. agents sync fails, naming the file, when frontend/src/dock does not match its MANIFEST.json or imports from the app, and agents/manifest.json lists the dock's tabs. A panel that moves to an earlier area on a workspace switch is no longer hidden by the area it left. The wiki, the workspace notes and the harness skill say that a plain shell tab carries no agent access. --- .../session-and-connection/SUB-SKILL.md | 2 +- .../session-and-connection/SUB-SKILL.md | 2 +- .docs/wiki/Agents.md | 2 +- agents/manifest.json | 6 +- backend/app/agent/consent.py | 18 ++++ backend/app/agent/templates/AGENTS.md | 2 +- backend/app/agent/templates/CLAUDE.md | 2 +- backend/app/agent/workspace.py | 9 +- backend/app/routers/mcp.py | 2 +- backend/app/routers/rpc.py | 2 +- backend/tests/test_dock_module.py | 83 +++++++++++++++++++ frontend/src/ui/dock.ts | 2 +- setup/agents.py | 34 +++++++- 13 files changed, 150 insertions(+), 16 deletions(-) create mode 100644 backend/tests/test_dock_module.py diff --git a/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md index c6de4d0..abbf396 100644 --- a/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -15,7 +15,7 @@ description: How an agent reaches formencoder. Use when the formencoder MCP serv | Started from | Trust | Configuration | | --- | --- | --- | -| formencoder's Terminal panel (the Claude Code, Codex or Cursor buttons, or typed) | trusted: the shell carries the session token, nothing asks | the agent workspace: `CLAUDE.md`, `AGENTS.md`, `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and this skill | +| formencoder's Terminal panel, a Claude Code, Codex or Cursor tab (its buttons or the ask line; the MCP server is named `formencoder_tab` there) | trusted while the tab is open: the program carries the tab's token, nothing asks; a program typed into a plain shell tab asks like any other | the agent workspace: `CLAUDE.md`, `AGENTS.md`, `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and this skill | | The formencoder repository | asks once per client in the window | `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` at the repository root | | Any other folder | asks once per client in the window | `./formencoder agents install` (or the Agents panel) adds the MCP server and this skill to the user's Claude Code, Codex and Cursor setup | diff --git a/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md index c6de4d0..abbf396 100644 --- a/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -15,7 +15,7 @@ description: How an agent reaches formencoder. Use when the formencoder MCP serv | Started from | Trust | Configuration | | --- | --- | --- | -| formencoder's Terminal panel (the Claude Code, Codex or Cursor buttons, or typed) | trusted: the shell carries the session token, nothing asks | the agent workspace: `CLAUDE.md`, `AGENTS.md`, `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and this skill | +| formencoder's Terminal panel, a Claude Code, Codex or Cursor tab (its buttons or the ask line; the MCP server is named `formencoder_tab` there) | trusted while the tab is open: the program carries the tab's token, nothing asks; a program typed into a plain shell tab asks like any other | the agent workspace: `CLAUDE.md`, `AGENTS.md`, `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and this skill | | The formencoder repository | asks once per client in the window | `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` at the repository root | | Any other folder | asks once per client in the window | `./formencoder agents install` (or the Agents panel) adds the MCP server and this skill to the user's Claude Code, Codex and Cursor setup | diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index dd11f03..ad7983a 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -4,7 +4,7 @@ formencoder's engine exposes every command to agents through MCP, the same comma ## Three ways in -- **In formencoder**: the Terminal panel (or the Agent workspace) opens a shell in formencoder's agent workspace. Its Claude Code, Codex and Cursor buttons start an agent that already has the `formencoder` MCP server and the `formencoder-harness` skill; it works without permission prompts. +- **In formencoder**: the Terminal panel (or the Agent workspace) opens tabs in formencoder's agent workspace. Its Claude Code, Codex and Cursor buttons each start that agent in a tab of its own; it already has formencoder's MCP server (named `formencoder_tab` there) and the `formencoder-harness` skill, and works without permission prompts while its tab is open. A plain shell tab carries no agent access: a program typed there asks like any outside agent. - **From the repository**: `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` run `./formencoder mcp`, which starts the engine when it is not running. The first change asks once in the formencoder window: Allow, Allow Always or Don't Allow. - **From anywhere**: `./formencoder agents install` (or the Agents panel) adds the MCP server and the skill to your Claude Code, Codex and Cursor setup. diff --git a/agents/manifest.json b/agents/manifest.json index 36e71f3..dca23ee 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -303,8 +303,10 @@ "floating" ], "tabs": [ - "terminal", - "agents" + "shell", + "claude", + "codex", + "cursor" ] }, "extensions": { diff --git a/backend/app/agent/consent.py b/backend/app/agent/consent.py index e8f556d..b142ca8 100644 --- a/backend/app/agent/consent.py +++ b/backend/app/agent/consent.py @@ -1,5 +1,7 @@ from __future__ import annotations +import asyncio +import contextlib import json import secrets import time @@ -106,6 +108,22 @@ def state() -> dict: "answers": list(ANSWERS), "alwaysScope": ALWAYS_SCOPE, "askSeconds": ASK_SECONDS, "blockedStopsTabs": True} +GONE = "The caller went away before the person answered." + + +async def gate_for(request, source: str, token: str | None, mutating: bool, detail: str = "", what: str = "") -> str | None: + asking = asyncio.ensure_future(gate(source, token, mutating, detail=detail, what=what)) + while True: + done, _ = await asyncio.wait({asking}, timeout=1.0) + if done: + return asking.result() + if await request.is_disconnected(): + asking.cancel() + with contextlib.suppress(asyncio.CancelledError): + await asking + return GONE + + async def gate(source: str, token: str | None, mutating: bool, detail: str = "", what: str = "") -> str | None: if not mutating: return None diff --git a/backend/app/agent/templates/AGENTS.md b/backend/app/agent/templates/AGENTS.md index 915175f..2b61084 100644 --- a/backend/app/agent/templates/AGENTS.md +++ b/backend/app/agent/templates/AGENTS.md @@ -2,7 +2,7 @@ This folder is formencoder {{VERSION}}'s agent workspace. formencoder (the form family's media encoder) is running on this computer and the person sees its window; your queue changes appear there live. -- Drive formencoder with the `formencoder` MCP server (`.codex/config.toml` and `.cursor/mcp.json` here run `{{MCP}}`), or with the `formencoder` command line (`formencoder encode FILE --preset ID`, `formencoder queue`, `formencoder exec ID JSON`, `formencoder batch JSON`, `formencoder commands FILTER`, `formencoder describe ID`, `formencoder presets QUERY`, `formencoder probe FILE`, `formencoder frame OUT.png --output '#1'`). +- Drive formencoder with the `formencoder_tab` MCP server (`.codex/config.toml` and `.cursor/mcp.json` here run `{{MCP}}`), or with the `formencoder` command line (`formencoder encode FILE --preset ID`, `formencoder queue`, `formencoder exec ID JSON`, `formencoder batch JSON`, `formencoder commands FILTER`, `formencoder describe ID`, `formencoder presets QUERY`, `formencoder probe FILE`, `formencoder frame OUT.png --output '#1'`). - Read `.agents/skills/formencoder-harness/SKILL.md` first: it routes to the sub-skill for the job (queue and presets, export settings, effects and loudness, captions and metadata, watch folders and ingest, the form family, verifying). - Loop: `status`, then `probe`, then `encode` or queue plus `export_settings`, then `preview_frame`, then `verify`. Never report an encode you did not verify. diff --git a/backend/app/agent/templates/CLAUDE.md b/backend/app/agent/templates/CLAUDE.md index fe78087..79ddfcb 100644 --- a/backend/app/agent/templates/CLAUDE.md +++ b/backend/app/agent/templates/CLAUDE.md @@ -4,7 +4,7 @@ You are running inside formencoder {{VERSION}}, the form family's media encoder, ## How to drive formencoder -- Use the `formencoder` MCP server (configured in `.mcp.json` here; it runs `{{MCP}}`). Agents started from this terminal are trusted; nothing asks for permission. +- Use the `formencoder_tab` MCP server (configured in `.mcp.json` here; it runs `{{MCP}}`). A Claude Code, Codex or Cursor tab started from formencoder's Terminal panel is trusted and nothing asks for permission; a program typed into a plain shell tab asks the person like any outside agent. - If MCP is unavailable, the same surface is on the command line: `formencoder encode FILE --preset system/youtube-1080p`, `formencoder queue`, `formencoder exec ID '{"json": "params"}'`, `formencoder batch '[...]'`, `formencoder commands FILTER`, `formencoder describe ID`, `formencoder presets QUERY`, `formencoder probe FILE`, `formencoder frame out.png --output '#1' --time 2`, `formencoder wait`. - Read `.claude/skills/formencoder-harness/SKILL.md` before a non-trivial job. It routes to sub-skills for the queue and presets, export settings, effects and loudness, captions and metadata, watch folders and ingest, the form family bridge, and verifying. diff --git a/backend/app/agent/workspace.py b/backend/app/agent/workspace.py index b3e97a8..74c274c 100644 --- a/backend/app/agent/workspace.py +++ b/backend/app/agent/workspace.py @@ -19,6 +19,7 @@ def client_args(client: str) -> list[str]: TEMPLATES = Path(__file__).resolve().parent / "templates" SKILLS = ("formencoder-harness",) MANAGED = ("CLAUDE.md", "AGENTS.md", ".mcp.json", ".claude/settings.json", ".codex/config.toml", ".cursor/mcp.json") +TAB_ENTRY = "formencoder_tab" def root() -> Path: @@ -128,11 +129,11 @@ def ensure() -> Path: _shell_rc(base) _write(base / "CLAUDE.md", _render("CLAUDE.md", values)) _write(base / "AGENTS.md", _render("AGENTS.md", values)) - _write(base / ".mcp.json", json.dumps({"mcpServers": {"formencoder": {"type": "stdio", "command": command, "args": client_args("claude")}}}, indent=2) + "\n") + _write(base / ".mcp.json", json.dumps({"mcpServers": {TAB_ENTRY: {"type": "stdio", "command": command, "args": client_args("claude")}}}, indent=2) + "\n") toml_cmd = command.replace("\\", "\\\\") - _write(base / ".codex" / "config.toml", f'[mcp_servers.formencoder]\ncommand = "{toml_cmd}"\nargs = {json.dumps(client_args("codex"))}\nstartup_timeout_sec = 90\ntool_timeout_sec = 3600\n') - _write(base / ".cursor" / "mcp.json", json.dumps({"mcpServers": {"formencoder": {"command": command, "args": client_args("cursor")}}}, indent=2) + "\n") - claude_settings = {"enableAllProjectMcpServers": True, "enabledMcpjsonServers": ["formencoder"], "permissions": {"allow": ["mcp__formencoder", "Bash(formencoder:*)"]}} + _write(base / ".codex" / "config.toml", f'[mcp_servers.{TAB_ENTRY}]\ncommand = "{toml_cmd}"\nargs = {json.dumps(client_args("codex"))}\nstartup_timeout_sec = 90\ntool_timeout_sec = 3600\n') + _write(base / ".cursor" / "mcp.json", json.dumps({"mcpServers": {TAB_ENTRY: {"command": command, "args": client_args("cursor")}}}, indent=2) + "\n") + claude_settings = {"enableAllProjectMcpServers": True, "enabledMcpjsonServers": [TAB_ENTRY], "permissions": {"allow": [f"mcp__{TAB_ENTRY}", "Bash(formencoder:*)"]}} _write(base / ".claude" / "settings.json", json.dumps(claude_settings, indent=2) + "\n") if not stamp.is_file() or stamp.read_text(encoding="utf-8").strip() != __version__: _copy_skills(base) diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index a88443d..7c84d17 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -81,7 +81,7 @@ async def mcp(request: Request) -> Response: else: mutating = not tools.read_only(name) and not (name == "execute" and consent.query_command(args.get("command"))) what = f"run the command {args.get('command')}"[:120] if name == "execute" and isinstance(args.get("command"), str) else "" - denied = await consent.gate(client, token, mutating, detail=name, what=what) + denied = await consent.gate_for(request, client, token, mutating, detail=name, what=what) out = _ok(rid, tools.fail(denied) if denied else await tools.call(name, args, client), modern) else: out = _err(rid, -32601, f"Method not found: {method}") diff --git a/backend/app/routers/rpc.py b/backend/app/routers/rpc.py index fe05aa1..71ea6a7 100644 --- a/backend/app/routers/rpc.py +++ b/backend/app/routers/rpc.py @@ -48,7 +48,7 @@ async def call(request: Request) -> Response: if source.strip().lower() == "ui": source = "cli" rid = message.get("id") if isinstance(message, dict) else None - denied = await consent.gate(source, request.headers.get("x-formencoder-agent-token"), mutating=consent.mutating_rpc(message), what=f"run {_label(message)}"[:120]) + 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: return Response(json.dumps({"jsonrpc": "2.0", "id": rid, "error": {"code": -32003, "message": denied}}), media_type="application/json") why = await _reasons(message) diff --git a/backend/tests/test_dock_module.py b/backend/tests/test_dock_module.py new file mode 100644 index 0000000..ab3951e --- /dev/null +++ b/backend/tests/test_dock_module.py @@ -0,0 +1,83 @@ +import importlib.util +import json +import shutil + +from conftest import REPO + +DOCK = REPO / "frontend" / "src" / "dock" +FRONTEND = REPO / "frontend" + + +def agents(): + spec = importlib.util.spec_from_file_location("formencoder_agents_sync", REPO / "setup" / "agents.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_the_dock_folder_matches_its_manifest(): + assert agents().dock_problems() == [] + + +def test_a_changed_missing_or_extra_dock_file_is_named(tmp_path): + copy = tmp_path / "dock" + shutil.copytree(DOCK, copy) + (copy / "keys.ts").write_text((copy / "keys.ts").read_text(encoding="utf-8") + "\n", encoding="utf-8") + (copy / "dom.ts").unlink() + (copy / "mine.ts").write_text("import { api } from '../engine/client';\n", encoding="utf-8") + problems = agents().dock_problems(copy) + assert "keys.ts differs from MANIFEST.json" in problems + assert "dom.ts is missing" in problems + assert "mine.ts is extra" in problems + assert "mine.ts imports ../engine/client from outside the dock folder" in problems + + +def test_the_agent_manifest_describes_the_dock(): + dock = json.loads((REPO / "agents" / "manifest.json").read_text(encoding="utf-8"))["dock"] + assert dock == {"present": True, "positions": ["left", "right", "bottom", "floating"], "tabs": ["shell", "claude", "codex", "cursor"]} + + +def test_the_dialog_offers_only_what_the_engine_sends(): + adapter = (FRONTEND / "src" / "dock-adapter.ts").read_text(encoding="utf-8") + assert "(['deny', 'once', 'always'] as ConsentChoice[]).filter((choice) => answers.includes(choice))" in adapter + assert "remember: choice === 'deny' ? 'none' : choice" in adapter + assert "mode: 'hosted'" in adapter + + +def test_the_old_terminal_panel_is_gone(): + assert not (FRONTEND / "src" / "panels" / "terminal.ts").exists() + for path in (FRONTEND / "src").rglob("*"): + if path.is_file() and path.suffix in (".ts", ".css") and DOCK not in path.parents: + text = path.read_text(encoding="utf-8") + assert "fx-term" not in text and "askConsent" not in text, path.name + + +def test_a_waiting_question_is_sent_again_to_a_window_that_connects(): + import asyncio + + from app.engine.bus import Bus + + async def run(): + bus = Bus() + bus.join("ui") + asked = asyncio.create_task(bus.ask_window({"type": "consent", "agent": "probe"}, timeout=5)) + await asyncio.sleep(0) + waiting = bus.waiting() + assert len(waiting) == 1 and waiting[0]["type"] == "consent" and waiting[0]["id"] == str(waiting[0]["requestId"]) + assert bus.answer(waiting[0]["requestId"], {"allow": False}) + assert await asked == {"allow": False} + assert bus.waiting() == [] + + asyncio.run(run()) + + +def test_the_workspace_names_its_entry_for_tabs(tmp_path, monkeypatch): + from app.agent import workspace + + assert workspace.TAB_ENTRY == "formencoder_tab" + monkeypatch.setenv("FORMENCODER_DATA_DIR", str(tmp_path)) + workspace.ensure() + base = workspace.root() + assert list(json.loads((base / ".mcp.json").read_text(encoding="utf-8"))["mcpServers"]) == ["formencoder_tab"] + assert list(json.loads((base / ".cursor" / "mcp.json").read_text(encoding="utf-8"))["mcpServers"]) == ["formencoder_tab"] + assert "[mcp_servers.formencoder_tab]" in (base / ".codex" / "config.toml").read_text(encoding="utf-8") diff --git a/frontend/src/ui/dock.ts b/frontend/src/ui/dock.ts index 912763d..ac3be33 100644 --- a/frontend/src/ui/dock.ts +++ b/frontend/src/ui/dock.ts @@ -385,7 +385,7 @@ export class Dock { for (const grp of this.groups[a]) { for (const id of grp.panels) { const p = this.made.get(id); - if (p) { + if (p && p.el.parentElement === grp.body) { p.el.hidden = true; p.hidden?.(); } diff --git a/setup/agents.py b/setup/agents.py index 51931c9..e8b7be0 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -11,8 +11,10 @@ from __future__ import annotations +import hashlib import json import os +import re import shutil import subprocess import sys @@ -25,7 +27,9 @@ MIRROR = ROOT / ".agents" / "skills" / "formencoder-harness" SKILLS = ROOT / ".claude" / "skills" MANIFEST = ROOT / "agents" / "manifest.json" -DOCK = {"present": True, "positions": ["left", "right", "bottom", "floating"], "tabs": ["terminal", "agents"]} +DOCK = {"present": True, "positions": ["left", "right", "bottom", "floating"], "tabs": ["shell", "claude", "codex", "cursor"]} +DOCK_FOLDER = ROOT / "frontend" / "src" / "dock" +DOCK_IMPORT = re.compile(r"""(?:from|import)\s*\(?\s*['"]([^'"]+)['"]""") 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." @@ -290,6 +294,26 @@ def surfaces() -> list[str]: return problems +def dock_problems(folder: Path | None = None) -> list[str]: + folder = folder or DOCK_FOLDER + listed = folder / "MANIFEST.json" + if not listed.is_file(): + return ["MANIFEST.json is missing"] + wanted = json.loads(listed.read_text(encoding="utf-8")).get("files") or {} + found = {p.name: p for p in sorted(folder.iterdir()) if p.name != "MANIFEST.json"} + problems = [f"{name} is missing" for name in wanted if name not in found] + for name, path in found.items(): + if name not in wanted: + problems.append(f"{name} is extra") + elif not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != wanted[name]: + problems.append(f"{name} differs from MANIFEST.json") + if path.is_file() and path.suffix == ".ts": + for target in DOCK_IMPORT.findall(path.read_text(encoding="utf-8")): + if target.startswith("..") or target.startswith("/"): + problems.append(f"{name} imports {target} from outside the dock folder") + return problems + + def _files(folder: Path) -> dict: return {str(p.relative_to(folder)): p.read_bytes() for p in sorted(folder.rglob("*")) if p.is_file()} @@ -300,6 +324,9 @@ def sync(check: bool) -> int: for p in problems: print(f"agents: surface: {p}") drift = ["the registry, the MCP tools and the command line disagree"] if problems else [] + for p in dock_problems(): + print(f"agents: dock: {p}") + drift.append(f"frontend/src/dock/{p.split(' ', 1)[0]}") wanted = manifest_text(Engine()) if not MANIFEST.exists() or MANIFEST.read_text(encoding="utf-8") != wanted: drift.append(str(MANIFEST.relative_to(ROOT))) @@ -321,7 +348,10 @@ def sync(check: bool) -> int: if check: print("agents: in step" if not drift else "agents: drifted: " + ", ".join(drift) + " (run ./formencoder agents sync)") return 1 if drift else 0 - print("agents: " + ("updated " + ", ".join(drift) if drift else "already in step")) + print("agents: " + ("updated " + ", ".join(d for d in drift if not d.startswith("frontend/src/dock/")) if drift else "already in step")) + if dock_problems(): + print("agents: frontend/src/dock does not match its MANIFEST.json; copy the folder again from the family's source, sync cannot repair it") + return 1 return 0 From 6bc616af072f7ff056162a912bd8099a5278fd30 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:08 -0500 Subject: [PATCH 22/30] docs(dock): the logs say how the Terminal panel became the shared dock and what was removed frontend/HASHOUT_LOG.md and backend/HASHOUT_LOG.md carry the reasons, the removed code and what was checked by running. --- backend/HASHOUT_LOG.md | 11 +++++++++++ frontend/HASHOUT_LOG.md | 17 +++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index b00b3f0..1f4647c 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -292,3 +292,14 @@ Refers to `routers/terminal.py` `PROGRAMS`, `_version`, `_program`, `agent_progr - Checked by running, before the tests: engine from source on 34201 with stand-in `claude`, `codex` and `cursor-agent` scripts first on its PATH. Status gave the three with their version lines; each kind opened a tab whose process had the token in `/proc//environ` while `ps -eo args` did not show it; the three tokens differed; each let a change through with no window open and was refused after exit, after restart (old one) and after close; the prompt and resume id arrived as arguments; an outside agent's `terminal_list` and `terminal_read` did not see the tabs; the typed socket gave `hello`, text, `exit`, `restart` on the same stream, `closed`, and `gone`. With PATH `/usr/bin:/bin`: all three not installed with install lines, opening each 404 `not_installed`. The present page's calls replayed: the panel socket (raw text in, text out, NUL resize, `launch`, `{"exit": true}`), `/status`, `/sessions`, the old `POST /sessions` with `launch`, restart on an attached old stream, `/api/agents/status`, `/api/agents/forget`, and the three consent answers the page sends. Write routes without the key: 17 operations, 4 open by name, 13 refused before; 18, 4 and 14 after, none answered. - Tests: `backend/tests/test_dock_engine.py`, written after the runs above. +## What the window's shared dock needed from the engine (unreleased, after 0.9.0) + +- A window that connects is sent the permission questions still waiting (`Bus.waiting()`, sent in `routers/live.py` after `hello`, type `consent` only), so a reload does not lose a question. Questions asked of one window (`first=True`, the extension run) are not kept for this. +- `consent.gate_for(request, ...)` wraps `gate` for `/mcp` and `/api/rpc`: it looks once a second whether the caller is still connected and cancels the question when it is not, so `ask_window` ends with `withdrawn`, reason `cancelled`, and the dialog closes unanswered. Before, a caller that hung up left its question up for the full 180 seconds. +- The agent workspace's `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and `.claude/settings.json` name the MCP entry `formencoder_tab` (`workspace.TAB_ENTRY`); the entry `agents install` writes for outside use stays `formencoder` (`connect.NAME`). The two can no longer be mistaken for each other in a client's list. +- A closed tab's token: after a Claude Code tab is closed, a call with its token is treated as an unknown outside agent's and the person is asked (seen: the dialog named the caller; refused when denied). It never runs unasked. +- Left in place and no longer used by the window: the socket without `session` that opens a private shell with a token, and `POST /api/terminal/sessions` with `launch`. The window's shells are `kind: shell` tabs with no token. +- `setup/agents.py`: `dock_problems()` checks `frontend/src/dock` against its `MANIFEST.json` and for imports that leave the folder; `sync` and `sync --check` fail on it. The manifest's `dock.tabs` is `shell, claude, codex, cursor`; positions are the panel framework's four. +- Checked by running against an engine from source: Allow once ran the call and the next call asked again; Always allow stored that one name and nothing else; Deny refused; two waiting, the first answered, the second still shown and pending; a caller cut off, its dialog gone after 1.0 s; a reload with a question waiting showed it again; with `FORMENCODER_AGENTS=deny` an outside call and a live Claude Code tab's token were both refused for a change while a shell tab and a Claude Code tab still opened and reads worked. Write routes without the window key: 18 operations, 14 refused, 4 open by name, as before; no route was added. +- Tests: `backend/tests/test_dock_module.py`, written after the runs above. + diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 14832d8..e498720 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -261,3 +261,20 @@ Refers to `styles/tokens.css` `:root[data-oled]`, `styles/base.css` `.cv-titleba - Left as they are by design: the `#141414` fields and menus, tab pills (`--surface-raised`), the selected row tint (accent at 10%), small thumbnails (`.fe-m-thumb`, `#090909`, 34 by 24 px) and the accent. - Checked: headless Chrome 1440 by 900, 4x CPU throttle (`Emulation.setCPUThrottlingRate`), 150 ms and 1.6 Mbit/s network, cache off, engine from source and Vite dev server on spare ports. Cold load and hard reload with `amoled` saved, about 150 screenshots each, 5 sample points (inset 14 px from the corners, and the centre) on each of the window, title bar, status bar, the four dock areas, queue, preset browser and log or encoding pane: every sample is `#000000` until the app is revealed at about 9.5 s (8.5 s for one sample); after that the only non-black samples are content (logo, tab pill, text, an icon, one error toast that appeared at 8.5 s in the bottom right corner; its cause was not looked into). Live switch Studio Dark to AMOLED Black and back: 717 elements before and after, none added or removed (MutationObserver), none moved (bounding boxes), `data-oled` set and removed. - Not checked: hover and press contrast in a screenshot, the Settings picker in a screenshot, a running encode's live preview, the desktop app, a real OLED screen. + +## The Terminal panel is the family's shared dock, module 2.1.0 (unreleased, after 0.9.0) + +- `src/dock/` is the family's module, 15 files copied byte for byte from FormVis at 8bbdf61b. Nothing in it is edited here, ever; `./formencoder agents sync` fails, naming the file, when a file differs from `MANIFEST.json`, is missing, is extra, or imports from outside the folder. This app never writes that manifest. +- `src/dock-adapter.ts` is the one place that knows both sides. It exports `TerminalPanel`, still the framework panel with id `terminal`, so the Window menu, the palette, the Agent button's menu, the `ui` tool's `panel: terminal` and saved workspaces keep working. The panel's element is a plain host (`.fe-dock-host`) with the module's root mounted in it once. +- Placement is the module's `hosted` mode: where the panel is, how big it is and whether it is shown stay the framework's (`ui/dock.ts`), per workspace, as before. The module keeps no layout of its own, writes nothing to `localStorage` and puts no `data-ft-dock*` attribute on ``; its grip, side button and hide button are not shown. So there is no storage key to pick and none to move, and the pre-paint script reserves nothing for it: the whole app stays hidden until the layout is applied, which is the reservation here. The panel's `shown()` and `hidden()` call `dock.shown()` and `dock.hidden()`. +- No chord. The app had none for the terminal, and closing a panel makes the framework forget its group, so a chord that hides and shows would move the panel on every second press. `isDockChord` returns false; Ctrl+J in a shell is a line feed as before and Cmd+J does nothing. `passKey` is absent: the app received no key while the person typed in the old terminal, and receives none now. +- Tabs: shells (plain, no agent access), Claude Code, Codex and Cursor each as a tab of its own started by the engine (`POST /api/terminal/tabs`), and read-only tabs for terminals an outside agent opened (kind `agent` from `/api/terminal/sessions`; the live `terminals` event calls `dock.sync()`). No Chat: the engine has none, so `chat` is left out and the module shows no Chat button. The ask line stays and opens Claude Code with what was typed. +- The channel buys a ticket, then opens `WS /api/terminal/ws?session=..&typed=1`: text frames are output, binary frames are control. `hello` is passed on as an empty write so the module knows the engine answered; `restart` clears the screen; `exit` strikes the tab through. +- The permission question is the module's dialog (``, top layer, so it is above the app's own dialogs without a z-index). It is created with the panel at start, so it works in workspaces that never show the terminal; the terminal emulator is still loaded only when the panel is first shown. Offers are what the engine lists, cut to the module's three: Deny, Allow once, Always allow that agent. The engine's fourth answer, "until the engine stops", has no button now. Escape refuses, as closing the old dialog did. `storedChoice` reports `blocked` when the engine was started with `FORMENCODER_AGENTS=deny`, else `ask`, and the broken-seal flag; it cannot be set from the window. "Outside agents" in the dock's menu opens the Agents panel. +- `--z-overlay` did not exist in this app; `styles/dock-tokens.css` sets it to `--z-modal` for the guide, beside the `--dock-*` map (head 34px, terminal 12.5px at line height 1.15, as the old panel). +- `ui/keys.ts` names the module's three roots where it named `.fx-term-host, .xterm`. `ui/dock.ts` `applyLayout` hid every panel of an old group even after the panel had been moved into a new group of an earlier area, so going from Default to Agent left the Terminal tab selected over an empty panel; it now hides only panels still inside the group being removed. +- Removed, `panels/terminal.ts` (163 lines), the one private shell with three buttons that typed a program's name into it: `const ws = new WebSocket(wsUrl(\`/api/terminal/ws?cols=${t.cols}&rows=${t.rows}&ticket=${encodeURIComponent(ticket)}${launch ? \`&launch=${launch}\` : ''}\`));`, `if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(\`\u0000${JSON.stringify({ launch: agent })}\`);`, and its hint "Agents started here are trusted and already know formencoder: CLAUDE.md, AGENTS.md, the formencoder MCP server and the formencoder-harness skill are in this folder." +- Removed from `app/app.ts`, `askConsent`: `const d = new Dialog('Allow an agent to change the queue?', 460);` with `d.button('Don’t Allow', 'ghost', () => answer(false, 'none')); d.button('Allow Always', '', () => answer(true, 'always')); d.button('Allow', 'primary', () => answer(true, 'session'));`, and `this.consent?.close()`, which answered a waiting question Don't Allow whenever a second one arrived. +- Removed from `styles/base.css`: the ten rules `.fx-term`, `.fx-term-bar`, `.fx-term-title`, `.fx-agent-btn` (three), `.fx-term-cwd`, `.fx-term-host` (two), `.fx-term-hint`. +- Lost with the old panel, for want of a place in the module: the working folder shown in the bar (it is the tab's tooltip now), the hint line under the terminal, and the automation ids `terminal.launch.claude|codex|cursor` and `consent`. `terminal.screen` is kept, on the module's stage. +- Checked in headless Chrome at 1440 by 900 against the Vite dev server and the engine from source with stand-in `claude`, `codex` and `cursor-agent`: captures before and after (panel closed: 0 differing pixels; Default workspace: 25,336, all inside the panel's own box), a shell command and its output, a second shell, Claude Code from the button and from the ask line with the text as its argument, Codex from its button, restart of an ended tab, tabs and their output back after a reload, the same terminal element and output after a move to the Agent workspace and back, theme colours changed in place, no key from the terminal, the ask line or a tab reaching the app, and the question's answers through `/mcp`. Cold loads under 4x CPU and a slow network with the panel at the bottom and at the right: one box in every frame after the reveal. Not checked: the real programs, the desktop app, macOS. From e2350c0fcecb1980400de4d63bc4e319898a5d49 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:08 -0500 Subject: [PATCH 23/30] feat(agents): the agent programs are found by the family's finder 1.0.1, and the status reports Claude Code, Codex, Cursor and Antigravity backend/app/services/agent_lookup.py is the family's file at version 1.0.1, copied unchanged from FormVis ddc893ae (SHA-256 62667f9b...c77d51); setup/agents.py records the hashes of 1.0.0 and 1.0.1 and agents sync fails naming the file when it differs. Every lookup and start of an agent program goes through it: the status route, the tab route, the old socket's launch and agents install for Claude Code. A program outside the engine's PATH is found in the known install folders or through the person's shell PATH; one that is found but does not start is reported as broken with its last line. The status answer has four programs and the fields finding, how, looked, error and said; version is now the version word, not the whole line. Agent tabs start through the login shell with the program's folder first on PATH. The tab route still takes claude, codex and cursor only. Run: tests/test_dock_engine.py, test_dock_module.py and test_agents_manifest.py against stand-in programs and a stand-in shell, 25 passed; agents sync --check in step. Three existing cases were changed because they pinned three programs, the whole version line and a bare argv. Not run: Windows, macOS, a frozen engine, any real agent program. --- backend/HASHOUT_LOG.md | 15 + backend/app/agent/connect.py | 16 +- backend/app/routers/terminal.py | 81 ++--- backend/app/services/agent_lookup.py | 443 +++++++++++++++++++++++++ backend/app/services/agent_programs.py | 55 +++ backend/tests/test_dock_engine.py | 51 ++- backend/tests/test_dock_module.py | 33 ++ setup/agents.py | 21 +- 8 files changed, 653 insertions(+), 62 deletions(-) create mode 100644 backend/app/services/agent_lookup.py create mode 100644 backend/app/services/agent_programs.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 1f4647c..a29aee8 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -303,3 +303,18 @@ Refers to `routers/terminal.py` `PROGRAMS`, `_version`, `_program`, `agent_progr - Checked by running against an engine from source: Allow once ran the call and the next call asked again; Always allow stored that one name and nothing else; Deny refused; two waiting, the first answered, the second still shown and pending; a caller cut off, its dialog gone after 1.0 s; a reload with a question waiting showed it again; with `FORMENCODER_AGENTS=deny` an outside call and a live Claude Code tab's token were both refused for a change while a shell tab and a Claude Code tab still opened and reads worked. Write routes without the window key: 18 operations, 14 refused, 4 open by name, as before; no route was added. - Tests: `backend/tests/test_dock_module.py`, written after the runs above. +## The agent programs are found by the family's finder, and the status reports four (unreleased, after 0.9.0) + +Refers to `services/agent_lookup.py` (the family's file, version 1.0.1, never edited here), `services/agent_programs.py` (new), `routers/terminal.py` `AGENTS`, `PROGRAMS`, `TABS`, `_program`, `_typed`, `_environment`, `status`, `open_tab`, `Term.program`, `Hub.open`; `agent/connect.py` `install_claude`, `clients`; `setup/agents.py` `LOOKUP`, `LOOKUP_HASHES`, `lookup_problems`, `sync` · kind: feat · logged: unreleased · 2026-11-19 + +- Why: the engine looked for `claude`, `codex` and `cursor-agent` with `shutil.which` on its own PATH. An app started from the Dock, the Start menu or a desktop launcher has a short PATH, so a program the person has in `~/.local/bin`, under nvm or only on their shell's PATH was reported as not installed. +- `agent_programs.located(kind, fresh)` is the one lookup: `agent_lookup.find` (the override variable `FORMENCODER_CLAUDE_BIN`, `FORMENCODER_CODEX_BIN`, `FORMENCODER_CURSOR_BIN` or `FORMENCODER_ANTIGRAVITY_BIN`, the engine's PATH, the known install folders, then the person's shell PATH read once) and `agent_lookup.check` (`--version` in the child environment, without the engine's `FORMENCODER_*` variables as before). The app has no path setting, so `setting` is `None`. `usable` asks once more, fresh, when the first answer is not `runs`. +- Removed from `routers/terminal.py`: `_version`, `_VERSIONS`, `VERSION_KEEP` and the two `shutil.which` calls; from `agent/connect.py` the bare `shutil.which("claude")` and the three `subprocess.run` calls, which now go through `agent_lookup.run` with the finder's child environment. `PROGRAMS` and `AGENTS` keep their names and are built from `agent_programs.PROGRAMS`; the install lines are the finder's. +- `GET /api/terminal/agents` answers `claude`, `codex`, `cursor` and `antigravity`. Each keeps `installed`, `path`, `version`, `signedIn`, `install`, `title`, `program` and gains `finding` (`runs`, `broken`, `missing`), `how`, `looked`, `error` and `said`. `installed` is true only when `--version` ran. `version` is now the first word with a digit in what the program printed (`9.9.9`), where it was the whole first line. `/api/terminal/status` and `connect.clients()` list four. +- An agent tab is started as `agent_lookup.start_argv([path, ...])`: through the person's login shell with `exec` on macOS and Linux, directly on Windows with the command interpreter in front of a `.cmd` or `.bat`. Its environment is `agent_lookup.child_env(path, base=, front=[workspace bin])`, so the program's own folder is first on PATH (a `#!/usr/bin/env node` script finds the node beside it) and `CLAUDE*` variables of the engine's parent are left out. A program that is found but does not start is refused with the finder's sentence, code `not_installed` as before, so the panel shows it. +- `TABS` is `claude`, `codex`, `cursor`: the tab route does not take `antigravity` in this change. +- The old socket's `launch` and `POST /sessions {launch}` type the found path (quoted) into the shell, or the bare name when nothing is found. +- `setup/agents.py`: `lookup_problems()` hashes the finder and compares with `LOOKUP_HASHES` for the version the file states; `sync` and `sync --check` exit 1 naming the file when it was edited in place or is missing. +- Tests changed, and why: `test_dock_engine.py` expected three programs, the whole version line and a bare argv; it now expects four, `9.9.9` and the argv `start_argv` gives. Added after seeing them pass against stand-ins: a broken program, a program found in a known folder and one found through the shell's PATH; three hash cases in `test_dock_module.py`. +- Not run: Windows, macOS, a frozen engine, a real Claude Code, Codex, Cursor or Antigravity. + diff --git a/backend/app/agent/connect.py b/backend/app/agent/connect.py index ec018cb..255ec42 100644 --- a/backend/app/agent/connect.py +++ b/backend/app/agent/connect.py @@ -4,11 +4,11 @@ import os import re import shutil -import subprocess import time from pathlib import Path from ..core import config +from ..services import agent_lookup, agent_programs from . import workspace SKILL = "formencoder-harness" @@ -50,19 +50,21 @@ def install_claude(home: Path, dry: bool, said: list) -> None: cmd = launch() args = workspace.client_args("claude") line = " ".join([cmd, *args]) - claude = shutil.which("claude") + found = agent_programs.usable("claude") + claude = found.path if found.state == "runs" else None if claude: - have = subprocess.run([claude, "mcp", "get", NAME], capture_output=True, text=True) + 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: - subprocess.run([claude, "mcp", "remove", NAME, "--scope", "user"], capture_output=True) - subprocess.run([claude, "mcp", "add", "--scope", "user", NAME, "--", cmd, *args], check=True, capture_output=True) + 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() else: - said.append(f" the claude command is not installed here; once it is, run: claude mcp add --scope user {NAME} -- {line}") + 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) @@ -119,4 +121,4 @@ def install(which: list[str] | None = None, dry: bool = False) -> list[str]: def clients() -> dict: - return {name: shutil.which(binary) is not None for name, binary in (("claude", "claude"), ("codex", "codex"), ("cursor", "cursor-agent"))} + return {name: agent_programs.program(name) is not None for name in agent_programs.PROGRAMS} diff --git a/backend/app/routers/terminal.py b/backend/app/routers/terminal.py index eec3274..9879e23 100644 --- a/backend/app/routers/terminal.py +++ b/backend/app/routers/terminal.py @@ -4,7 +4,7 @@ import json import os import re -import shutil +import shlex import signal import struct import subprocess @@ -15,44 +15,30 @@ from ..agent import consent, workspace from ..core import config, window_key +from ..services import agent_lookup +from ..services import agent_programs as finder router = APIRouter(prefix="/api/terminal", tags=["terminal"]) POSIX = os.name == "posix" -AGENTS = {"claude": "claude", "codex": "codex", "cursor": "cursor-agent"} -PROGRAMS = { - "claude": {"title": "Claude Code", "install": "irm https://claude.ai/install.ps1 | iex" if os.name == "nt" else "curl -fsSL https://claude.ai/install.sh | bash"}, - "codex": {"title": "Codex", "install": "npm install -g @openai/codex"}, - "cursor": {"title": "Cursor", "install": "curl https://cursor.com/install -fsS | bash"}, -} +AGENTS = {kind: spec["bin"] for kind, spec in finder.PROGRAMS.items()} +PROGRAMS = {kind: {"title": spec["title"], "install": finder.install(kind)} for kind, spec in finder.PROGRAMS.items()} +TABS = ("claude", "codex", "cursor") RESUME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{7,79}") PROMPT_MAX = 20000 -VERSION_KEEP = 60.0 -_VERSIONS: dict[str, tuple[float, str | None]] = {} -def _version(path: str) -> str | None: - now = time.monotonic() - kept = _VERSIONS.get(path) - if kept and now - kept[0] < VERSION_KEEP: - return kept[1] - env = {k: v for k, v in os.environ.items() if not k.startswith("FORMENCODER_")} - try: - out = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=5, stdin=subprocess.DEVNULL, env=env) - lines = out.stdout.strip().splitlines() if out.returncode == 0 else [] - except (OSError, subprocess.SubprocessError): - lines = [] - found = lines[0].strip()[:80] if lines else None - _VERSIONS[path] = (now, found) - return found +def _program(kind: str) -> dict: + return finder.status(kind) -def _program(kind: str) -> dict: - path = shutil.which(AGENTS[kind]) - return {"installed": path is not None, "path": path, "version": _version(path) if path else None, "signedIn": None, - "install": PROGRAMS[kind]["install"], "title": PROGRAMS[kind]["title"], "program": AGENTS[kind]} +def _typed(kind: str) -> str: + path = finder.program(kind) + if not path: + return AGENTS[kind] + return shlex.quote(path) if POSIX else (f'"{path}"' if " " in path else path) -def _environment(base_url: str, token: str | None) -> dict: +def _environment(base_url: str, token: str | None, program: str | None = None) -> dict: ws = workspace.ensure() env = dict(os.environ) env["FORMENCODER_URL"] = base_url @@ -68,7 +54,7 @@ def _environment(base_url: str, token: str | None) -> dict: env.setdefault("TERM", "xterm-256color") env["COLORTERM"] = "truecolor" env.pop("FORMENCODER_DESKTOP", None) - return env + return agent_lookup.child_env(program, base=env, front=[str(ws / "bin")]) if program else env def _shell_path() -> str: @@ -181,7 +167,7 @@ def status() -> dict: "pty": POSIX, "shell": _shell()[0], "cwd": str(ws), - "agents": {name: shutil.which(binary) is not None for name, binary in AGENTS.items()}, + "agents": {name: finder.program(name) is not None for name in AGENTS}, "launch": AGENTS, } @@ -197,10 +183,10 @@ def agent_programs(request: Request) -> dict: class Term: def __init__(self, tid: str, title: str, cwd: str, cols: int, rows: int, base: str, owned: bool, trusted: bool = False, - kind: str = "shell", window: bool = False, argv: list[str] | None = None) -> None: + kind: str = "shell", window: bool = False, argv: list[str] | None = None, program: str | None = None) -> None: self.id, self.title, self.cwd, self.base, self.owned = tid, title, cwd, base, owned self.trusted = trusted - self.kind, self.window, self.argv = kind, window, argv + self.kind, self.window, self.argv, self.program = kind, window, argv, program self.token: str | None = None self.opener = "ui" self.created = time.time() @@ -216,7 +202,7 @@ def _start(self, cols: int, rows: int) -> None: self.exited = False consent.revoke(self.token) self.token = consent.issue() if self.trusted else None - self.session = Session(cols, rows, _environment(self.base, self.token), self.cwd, self.argv) + self.session = Session(cols, rows, _environment(self.base, self.token, self.program), self.cwd, self.argv) session = self.session def pump() -> None: @@ -313,11 +299,11 @@ def listed(self, tid: str) -> Term: return term def open(self, title: str | None, cwd: str | None, cols: int, rows: int, base: str, owned: bool = False, run: str | None = None, trusted: bool = False, - kind: str = "shell", window: bool = False, argv: list[str] | None = None) -> Term: + kind: str = "shell", window: bool = False, argv: list[str] | None = None, program: str | None = None) -> Term: self._n += 1 tid = f"t{self._n}" place = cwd or str(workspace.ensure()) - term = Term(tid, title or f"Terminal {self._n}", place, cols, rows, base, owned, trusted, kind, window, argv) + term = Term(tid, title or f"Terminal {self._n}", place, cols, rows, base, owned, trusted, kind, window, argv, program) self.terms[tid] = term if run: term.write(run + "\r") @@ -367,8 +353,8 @@ async def open_tab(request: Request) -> dict: body = {} kind = body.get("kind") or "shell" prompt, resume = body.get("prompt") or None, body.get("resume") or None - if kind != "shell" and kind not in PROGRAMS: - raise HTTPException(422, {"code": "unknown_kind", "message": f"No tab kind called {kind}. Kinds: shell, {', '.join(PROGRAMS)}."}) + if kind != "shell" and kind not in TABS: + raise HTTPException(422, {"code": "unknown_kind", "message": f"No tab kind called {kind}. Kinds: shell, {', '.join(TABS)}."}) if prompt is not None and (kind == "shell" or not isinstance(prompt, str) or len(prompt) > PROMPT_MAX): raise HTTPException(422, {"code": "bad_prompt", "message": f"A prompt is text of at most {PROMPT_MAX} characters for an agent tab."}) if resume is not None and (kind != "claude" or not isinstance(resume, str) or not RESUME.fullmatch(resume)): @@ -377,16 +363,17 @@ async def open_tab(request: Request) -> dict: cols, rows = int(body.get("cols") or 100), int(body.get("rows") or 30) except (TypeError, ValueError): cols, rows = 100, 30 - argv = None - if kind in PROGRAMS: - path = shutil.which(AGENTS[kind]) - if path is None: - raise HTTPException(404, {"code": "not_installed", "message": f"{PROGRAMS[kind]['title']} is not installed on this computer.", "install": PROGRAMS[kind]["install"]}) - argv = [path, *(["--resume", resume] if resume else []), *((["--", prompt] if prompt.startswith("-") else [prompt]) if prompt else [])] + argv = path = None + if kind in TABS: + found = finder.usable(kind) + 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 [])]) title = body.get("title") if isinstance(body.get("title"), str) else None cwd = body.get("cwd") if isinstance(body.get("cwd"), str) else None try: - term = hub.open(title or (PROGRAMS[kind]["title"] if argv else None), cwd, cols, rows, _base(request.headers.get("host")), trusted=argv is not None, kind=kind, window=True, argv=argv) + term = hub.open(title or (PROGRAMS[kind]["title"] if argv else None), cwd, cols, rows, _base(request.headers.get("host")), trusted=argv is not None, kind=kind, window=True, argv=argv, program=path) except OSError as exc: raise HTTPException(500, {"code": "failed", "message": f"The program could not start: {exc}"}) from None return term.row() @@ -396,7 +383,7 @@ async def open_tab(request: Request) -> dict: async def open_session(request: Request) -> dict: body = await request.json() if (await request.body()) else {} launch = body.get("launch") - run = AGENTS.get(launch) if launch in AGENTS else None + run = _typed(launch) if launch in AGENTS else None term = hub.open(body.get("title"), body.get("cwd"), int(body.get("cols") or 100), int(body.get("rows") or 30), _base(request.headers.get("host")), run=run, trusted=True) return term.row() @@ -509,7 +496,7 @@ async def send() -> None: sender = asyncio.create_task(send()) launch = socket.query_params.get("launch") if launch in AGENTS: - term.write(AGENTS[launch] + "\r") + term.write(_typed(launch) + "\r") try: while True: message = await socket.receive_text() @@ -534,7 +521,7 @@ async def send() -> None: if isinstance(control.get("resize"), list) and len(control["resize"]) == 2 and term.session: term.session.resize(int(control["resize"][0]), int(control["resize"][1])) if control.get("launch") in AGENTS: - term.write(AGENTS[control["launch"]] + "\r") + term.write(_typed(control["launch"]) + "\r") continue term.write(message) except WebSocketDisconnect: diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py new file mode 100644 index 0000000..ea34eba --- /dev/null +++ b/backend/app/services/agent_lookup.py @@ -0,0 +1,443 @@ +"""One finder and one starter for the agent programs a Form engine runs for the person: Claude Code, Codex, Cursor's agent +and Antigravity, held as a table (PROGRAMS) so another program is one more entry. + +A program started from the Dock, the Finder, the Start menu or a desktop launcher gets the system's short PATH, not the one a +terminal has, so a bare PATH search reports programs installed by Homebrew, npm, a version manager or into the home folder as +missing. This file looks in order: the person's setting, the app's development override variable, the engine's PATH, the known +install folders for the system, then the person's own shell PATH (read once and kept). It builds the one environment every +start uses (the program's own folder first on PATH, so a node script finds the node beside it), starts tabs, Chat and checks +the same way, answers "installed" three ways (runs, found but does not start, not found) and keeps the record of where it +looked so the message can say so. + +Shared by the Form family: standard library only, nothing imported from the app, copied unchanged between engines and held +to the hash recorded for VERSION. The app passes in what is its own: the setting's value, the names of its override +variables, its base environment and how long to wait.""" + +from __future__ import annotations + +import os +import re +import shutil +import signal +import subprocess +import sys +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path + +VERSION = "1.0.1" +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", + "home": (".claude/local", ".claude/bin"), "windows": ("home:.claude/local", "home:.claude/bin", "local:Programs/claude", "roaming:Programs/claude")}, + "codex": {"title": "Codex", "names": ("codex",), "setting": "codexBin", "install": "npm install -g @openai/codex", + "windows": ("local:Programs/OpenAI/Codex/bin",), "mac_files": ("Codex.app/Contents/Resources/codex", "Codex.app/Contents/Resources/bin/codex")}, + "cursor": {"title": "Cursor", "names": ("cursor-agent", "agent"), "setting": "cursorBin", "install": "curl https://cursor.com/install -fsS | bash", + "home": (".local/share/cursor-agent/versions/*",), "windows": ("local:cursor-agent",), "real": {"agent": "cursor"}}, + "antigravity": {"title": "Antigravity", "names": ("agy",), "setting": "antigravityBin", + "install": "curl -fsSL https://antigravity.google/cli/install.sh | bash", "install_windows": "irm https://antigravity.google/cli/install.ps1 | iex", + "windows_search": ("antigravity", "agy")}, +} +KEEP_ENV = frozenset({"CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CONFIG_DIR"}) +LIBRARY_VARS = ("LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH") +WINDOWS_ENDINGS = (".exe", ".cmd", ".bat") +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 + +_lock = threading.RLock() +_shell: dict = {} +_checked: dict = {} + + +@dataclass +class Found: + program: str + title: str + path: str | None = None + how: str = "" + state: str = "missing" + version: str | None = None + error: str = "" + looked: list[str] = field(default_factory=list) + + +def register(key: str, title: str, names: tuple | list, **more) -> None: + """Adds a program to the table, or replaces one, without changing this file. The keys of an entry: title (the name + shown to people), names (the program's file names, first wins), setting (the family's name for its path setting), + install and install_windows (the install command), home (folders under the home folder on macOS and Linux; a * stands + for version folders, newest first), windows (folders as local:, roaming: or home: and a path), mac_files (files inside + an application bundle), windows_search (name fragments of folders one and two levels under %LOCALAPPDATA%) and real + (for a name other programs also use: the word its real path must contain).""" + PROGRAMS[key] = {"title": title, "names": tuple(names), **more} + + +def install(program: str, platform: str | None = None) -> str: + spec = PROGRAMS[program] + return (spec.get("install_windows") if windows(platform) else "") or spec.get("install", "") + + +def forget() -> None: + with _lock: + _shell.clear() + _checked.clear() + + +def windows(platform: str | None = None) -> bool: + return (platform or sys.platform).startswith("win") + + +def runnable(path: str | os.PathLike, platform: str | None = None) -> bool: + p = Path(path).expanduser() + return p.is_file() and (windows(platform) or os.access(p, os.X_OK)) + + +def short(path: str | os.PathLike, home: str | os.PathLike | None = None) -> str: + text, base = str(path), str(home or Path.home()) + return "~" + text[len(base):] if base not in ("", os.sep) and (text == base or text.startswith(base + os.sep)) else text + + +def _version_key(p: Path) -> tuple: + return tuple(int(x) for x in re.findall(r"\d+", p.name)) or (0,) + + +def _versions(base: Path, tail: str = "") -> list[Path]: + try: + kept = [d for d in base.iterdir() if d.is_dir()] + except OSError: + return [] + return [d / tail if tail else d for d in sorted(kept, key=_version_key, reverse=True)] + + +def system_folders(platform: str | None = None) -> list[Path]: + platform = platform or sys.platform + if windows(platform): + return [] + if platform == "darwin": + return [Path("/opt/homebrew/bin"), Path("/usr/local/bin"), Path("/opt/local/bin")] + return [Path("/usr/local/bin"), Path("/usr/bin"), Path("/snap/bin"), Path("/home/linuxbrew/.linuxbrew/bin")] + + +def folders(program: str, home: str | os.PathLike | None = None, env: dict | None = None, platform: str | None = None) -> list[Path]: + platform = platform or sys.platform + home = Path(home) if home else Path.home() + env = os.environ if env is None else env + win = windows(platform) + spec = PROGRAMS[program] + out: list[Path] = [] + for key in ("NPM_CONFIG_PREFIX", "npm_config_prefix"): + if env.get(key): + out.append(Path(env[key]) if win else Path(env[key]) / "bin") + for key, tail in (("PNPM_HOME", ""), ("VOLTA_HOME", "bin"), ("BUN_INSTALL", "bin"), ("NVM_SYMLINK", "")): + if env.get(key): + out.append(Path(env[key]) / tail if tail else Path(env[key])) + if win: + roots = {"home": home, "roaming": Path(env.get("APPDATA") or home / "AppData" / "Roaming"), "local": Path(env.get("LOCALAPPDATA") or home / "AppData" / "Local")} + out += [home / ".local" / "bin", roots["roaming"] / "npm", roots["local"] / "npm", roots["local"] / "pnpm", roots["local"] / "Volta" / "bin", + home / ".bun" / "bin", home / ".volta" / "bin"] + for place in spec.get("windows", ()): + root, _, rest = place.partition(":") + out.append(roots[root].joinpath(*rest.split("/"))) + return list(dict.fromkeys(out)) + out += [home / ".local" / "bin", home / ".npm-global" / "bin", home / ".bun" / "bin", home / ".volta" / "bin", home / ".local" / "share" / "pnpm"] + if platform == "darwin": + out.append(home / "Library" / "pnpm") + out += _versions(home / ".nvm" / "versions" / "node", "bin") + out += _versions(home / ".local" / "share" / "fnm" / "node-versions", "installation/bin") + out += _versions(home / "Library" / "Application Support" / "fnm" / "node-versions", "installation/bin") + out += _versions(home / ".asdf" / "installs" / "nodejs", "bin") + out += _versions(home / ".local" / "share" / "mise" / "installs" / "node", "bin") + out += [home / ".asdf" / "shims", home / ".local" / "share" / "mise" / "shims"] + for place in spec.get("home", ()): + base, star, tail = place.partition("*") + out += _versions(home.joinpath(*base.strip("/").split("/")), tail.strip("/")) if star else [home.joinpath(*place.split("/"))] + out += system_folders(platform) + return list(dict.fromkeys(out)) + + +def _searched(root: Path, fragments: tuple) -> list[Path]: + out: list[Path] = [] + named = lambda d: any(f in d.name.lower() for f in fragments) + try: + first = sorted(d for d in root.iterdir() if d.is_dir()) + except OSError: + return out + for one in first: + if named(one): + out.append(one) + try: + out += [two for two in sorted(one.iterdir()) if two.is_dir() and (named(one) or named(two))] + except OSError: + continue + return out + + +def candidates(program: str, home: str | os.PathLike | None = None, env: dict | None = None, platform: str | None = None) -> list[Path]: + platform = platform or sys.platform + home = Path(home) if home else Path.home() + env = os.environ if env is None else env + spec = PROGRAMS[program] + endings = WINDOWS_ENDINGS if windows(platform) else ("",) + places = folders(program, home, env, platform) + if windows(platform) and spec.get("windows_search"): + places += _searched(Path(env.get("LOCALAPPDATA") or home / "AppData" / "Local"), tuple(spec["windows_search"])) + out = [folder / (name + ending) for folder in dict.fromkeys(places) for name in spec["names"] for ending in endings] + if platform == "darwin": + out += [apps.joinpath(*inside.split("/")) for apps in (Path("/Applications"), home / "Applications") for inside in spec.get("mac_files", ())] + return out + + +def _trusted(program: str, path: str | os.PathLike) -> bool: + name = Path(path).name.lower() + stem = name.rsplit(".", 1)[0] if name.endswith(WINDOWS_ENDINGS) else name + word = PROGRAMS[program].get("real", {}).get(stem) + return not word or word in os.path.realpath(path).lower() + + +def _on_path(program: str, path: str) -> str | None: + if not path: + return None + for name in PROGRAMS[program]["names"]: + hit = shutil.which(name, path=path) + if hit and _trusted(program, hit): + return os.path.abspath(hit) + return None + + +def login_shell(env: dict | None = None, platform: str | None = None) -> str: + env = os.environ if env is None else env + chosen = env.get("SHELL") + if chosen: + return chosen + if (platform or sys.platform) == "darwin" and os.path.exists("/bin/zsh"): + return "/bin/zsh" + return shutil.which("bash") or "/bin/sh" + + +def _stop(proc: subprocess.Popen) -> None: + try: + os.killpg(proc.pid, signal.SIGKILL) + except (OSError, AttributeError): + pass + try: + proc.kill() + except OSError: + pass + try: + proc.communicate(timeout=2) + except (OSError, ValueError, subprocess.SubprocessError): + pass + + +def _ask_shell(shell: str, flags: list[str], env: dict, timeout: float) -> list[str] | None: + script = f"printf '%s%s%s' {MARK} (string join : $PATH) {MARK}" if Path(shell).name == "fish" else f'printf "%s%s%s" {MARK} "$PATH" {MARK}' + try: + proc = subprocess.Popen([shell, *flags, "-c", script], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, + env=env, text=True, errors="replace", start_new_session=True) + except OSError: + return None + try: + out, _ = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + _stop(proc) + return None + hit = re.search(re.escape(MARK) + "(.*?)" + re.escape(MARK), out or "", re.S) + parts = [p for p in hit.group(1).split(os.pathsep) if p] if hit else [] + return parts or None + + +def _registry_path() -> list[str]: + try: + import winreg + except ImportError: + return [] + out: list[str] = [] + for root, key in ((winreg.HKEY_CURRENT_USER, "Environment"), (winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")): + try: + with winreg.OpenKey(root, key) as opened: + value, _kind = winreg.QueryValueEx(opened, "Path") + except OSError: + continue + out += [p.strip() for p in winreg.ExpandEnvironmentStrings(str(value)).split(";") if p.strip()] + return list(dict.fromkeys(out)) + + +def shell_path(env: dict | None = None, timeout: float = 10.0, fresh: bool = False, platform: str | None = None) -> tuple[list[str], str]: + """The person's own PATH: on macOS and Linux what their login, interactive shell ends up with (login only when the + interactive start gives nothing), on Windows the user and system Path values in the registry. Asked once and kept; an + empty answer is asked again after a minute, or at once with fresh.""" + env = dict(os.environ if env is None else env) + with _lock: + if _shell and not fresh and (_shell["path"] or time.monotonic() - _shell["at"] < RETRY_SECONDS): + return list(_shell["path"]), _shell["note"] + if windows(platform): + path = _registry_path() + note = "the Path values in the registry" if path else "the Path values in the registry (none could be read)" + else: + shell = login_shell(env, platform) + name = Path(shell).name + path = _ask_shell(shell, ["-l", "-i"], env, timeout) + note = f"your shell ({name}, login and interactive)" + if path is None: + path = _ask_shell(shell, ["-l"], env, timeout) + note = f"your shell ({name}, login only: the interactive start gave no PATH within {timeout:g} s)" + if path is None: + path, note = [], f"your shell ({name} gave no PATH within {timeout:g} s)" + _shell.update(path=list(path), note=note, at=time.monotonic()) + return list(path), note + + +def find(program: str, setting: str | None = None, override_vars: tuple = (), env: dict | None = None, home: str | os.PathLike | None = None, + platform: str | None = None, shell_timeout: float = 10.0, fresh: bool = False) -> Found: + """Where the program is, in the family's order. setting is the person's path for it ("" when empty, None when the app + has no such setting); override_vars are the names of the app's development override variables, read from env.""" + env = os.environ if env is None else env + platform = platform or sys.platform + spec = PROGRAMS[program] + found = Found(program, spec["title"]) + + def at(path: str | os.PathLike, how: str) -> Found: + found.path, found.how, found.state = str(path), how, "found" + return found + + if setting is not None: + chosen = setting.strip() + if chosen and runnable(chosen, platform): + return at(Path(chosen).expanduser(), "setting") + found.looked.append(f"your setting ({chosen}, which is not a program that can run)" if chosen else "your setting (empty)") + for var in override_vars: + value = (env.get(var) or "").strip() + if value and runnable(value, platform): + return at(Path(value).expanduser(), "override") + if value: + found.looked.append(f"{var} ({value}, which is not a program that can run)") + engine_path = env.get("PATH", "") + hit = _on_path(program, engine_path) + if hit: + return at(hit, "path") + found.looked.append(f"PATH ({engine_path or 'empty'})") + places = candidates(program, home, env, platform) + for place in places: + if runnable(place, platform) and _trusted(program, place): + return at(place, "folder") + found.looked.append(", ".join(dict.fromkeys(short(place.parent, home) for place in places))) + dirs, note = shell_path(env, shell_timeout, fresh, platform) + hit = _on_path(program, os.pathsep.join(dirs)) + if hit: + return at(hit, "shell") + found.looked.append(note) + return found + + +def child_env(path: str | os.PathLike | None = None, base: dict | None = None, extra: dict | None = None, front: tuple | list = (), + home: str | os.PathLike | None = None, platform: str | None = None, shell_timeout: float = 10.0, keep: frozenset | set = KEEP_ENV) -> dict: + """The environment every start of an agent program gets. PATH is the program's own folder, the app's own folders + (front), the person's shell PATH, the known install folders that exist, then the engine's PATH. CLAUDE* variables other + than keep are left out, and a frozen engine's library path is put back as it was. extra is applied last.""" + base = dict(os.environ if base is None else base) + env = {k: v for k, v in base.items() if not k.startswith("CLAUDE") or k in keep} + for name in LIBRARY_VARS: + original = base.get(name + "_ORIG") + if original is not None: + env[name] = original + elif getattr(sys, "frozen", False) or base.get("_MEIPASS2"): + env.pop(name, None) + dirs, _note = shell_path(base, shell_timeout, False, platform) + known = [str(f) for program in PROGRAMS for f in folders(program, home, base, platform) if f.is_dir()] + parts = ([str(Path(path).parent)] if path else []) + [str(f) for f in front] + dirs + known + base.get("PATH", "").split(os.pathsep) + env["PATH"] = os.pathsep.join(dict.fromkeys(p for p in parts if p)) + env.update(extra or {}) + return env + + +def _quote(word: str, fish: bool) -> str: + if word and re.fullmatch(r"[A-Za-z0-9_@%+=:,./-]+", word): + return word + if fish: + return "'" + word.replace("\\", "\\\\").replace("'", "\\'") + "'" + return "'" + word.replace("'", "'\"'\"'") + "'" + + +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.""" + 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 + shell = login_shell(env, platform) + fish = Path(shell).name == "fish" + return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] + + +def run(cmd: list, env: dict, timeout: float = 15.0, platform: str | None = None) -> subprocess.CompletedProcess: + return subprocess.run(start_argv(cmd, env, platform), capture_output=True, text=True, errors="replace", timeout=timeout, env=env, stdin=subprocess.DEVNULL) + + +def _last_line(text: str) -> str: + lines = [line.strip() for line in (text or "").splitlines() if line.strip() and "use -[v]S to pass options" not in line] + return lines[-1][:300] if lines else "" + + +def _version(text: str) -> str | None: + words = (text or "").split() + return next((w for w in words if any(ch.isdigit() for ch in w)), words[0] if words else None) + + +def _stamp(path: str) -> tuple: + try: + st = os.stat(path) + return (path, st.st_mtime_ns, st.st_size) + except OSError: + return (path, 0, 0) + + +def check(found: Found, env: dict | None = None, timeout: float = 15.0, fresh: bool = False, platform: str | None = None) -> Found: + """Whether a found program starts: `--version` in the child environment, started as a tab would start it. The state + becomes runs (with the version) or broken (with the error line). An answer is kept for that file until it changes or + fresh asks again; a broken answer is asked again after a minute.""" + if not found.path: + return found + key = _stamp(found.path) + with _lock: + kept = None if fresh else _checked.get(key) + if kept is not None and kept[0] != "runs" and time.monotonic() - kept[3] >= RETRY_SECONDS: + kept = None + if kept is None: + env = child_env(found.path, platform=platform) if env is None else env + try: + out = run([found.path, "--version"], env, timeout, platform) + if out.returncode == 0: + kept = ("runs", _version(out.stdout), "", time.monotonic()) + else: + 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()) + with _lock: + _checked[key] = kept + found.state, found.version, found.error = kept[0], kept[1], kept[2] + return found + + +def sentence(found: Found, install: str = "", otherwise: str = "") -> str: + """The truthful message, built from the record. install is the app's install command for the program; otherwise is + what else the person can do in this app, as a clause ("give its path in Preferences").""" + if found.state == "missing": + ways = ([f"install it with: {install}"] if install else []) + ([otherwise] if otherwise else []) + tail = " " + ", or ".join(ways) + "." if ways else "" + return f"{found.title} was not found. Looked in: {'; '.join(found.looked)}." + (tail[:1] + tail[1:2].upper() + tail[2:] if tail else "") + where = f"{found.path} ({HOW.get(found.how, found.how)})" + if found.state == "broken": + tail = f" To use another copy, {otherwise}." if otherwise else "" + return f"{found.title} was found at {where} but does not start: {found.error}.{tail}" + return f"{found.title} is at {where}." + + +def answer(found: Found, install: str = "", otherwise: str = "") -> dict: + """The fields a status route adds for one program: installed is true only when the program runs, and finding is + the three-way answer (runs, broken, missing).""" + return {"installed": found.state == "runs", "path": found.path, "version": found.version, "finding": found.state, "how": found.how, + "looked": list(found.looked), "error": found.error, "said": sentence(found, install, otherwise)} diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py new file mode 100644 index 0000000..2e4792f --- /dev/null +++ b/backend/app/services/agent_programs.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import os + +from . import agent_lookup + +PROGRAMS = { + "claude": {"bin": "claude", "title": "Claude Code"}, + "codex": {"bin": "codex", "title": "Codex"}, + "cursor": {"bin": "cursor-agent", "title": "Cursor"}, + "antigravity": {"bin": "agy", "title": "Antigravity"}, +} +OVERRIDES = { + "claude": ("FORMENCODER_CLAUDE_BIN",), + "codex": ("FORMENCODER_CODEX_BIN",), + "cursor": ("FORMENCODER_CURSOR_BIN",), + "antigravity": ("FORMENCODER_ANTIGRAVITY_BIN",), +} +OTHERWISE = "" + + +def install(kind: str) -> str: + return agent_lookup.install(kind) + + +def base_env() -> dict: + return {k: v for k, v in os.environ.items() if not k.startswith("FORMENCODER_")} + + +def child_env(path: str | None = None, base: dict | None = None, front: tuple | list = (), extra: dict | None = None) -> dict: + return agent_lookup.child_env(path, base=base_env() if base is None else base, front=front, extra=extra, shell_timeout=10.0) + + +def located(kind: str, fresh: bool = False) -> agent_lookup.Found: + found = agent_lookup.find(kind, setting=None, override_vars=OVERRIDES.get(kind, ()), shell_timeout=10.0, fresh=fresh) + return agent_lookup.check(found, child_env(found.path), 15.0, fresh) + + +def usable(kind: str) -> agent_lookup.Found: + found = located(kind) + return found if found.state == "runs" else located(kind, True) + + +def said(found: agent_lookup.Found) -> str: + return agent_lookup.sentence(found, install(found.program), OTHERWISE) + + +def program(kind: str) -> str | None: + found = located(kind) + return found.path if found.state == "runs" else None + + +def status(kind: str, fresh: bool = False) -> dict: + found = located(kind, fresh) + return agent_lookup.answer(found, install(kind), OTHERWISE) | {"signedIn": None, "install": install(kind), "title": PROGRAMS[kind]["title"], "program": PROGRAMS[kind]["bin"]} diff --git a/backend/tests/test_dock_engine.py b/backend/tests/test_dock_engine.py index 0520675..91e35cf 100644 --- a/backend/tests/test_dock_engine.py +++ b/backend/tests/test_dock_engine.py @@ -88,17 +88,51 @@ async def run(): def test_the_agent_status_names_each_program_its_version_and_its_install_line(client, bare, stand_ins): assert bare.get("/api/terminal/agents").status_code == 403 agents = client.get("/api/terminal/agents").json()["agents"] - assert list(agents) == ["claude", "codex", "cursor"] - assert agents["codex"] == agents["codex"] | {"installed": True, "path": str(stand_ins / "codex"), "version": "codex 9.9.9", "signedIn": None, "title": "Codex", "program": "codex"} - assert agents["cursor"]["version"] == "cursor-agent 9.9.9" and agents["claude"]["version"] == "claude 9.9.9" + assert list(agents) == ["claude", "codex", "cursor", "antigravity"] + assert agents["codex"] == agents["codex"] | {"installed": True, "path": str(stand_ins / "codex"), "version": "9.9.9", "finding": "runs", "how": "path", "signedIn": None, "title": "Codex", "program": "codex"} + assert agents["cursor"]["version"] == "9.9.9" and agents["claude"]["version"] == "9.9.9" + assert agents["codex"]["said"] == f"Codex is at {stand_ins / 'codex'} (the engine's PATH)." assert all(a["install"] for a in agents.values()) def test_the_agent_status_says_what_is_missing(client, no_programs): agents = client.get("/api/terminal/agents").json()["agents"] - for kind in ("claude", "codex", "cursor"): + for kind in ("claude", "codex", "cursor", "antigravity"): assert agents[kind]["installed"] is False and agents[kind]["path"] is None and agents[kind]["version"] is None and agents[kind]["install"] - assert client.get("/api/terminal/status").json()["agents"] == {"claude": False, "codex": False, "cursor": False} + assert agents[kind]["finding"] == "missing" and agents[kind]["looked"] and "was not found. Looked in:" in agents[kind]["said"] + assert client.get("/api/terminal/status").json()["agents"] == {"claude": False, "codex": False, "cursor": False, "antigravity": False} + + +@POSIX_ONLY +def test_a_program_that_does_not_start_is_found_and_reported_as_broken(client, tmp_path, monkeypatch): + folder = tmp_path / "bin" + folder.mkdir() + script = folder / "codex" + script.write_text("#!/bin/sh\necho 'node: not found' >&2\nexit 127\n") + script.chmod(0o755) + monkeypatch.setenv("PATH", str(folder)) + codex = client.get("/api/terminal/agents").json()["agents"]["codex"] + assert codex == codex | {"installed": False, "path": str(script), "finding": "broken", "error": "node: not found", "version": None} + refused = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "codex"}) + assert refused.status_code == 404 and "but does not start: node: not found" in refused.json()["detail"]["message"] + + +@POSIX_ONLY +def test_a_program_outside_the_engine_path_is_found_in_a_known_folder_and_through_the_shell(client, tmp_path, monkeypatch): + home = tmp_path / "home" + known, named = home / ".local" / "bin", tmp_path / "elsewhere" + for folder, name in ((known, "claude"), (named, "codex")): + folder.mkdir(parents=True) + script = folder / name + script.write_text('#!/bin/sh\nif [ "$1" = "--version" ]; then echo "7.7.7"; exit 0; fi\nread line\n') + script.chmod(0o755) + (home / ".zshrc-path").write_text(str(named)) + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("PATH", "/usr/bin:/bin") + agents = client.get("/api/terminal/agents").json()["agents"] + assert agents["claude"] == agents["claude"] | {"installed": True, "path": str(known / "claude"), "how": "folder", "version": "7.7.7"} + assert agents["codex"] == agents["codex"] | {"installed": True, "path": str(named / "codex"), "how": "shell", "version": "7.7.7"} + assert agents["cursor"]["finding"] == "missing" @POSIX_ONLY @@ -126,12 +160,15 @@ def test_an_agent_tab_runs_the_program_with_its_own_token_which_dies_with_the_ta @POSIX_ONLY def test_a_prompt_and_a_resume_id_reach_the_program_as_arguments(client, stand_ins): from app.routers.terminal import hub + from app.services import agent_lookup row = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "claude", "prompt": "make a small file", "resume": "0123abcd-4567"}).json() - assert hub.terms[row["id"]].argv == [str(stand_ins / "claude"), "--resume", "0123abcd-4567", "make a small file"] + assert hub.terms[row["id"]].argv == agent_lookup.start_argv([str(stand_ins / "claude"), "--resume", "0123abcd-4567", "make a small file"]) + assert hub.terms[row["id"]].argv[:3] == [os.environ["SHELL"], "-l", "-c"] assert "args=--resume 0123abcd-4567 make a small file" in printed(client, row["id"], "args=") dashed = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "codex", "prompt": "-v"}).json() - assert hub.terms[dashed["id"]].argv == [str(stand_ins / "codex"), "--", "-v"] + assert hub.terms[dashed["id"]].argv == agent_lookup.start_argv([str(stand_ins / "codex"), "--", "-v"]) + assert "args=-- -v" in printed(client, dashed["id"], "args=") for tid in (row["id"], dashed["id"]): client.delete(f"/api/terminal/sessions/{tid}", headers=LOCAL) diff --git a/backend/tests/test_dock_module.py b/backend/tests/test_dock_module.py index ab3951e..e578783 100644 --- a/backend/tests/test_dock_module.py +++ b/backend/tests/test_dock_module.py @@ -1,9 +1,12 @@ +import hashlib import importlib.util import json +import re import shutil from conftest import REPO +LOOKUP = "backend/app/services/agent_lookup.py" DOCK = REPO / "frontend" / "src" / "dock" FRONTEND = REPO / "frontend" @@ -81,3 +84,33 @@ def test_the_workspace_names_its_entry_for_tabs(tmp_path, monkeypatch): assert list(json.loads((base / ".mcp.json").read_text(encoding="utf-8"))["mcpServers"]) == ["formencoder_tab"] assert list(json.loads((base / ".cursor" / "mcp.json").read_text(encoding="utf-8"))["mcpServers"]) == ["formencoder_tab"] assert "[mcp_servers.formencoder_tab]" in (base / ".codex" / "config.toml").read_text(encoding="utf-8") + + +def finder_version(): + return re.search(r'^VERSION = "([^"]+)"$', (REPO / LOOKUP).read_text(encoding="utf-8"), re.M).group(1) + + +def test_the_shared_finder_matches_the_hash_recorded_for_its_version(): + module = agents() + assert module.LOOKUP_HASHES[finder_version()] == hashlib.sha256((REPO / LOOKUP).read_bytes()).hexdigest() + assert module.lookup_problems() == [] + + +def test_the_check_names_the_shared_finder_edited_in_place_or_missing(tmp_path, monkeypatch): + module = agents() + copy = tmp_path / "repo" + (copy / "backend" / "app" / "services").mkdir(parents=True) + shutil.copy(REPO / LOOKUP, copy / LOOKUP) + monkeypatch.setattr(module, "ROOT", copy) + monkeypatch.setattr(module, "LOOKUP", copy / LOOKUP) + assert module.lookup_problems() == [] + with open(copy / LOOKUP, "a", encoding="utf-8") as f: + f.write("\n") + assert module.lookup_problems() == [f"{LOOKUP}: does not match the hash recorded for version {finder_version()} (the shared finder changes only as a whole new version)"] + (copy / LOOKUP).unlink() + assert module.lookup_problems() == [f"{LOOKUP}: missing (the shared finder for the agent programs)"] + + +def test_the_shared_finder_imports_nothing_from_the_app(): + imports = set(re.findall(r"^\s*(?:from|import)\s+([\w.]+)", (REPO / LOOKUP).read_text(encoding="utf-8"), re.M)) + assert imports == {"__future__", "dataclasses", "os", "pathlib", "re", "shutil", "signal", "subprocess", "sys", "threading", "time", "winreg"} diff --git a/setup/agents.py b/setup/agents.py index e8b7be0..517d56b 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -30,6 +30,8 @@ DOCK = {"present": True, "positions": ["left", "right", "bottom", "floating"], "tabs": ["shell", "claude", "codex", "cursor"]} 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"} 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." @@ -314,6 +316,19 @@ def dock_problems(folder: Path | None = None) -> list[str]: return problems +def lookup_problems() -> list[str]: + rel = LOOKUP.relative_to(ROOT).as_posix() + try: + raw = LOOKUP.read_bytes() + except OSError: + return [f"{rel}: missing (the shared finder for the agent programs)"] + said = re.search(rb'^VERSION = "([^"\r\n]+)"\r?$', raw, re.M) + version = said.group(1).decode("ascii", "replace") if said else "unknown" + if LOOKUP_HASHES.get(version) != hashlib.sha256(raw).hexdigest(): + return [f"{rel}: does not match the hash recorded for version {version} (the shared finder changes only as a whole new version)"] + return [] + + def _files(folder: Path) -> dict: return {str(p.relative_to(folder)): p.read_bytes() for p in sorted(folder.rglob("*")) if p.is_file()} @@ -327,6 +342,10 @@ def sync(check: bool) -> int: for p in dock_problems(): print(f"agents: dock: {p}") drift.append(f"frontend/src/dock/{p.split(' ', 1)[0]}") + finder = lookup_problems() + for p in finder: + print(f"agents: finder: {p}") + drift.append(p.split(":", 1)[0]) wanted = manifest_text(Engine()) if not MANIFEST.exists() or MANIFEST.read_text(encoding="utf-8") != wanted: drift.append(str(MANIFEST.relative_to(ROOT))) @@ -352,7 +371,7 @@ def sync(check: bool) -> int: if dock_problems(): print("agents: frontend/src/dock does not match its MANIFEST.json; copy the folder again from the family's source, sync cannot repair it") return 1 - return 0 + return 1 if finder else 0 def install(args: list[str]) -> int: From 1aec7f9206b7d92aad71a894009951d937066a2d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:08 -0500 Subject: [PATCH 24/30] test(agents): the whole test run finds only stand-in agent programs conftest puts stand-ins for claude, codex, cursor-agent, agent and agy first on PATH, a stand-in login shell as SHELL and removes the package manager variables before the app is imported; an autouse fixture empties the finder's system folders and its kept answers for every test. The run prints how many times a stand-in was started. Run: the agent and dock test files, 25 passed, the line said 1 start (agy --version). --- backend/HASHOUT_LOG.md | 9 ++++++++ backend/tests/conftest.py | 44 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index a29aee8..68a0929 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -318,3 +318,12 @@ Refers to `services/agent_lookup.py` (the family's file, version 1.0.1, never ed - Tests changed, and why: `test_dock_engine.py` expected three programs, the whole version line and a bare argv; it now expects four, `9.9.9` and the argv `start_argv` gives. Added after seeing them pass against stand-ins: a broken program, a program found in a known folder and one found through the shell's PATH; three hash cases in `test_dock_module.py`. - Not run: Windows, macOS, a frozen engine, a real Claude Code, Codex, Cursor or Antigravity. +## No test can start a real agent program (unreleased, after 0.9.0) + +Refers to `backend/tests/conftest.py` `AGENT_STAND_INS`, `AGENT_CALLS`, `AGENT_SHELL`, `only_stand_in_agent_programs`, `pytest_sessionfinish`, `pytest_terminal_summary` · kind: test · logged: unreleased · 2026-11-19 + +- Why: the finder reads the person's shell PATH and the known install folders, so a test run on a machine with a real `claude` could have found and started it. +- Before any test imports the app, the run gets stand-ins named `claude`, `codex`, `cursor-agent`, `agent` and `agy` first on PATH (they answer `--version`, log every start and otherwise exit 1), a stand-in login shell as `SHELL` that never reads the machine's profile, the made-up home it already had, and no `NPM_CONFIG_PREFIX`, `npm_config_prefix`, `PNPM_HOME`, `VOLTA_HOME`, `BUN_INSTALL` or `NVM_SYMLINK`. The autouse fixture replaces `agent_lookup.system_folders` with an empty list and drops the finder's kept answers before and after each test. +- The run ends with one line saying how many times a stand-in was started and with what arguments. +- Not on Windows: the stand-ins are shell scripts, and the tests that start programs are skipped there. + diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index a36fc90..0f624ad 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -91,13 +91,57 @@ def window_ticket(): os.environ["USERPROFILE"] = str(_SANDBOX / "home") for _key in ("XDG_DATA_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"): os.environ[_key] = str(_SANDBOX / "home" / _key.lower()) +AGENT_STAND_INS = ("claude", "codex", "cursor-agent", "agent", "agy") +AGENT_CALLS = _SANDBOX / "agent-calls.log" +AGENT_SHELL = """#!/bin/sh +login=0; inter=0; script="" +while [ $# -gt 0 ]; do + case "$1" in -l) login=1 ;; -i) inter=1 ;; -c) shift; script="$1" ;; esac + shift +done +if [ "$login" = 1 ] && [ -f "$HOME/.zprofile-path" ]; then PATH="$(cat "$HOME/.zprofile-path"):$PATH"; fi +if [ "$inter" = 1 ] && [ -f "$HOME/.zshrc-path" ]; then PATH="$(cat "$HOME/.zshrc-path"):$PATH"; fi +export PATH +if [ -n "$script" ]; then exec /bin/sh -c "$script"; fi +exec /bin/sh +""" +_agent_calls: list[str] = [] +if os.name != "nt": + for _name in ("bin", "shell"): + (_SANDBOX / _name).mkdir() + for _name in AGENT_STAND_INS: + (_SANDBOX / "bin" / _name).write_text(f'#!/bin/sh\necho "{_name} $*" >> "{AGENT_CALLS}"\nif [ "$1" = "--version" ]; then echo "0.0.0 (stand-in)"; exit 0; fi\nexit 1\n') + (_SANDBOX / "bin" / _name).chmod(0o755) + (_SANDBOX / "shell" / "zsh").write_text(AGENT_SHELL) + (_SANDBOX / "shell" / "zsh").chmod(0o755) + os.environ["SHELL"] = str(_SANDBOX / "shell" / "zsh") + os.environ["PATH"] = os.pathsep.join([str(_SANDBOX / "bin"), os.environ.get("PATH", "")]) + for _key in ("NPM_CONFIG_PREFIX", "npm_config_prefix", "PNPM_HOME", "VOLTA_HOME", "BUN_INSTALL", "NVM_SYMLINK"): + os.environ.pop(_key, None) sys.path.insert(0, str(BACKEND)) +@pytest.fixture(autouse=True) +def only_stand_in_agent_programs(monkeypatch): + agent_lookup = importlib.import_module("app.services.agent_lookup") + monkeypatch.setattr(agent_lookup, "system_folders", lambda platform=None: []) + agent_lookup.forget() + yield + agent_lookup.forget() + + def pytest_sessionfinish(session, exitstatus): + try: + _agent_calls.extend(AGENT_CALLS.read_text(encoding="utf-8").splitlines()) + except OSError: + pass shutil.rmtree(_SANDBOX, ignore_errors=True) +def pytest_terminal_summary(terminalreporter): + terminalreporter.write_line(f"agent program stand-ins started {len(_agent_calls)} time(s): " + (", ".join(sorted(set(_agent_calls))) or "none")) + + def own_origin(): return f"http://127.0.0.1:{ENGINE_PORT}" From 50691eda957072dab42889a011ce300696c8aa35 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:08 -0500 Subject: [PATCH 25/30] feat(dock): the family's shared dock module is 2.2.0, unchanged The 16 entries of frontend/src/dock (15 files and MANIFEST.json; agents.ts is new) are copied byte for byte from FormVis at ddc893ae: the agent kinds are a list and Antigravity is the fourth. diff -r against the source is clean. The adapter still lists three kinds in this commit. --- frontend/src/dock/CONTRACT.md | 14 ++- frontend/src/dock/MANIFEST.json | 21 ++--- frontend/src/dock/adapter.ts | 30 ++++--- frontend/src/dock/agents.ts | 22 +++++ frontend/src/dock/chat.ts | 2 +- frontend/src/dock/consent.ts | 8 +- frontend/src/dock/dock.css | 4 +- frontend/src/dock/dock.ts | 147 ++++++++++++++++++++------------ frontend/src/dock/icons.ts | 1 + frontend/src/dock/strings.ts | 1 + frontend/src/dock/tour.ts | 2 +- 11 files changed, 165 insertions(+), 87 deletions(-) create mode 100644 frontend/src/dock/agents.ts diff --git a/frontend/src/dock/CONTRACT.md b/frontend/src/dock/CONTRACT.md index be1995e..a52a17e 100644 --- a/frontend/src/dock/CONTRACT.md +++ b/frontend/src/dock/CONTRACT.md @@ -1,6 +1,6 @@ # The dock's engine contract -Module version 2.1.0. This file travels with the shared dock folder and is the same in every app. +Module version 2.2.0. This file travels with the shared dock folder and is the same in every app. The dock's frontend never talks to an engine. It calls the functions of `DockAdapter` (adapter.ts), and each app's adapter turns them into its engine's routes, sockets or event streams. This file says what an engine has to provide so that an adapter can deliver each function, in words that do not depend on the engine's language. Paths, header names and transports are each app's own. Where a clause says "the adapter", the engine may do the work instead; where it says "the engine", the adapter cannot make it up. @@ -56,6 +56,18 @@ Nothing an engine provides changed in 2.1.0: the sixteen clauses read as they di - **Names.** The classes, attributes and tokens an app may rely on are `DOCK_PUBLIC` in adapter.ts and nowhere else; 2.1.0 added the classes `has-ask-line`, `ft-dock-ask`, `ft-dock-ask-own`, `ft-dock-head`, `ft-dock-tab`, `ft-dock-stage`, `ft-icon`, `is-on`, `is-own` and the tokens `--dock-stage-pad`, `--dock-ask-ctl-h`, `--dock-tab-accent`, each token defaulting to the value 2.0 had written. - **Type check.** Before a module version is cut, and as a step of every port, the folder is compiled with `noUnusedLocals`, `noUnusedParameters`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`, `verbatimModuleSyntax`, `noImplicitOverride` and `noImplicitReturns` on. +## Module 2.2.0: the agent kinds are a list, and Antigravity is the fourth + +An adapter written for 2.1.0 compiles and behaves as before: copying the 2.2.0 folder into an app changes nothing there until its adapter names a further kind. Every type an adapter uses is the 2.1.0 type unless the adapter gives the type argument described below. `keyHeaders` became optional. + +- **The list.** `agents.ts` holds the kinds the module knows: `claude` (Claude Code), `codex` (Codex), `cursor` (Cursor) and `antigravity` (Antigravity, Google's `agy` program), each with its label, its picture and its two sentences. Claude Code keeps its own button, the ask line and the guide. Every other kind gets a head button and a row in the More agents menu. +- **Offering a kind.** A kind is shown when the adapter lists its id in `tabs().builtin` and `agentStatus()` reports it; both. So clause 10's answer may hold further keys, `{ claude?, codex?, cursor?, antigravity?, ... }`, and a key the adapter does not also list is ignored. The module then calls `terminal.open('antigravity', { cols, rows })`, and clause 3's `kind` may be that id. An adapter that adds kinds is typed `DockAdapter<'antigravity'>` (a union for several); `Dock`, `DockTabs`, `DockTerminal` and `DockAgentStatus` follow from it. +- **What the engine needs for a further kind.** Clause 10 for it (found, version, install line, `signedIn` null when it cannot tell, which is always so for Antigravity: it has no status command), clause 4 for its tab, and clause 11: Antigravity reads its MCP servers from a file, so the tab's entry (named `[app]_tab`, with the tab's token) goes into `.agents/mcp_config.json` of the tab's working folder, mode 0600, every other entry kept, and is taken out when the tab closes. +- **A kind that is not in the list** needs no change in this folder: the adapter lists its id, and its status carries `label`. It is drawn with the terminal picture and the sentences of the other programs. +- **`DockProgramStatus.note`** is a whole sentence shown in the kind's menu row in place of the module's (where the engine looked for the program, why it does not start, a step that is not a command). The install line still shows under it. +- **Part names.** Every control of the module carries `data-dock-part`; the attribute and the names are `DOCK_PUBLIC.partAttribute`, `parts` and `partsByKind` (`launch.[kind]`, `menu.launch.[kind]`, `tab.[kind]`). Automation and command layers use these and no class name. +- **A status line for a tab.** A terminal record may carry `status`, and a channel may give `onStatus(handler)` and call the handler with new text ("reconnecting", an exit code). The text of the tab in front shows in the head between the tabs and the buttons, clipped; an empty string clears it. + ## The manifest `MANIFEST.json` in this folder lists the module version and the SHA-256 of every other file here, this one included. The source app (FormVis) writes it; every other app only checks it: read the file names and hashes from the manifest, hash each file's bytes, and fail naming any file that differs, is missing or is extra. The check is small enough to write in any language an app's tools use. diff --git a/frontend/src/dock/MANIFEST.json b/frontend/src/dock/MANIFEST.json index fdeee27..819f4ea 100644 --- a/frontend/src/dock/MANIFEST.json +++ b/frontend/src/dock/MANIFEST.json @@ -1,20 +1,21 @@ { "module": "dock", - "version": "2.1.0", + "version": "2.2.0", "files": { - "CONTRACT.md": "3fa57822b0024100bd4f5db5e06525f774539c4595493da171f1bd14871d2e05", - "adapter.ts": "fe8e9212273a49ffefa37baac056bab5d499581ae78f995ab691ac9867d5fd6a", - "chat.ts": "91fef36e0ee61a1681194fe441458cd766660277718b0ba854e2960fddc5ca1b", - "consent.ts": "83873a14cb337ea679f0f372c4865428ab8cf136cecce8f8c7ab159a656c777b", - "dock.css": "7fbb58622379689a0fcf980e726a4f452ccf8d3acb394e9b6cf04f7a0c8d77d7", - "dock.ts": "d3ff0afa24c06afd6f80ba478e4b4f8e90f5a150ec9f9f96a3d4b14179b6849f", + "CONTRACT.md": "ccef67fcf0017569c0bf68df0eae2e1e3ddf376117ac929789b803713c427df6", + "adapter.ts": "1128c16892424485fe68bb2bf92ebc7229a9c2ff749db2fcd2419662d9c3ada9", + "agents.ts": "db666d1042555f8bbda4a697dbfc475df23779d0c5a25abd532bcfa43ae81043", + "chat.ts": "994878030b9fbff729734d34e2baa5b018e7d0b8555c24bfb7c98962c50446fa", + "consent.ts": "922a2c9fb6a3d83a6b70f1bb02918646ae180f5ed1ed7325e71b2caf01358737", + "dock.css": "ffdb5be7e849c393f173fac9cd0fb0503c0ef4e53e4c1c86a8e198abfbbdb8d2", + "dock.ts": "abbb2929d52d592eb2730a8a90763e8caf333c458250fc89a08d637489ef4571", "dom.ts": "dc2adf64e70e600f28eaa2d84eed0b4ad7deadb6e200cd489ee7abb583269e62", - "icons.ts": "a8b146eb3772621e4b4349ad143da14170d28ed3dd68aad41748dbaeb8e99988", + "icons.ts": "2e3ec58ea5ccaae4243d72d55da10c39611bd02f486cdcd5b11b9459c6beb402", "keys.ts": "1adfc7daefa35b0e6eb8957250dca3926ded1c59fd51db7d60da6346caf0d561", "placement.ts": "0f7e03ef0b720af07995111f30dcb5ed124529d44cf5cb67ae4bfb1f96c7f880", "state.ts": "bef508e8343737f67adfbd7ae8cb8efb446968dfd4e7e0aff37da11f996955d7", - "strings.ts": "b1ad5ff88bd46e3631b12fc831fc919329ad051ba38c99927c1d5aed9eea5de8", + "strings.ts": "19a6a32f235b61dfed6179e2271a6d599f4357c9a6b9c09118bb65990d1e114f", "terminal.ts": "8bf886a7ad4dc69323e803acc13641a66e1d8614e9b85a6a60977fa30d8a56fc", - "tour.ts": "9b72d54ece42fd15b84054e21264453207c5e73261d387110a9abf91d29586aa" + "tour.ts": "2f83994051f4370c5d1630a827b4539eb12fd50e7fe9531f5641a4bf75615782" } } diff --git a/frontend/src/dock/adapter.ts b/frontend/src/dock/adapter.ts index 59476b9..6f13d08 100644 --- a/frontend/src/dock/adapter.ts +++ b/frontend/src/dock/adapter.ts @@ -7,18 +7,19 @@ export type DockProgram = 'claude' | 'codex' | 'cursor'; export type PtyKind = 'shell' | 'claude' | 'codex' | 'cursor' | 'agent'; export type ChatMode = 'ask' | 'auto-edits' | 'plan'; -export interface DockTerminal { id: string; title: string; alive: boolean; kind: PtyKind; tip?: string } +export interface DockTerminal { id: string; title: string; alive: boolean; kind: PtyKind | K; tip?: string; status?: string } export interface DockChannel { send(data: string): void; resize(cols: number, rows: number): void; onData(handler: (data: string | Uint8Array) => void): void; onExit(handler: () => void): void; onClose?(handler: () => void): void; + onStatus?(handler: (text: string) => void): void; close(): void; } export interface DockOpen { cols: number; rows: number; prompt?: string; resume?: string } -export interface DockProgramStatus { installed: boolean; version: string | null; install: string; signedIn: boolean | null } -export type DockAgentStatus = Partial>; +export interface DockProgramStatus { installed: boolean; version: string | null; install: string; signedIn: boolean | null; label?: string; note?: string } +export type DockAgentStatus = Partial>; export interface DockChatStatus { installed: boolean; version: string | null; @@ -53,8 +54,8 @@ export interface DockOwnChat { busy?(): boolean; askTarget?: HTMLElement; } -export interface DockOwnAsk { send?(text: string, tab: DockKind | null): DockSent; element?: HTMLElement } -export interface DockChatPane { pane(host: HTMLElement): DockOwnChat | void; ask?: 'none' | 'line' | DockOwnAsk } +export interface DockOwnAsk { send?(text: string, tab: DockKind | K | null): DockSent; element?: HTMLElement } +export interface DockChatPane { pane(host: HTMLElement): DockOwnChat | void; ask?: 'none' | 'line' | DockOwnAsk } export type DockChatEvent = | { type: 'state'; running: boolean; state: string; session: string | null; mode?: ChatMode } | { type: 'user'; text: string; note?: string } @@ -84,36 +85,36 @@ export interface DockSizes { export type DockErrorKind = 'refused' | 'unreachable' | 'notInstalled' | 'oldEngine' | 'busy'; export interface DockWords { app: string; noun: string; lead: string; example: string; start?: string } export interface DockAppTab { id: string; label: string; icon: string; mount(host: HTMLElement): void | (() => void) } -export interface DockTabs { builtin: DockKind[]; own?: DockAppTab[] } +export interface DockTabs { builtin: Array; own?: DockAppTab[] } export interface DockStorage { key: string; legacy?: DockLegacy | string[] } export type DockPlacement = | { mode: 'own'; storage: DockStorage; sizes: DockSizes; canDockRight?(): boolean } | { mode: 'hosted'; request(open: boolean): void }; -export interface DockAdapter { +export interface DockAdapter { words: DockWords; strings?: Partial>; placement: DockPlacement; passKey?(event: KeyboardEvent): boolean; isDockChord?(event: KeyboardEvent): boolean; chordLabel?(): string; - tabs(): DockTabs; + tabs(): DockTabs; classes: { iconButton: string; button: string; primaryButton: string; input: string; select: string; note: string }; t(key: string, english: string): string; onTheme(handler: () => void): void; - keyHeaders(): Record; + keyHeaders?(): Record; errors: { message(err: unknown): string | null; kind?(err: unknown): DockErrorKind | null }; firstRun?(): boolean; terminal: { - list(): Promise; - open(kind: Exclude, options: DockOpen): Promise; + list(): Promise[]>; + open(kind: Exclude | K, options: DockOpen): Promise>; restart?(id: string): Promise; close(id: string): Promise; channel(id: string): DockChannel | Promise; scrollback?: number; }; - agentStatus(): Promise; - chat?: DockChatEngine | DockChatPane; + agentStatus(): Promise | null>; + chat?: DockChatEngine | DockChatPane; consent?: { subscribe(add: (request: ConsentRequest) => void, withdraw: (id: string) => void): void; answer(id: string, choice: ConsentChoice): Promise; @@ -128,6 +129,9 @@ export interface DockAdapter { export const DOCK_PUBLIC = { classes: ['ft-dock', 'ft-consent', 'ft-tour', 'ft-term', 'ft-chat', 'ft-dock-pane', 'ft-notranslate', 'is-hosted', 'has-own-chat', 'has-no-ask', 'has-ask-line', 'ft-dock-ask', 'ft-dock-ask-own', 'ft-dock-head', 'ft-dock-tab', 'ft-dock-stage', 'ft-icon', 'is-on', 'is-own'], rootAttributes: ['data-ft-dock', 'data-ft-dock-side', 'data-ft-dock-h', 'data-ft-dock-w'], + partAttribute: 'data-dock-part', + parts: ['new', 'chat', 'launch.claude', 'more', 'restart', 'side', 'hide', 'menu', 'menu.settings', 'menu.guide', 'screen', 'note.copy', 'note.dismiss', 'ask', 'send', 'tab.chat', 'tab.close', 'consent', 'consent.deny', 'consent.once', 'consent.always'], + partsByKind: ['launch.', 'menu.launch.', 'tab.'], rootProperties: ['--ft-dock-size', '--ft-dock-wsize'], tokens: [ '--dock-bg', '--dock-bar-bg', '--dock-raised', '--dock-hover', '--dock-input-bg', '--dock-border', '--dock-edge', '--dock-divider', '--dock-tab-border', '--dock-outline', '--dock-scrim', diff --git a/frontend/src/dock/agents.ts b/frontend/src/dock/agents.ts new file mode 100644 index 0000000..083297e --- /dev/null +++ b/frontend/src/dock/agents.ts @@ -0,0 +1,22 @@ +import type { StringKey } from './strings'; + +export interface DockAgentKind { id: string; label: string; name?: StringKey; icon: string; ready: StringKey; missing: StringKey } + +export const DOCK_AGENTS: readonly DockAgentKind[] = [ + { id: 'claude', label: 'Claude Code', name: 'claudeCode', icon: 'agent', ready: 'programReady', missing: 'notInstalled' }, + { id: 'codex', label: 'Codex', name: 'codex', icon: 'codex', ready: 'programReady', missing: 'programMissing' }, + { id: 'cursor', label: 'Cursor', name: 'cursor', icon: 'cursor', ready: 'programReady', missing: 'programMissing' }, + { id: 'antigravity', label: 'Antigravity', name: 'antigravity', icon: 'antigravity', ready: 'programReady', missing: 'programMissing' }, +]; + +export const DOCK_PLAIN: readonly string[] = ['shell', 'chat', 'agent']; + +export function agentKind(id: string): DockAgentKind { + return DOCK_AGENTS.find((k) => k.id === id) ?? { id, label: id, icon: id, ready: 'programReady', missing: 'programMissing' }; +} + +export function agentKinds(builtin: readonly string[]): DockAgentKind[] { + const listed = DOCK_AGENTS.filter((k) => builtin.includes(k.id)); + const more = builtin.filter((id) => !DOCK_PLAIN.includes(id) && !DOCK_AGENTS.some((k) => k.id === id)).map(agentKind); + return [...listed, ...more]; +} diff --git a/frontend/src/dock/chat.ts b/frontend/src/dock/chat.ts index 64d02ae..2c02755 100644 --- a/frontend/src/dock/chat.ts +++ b/frontend/src/dock/chat.ts @@ -9,7 +9,7 @@ function toolName(name: string): string { return name.replace(/^mcp__/, '').replace(/__/g, ' '); } -export type ChatHost = Omit & { chat: DockChatEngine }; +export type ChatHost = Omit, 'chat'> & { chat: DockChatEngine }; export interface DockChatView { readonly root: HTMLElement; diff --git a/frontend/src/dock/consent.ts b/frontend/src/dock/consent.ts index 652b41d..ec20659 100644 --- a/frontend/src/dock/consent.ts +++ b/frontend/src/dock/consent.ts @@ -31,7 +31,7 @@ export class Consent { if (this.root) return this.root; const s = this.s; const c = this.a.classes; - const root = el(` + const root = el(` `); diff --git a/frontend/src/dock/dock.css b/frontend/src/dock/dock.css index 69eff56..1d1a8a5 100644 --- a/frontend/src/dock/dock.css +++ b/frontend/src/dock/dock.css @@ -22,11 +22,11 @@ .ft-dock-grip:hover { background: var(--dock-accent-line); } .ft-dock-head { flex: none; display: flex; align-items: center; gap: var(--dock-space-2); height: var(--dock-head-h); padding: 0 var(--dock-space-2); background: var(--dock-bar-bg); border-bottom: 1px solid var(--dock-divider, var(--dock-border)); min-width: 0; } .ft-dock-tabs { display: flex; align-items: center; gap: 2px; min-width: 0; overflow-x: auto; scrollbar-width: none; } -.ft-dock-spacer { flex: 1; } +.ft-dock-spacer { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; text-align: end; color: var(--dock-text-muted); font-size: var(--dock-fs-xs); user-select: text; -webkit-user-select: text; } .ft-dock-tab { display: inline-flex; align-items: center; flex: none; gap: 6px; height: var(--dock-tab-h, 26px); padding: 0 6px 0 9px; border: 1px solid transparent; border-radius: var(--dock-tab-radius, 6px); background: transparent; color: var(--dock-tab-text, var(--dock-text-dim)); font: inherit; font-size: var(--dock-fs-sm); cursor: pointer; white-space: nowrap; } .ft-dock-tab:hover { color: var(--dock-text); } .ft-dock-tab.is-on { border-color: var(--dock-tab-border); background: var(--dock-raised); color: var(--dock-text); } -.ft-dock-tab.is-claude > .ft-icon, .ft-dock-tab.is-chat > .ft-icon, .ft-dock-tab.is-codex > .ft-icon, .ft-dock-tab.is-cursor > .ft-icon { color: var(--dock-tab-accent, var(--dock-accent)); } +.ft-dock-tab.is-claude > .ft-icon, .ft-dock-tab.is-chat > .ft-icon, .ft-dock-tab.is-codex > .ft-icon, .ft-dock-tab.is-cursor > .ft-icon, .ft-dock-tab.is-program > .ft-icon { color: var(--dock-tab-accent, var(--dock-accent)); } .ft-dock-head .ft-dock-ibtn[hidden] { display: none; } .ft-dock-menu { position: absolute; top: calc(var(--dock-head-h) + var(--dock-space-1)); right: var(--dock-space-2); z-index: var(--z-raised); display: flex; flex-direction: column; gap: var(--dock-space-2); width: min(340px, calc(100% - 16px)); padding: var(--dock-space-2) var(--dock-space-3); border: 1px solid var(--dock-border); border-radius: var(--dock-radius-md); background: var(--dock-bar-bg); color: var(--dock-text); font-size: var(--dock-fs-sm); user-select: text; -webkit-user-select: text; } .ft-dock-menu[hidden], .ft-dock-menu-go[hidden], .ft-dock-menu-cmd[hidden] { display: none; } diff --git a/frontend/src/dock/dock.ts b/frontend/src/dock/dock.ts index 84312cd..bcbd54b 100644 --- a/frontend/src/dock/dock.ts +++ b/frontend/src/dock/dock.ts @@ -1,4 +1,5 @@ -import type { DockAdapter, DockAgentStatus, DockAppTab, DockChannel, DockKind, DockOwnAsk, DockPaneHidden, DockTerminal, PtyKind } from './adapter'; +import type { DockAdapter, DockAgentStatus, DockAppTab, DockChannel, DockKind, DockOwnAsk, DockPaneHidden, DockProgramStatus, DockTerminal } from './adapter'; +import { DOCK_AGENTS, agentKind, agentKinds, type DockAgentKind } from './agents'; import { ChatPane, OwnChat, type DockChatView } from './chat'; import { Consent } from './consent'; import { el, q, setClass, setDisabled, setHidden, setText } from './dom'; @@ -12,22 +13,24 @@ import { Tour, type TourStep } from './tour'; export type { DockAdapter, DockKind } from './adapter'; -const PROGRAMS = ['codex', 'cursor'] as const; -type Program = typeof PROGRAMS[number]; - interface Tab { id: string; term: DockTerm | null; host: HTMLElement; tab: HTMLElement; channel: DockChannel | null; - kind: PtyKind; + kind: string; seen: boolean; closed: boolean; + status: string; } -export class Dock { +interface Program { kind: DockAgentKind; button: HTMLButtonElement; row: HTMLElement } + +export class Dock { + private readonly a: DockAdapter; private readonly s: Say; + private readonly kinds = new Map(); readonly root: HTMLElement; private readonly tabsEl: HTMLElement; private readonly stage: HTMLElement; @@ -41,13 +44,13 @@ export class Dock { private readonly tabs = new Map(); private readonly owned = new Map void) | undefined }>(); private chat: DockChatView | null = null; - private readonly ownAsk: DockOwnAsk | null; + private readonly ownAsk: DockOwnAsk | null; private chatTab: HTMLElement | null = null; private active: string | null = null; private started = false; private pending: Promise | null = null; private emulator: Promise | null = null; - private asked: Promise | null = null; + private asked: Promise | null> | null = null; private mounted = false; private revealing = false; private readonly place: Placement; @@ -57,37 +60,35 @@ export class Dock { readonly consent: Consent | null; private readonly tour: Tour; - constructor(private readonly a: DockAdapter, parts: { consent?: Consent } = {}) { + constructor(adapter: DockAdapter, parts: { consent?: Consent } = {}) { + const a = adapter as unknown as DockAdapter; const s = strings(a); const c = a.classes; const ib = `${c.iconButton} ft-dock-ibtn`; + this.a = a; this.s = s; this.root = el(`
- - - - - - - - - - + + + + + + + +
-
`); this.tabsEl = q(this.root, '.ft-dock-tabs'); @@ -105,10 +106,6 @@ export class Dock { q(this.root, '.ft-dock-chat').addEventListener('click', () => void this.showChat()); q(this.root, '.ft-dock-hide').addEventListener('click', () => this.toggle(false)); q(this.root, '.ft-dock-side').addEventListener('click', () => { this.setSide(this.side() === 'right' ? 'bottom' : 'right'); this.focus(); }); - for (const kind of PROGRAMS) { - q(this.root, `.ft-dock-${kind}`).addEventListener('click', () => void this.program(kind)); - q(this.root, `.ft-dock-menu-row[data-kind="${kind}"] .ft-dock-menu-go`).addEventListener('click', () => { this.menu(false); void this.program(kind); }); - } q(this.root, '.ft-dock-more').addEventListener('click', () => { this.menu(q(this.root, '.ft-dock-menu').hidden === true); }); q(this.root, '.ft-dock-menu-settings').addEventListener('click', () => { this.menu(false); a.openSettings?.(); }); setHidden(q(this.root, '.ft-dock-menu-settings'), !a.openSettings); @@ -198,48 +195,80 @@ export class Dock { else await this.open(); } - activeKind(): DockKind | null { + activeKind(): DockKind | K | null { if (this.active === 'chat') return 'chat'; const kind = this.active ? this.tabs.get(this.active)?.kind : undefined; - return kind && kind !== 'agent' ? kind : null; + return kind && kind !== 'agent' ? kind as DockKind | K : null; } - isShowing(kind: DockKind): boolean { return this.isOpen() && this.activeKind() === kind; } + isShowing(kind: DockKind | K): boolean { return this.isOpen() && this.activeKind() === kind; } - async show(kind: DockKind): Promise { + async show(kind: DockKind | K): Promise { if (!this.isOpen()) this.toggle(true, 'none'); await this.ensure('none'); if (kind === 'chat') { await this.showChat(); return; } const own = [...this.tabs.values()].find((x) => x.kind === kind); if (own) this.select(own.id); else if (kind === 'claude') await this.claude(); - else if (kind === 'codex' || kind === 'cursor') await this.program(kind); + else if (kind !== 'shell') await this.program(kind); else await this.open(); } + private label(kind: DockAgentKind, status?: DockProgramStatus): string { + return kind.name ? this.s(kind.name) : this.a.t(kind.id, status?.label ?? kind.label); + } + + private listPrograms(): void { + const order = agentKinds(this.a.tabs().builtin).filter((kind) => kind.id !== 'claude'); + const c = this.a.classes; + for (const [at, kind] of order.entries()) { + if (this.kinds.has(kind.id)) continue; + const name = this.label(kind); + const button = el(``); + const row = el(`

`); + button.title = name; + button.setAttribute('aria-label', name); + row.dataset.kind = kind.id; + button.dataset.dockPart = `launch.${kind.id}`; + q(row, '.ft-dock-menu-go').dataset.dockPart = `menu.launch.${kind.id}`; + setText(q(row, '.ft-dock-menu-go > span:last-child'), name); + button.addEventListener('click', () => void this.program(kind.id)); + q(row, '.ft-dock-menu-go').addEventListener('click', () => { this.menu(false); void this.program(kind.id); }); + const next = order.slice(at + 1).map((later) => this.kinds.get(later.id)).find((later) => later !== undefined); + q(this.root, '.ft-dock-head').insertBefore(button, next?.button ?? q(this.root, '.ft-dock-new')); + q(this.root, '.ft-dock-menu').insertBefore(row, next?.row ?? q(this.root, '.ft-dock-menu-links')); + this.kinds.set(kind.id, { kind, button, row }); + } + } + private async programs(): Promise { const status = await this.agents(); - for (const kind of PROGRAMS) { - const st = status?.[kind]; - const offered = this.offers(kind); + for (const { kind, button, row } of this.kinds.values()) { + const st = status?.[kind.id]; + const offered = this.offers(kind.id); const found = offered && !!st?.installed; - const row = q(this.root, `.ft-dock-menu-row[data-kind="${kind}"]`); setHidden(row, !offered || !st); - setHidden(q(this.root, `.ft-dock-${kind}`), !found); + setHidden(button, !found); setHidden(q(row, '.ft-dock-menu-go'), !found); - setText(q(row, '.ft-dock-menu-how'), this.s(found ? 'programReady' : 'programMissing', { program: this.s(kind) })); + const name = this.label(kind, st); + setText(q(row, '.ft-dock-menu-how'), st?.note || this.s(found ? kind.ready : kind.missing, { program: name })); setText(q(row, '.ft-dock-menu-cmd'), found ? '' : st?.install ?? ''); setHidden(q(row, '.ft-dock-menu-cmd'), found || !st?.install); + if (kind.name || button.title === name) continue; + button.title = name; + button.setAttribute('aria-label', name); + setText(q(row, '.ft-dock-menu-go > span:last-child'), name); } } - private offers(kind: DockKind): boolean { + private offers(kind: string): boolean { return this.a.tabs().builtin.includes(kind) && (kind !== 'chat' || !!this.a.chat); } activeTab(): string | null { return this.active; } refresh(): void { + this.listPrograms(); setHidden(q(this.root, '.ft-dock-new'), !this.offers('shell')); setHidden(q(this.root, '.ft-dock-chat'), !this.offers('chat')); setHidden(q(this.root, '.ft-dock-claude'), !this.offers('claude')); @@ -281,7 +310,7 @@ export class Dock { q(this.root, '.ft-dock-more').setAttribute('aria-expanded', String(open)); } - async program(kind: Program): Promise { + async program(kind: string): Promise { const size = this.size(); try { const info = await this.a.terminal.open(kind, { cols: size.cols, rows: size.rows }); @@ -297,7 +326,7 @@ export class Dock { } } - async toggleKind(kind: DockKind): Promise { + async toggleKind(kind: DockKind | K): Promise { if (this.isShowing(kind)) this.toggle(false); else await this.show(kind); } @@ -363,7 +392,7 @@ export class Dock { return this.emulator; } - private agents(): Promise { + private agents(): Promise | null> { if (!this.asked) { this.asked = this.a.agentStatus().catch(() => null); void this.asked.then(() => window.setTimeout(() => { this.asked = null; }, 1500)); @@ -371,7 +400,7 @@ export class Dock { return this.asked; } - private async list(): Promise { + private async list(): Promise[]> { try { return await this.a.terminal.list(); } catch { return []; } } @@ -444,7 +473,7 @@ export class Dock { this.stage.appendChild(this.chat.root); } if (!this.chatTab) { - const tab = el(``); + const tab = el(``); tab.addEventListener('click', (e) => { if ((e.target as HTMLElement).closest('.ft-dock-tab-x')) this.closeChat(); else this.select('chat'); @@ -537,7 +566,7 @@ export class Dock { if (x.tab.title !== tip) x.tab.title = tip; } - private adopt(info: DockTerminal): void { + private adopt(info: DockTerminal): void { if (this.tabs.has(info.id)) return; void this.attach(info, this.active === null || info.kind !== 'agent'); } @@ -570,13 +599,14 @@ export class Dock { return tab?.term ? { cols: tab.term.cols(), rows: tab.term.rows() } : { cols: 100, rows: 20 }; } - private async attach(info: DockTerminal, show: boolean): Promise { + private async attach(info: DockTerminal, show: boolean): Promise { if (this.tabs.has(info.id)) { if (show) this.select(info.id); return; } - const kind: PtyKind = ['claude', 'agent', 'codex', 'cursor'].includes(info.kind) ? info.kind : 'shell'; + const program = DOCK_AGENTS.some((k) => k.id === info.kind) || this.kinds.has(info.kind); + const kind: string = program || info.kind === 'agent' ? info.kind : 'shell'; const agent = kind === 'agent'; - const mark = kind === 'claude' ? 'agent' : kind === 'codex' || kind === 'cursor' ? kind : 'terminal'; + const mark = program ? agentKind(kind).icon : 'terminal'; const host = el(''); - const tab = el(``); + const tab = el(``); setText(q(tab, '.ft-dock-tab-title'), info.title); if (agent) tab.title = this.s('agentTab'); tab.addEventListener('click', (e) => { @@ -586,7 +616,7 @@ export class Dock { this.stage.appendChild(host); this.tabsEl.appendChild(tab); if (info.tip) tab.dataset.tip = info.tip; - const entry: Tab = { id: info.id, term: null, host, tab, channel: null, kind, seen: false, closed: false }; + const entry: Tab = { id: info.id, term: null, host, tab, channel: null, kind, seen: false, closed: false, status: info.status ?? '' }; this.tabs.set(info.id, entry); setHidden(this.empty, true); this.ended(entry, !info.alive); @@ -610,9 +640,15 @@ export class Dock { channel.onData((data) => { entry.seen = true; entry.term?.write(data); }); channel.onExit(() => { entry.seen = true; this.ended(entry, true); }); channel.onClose?.(() => { if (entry.channel === channel) entry.channel = null; silent(); }); + channel.onStatus?.((text) => { entry.status = text; this.showStatus(); }); this.sendSize(entry); } + private showStatus(): void { + const x = this.active ? this.tabs.get(this.active) : undefined; + setText(q(this.root, '.ft-dock-spacer'), x?.status ?? ''); + } + private sendSize(x: Tab): void { if (x.term) x.channel?.resize(x.term.cols(), x.term.rows()); } @@ -644,6 +680,7 @@ export class Dock { o.tab.setAttribute('aria-selected', String(on)); } this.syncAsk(); + this.showStatus(); setDisabled(this.restartBtn, !this.tabs.has(id) || this.tabs.get(id)?.kind === 'agent'); this.fitActive(); if (focus) this.focus(); @@ -676,7 +713,7 @@ export class Dock { this.active = null; const next = [...this.tabs.keys()].pop() ?? (this.chatTab ? 'chat' : undefined); if (next) this.select(next); - else { setDisabled(this.restartBtn, true); this.syncAsk(); this.onTab(); } + else { setDisabled(this.restartBtn, true); this.syncAsk(); this.showStatus(); this.onTab(); } } setHidden(this.empty, this.tabs.size > 0 || !!this.chatTab); } diff --git a/frontend/src/dock/icons.ts b/frontend/src/dock/icons.ts index eccfac8..b57b519 100644 --- a/frontend/src/dock/icons.ts +++ b/frontend/src/dock/icons.ts @@ -8,6 +8,7 @@ const ICONS: Record = { terminal: ``, codex: ``, cursor: ``, + antigravity: ``, dockRight: ``, dockBottom: ``, menu: ``, diff --git a/frontend/src/dock/strings.ts b/frontend/src/dock/strings.ts index 5de91b9..1aae816 100644 --- a/frontend/src/dock/strings.ts +++ b/frontend/src/dock/strings.ts @@ -12,6 +12,7 @@ export const STRINGS = { hide: 'Hide Terminal', codex: 'Codex', cursor: 'Cursor', + antigravity: 'Antigravity', moreAgents: 'More agents', programMissing: '{program} is not on this computer yet: install it with the command below, then sign in once in a terminal.', programReady: '{program} is installed. Start it in a new tab.', diff --git a/frontend/src/dock/tour.ts b/frontend/src/dock/tour.ts index 94eb988..358cac3 100644 --- a/frontend/src/dock/tour.ts +++ b/frontend/src/dock/tour.ts @@ -40,7 +40,7 @@ export class Tour { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.end(true); } }; - constructor(private readonly a: DockAdapter) { + constructor(private readonly a: DockAdapter) { this.s = strings(a); } From 4f4a205cc2965b7f0f6899793e0748f5d548a91f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:08 -0500 Subject: [PATCH 26/30] feat(agents): formencoder opens an Antigravity tab, and agents install adds formencoder to Antigravity The tab route takes kind antigravity and starts agy the way it starts the other three: found by the family's finder, started through its start path, with the tab's own token in its environment. The tab runs in the agent workspace, where the other agent tabs run, and gets the entry formencoder_tab (the stdio bridge with the tab's token) in .agents/mcp_config.json there; everything else in the file is kept, the file is the user's alone, and the entry is taken out when the tab closes or the program ends, when the token also stops being accepted. The dock adapter lists the fourth kind and gives the engine's sentence for a missing program; the Agent button's menu and the Agents panel's set-up row have Antigravity. agents install antigravity writes ~/.gemini/config/mcp_config.json, keeps what is there, leaves a foreign entry alone and says when only the older file was seen. agents/manifest.json was rewritten by ./formencoder agents sync. Seen with an engine from source on port 4741 and stand-ins (a real agy was never started): four programs in the status, the tab showing the stand-in's banner, the file holding its seeded server and key beside formencoder_tab at mode 0600, a call with the tab's token served unasked, the file exactly as seeded after close and the dead token treated as an outside agent's; the install route dry, first, second and with a foreign entry. Tests after that: 28 passed in the agent and dock files. tsc --noEmit clean, vite build completed. Not looked at in a browser. Not run: a real agy, Windows, macOS, the desktop window. Known limit: two Antigravity tabs share one entry. --- agents/manifest.json | 3 +- backend/HASHOUT_LOG.md | 14 +++++++ backend/app/agent/connect.py | 35 +++++++++++++++- backend/app/agent/workspace.py | 2 +- backend/app/routers/terminal.py | 23 ++++++++++- backend/app/services/agent_programs.py | 45 +++++++++++++++++++++ backend/tests/test_dock_engine.py | 55 +++++++++++++++++++++++++- backend/tests/test_dock_module.py | 4 +- frontend/HASHOUT_LOG.md | 11 ++++++ frontend/src/app/app.ts | 1 + frontend/src/dock-adapter.ts | 38 ++++++++++-------- frontend/src/panels/agents.ts | 3 +- setup/agents.py | 2 +- 13 files changed, 208 insertions(+), 28 deletions(-) diff --git a/agents/manifest.json b/agents/manifest.json index dca23ee..4e8c656 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -306,7 +306,8 @@ "shell", "claude", "codex", - "cursor" + "cursor", + "antigravity" ] }, "extensions": { diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 68a0929..bb092c0 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -327,3 +327,17 @@ Refers to `backend/tests/conftest.py` `AGENT_STAND_INS`, `AGENT_CALLS`, `AGENT_S - The run ends with one line saying how many times a stand-in was started and with what arguments. - Not on Windows: the stand-ins are shell scripts, and the tests that start programs are skipped there. +## An Antigravity tab, and Antigravity as the fourth target of agents install (unreleased, after 0.9.0) + +Refers to `routers/terminal.py` `TABS`, `_tab_entry`, `Term._start`, `Term._ended`, `Term.close`, `Term._forget`, `open_tab`; `services/agent_programs.py` `TAB_ENTRY`, `TOKEN_VAR`, `write_tab_entry`, `remove_tab_entry`; `agent/workspace.py` `CLIENT_PROFILES`; `agent/connect.py` `install_antigravity`, `CLIENTS`; `setup/agents.py` `DOCK` · kind: feat · logged: unreleased · 2026-11-19 + +- `POST /api/terminal/tabs {kind: antigravity}` starts `agy` as the other agent kinds are started: found by the finder, through its start path, with the tab's own token in the environment. +- Antigravity reads its MCP servers from a file. Decision: every agent tab of formencoder already runs in the agent workspace (`[data folder]/agent-workspace`), where Claude Code, Codex and Cursor have their files, so the Antigravity tab runs there too and its entry goes to `.agents/mcp_config.json` in that folder. A `cwd` in the request is ignored for this kind, so the token is never written into a folder of the person's. +- The entry is `formencoder_tab`: `{command: , args: ["mcp", "--profile", "core"], env: {FORMENCODER_URL, FORMENCODER_AGENT_TOKEN, FORMENCODER_AGENT_NAME}}`, the stdio bridge the Cursor tab uses, with the tab's token in `env` because nothing read says Antigravity hands its own environment to a server it starts. The profile is `core`, as for Cursor: nothing read says how many tools Antigravity lists. Every other entry and key in the file is kept; the file is written whole through a part file with mode 0600. +- The entry is taken out when the program ends and when the tab closes, only while it still carries that tab's token; the token is revoked as for the other kinds. A restart writes the new token. +- Known limit: two Antigravity tabs share the one entry. The second replaces it, and closing the second removes it while the first is still open; the first program has read the file at its start. Not tried beyond seeing the entry go. +- `agents install antigravity` (and the default set, and the Agents panel's button) writes `mcpServers.formencoder = {command, args: ["mcp", "--profile", "core"]}` into `~/.gemini/config/mcp_config.json`: backup, part file, replace. A second run changes nothing; a `formencoder` entry that formencoder did not write is left alone and reported; a file that is not an MCP servers file is left alone; when only `~/.gemini/antigravity-cli/mcp_config.json` exists the documented path is written and the result says the older file was seen. No skill is copied for Antigravity. +- Checked by running an engine from source on 4741 with its own home, data folder, a stand-in login shell and stand-in `claude`, `codex`, `cursor-agent` and `agy` first on PATH: the status listed four as `runs` with their versions; the Antigravity tab showed the stand-in's banner with the token present and the entry in the file; the file, seeded with another server and a top-level key, held both beside `formencoder_tab` at mode 0600; a call with the live token ran unasked; after close the file was byte for byte the seed and a call with the dead token was treated as an outside agent's; without `agy` the status and the tab route gave the finder's sentence. The install route: dry run wrote nothing, first run wrote the file, second run said already, a foreign entry was left with the same hash. +- Tests, written after that: `test_dock_engine.py` (the Antigravity case of the tab test, the entry in the file, the install cases), `test_dock_module.py` (the manifest lists five tabs). `agents/manifest.json` was rewritten by `./formencoder agents sync`. +- Not run: a real `agy` (whether it reads `.agents/mcp_config.json` in the workspace, wants the workspace trusted first, or passes `env` to the bridge), Windows, macOS. + diff --git a/backend/app/agent/connect.py b/backend/app/agent/connect.py index 255ec42..7eec374 100644 --- a/backend/app/agent/connect.py +++ b/backend/app/agent/connect.py @@ -105,7 +105,38 @@ def install_cursor(home: Path, dry: bool, said: list) -> None: _copy_skill(home / ".agents" / "skills" / SKILL, dry, said) -CLIENTS = {"claude": install_claude, "codex": install_codex, "cursor": install_cursor} +def install_antigravity(home: Path, dry: bool, said: list) -> None: + said.append("Antigravity:") + cfg = home / ".gemini" / "config" / "mcp_config.json" + older = home / ".gemini" / "antigravity-cli" / "mcp_config.json" + if older.exists() and not cfg.exists(): + said.append(f" an older file was seen at {older} and left alone; the documented file is {cfg}") + try: + data = json.loads(cfg.read_text(encoding="utf-8") or "{}") if cfg.exists() else {} + except ValueError: + data = None + if not isinstance(data, dict) or not isinstance(data.get("mcpServers", {}), dict): + said.append(f" {cfg} is not an MCP servers file formencoder can read; left alone") + return + entry = {"command": launch(), "args": workspace.client_args("antigravity")} + have = data.get("mcpServers", {}).get(NAME) + ours = isinstance(have, dict) and have.get("args") == entry["args"] and Path(str(have.get("command", ""))).name == Path(entry["command"]).name + if have == entry: + said.append(f" MCP server {NAME} already in {cfg}") + elif have is not None and not ours: + said.append(f" {cfg} has a server named {NAME} that formencoder did not write; left alone") + else: + said.append(f" MCP server {NAME} -> {cfg}") + if not dry: + _backup(cfg, dry) + data.setdefault("mcpServers", {})[NAME] = entry + cfg.parent.mkdir(parents=True, exist_ok=True) + part = cfg.with_name(cfg.name + f".part-{os.getpid()}") + part.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + os.replace(part, cfg) + + +CLIENTS = {"claude": install_claude, "codex": install_codex, "cursor": install_cursor, "antigravity": install_antigravity} def install(which: list[str] | None = None, dry: bool = False) -> list[str]: @@ -116,7 +147,7 @@ def install(which: list[str] | None = None, dry: bool = False) -> list[str]: if w in CLIENTS: CLIENTS[w](home, dry, said) else: - said.append(f"unknown client {w} (claude, codex or cursor)") + said.append(f"unknown client {w} (claude, codex, cursor or antigravity)") return said diff --git a/backend/app/agent/workspace.py b/backend/app/agent/workspace.py index 74c274c..7beda94 100644 --- a/backend/app/agent/workspace.py +++ b/backend/app/agent/workspace.py @@ -10,7 +10,7 @@ from .. import __version__ from ..core import config -CLIENT_PROFILES = {"claude": "full", "codex": "full", "cursor": "core"} +CLIENT_PROFILES = {"claude": "full", "codex": "full", "cursor": "core", "antigravity": "core"} def client_args(client: str) -> list[str]: diff --git a/backend/app/routers/terminal.py b/backend/app/routers/terminal.py index 9879e23..110a8e1 100644 --- a/backend/app/routers/terminal.py +++ b/backend/app/routers/terminal.py @@ -22,7 +22,7 @@ POSIX = os.name == "posix" AGENTS = {kind: spec["bin"] for kind, spec in finder.PROGRAMS.items()} PROGRAMS = {kind: {"title": spec["title"], "install": finder.install(kind)} for kind, spec in finder.PROGRAMS.items()} -TABS = ("claude", "codex", "cursor") +TABS = ("claude", "codex", "cursor", "antigravity") RESUME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{7,79}") PROMPT_MAX = 20000 @@ -38,6 +38,12 @@ def _typed(kind: str) -> str: return shlex.quote(path) if POSIX else (f'"{path}"' if " " in path else path) +def _tab_entry(base_url: str, token: str) -> dict: + command, _ = workspace.mcp_command() + return {"command": command, "args": workspace.client_args("antigravity"), + "env": {"FORMENCODER_URL": base_url, finder.TOKEN_VAR: token, "FORMENCODER_AGENT_NAME": "terminal"}} + + def _environment(base_url: str, token: str | None, program: str | None = None) -> dict: ws = workspace.ensure() env = dict(os.environ) @@ -202,6 +208,13 @@ def _start(self, cols: int, rows: int) -> None: self.exited = False consent.revoke(self.token) self.token = consent.issue() if self.trusted else None + if self.kind == "antigravity" and self.token: + try: + finder.write_tab_entry(self.cwd, _tab_entry(self.base, self.token)) + except OSError: + consent.revoke(self.token) + self.token = None + raise self.session = Session(cols, rows, _environment(self.base, self.token, self.program), self.cwd, self.argv) session = self.session @@ -233,6 +246,7 @@ def _ended(self, session: "Session") -> None: return self.exited = True if self.window: + self._forget() consent.revoke(self.token) self.token = None for q in list(self.listeners): @@ -264,12 +278,17 @@ def close(self) -> None: if self.session: self.session.close() self.exited = True + self._forget() consent.revoke(self.token) self.token = None for q in list(self.listeners): with contextlib.suppress(asyncio.QueueFull): q.put_nowait({"type": "closed"}) + def _forget(self) -> None: + if self.kind == "antigravity": + finder.remove_tab_entry(self.cwd, self.token) + def row(self) -> dict: return {"id": self.id, "title": self.title, "cwd": self.cwd, "created": self.created, "exited": self.exited, "owned": self.owned, "offset": self.offset, "opener": self.opener, "kind": self.kind if self.opener == "ui" else "agent", "alive": not self.exited} @@ -371,7 +390,7 @@ async def open_tab(request: Request) -> dict: path = found.path argv = agent_lookup.start_argv([path, *(["--resume", resume] if resume else []), *((["--", prompt] if prompt.startswith("-") else [prompt]) if prompt else [])]) title = body.get("title") if isinstance(body.get("title"), str) else None - cwd = body.get("cwd") if isinstance(body.get("cwd"), str) else None + cwd = body.get("cwd") if isinstance(body.get("cwd"), str) and kind != "antigravity" else None try: term = hub.open(title or (PROGRAMS[kind]["title"] if argv else None), cwd, cols, rows, _base(request.headers.get("host")), trusted=argv is not None, kind=kind, window=True, argv=argv, program=path) except OSError as exc: diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py index 2e4792f..b93ba90 100644 --- a/backend/app/services/agent_programs.py +++ b/backend/app/services/agent_programs.py @@ -1,6 +1,8 @@ from __future__ import annotations +import json import os +from pathlib import Path from . import agent_lookup @@ -17,6 +19,8 @@ "antigravity": ("FORMENCODER_ANTIGRAVITY_BIN",), } OTHERWISE = "" +TAB_ENTRY = "formencoder_tab" +TOKEN_VAR = "FORMENCODER_AGENT_TOKEN" def install(kind: str) -> str: @@ -50,6 +54,47 @@ def program(kind: str) -> str | None: return found.path if found.state == "runs" else None +def _mcp_file(folder: str | os.PathLike) -> Path: + return Path(folder) / ".agents" / "mcp_config.json" + + +def _servers(path: Path) -> dict: + data = json.loads(path.read_text(encoding="utf-8") or "{}") if path.exists() else {} + if not isinstance(data, dict) or not isinstance(data.get("mcpServers", {}), dict): + raise OSError(f"{path} is not an MCP servers file formencoder can read, so it was left alone") + return data + + +def _replace(path: Path, data: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + part = path.with_name(path.name + f".part-{os.getpid()}") + with os.fdopen(os.open(part, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w", encoding="utf-8") as f: + f.write(json.dumps(data, indent=2) + "\n") + os.replace(part, path) + + +def write_tab_entry(folder: str | os.PathLike, entry: dict) -> None: + path = _mcp_file(folder) + data = _servers(path) + data.setdefault("mcpServers", {})[TAB_ENTRY] = entry + _replace(path, data) + + +def remove_tab_entry(folder: str | os.PathLike, token: str | None) -> None: + if not token: + return + path = _mcp_file(folder) + try: + data = _servers(path) + entry = data.get("mcpServers", {}).get(TAB_ENTRY) + if not isinstance(entry, dict) or (entry.get("env") or {}).get(TOKEN_VAR) != token: + return + del data["mcpServers"][TAB_ENTRY] + _replace(path, data) + except (OSError, ValueError): + return + + def status(kind: str, fresh: bool = False) -> dict: found = located(kind, fresh) return agent_lookup.answer(found, install(kind), OTHERWISE) | {"signedIn": None, "install": install(kind), "title": PROGRAMS[kind]["title"], "program": PROGRAMS[kind]["bin"]} diff --git a/backend/tests/test_dock_engine.py b/backend/tests/test_dock_engine.py index 91e35cf..d671f35 100644 --- a/backend/tests/test_dock_engine.py +++ b/backend/tests/test_dock_engine.py @@ -16,7 +16,7 @@ def stand_ins(tmp_path, monkeypatch): folder = tmp_path / "bin" folder.mkdir() - for name in ("claude", "codex", "cursor-agent"): + for name in ("claude", "codex", "cursor-agent", "agy"): script = folder / name script.write_text(f'#!/bin/sh\nif [ "$1" = "--version" ]; then echo "{name} 9.9.9"; exit 0; fi\n' 'echo "stand-in args=$*"\necho "token-present=${FORMENCODER_AGENT_TOKEN:+yes}"\nread line\n') @@ -136,7 +136,7 @@ def test_a_program_outside_the_engine_path_is_found_in_a_known_folder_and_throug @POSIX_ONLY -@pytest.mark.parametrize("kind,title", [("claude", "Claude Code"), ("codex", "Codex"), ("cursor", "Cursor")]) +@pytest.mark.parametrize("kind,title", [("claude", "Claude Code"), ("codex", "Codex"), ("cursor", "Cursor"), ("antigravity", "Antigravity")]) def test_an_agent_tab_runs_the_program_with_its_own_token_which_dies_with_the_tab(client, stand_ins, kind, title): from app.agent import consent from app.routers.terminal import hub @@ -157,6 +157,57 @@ def test_an_agent_tab_runs_the_program_with_its_own_token_which_dies_with_the_ta assert client.get("/api/terminal/tabs").json()["tabs"] == [] +@POSIX_ONLY +def test_an_antigravity_tab_has_its_entry_in_the_workspace_file_until_it_closes(client, stand_ins): + from app.agent import consent, workspace + from app.routers.terminal import hub + + path = workspace.ensure() / ".agents" / "mcp_config.json" + seed = json.dumps({"mcpServers": {"other": {"command": "/bin/true", "args": []}}, "theme": "kept"}, indent=2) + "\n" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(seed, encoding="utf-8") + row = client.post("/api/terminal/tabs", headers=LOCAL, json={"kind": "antigravity", "cwd": "/tmp"}).json() + term = hub.terms[row["id"]] + assert row["kind"] == "antigravity" and term.cwd == str(workspace.root()) + held = json.loads(path.read_text(encoding="utf-8")) + assert list(held["mcpServers"]) == ["other", "formencoder_tab"] and held["theme"] == "kept" and held["mcpServers"]["other"] == {"command": "/bin/true", "args": []} + entry = held["mcpServers"]["formencoder_tab"] + assert entry["command"] == workspace.mcp_command()[0] and entry["args"] == ["mcp", "--profile", "core"] + assert entry["env"]["FORMENCODER_AGENT_TOKEN"] == term.token and consent.inapp(term.token) + assert path.stat().st_mode & 0o777 == 0o600 + token = term.token + client.delete(f"/api/terminal/sessions/{row['id']}", headers=LOCAL) + assert path.read_text(encoding="utf-8") == seed and not consent.inapp(token) + + +def test_agents_install_adds_formencoder_to_antigravity_and_leaves_a_foreign_entry_alone(tmp_path): + from app.agent import connect + + cfg = tmp_path / ".gemini" / "config" / "mcp_config.json" + older = tmp_path / ".gemini" / "antigravity-cli" / "mcp_config.json" + older.parent.mkdir(parents=True) + older.write_text("{}", encoding="utf-8") + said: list = [] + connect.install_antigravity(tmp_path, True, said) + assert not cfg.exists() and "an older file was seen" in said[1] + connect.install_antigravity(tmp_path, False, said) + entry = {"command": connect.launch(), "args": ["mcp", "--profile", "core"]} + assert json.loads(cfg.read_text(encoding="utf-8")) == {"mcpServers": {"formencoder": entry}} and older.read_text(encoding="utf-8") == "{}" + again: list = [] + connect.install_antigravity(tmp_path, False, again) + assert again == ["Antigravity:", f" MCP server formencoder already in {cfg}"] and sorted(p.name for p in cfg.parent.iterdir()) == ["mcp_config.json"] + foreign = json.dumps({"mcpServers": {"formencoder": {"command": "/somewhere/else", "args": ["x"]}, "kept": {"command": "k"}}, "top": 1}) + cfg.write_text(foreign, encoding="utf-8") + left: list = [] + connect.install_antigravity(tmp_path, False, left) + assert cfg.read_text(encoding="utf-8") == foreign and "did not write; left alone" in left[1] + cfg.write_text("[1]", encoding="utf-8") + unread: list = [] + connect.install_antigravity(tmp_path, False, unread) + assert cfg.read_text(encoding="utf-8") == "[1]" and "is not an MCP servers file" in unread[1] + assert list(connect.CLIENTS) == ["claude", "codex", "cursor", "antigravity"] and connect.install(["vim"], True) == ["unknown client vim (claude, codex, cursor or antigravity)"] + + @POSIX_ONLY def test_a_prompt_and_a_resume_id_reach_the_program_as_arguments(client, stand_ins): from app.routers.terminal import hub diff --git a/backend/tests/test_dock_module.py b/backend/tests/test_dock_module.py index e578783..43d6721 100644 --- a/backend/tests/test_dock_module.py +++ b/backend/tests/test_dock_module.py @@ -37,7 +37,9 @@ def test_a_changed_missing_or_extra_dock_file_is_named(tmp_path): def test_the_agent_manifest_describes_the_dock(): dock = json.loads((REPO / "agents" / "manifest.json").read_text(encoding="utf-8"))["dock"] - assert dock == {"present": True, "positions": ["left", "right", "bottom", "floating"], "tabs": ["shell", "claude", "codex", "cursor"]} + assert dock == {"present": True, "positions": ["left", "right", "bottom", "floating"], "tabs": ["shell", "claude", "codex", "cursor", "antigravity"]} + adapter = (FRONTEND / "src" / "dock-adapter.ts").read_text(encoding="utf-8") + assert "builtin: ['shell', 'claude', 'codex', 'cursor', 'antigravity']" in adapter and "DockAdapter" in adapter def test_the_dialog_offers_only_what_the_engine_sends(): diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index e498720..8894e33 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -278,3 +278,14 @@ Refers to `styles/tokens.css` `:root[data-oled]`, `styles/base.css` `.cv-titleba - Removed from `styles/base.css`: the ten rules `.fx-term`, `.fx-term-bar`, `.fx-term-title`, `.fx-agent-btn` (three), `.fx-term-cwd`, `.fx-term-host` (two), `.fx-term-hint`. - Lost with the old panel, for want of a place in the module: the working folder shown in the bar (it is the tab's tooltip now), the hint line under the terminal, and the automation ids `terminal.launch.claude|codex|cursor` and `consent`. `terminal.screen` is kept, on the module's stage. - Checked in headless Chrome at 1440 by 900 against the Vite dev server and the engine from source with stand-in `claude`, `codex` and `cursor-agent`: captures before and after (panel closed: 0 differing pixels; Default workspace: 25,336, all inside the panel's own box), a shell command and its output, a second shell, Claude Code from the button and from the ask line with the text as its argument, Codex from its button, restart of an ended tab, tabs and their output back after a reload, the same terminal element and output after a move to the Agent workspace and back, theme colours changed in place, no key from the terminal, the ask line or a tab reaching the app, and the question's answers through `/mcp`. Cold loads under 4x CPU and a slow network with the panel at the bottom and at the right: one box in every frame after the reveal. Not checked: the real programs, the desktop app, macOS. + +## The shared dock is module 2.2.0, and Antigravity is the fourth agent tab (unreleased, after 0.9.0) + +Refers to `src/dock/` (16 entries, copied from FormVis ddc893ae, never edited here), `src/dock-adapter.ts` `Agy`, `Kind`, `Program`, `KINDS`, `PROGRAMS`, `NOTES`, `record`, `program`, `adapterFor`, `TerminalPanel.dock`, `TerminalPanel.launch`; `src/app/app.ts` (the Agent button's menu); `src/panels/agents.ts` (the set-up row) · kind: feat · logged: unreleased · 2026-11-19 + +- Why: the family offers Google's Antigravity (`agy`) beside Claude Code, Codex and Cursor. Module 2.2.0 takes its agent kinds from the adapter, so the fourth tab is a matter of listing it. +- The adapter is `DockAdapter<'antigravity'>`: `tabs().builtin` lists `antigravity`, `agentStatus()` returns the engine's `antigravity` answer, and when the program is missing or does not start the engine's own sentence is given as the row's `note`. `terminal.open('antigravity', ...)` goes to the same tab route as the other kinds. +- The Agent button's menu gained Start Antigravity; the Agents panel's set-up row gained Set up Antigravity, which posts `client: antigravity` to the same install route. The row wraps as before; nothing else in the panel moved. +- Kept as it was: `keyHeaders`, the automation id on the stage, the hosted placement. The steps the 2.2.0 notes call optional (part names, a status line) were not taken. +- Known differences in the DOM that come with the module, not seen in a window here: every control carries `data-dock-part`, agent tabs carry `is-program`. +- Checked: `tsc --noEmit` with the app's flags clean; `vite build` into a scratch folder completed. Not looked at in a browser in this change: the fourth button, its menu row and the tab were not seen in a window. The engine side was run with a stand-in `agy` (see `backend/HASHOUT_LOG.md`). diff --git a/frontend/src/app/app.ts b/frontend/src/app/app.ts index 540521a..af36b8f 100644 --- a/frontend/src/app/app.ts +++ b/frontend/src/app/app.ts @@ -191,6 +191,7 @@ class App { { label: 'Start Claude Code', run: () => this.terminal.launch('claude') }, { label: 'Start Codex', run: () => this.terminal.launch('codex') }, { label: 'Start Cursor', run: () => this.terminal.launch('cursor') }, + { label: 'Start Antigravity', run: () => this.terminal.launch('antigravity') }, '-', { label: 'Agent Workspace Layout', run: () => this.dock.switchTo('Agent') }, { label: 'Agent Activity and Setup', run: () => this.dock.show('agents') }, diff --git a/frontend/src/dock-adapter.ts b/frontend/src/dock-adapter.ts index d55bfe2..aa680b6 100644 --- a/frontend/src/dock-adapter.ts +++ b/frontend/src/dock-adapter.ts @@ -6,9 +6,10 @@ import type { Panel } from './ui/dock'; import './dock/dock.css'; import './styles/dock-tokens.css'; -type Kind = Exclude; +type Agy = 'antigravity'; +type Kind = Exclude | Agy; interface Row { id: string; title: string; cwd?: string; kind?: string; alive?: boolean; exited?: boolean } -interface Program { installed: boolean; version: string | null; signedIn: boolean | null; install: string } +interface Program { installed: boolean; version: string | null; signedIn: boolean | null; install: string; finding?: string; said?: string } interface Refusal { code?: string; message?: string } export interface PanelHost { @@ -17,9 +18,9 @@ export interface PanelHost { settings(): void; } -const KINDS: PtyKind[] = ['shell', 'claude', 'codex', 'cursor', 'agent']; -const PROGRAMS: DockProgram[] = ['claude', 'codex', 'cursor']; -const NOTES = ['Changes to the queue can be undone.', 'Claude Code, Codex and Cursor tabs you start in the Terminal panel do not ask.']; +const KINDS: (PtyKind | Agy)[] = ['shell', 'claude', 'codex', 'cursor', 'antigravity', 'agent']; +const PROGRAMS: (DockProgram | Agy)[] = ['claude', 'codex', 'cursor', 'antigravity']; +const NOTES = ['Changes to the queue can be undone.', 'Claude Code, Codex, Cursor and Antigravity tabs you start in the Terminal panel do not ask.']; function detail(err: unknown): Refusal | string | null { if (!(err instanceof RpcFailure)) return null; @@ -44,8 +45,8 @@ function errorKind(err: unknown): DockErrorKind | null { return null; } -function record(row: Row): DockTerminal { - const kind = KINDS.includes(row.kind as PtyKind) ? row.kind as PtyKind : 'shell'; +function record(row: Row): DockTerminal { + const kind = KINDS.includes(row.kind as PtyKind | Agy) ? row.kind as PtyKind | Agy : 'shell'; const alive = row.alive ?? row.exited !== true; return row.cwd ? { id: row.id, title: row.title, alive, kind, tip: row.cwd } : { id: row.id, title: row.title, alive, kind }; } @@ -105,8 +106,11 @@ function channel(id: string): DockChannel { }; } -function program(value: Program | undefined): DockProgramStatus | undefined { - return value ? { installed: value.installed, version: value.version, install: value.install, signedIn: value.signedIn } : undefined; +function program(value: Program | undefined, own: boolean): DockProgramStatus | undefined { + if (!value) return undefined; + const status: DockProgramStatus = { installed: value.installed, version: value.version, install: value.install, signedIn: value.signedIn }; + if (own && value.finding !== 'runs' && typeof value.said === 'string') status.note = value.said; + return status; } function question(ev: ServerEvent): ConsentRequest { @@ -125,7 +129,7 @@ function question(ev: ServerEvent): ConsentRequest { return request; } -function adapterFor(ctx: Ctx, host: PanelHost): DockAdapter { +function adapterFor(ctx: Ctx, host: PanelHost): DockAdapter { return { words: { app: 'formencoder', @@ -144,7 +148,7 @@ function adapterFor(ctx: Ctx, host: PanelHost): DockAdapter { placement: { mode: 'hosted', request: (open) => { if (open) host.show(); else host.close(); } }, isDockChord: () => false, chordLabel: () => '', - tabs: () => ({ builtin: ['shell', 'claude', 'codex', 'cursor'] }), + tabs: () => ({ builtin: ['shell', 'claude', 'codex', 'cursor', 'antigravity'] }), classes: { iconButton: 'cv-icon-btn', button: 'cv-btn', primaryButton: 'cv-btn-primary', input: 'cv-input', select: 'fx-select', note: 'cv-note' }, t: (_key, english) => english, onTheme: (handler) => { document.addEventListener('nm:ui-settings-changed', handler); }, @@ -176,11 +180,11 @@ function adapterFor(ctx: Ctx, host: PanelHost): DockAdapter { channel, scrollback: 8000, }, - agentStatus: async (): Promise => { - const status = await api<{ agents: Partial> }>('/api/terminal/agents'); - const out: DockAgentStatus = {}; + agentStatus: async (): Promise | null> => { + const status = await api<{ agents: Partial> }>('/api/terminal/agents'); + const out: DockAgentStatus = {}; for (const kind of PROGRAMS) { - const found = program(status.agents[kind]); + const found = program(status.agents[kind], kind === 'antigravity'); if (found) out[kind] = found; } return out; @@ -211,7 +215,7 @@ export class TerminalPanel implements Panel { readonly id = 'terminal'; readonly title = 'Terminal'; readonly el: HTMLElement; - readonly dock: Dock; + readonly dock: Dock; constructor(ctx: Ctx, private readonly host: PanelHost) { this.el = document.createElement('div'); @@ -231,7 +235,7 @@ export class TerminalPanel implements Panel { this.dock.hidden(); } - launch(kind: 'shell' | DockProgram): void { + launch(kind: 'shell' | DockProgram | Agy): void { this.host.show(); void this.dock.show(kind); } diff --git a/frontend/src/panels/agents.ts b/frontend/src/panels/agents.ts index c0e3ec3..f3a7618 100644 --- a/frontend/src/panels/agents.ts +++ b/frontend/src/panels/agents.ts @@ -31,11 +31,12 @@ export class AgentsPanel implements Panel { this.el = el(`
${icon('agent', 14)}Drive formencoder with an agent
-

Start Claude Code, Codex or Cursor in the Terminal panel: they open in formencoder's agent workspace and already know the queue, presets, export settings and the form family. From any other folder, set your account up once:

+

Start Claude Code, Codex, Cursor or Antigravity in the Terminal panel: they open in formencoder's agent workspace and already know the queue, presets, export settings and the form family. From any other folder, set your account up once:

+
MCP (stdio)
MCP (HTTP)${location.origin}/mcp
diff --git a/setup/agents.py b/setup/agents.py index 517d56b..f2ff99e 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -27,7 +27,7 @@ MIRROR = ROOT / ".agents" / "skills" / "formencoder-harness" SKILLS = ROOT / ".claude" / "skills" MANIFEST = ROOT / "agents" / "manifest.json" -DOCK = {"present": True, "positions": ["left", "right", "bottom", "floating"], "tabs": ["shell", "claude", "codex", "cursor"]} +DOCK = {"present": True, "positions": ["left", "right", "bottom", "floating"], "tabs": ["shell", "claude", "codex", "cursor", "antigravity"]} DOCK_FOLDER = ROOT / "frontend" / "src" / "dock" DOCK_IMPORT = re.compile(r"""(?:from|import)\s*\(?\s*['"]([^'"]+)['"]""") LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" From 9b8d25d713ef6ec1bd263b920344f55afe1ae2dd Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:08 -0500 Subject: [PATCH 27/30] fix(engine): the engine starts when it has no output streams backend/formencoder_engine.py replaces a missing stdin, stdout or stderr with the null device before anything else is imported, so an engine built without a console no longer stops at its first print. Seen on Linux: started with its output streams closed (>&- 2>&-) the engine did not answer its health route before this change and answered after it; started normally it still prints its address. Not run on Windows and not with a frozen engine. --- backend/HASHOUT_LOG.md | 9 +++++++++ backend/formencoder_engine.py | 12 ++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index bb092c0..d08fd02 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -341,3 +341,12 @@ Refers to `routers/terminal.py` `TABS`, `_tab_entry`, `Term._start`, `Term._ende - Tests, written after that: `test_dock_engine.py` (the Antigravity case of the tab test, the entry in the file, the install cases), `test_dock_module.py` (the manifest lists five tabs). `agents/manifest.json` was rewritten by `./formencoder agents sync`. - Not run: a real `agy` (whether it reads `.agents/mcp_config.json` in the workspace, wants the workspace trusted first, or passes `env` to the bridge), Windows, macOS. +## The engine starts when it has no output streams (unreleased, after 0.9.0) + +Refers to `backend/formencoder_engine.py` (the first lines) · kind: fix · logged: unreleased · 2026-11-19 + +- Why: an engine built for Windows without a console is started with `sys.stdout` and `sys.stderr` set to `None`, and the first `print` ends it. A tester saw this in another app of the family; this entry script printed its address the same way. +- Before any other import, a stream that is `None` is replaced with one opened on the null device (`stdin` for reading, `stdout` and `stderr` for writing). Streams that exist are not touched. +- Checked on Linux: started with `>&- 2>&-` on port 4743 the engine gave no answer on its health route before this change and answered `{"status":"ok",...}` after it; started normally it still printed `Uvicorn running on http://127.0.0.1:4741`. +- Not run: Windows, a frozen engine. + diff --git a/backend/formencoder_engine.py b/backend/formencoder_engine.py index 6d2fc35..5aa8841 100644 --- a/backend/formencoder_engine.py +++ b/backend/formencoder_engine.py @@ -1,7 +1,15 @@ -import json import os -import socket import sys + +if sys.stdin is None: + sys.stdin = open(os.devnull, encoding="utf-8") +if sys.stdout is None: + sys.stdout = open(os.devnull, "w", encoding="utf-8") +if sys.stderr is None: + sys.stderr = open(os.devnull, "w", encoding="utf-8") + +import json +import socket import threading import time from pathlib import Path From 480c7f75404c6e86499c442c8b07be7677d2e03e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:09 -0500 Subject: [PATCH 28/30] docs(agents): the texts name four agent programs: Claude Code, Codex, Cursor and Antigravity The launcher's help, the agents command's help, the README's command list, the wiki's Home and Agents pages, the agent workspace's CLAUDE.md, the harness and skillset skills and the Agents panel's policy line say four. The generated tools reference says the core profile is for Cursor and Antigravity; it and the .agents mirror were rewritten by ./formencoder agents sync. Left as they are: the README's description of the Agents panel picture (the picture shows three buttons), docs/PARITY.md and its page, the repository's own AGENTS.md (it describes the repository's Codex and Cursor files), CHANGELOG and log history. Run: agents sync --check in step, lint_text 0 findings. --- .agents/skills/formencoder-harness/references/tools.md | 2 +- .../sub-skills/session-and-connection/SUB-SKILL.md | 4 ++-- .../sub-skills/ui-automation/SUB-SKILL.md | 2 +- .claude/skills/formencoder-harness/references/tools.md | 2 +- .../sub-skills/session-and-connection/SUB-SKILL.md | 4 ++-- .../sub-skills/ui-automation/SUB-SKILL.md | 2 +- .../sub-skills/agent-substrate/SUB-SKILL.md | 2 +- .docs/wiki/Agents.md | 4 ++-- .docs/wiki/Home.md | 2 +- README.md | 2 +- backend/app/agent/templates/CLAUDE.md | 2 +- formencoder | 2 +- frontend/HASHOUT_LOG.md | 1 + frontend/src/panels/agents.ts | 2 +- setup/agents.py | 9 +++++---- 15 files changed, 22 insertions(+), 20 deletions(-) diff --git a/.agents/skills/formencoder-harness/references/tools.md b/.agents/skills/formencoder-harness/references/tools.md index fc0c49a..3106f21 100644 --- a/.agents/skills/formencoder-harness/references/tools.md +++ b/.agents/skills/formencoder-harness/references/tools.md @@ -2,7 +2,7 @@ Generated from the formencoder engine by `./formencoder agents sync`; do not edit by hand. -The `formencoder` MCP server has 29 curated tools, listed here, plus one tool per engine command named from its id (`queue.addSource` is `queue_add_source`; commands.md gives every name). `./formencoder mcp` serves them over stdio (it starts the engine when it is not running); the engine also serves them over Streamable HTTP at `http://127.0.0.1:8270/mcp`. A profile chooses what a client lists: `--profile full` (curated plus every command tool; Claude Code and Codex), `--profile core` (the curated tools only; Cursor) or `--profile core,queue,preset` (curated plus those namespaces); over HTTP pass `?profile=`. Every tool can be called by name whatever the profile. Resources: `formencoder://status`, `queue`, `presets`, `formats`, `encoders`, `commands`, `log/encoding`, `log/error`, `guide/[topic]`, and the templates `output/[id]`, `preset/[id]`, `format/[id]`, `command/[id]`. Prompts: `workflow`, `youtube_version`, `broadcast_master`, `proxies`, `review_copy`. The shell equivalents are in the last section. +The `formencoder` MCP server has 29 curated tools, listed here, plus one tool per engine command named from its id (`queue.addSource` is `queue_add_source`; commands.md gives every name). `./formencoder mcp` serves them over stdio (it starts the engine when it is not running); the engine also serves them over Streamable HTTP at `http://127.0.0.1:8270/mcp`. A profile chooses what a client lists: `--profile full` (curated plus every command tool; Claude Code and Codex), `--profile core` (the curated tools only; Cursor and Antigravity) or `--profile core,queue,preset` (curated plus those namespaces); over HTTP pass `?profile=`. Every tool can be called by name whatever the profile. Resources: `formencoder://status`, `queue`, `presets`, `formats`, `encoders`, `commands`, `log/encoding`, `log/error`, `guide/[topic]`, and the templates `output/[id]`, `preset/[id]`, `format/[id]`, `command/[id]`. Prompts: `workflow`, `youtube_version`, `broadcast_master`, `proxies`, `review_copy`. The shell equivalents are in the last section. ## Contents diff --git a/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md index abbf396..fae9dd6 100644 --- a/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.agents/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -15,9 +15,9 @@ description: How an agent reaches formencoder. Use when the formencoder MCP serv | Started from | Trust | Configuration | | --- | --- | --- | -| formencoder's Terminal panel, a Claude Code, Codex or Cursor tab (its buttons or the ask line; the MCP server is named `formencoder_tab` there) | trusted while the tab is open: the program carries the tab's token, nothing asks; a program typed into a plain shell tab asks like any other | the agent workspace: `CLAUDE.md`, `AGENTS.md`, `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and this skill | +| formencoder's Terminal panel, a Claude Code, Codex, Cursor or Antigravity tab (its buttons or the ask line; the MCP server is named `formencoder_tab` there) | trusted while the tab is open: the program carries the tab's token, nothing asks; a program typed into a plain shell tab asks like any other | the agent workspace: `CLAUDE.md`, `AGENTS.md`, `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and this skill | | The formencoder repository | asks once per client in the window | `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` at the repository root | -| Any other folder | asks once per client in the window | `./formencoder agents install` (or the Agents panel) adds the MCP server and this skill to the user's Claude Code, Codex and Cursor setup | +| Any other folder | asks once per client in the window | `./formencoder agents install` (or the Agents panel) adds the MCP server and this skill to the user's Claude Code, Codex and Cursor setup, and the MCP server to Antigravity's | ## Permission diff --git a/.agents/skills/formencoder-harness/sub-skills/ui-automation/SUB-SKILL.md b/.agents/skills/formencoder-harness/sub-skills/ui-automation/SUB-SKILL.md index e492835..2723c44 100644 --- a/.agents/skills/formencoder-harness/sub-skills/ui-automation/SUB-SKILL.md +++ b/.agents/skills/formencoder-harness/sub-skills/ui-automation/SUB-SKILL.md @@ -34,7 +34,7 @@ These are queries: they change what the window shows, not the queue, so they nev - **Family**: the running form family apps and their sources. - **Log**: the Encoding and Error logs. - **Info**: the selected source or output's details. -- **Terminal**: the embedded terminal where Claude Code, Codex and Cursor run as trusted agents. +- **Terminal**: the embedded terminal where Claude Code, Codex, Cursor and Antigravity run as trusted agents. - **Agents**: which outside agents are allowed, the MCP address, and installing the clients. ## Extensions diff --git a/.claude/skills/formencoder-harness/references/tools.md b/.claude/skills/formencoder-harness/references/tools.md index fc0c49a..3106f21 100644 --- a/.claude/skills/formencoder-harness/references/tools.md +++ b/.claude/skills/formencoder-harness/references/tools.md @@ -2,7 +2,7 @@ Generated from the formencoder engine by `./formencoder agents sync`; do not edit by hand. -The `formencoder` MCP server has 29 curated tools, listed here, plus one tool per engine command named from its id (`queue.addSource` is `queue_add_source`; commands.md gives every name). `./formencoder mcp` serves them over stdio (it starts the engine when it is not running); the engine also serves them over Streamable HTTP at `http://127.0.0.1:8270/mcp`. A profile chooses what a client lists: `--profile full` (curated plus every command tool; Claude Code and Codex), `--profile core` (the curated tools only; Cursor) or `--profile core,queue,preset` (curated plus those namespaces); over HTTP pass `?profile=`. Every tool can be called by name whatever the profile. Resources: `formencoder://status`, `queue`, `presets`, `formats`, `encoders`, `commands`, `log/encoding`, `log/error`, `guide/[topic]`, and the templates `output/[id]`, `preset/[id]`, `format/[id]`, `command/[id]`. Prompts: `workflow`, `youtube_version`, `broadcast_master`, `proxies`, `review_copy`. The shell equivalents are in the last section. +The `formencoder` MCP server has 29 curated tools, listed here, plus one tool per engine command named from its id (`queue.addSource` is `queue_add_source`; commands.md gives every name). `./formencoder mcp` serves them over stdio (it starts the engine when it is not running); the engine also serves them over Streamable HTTP at `http://127.0.0.1:8270/mcp`. A profile chooses what a client lists: `--profile full` (curated plus every command tool; Claude Code and Codex), `--profile core` (the curated tools only; Cursor and Antigravity) or `--profile core,queue,preset` (curated plus those namespaces); over HTTP pass `?profile=`. Every tool can be called by name whatever the profile. Resources: `formencoder://status`, `queue`, `presets`, `formats`, `encoders`, `commands`, `log/encoding`, `log/error`, `guide/[topic]`, and the templates `output/[id]`, `preset/[id]`, `format/[id]`, `command/[id]`. Prompts: `workflow`, `youtube_version`, `broadcast_master`, `proxies`, `review_copy`. The shell equivalents are in the last section. ## Contents diff --git a/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md index abbf396..fae9dd6 100644 --- a/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.claude/skills/formencoder-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -15,9 +15,9 @@ description: How an agent reaches formencoder. Use when the formencoder MCP serv | Started from | Trust | Configuration | | --- | --- | --- | -| formencoder's Terminal panel, a Claude Code, Codex or Cursor tab (its buttons or the ask line; the MCP server is named `formencoder_tab` there) | trusted while the tab is open: the program carries the tab's token, nothing asks; a program typed into a plain shell tab asks like any other | the agent workspace: `CLAUDE.md`, `AGENTS.md`, `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and this skill | +| formencoder's Terminal panel, a Claude Code, Codex, Cursor or Antigravity tab (its buttons or the ask line; the MCP server is named `formencoder_tab` there) | trusted while the tab is open: the program carries the tab's token, nothing asks; a program typed into a plain shell tab asks like any other | the agent workspace: `CLAUDE.md`, `AGENTS.md`, `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` and this skill | | The formencoder repository | asks once per client in the window | `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` at the repository root | -| Any other folder | asks once per client in the window | `./formencoder agents install` (or the Agents panel) adds the MCP server and this skill to the user's Claude Code, Codex and Cursor setup | +| Any other folder | asks once per client in the window | `./formencoder agents install` (or the Agents panel) adds the MCP server and this skill to the user's Claude Code, Codex and Cursor setup, and the MCP server to Antigravity's | ## Permission diff --git a/.claude/skills/formencoder-harness/sub-skills/ui-automation/SUB-SKILL.md b/.claude/skills/formencoder-harness/sub-skills/ui-automation/SUB-SKILL.md index e492835..2723c44 100644 --- a/.claude/skills/formencoder-harness/sub-skills/ui-automation/SUB-SKILL.md +++ b/.claude/skills/formencoder-harness/sub-skills/ui-automation/SUB-SKILL.md @@ -34,7 +34,7 @@ These are queries: they change what the window shows, not the queue, so they nev - **Family**: the running form family apps and their sources. - **Log**: the Encoding and Error logs. - **Info**: the selected source or output's details. -- **Terminal**: the embedded terminal where Claude Code, Codex and Cursor run as trusted agents. +- **Terminal**: the embedded terminal where Claude Code, Codex, Cursor and Antigravity run as trusted agents. - **Agents**: which outside agents are allowed, the MCP address, and installing the clients. ## Extensions diff --git a/.claude/skills/formencoder-skillset/sub-skills/agent-substrate/SUB-SKILL.md b/.claude/skills/formencoder-skillset/sub-skills/agent-substrate/SUB-SKILL.md index 65536a6..10973c8 100644 --- a/.claude/skills/formencoder-skillset/sub-skills/agent-substrate/SUB-SKILL.md +++ b/.claude/skills/formencoder-skillset/sub-skills/agent-substrate/SUB-SKILL.md @@ -18,7 +18,7 @@ description: Changing how agents drive formencoder. Use for the MCP tools and gu | `backend/app/agent/approvals.py` | which actions need the person's approval (`reasons`), the guard that waits or answers `pendingApproval`, `decide`, full faith (`approvals.json`), the agent activity record; decisions and full faith only over the live socket (`agents.decide`, `agents.fullFaith` in `engine/rpc.py`) | | `backend/app/routers/terminal.py` | the terminal hub: sessions with ids, history, readers and restart; REST under `/api/terminal/sessions`; the websocket attaching with `?session=`; the shell started with the workspace's bash rc file or zsh ZDOTDIR so the `formencoder` shim stays on PATH | | `backend/app/agent/workspace.py`, `templates/` | the agent workspace (`CLAUDE.md`, `AGENTS.md`, MCP configs, skills) the Terminal panel opens | -| `backend/app/agent/connect.py` | `./formencoder agents install`: user-level MCP entries and skill copies for Claude Code, Codex and Cursor | +| `backend/app/agent/connect.py` | `./formencoder agents install`: user-level MCP entries for Claude Code, Codex, Cursor and Antigravity, and skill copies for the first three | | `backend/app/agent/cli.py`, `setup/fe.py` | the command line (`encode`, `queue`, `exec`, `batch`, `commands`, `describe`, `presets`, `probe`, `frame`, `wait`) | | `setup/agents.py` | `sync` generates `references/commands.md`, `tools.md`, `presets.md` and `formats.md` from the engine and mirrors the skill to `.agents/skills` | | `.claude/skills/formencoder-harness` | the hand-written skill: `SKILL.md`, sub-skills, `references/concepts.md` | diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index ad7983a..17eb6b2 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -4,9 +4,9 @@ formencoder's engine exposes every command to agents through MCP, the same comma ## Three ways in -- **In formencoder**: the Terminal panel (or the Agent workspace) opens tabs in formencoder's agent workspace. Its Claude Code, Codex and Cursor buttons each start that agent in a tab of its own; it already has formencoder's MCP server (named `formencoder_tab` there) and the `formencoder-harness` skill, and works without permission prompts while its tab is open. A plain shell tab carries no agent access: a program typed there asks like any outside agent. +- **In formencoder**: the Terminal panel (or the Agent workspace) opens tabs in formencoder's agent workspace. Its Claude Code, Codex, Cursor and Antigravity buttons each start that agent in a tab of its own; it already has formencoder's MCP server (named `formencoder_tab` there) and the `formencoder-harness` skill, and works without permission prompts while its tab is open. A plain shell tab carries no agent access: a program typed there asks like any outside agent. - **From the repository**: `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` run `./formencoder mcp`, which starts the engine when it is not running. The first change asks once in the formencoder window: Allow, Allow Always or Don't Allow. -- **From anywhere**: `./formencoder agents install` (or the Agents panel) adds the MCP server and the skill to your Claude Code, Codex and Cursor setup. +- **From anywhere**: `./formencoder agents install` (or the Agents panel) adds the MCP server and the skill to your Claude Code, Codex and Cursor setup, and the MCP server to Antigravity's (`~/.gemini/config/mcp_config.json`). `FORMENCODER_AGENTS=deny` refuses every change from every agent, whatever was allowed before, Terminal agents included; reads still work. Any other value, `allow` included, means the stored choice decides (ask by default). Only the person, in the formencoder window, can allow an outside agent, so an unattended outside agent with no window open is refused its changes; start it from the Terminal panel instead. diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index 453a96e..0c396b0 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -2,7 +2,7 @@ The media encoder of the form family, beside formcut (video), formvfx (motion graphics), formwav (audio) and formvis (images). A queue of sources with several outputs each, 93 encoding presets and 5 ingest presets, 40 formats from H.264, HEVC, AV1 and WebM to ProRes, DNxHR, XDCAM MXF, AS-10, AS-11, P2, Blu-ray and DCP, image sequences, GIF and audio, watch folders, card ingest with checksums, proxies, LUTs, HDR to SDR conform, overlays, Fit Tuning, loudness normalisation, captions with speech to text, metadata, Content Credentials, plug-ins and publishing to storage, YouTube, Vimeo and Facebook, on macOS, Windows and Linux. -Every action in formencoder is a command with an id, so people and agents use the same tools: Claude Code, Codex and Cursor drive formencoder from its embedded terminal through MCP, with a skill that teaches them the workflow. +Every action in formencoder is a command with an id, so people and agents use the same tools: Claude Code, Codex, Cursor and Antigravity drive formencoder from its embedded terminal through MCP, with a skill that teaches them the workflow. ## Pages diff --git a/README.md b/README.md index 8b32c94..efefb19 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ The window, the command line and the MCP server call the same 96 commands. ./formencoder encode clip.mov --preset system/youtube-1080p # queue, encode and print results ./formencoder queue # every output and its status ./formencoder probe clip.mov # media information -./formencoder mcp # MCP server on stdio for Claude Code, Codex and Cursor +./formencoder mcp # MCP server on stdio for Claude Code, Codex, Cursor and Antigravity ``` `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json` are already wired in this repo. See [`AGENTS.md`](AGENTS.md). diff --git a/backend/app/agent/templates/CLAUDE.md b/backend/app/agent/templates/CLAUDE.md index 79ddfcb..873231a 100644 --- a/backend/app/agent/templates/CLAUDE.md +++ b/backend/app/agent/templates/CLAUDE.md @@ -4,7 +4,7 @@ You are running inside formencoder {{VERSION}}, the form family's media encoder, ## How to drive formencoder -- Use the `formencoder_tab` MCP server (configured in `.mcp.json` here; it runs `{{MCP}}`). A Claude Code, Codex or Cursor tab started from formencoder's Terminal panel is trusted and nothing asks for permission; a program typed into a plain shell tab asks the person like any outside agent. +- Use the `formencoder_tab` MCP server (configured in `.mcp.json` here; it runs `{{MCP}}`). A Claude Code, Codex, Cursor or Antigravity tab started from formencoder's Terminal panel is trusted and nothing asks for permission; a program typed into a plain shell tab asks the person like any outside agent. - If MCP is unavailable, the same surface is on the command line: `formencoder encode FILE --preset system/youtube-1080p`, `formencoder queue`, `formencoder exec ID '{"json": "params"}'`, `formencoder batch '[...]'`, `formencoder commands FILTER`, `formencoder describe ID`, `formencoder presets QUERY`, `formencoder probe FILE`, `formencoder frame out.png --output '#1' --time 2`, `formencoder wait`. - Read `.claude/skills/formencoder-harness/SKILL.md` before a non-trivial job. It routes to sub-skills for the queue and presets, export settings, effects and loudness, captions and metadata, watch folders and ingest, the form family bridge, and verifying. diff --git a/formencoder b/formencoder index bea9fa0..ec1edf2 100755 --- a/formencoder +++ b/formencoder @@ -36,7 +36,7 @@ usage: ./formencoder [command] [options] extension ID COMMAND [--args JSON] run a command an extension contributes, in the open window mcp formencoder over MCP's stdio transport (starts the engine when needed) - agents install|sync|status set Claude Code, Codex and Cursor up (install), refresh the skill references (sync) + agents install|sync|status set Claude Code, Codex, Cursor and Antigravity up (install), refresh the skill references (sync) counts [--write|--check] lines of code by area (the README's Code size table) clean [--all] remove build output (--all also venv and node_modules) help this text diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 8894e33..90089ad 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -289,3 +289,4 @@ Refers to `src/dock/` (16 entries, copied from FormVis ddc893ae, never edited he - Kept as it was: `keyHeaders`, the automation id on the stage, the hosted placement. The steps the 2.2.0 notes call optional (part names, a status line) were not taken. - Known differences in the DOM that come with the module, not seen in a window here: every control carries `data-dock-part`, agent tabs carry `is-program`. - Checked: `tsc --noEmit` with the app's flags clean; `vite build` into a scratch folder completed. Not looked at in a browser in this change: the fourth button, its menu row and the tab were not seen in a window. The engine side was run with a stand-in `agy` (see `backend/HASHOUT_LOG.md`). +- Words, with the texts that name the supported programs: the Agents panel's policy line in `src/panels/agents.ts` says Claude Code, Codex, Cursor and Antigravity tabs are trusted. The README's picture of the Agents panel still shows three set-up buttons, so its description was left as it is. diff --git a/frontend/src/panels/agents.ts b/frontend/src/panels/agents.ts index f3a7618..bb78443 100644 --- a/frontend/src/panels/agents.ts +++ b/frontend/src/panels/agents.ts @@ -102,7 +102,7 @@ export class AgentsPanel implements Panel { setText(q(this.el, '.fx-agents-ws'), s.workspace.path); for (const b of Array.from(this.el.querySelectorAll('[data-install]'))) setClass(b, 'is-missing', !s.clients[b.dataset.install as string]); const allowed = [...s.consent.always.map((c) => `${c} (always)`), ...s.consent.session.filter((c) => !s.consent.always.includes(c)).map((c) => `${c} (this session)`)]; - setText(q(this.el, '.fx-agents-allowed'), allowed.length ? allowed.join(', ') : `Policy: ${s.consent.policy}. Claude Code, Codex and Cursor tabs started in the Terminal panel are trusted; every other agent asks.`); + setText(q(this.el, '.fx-agents-allowed'), allowed.length ? allowed.join(', ') : `Policy: ${s.consent.policy}. Claude Code, Codex, Cursor and Antigravity tabs started in the Terminal panel are trusted; every other agent asks.`); setClass(q(this.el, '.fx-agents-seal'), 'is-shown', s.consent.sealBroken === true); if (!this.feed.length) this.feed = s.activity.filter((a) => a.source !== 'ui'); this.renderFeed(); diff --git a/setup/agents.py b/setup/agents.py index f2ff99e..3166b32 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -1,11 +1,12 @@ #!/usr/bin/env python3 -"""./formencoder agents: Claude Code, Codex and Cursor driving formencoder. +"""./formencoder agents: Claude Code, Codex, Cursor and Antigravity driving formencoder. sync [--check] regenerate the formencoder-harness skill's generated references from the engine (commands, MCP tools, presets, formats and settings), mirror .claude/skills/formencoder-harness to .agents/skills and write agents/manifest.json (what the app offers agents); --check exits 1 when anything drifted - install [--dry-run] [claude|codex|cursor ...] - set the clients up for this user account: the MCP server and the skill (all three by default) + install [--dry-run] [claude|codex|cursor|antigravity ...] + set the clients up for this user account: the MCP server and the skill (all four by default; + Antigravity gets the MCP server only, in ~/.gemini/config/mcp_config.json) status which clients are on this computer and whether the skill is in step """ @@ -123,7 +124,7 @@ def tools_md() -> str: "(`queue.addSource` is `queue_add_source`; commands.md gives every name). `./formencoder mcp` serves them over stdio (it starts " "the engine when it is not running); the engine also serves them over Streamable HTTP at `http://127.0.0.1:8270/mcp`. A profile " "chooses what a client lists: `--profile full` (curated plus every command tool; Claude Code and Codex), `--profile core` (the " - "curated tools only; Cursor) or `--profile core,queue,preset` (curated plus those namespaces); over HTTP pass `?profile=`. Every " + "curated tools only; Cursor and Antigravity) or `--profile core,queue,preset` (curated plus those namespaces); over HTTP pass `?profile=`. Every " "tool can be called by name whatever the profile. Resources: `formencoder://status`, `queue`, `presets`, `formats`, `encoders`, " "`commands`, `log/encoding`, `log/error`, `guide/[topic]`, and the templates `output/[id]`, `preset/[id]`, `format/[id]`, " "`command/[id]`. Prompts: `workflow`, `youtube_version`, `broadcast_master`, `proxies`, `review_copy`. The shell equivalents " From f8b47ef11c8ca0294980a18383d77f4963e514b8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 21:28:09 -0500 Subject: [PATCH 29/30] chore(release): 0.10.0 Sets 0.10.0 at the version sites of the 0.9.0 release (README, backend, frontend package and lock, version.ts, the native and desktop Cargo files and their lock entries, pyproject, tauri.conf.json, the three demo bundles), adds the CHANGELOG entry, which also covers the four terminal panel commits already on the branch, and lets the function manifest's own generator rewrite form-functions.json. Run: the whole backend suite before the bump, 261 passed, 3 failed (three cases of one test in test_functions.py that failed the same way before this branch and are not touched here), with decoy agent programs first on PATH started 0 times; after the bump the version, boot, agent, dock and function test files, 73 passed and the same 3 failed; the function manifest check and agents sync --check in step; tsc --noEmit clean before the bump. Not run: Windows, macOS, the desktop shell (not compiled here; the native engine was not rebuilt), any real agent program, a browser. --- CHANGELOG.md | 19 +++++++++++++++++++ README.md | 4 ++-- backend/app/__init__.py | 2 +- demo/assets/demo.js | 2 +- demos/broadcast/assets/broadcast.js | 2 +- demos/inspect/assets/inspect.js | 2 +- form-functions.json | 2 +- frontend/package-lock.json | 4 ++-- frontend/package.json | 2 +- frontend/src/version.ts | 2 +- native/Cargo.lock | 14 +++++++------- native/Cargo.toml | 2 +- native/fencoder-py/pyproject.toml | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 16 files changed, 42 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5079ce..66c5499 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## v0.10.0 · 2026-11-19 + +The family's terminal panel, and four agent programs. The Terminal panel is now the one the other Form apps have, Google's Antigravity (`agy`) is offered beside Claude Code, Codex and Cursor, and FormEncoder finds these programs however it was started. + +- The Terminal panel is the family's shared panel. It keeps its place in FormEncoder (any group, floating, per workspace, opened from the Window menu). Inside it are tabs: plain shells, Claude Code, Codex, Cursor and Antigravity each in a tab of its own, and read-only tabs for terminals an outside agent opened. A line at the bottom opens Claude Code with what you type. +- Changed on purpose: a plain shell tab carries no agent access. A program you type into a shell asks like any outside agent; the agent tabs you start from the panel's buttons do not ask. +- The permission question is the panel's dialog in the middle of the window: Deny, Allow once, or Always allow that agent. Escape refuses. A question that is still waiting is shown again after a reload, and it closes by itself within about a second when the agent that asked goes away. +- Antigravity is the fourth agent program. It has its own button and tab in the Terminal panel, a Start Antigravity entry in the Agent button's menu and a Set up Antigravity button in the Agents panel. `./formencoder agents install antigravity` adds FormEncoder to `~/.gemini/config/mcp_config.json`, keeps everything else in that file, and leaves alone an entry of the same name that FormEncoder did not write. Antigravity gets the MCP server only; no skill is copied for it. +- FormEncoder finds the agent programs however it was started. An app opened from the Dock, the Start menu or a desktop launcher used to see only a short list of folders and could report a program as not installed. It now also looks in the usual install folders and reads your shell's own list once. The status says where each program was found, and tells apart a program that is missing from one that was found but does not start, with the program's own error line. `FORMENCODER_CLAUDE_BIN`, `FORMENCODER_CODEX_BIN`, `FORMENCODER_CURSOR_BIN` and `FORMENCODER_ANTIGRAVITY_BIN` name a program's file directly. +- An agent tab is started through your login shell, with the program's own folder first on its PATH, so a program that needs the `node` installed beside it starts. +- The reported version of an agent program is now the version itself (for example `2.1.0`), not the whole line the program prints. +- The engine starts when it has no output streams. An engine built without a console no longer stops at its first line of output. This was seen in a Windows build of another Form app; the fix here was run on Linux only. +- The MCP entry the agent tabs use inside FormEncoder's agent workspace is named `formencoder_tab`, apart from the `formencoder` entry that `agents install` writes for use outside the app. +- `agents/manifest.json` lists the Terminal panel's tabs, and `./formencoder agents sync --check` fails when the shared panel's files or the shared program finder were changed in place. +- FormEncoder's own tests can no longer start a real agent program: the whole run sees stand-ins only. +- The README, the wiki, the command help and the agent skills name four agent programs. +- Not run for this release: Windows, macOS, the desktop app, and the real Claude Code, Codex, Cursor and Antigravity (stand-ins were used). The Antigravity button and tab were not looked at in a browser. +- The version string inside the three browser demo bundles (`demo/assets/demo.js`, `demos/broadcast/assets/broadcast.js`, `demos/inspect/assets/inspect.js`) is bumped to 0.10.0 by hand, without a rebuild. + ## v0.9.0 · 2026-11-19 The family update. Only the FormEncoder window can change things or answer for the person, an agent's permission is asked for in clearer words, encodes write to local files only, and there is a true-black theme. FormEncoder keeps its own Terminal panel in this release. diff --git a/README.md b/README.md index efefb19..0663c0e 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@

- version 0.9.0 + version 0.10.0 Rust TypeScript macOS, Windows, Linux @@ -102,7 +102,7 @@ FormEncoder loads extensions made to the Form Extension Contract (API 1): FormPo ## Under the hood -Version 0.9.0 · Apache-2.0 · Rust encoding engine, Python service, TypeScript interface, Tauri 2 shell +Version 0.10.0 · Apache-2.0 · Rust encoding engine, Python service, TypeScript interface, Tauri 2 shell - **Engine:** seven `fencoder` Rust crates in `native/`, loaded by the Python service as the `fe_core` extension. - **FFmpeg:** a pinned LGPL build, run as a separate program and never linked. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 3e2f46a..61fb31c 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.9.0" +__version__ = "0.10.0" diff --git a/demo/assets/demo.js b/demo/assets/demo.js index 95ead4a..5af73cc 100644 --- a/demo/assets/demo.js +++ b/demo/assets/demo.js @@ -10,7 +10,7 @@

-
`),this.areas=Object.fromEntries(ne.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,r=>{r.preventDefault(),e.setPointerCapture(r.pointerId),n(e,`is-dragging`,!0);let i={x:r.clientX,y:r.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},a=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,i.l+e.clientX-i.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,i.r-(e.clientX-i.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,i.b-(e.clientY-i.y)))),this.applySizes()},o=()=>{n(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,a),e.removeEventListener(`pointerup`,o),this.save()};e.addEventListener(`pointermove`,a),e.addEventListener(`pointerup`,o)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,r=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${r}px`),n(this.el,`no-left`,!e),n(this.el,`no-right`,!t),n(this.el,`no-bottom`,!r);for(let e of te){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ne){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new re(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(T);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??w[e]??w.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(T),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(T,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(T)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(T)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??w[e]??w.Default,e),this.save()}resetWorkspace(){this.applyLayout(w[this.workspace]??w.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(T)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(T,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ne)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new re(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,n(this.el,`is-maximized`,!1),n(e.el,`is-max`,!1)):(this.maximized&&n(this.maximized.el,`is-max`,!1),this.maximized=e,n(this.el,`is-maximized`,!0),n(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&n(t.el,`is-focused`,!1),this.focused=e;let r=this.find(e);r&&n(r.el,`is-focused`,!0),this.onFocus?.(e)}},E={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},ae=`studio`,oe=`#f2545b`,se=`formencoder_ui_settings`,ce=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function le(){try{let e=localStorage.getItem(se);if(e){let t=JSON.parse(e);return{theme:t.theme&&E[t.theme]?t.theme:ae,accentColor:t.accentColor||`#f2545b`,intensity:ce(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:ae,accentColor:oe,intensity:1}}function ue(e){try{let t=localStorage.getItem(se),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(se,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function de(e=le()){let t=document.documentElement,n=E[e.theme]||E.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(ce(e.intensity))),t.style.setProperty(`--accent-tint`,pe(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,pe(e.accentColor,.1))}function fe(e){let t={...le(),theme:e};ue(t),de(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function pe(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var me=`0.9.0`;function he(e,t){let n=(e,t)=>e>>16-t*8&255,r=Array.from(e.keys()),i=[{lo:0,hi:r.length}],a=r,o=t=>{let r=0,i=-1;for(let o=0;o<3;o++){let s=255,c=0;for(let r=t.lo;rc&&(c=t)}c-s>i&&(i=c-s,r=o)}return{c:r,span:i}};for(;i.length{if(e.hi-e.lo<2)return;let i=o(e),a=i.span*Math.sqrt(e.hi-e.lo);a>r&&(r=a,t=n,s=i.c)}),t<0)break;let c=i[t],l=a.slice(c.lo,c.hi).sort((t,r)=>n(e[t],s)-n(e[r],s));for(let e=0;e>1);i.splice(t,1,{lo:c.lo,hi:u},{lo:u,hi:c.hi})}let s=new Uint8Array(768);return i.forEach((t,r)=>{let i=0,o=0,c=0,l=Math.max(1,t.hi-t.lo);for(let r=t.lo;r{for(a|=e<=8;)t.push(a&255),a>>>=8,o-=8};s(256);let c=e[0];for(let t=1;t1<0&&t.push(a&255),Uint8Array.from(t)}var ve=class{width;height;parts=[];constructor(e,t){this.width=e,this.height=t;let n=new Uint8Array(13),r=new DataView(n.buffer);n.set(new TextEncoder().encode(`GIF89a`),0),r.setUint16(6,e,!0),r.setUint16(8,t,!0),n[10]=0,n[11]=0,n[12]=0,this.parts.push(n),this.parts.push(Uint8Array.from([33,255,11,...new TextEncoder().encode(`NETSCAPE2.0`),3,1,0,0,0]))}addFrame(e,t){let n=this.width*this.height,r=Math.max(1,Math.floor(n/12e3)),i=[];for(let t=0;t{let r=e>>3<<10|t>>3<<5|n>>3,i=o.get(r);if(i!==void 0)return i;let s=e>>3<<3|4,c=t>>3<<3|4,l=n>>3<<3|4,u=0,d=1/0;for(let e=0;e<256;e++){let t=a[e*3]-s,n=a[e*3+1]-c,r=a[e*3+2]-l,i=t*t*2+n*n*4+r*r*3;i>8&255,0,0]));let l=new Uint8Array(10),u=new DataView(l.buffer);l[0]=44,u.setUint16(5,this.width,!0),u.setUint16(7,this.height,!0),l[9]=135,this.parts.push(l),this.parts.push(a),this.parts.push(Uint8Array.from([8]));let d=_e(c);for(let e=0;ee>0?-.691+10*Math.log10(e):-1/0;function Ce(e,t){if(!e.length)return-1/0;let n=(e.length-1)*t,r=Math.floor(n),i=Math.min(e.length-1,r+1);return e[r]+(e[i]-e[r])*(n-r)}function we(e,t){let n=[];for(let r=0;r+t<=e.length;r++){let i=0;for(let n=0;n=e.length)continue;let o=i-n,s=Math.abs(o)<1e-9?1:Math.sin(Math.PI*o)/(Math.PI*o),c=.5+.5*Math.cos(Math.PI*o/9);r+=e[a]*s*c}return r}function Ee(e){let t=0;for(let n of e)for(let e=0;et&&(t=r)}let n=t,r=t*.55;for(let t of e)for(let e=0;en&&(n=i)}return{sample:t,truePeak:n}}function De(e,t){let n=e=>e>0?20*Math.log10(e):-1/0,r=e[0]?.length??0,i=Ee(e),a=Math.round(t*.1),o=Math.floor(r/a),s=Se(e.length),c=new Float64Array(o);e.forEach((e,n)=>{if(!s[n])return;let r=xe(e,t);for(let e=0;eD(e)>-70),d=-1/0;if(u.length){let e=D(u.reduce((e,t)=>e+t,0)/u.length)-10,t=l.filter(t=>D(t)>-70&&D(t)>e);t.length&&(d=D(t.reduce((e,t)=>e+t,0)/t.length))}let f=we(c,30).filter(e=>D(e)>-70),p=0,m=-1/0;if(f.length){let e=D(f.reduce((e,t)=>e+t,0)/f.length)-20,t=f.map(D).filter(t=>t>e).sort((e,t)=>e-t);t.length&&(p=Ce(t,.95)-Ce(t,.1),m=t[t.length-1])}return{integrated:d,lra:p,samplePeak:n(i.sample),truePeak:n(i.truePeak),shortTermMax:m}}function Oe(e){return Number.isFinite(e)?e.toFixed(1):`-inf`}function O(e){return`${Oe(e.integrated)} LUFS, LRA ${e.lra.toFixed(1)} LU, peak ${Oe(e.truePeak)} dBTP`}function ke(e,t,n=-1){if(!Number.isFinite(e.integrated))return{gainDb:0,limited:!1};let r=t-e.integrated,i=n-e.truePeak;return Number.isFinite(i)&&r>i?{gainDb:i,limited:!0}:{gainDb:r,limited:!1}}function k(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Ae(e){let t=[],n=e;for(;n>0;)t.unshift(n&255),n=Math.floor(n/256);return Uint8Array.from(t)}function je(e){let t=1;for(;t<8&&e>=2**(7*t)-1;)t++;let n=new Uint8Array(t),r=e;for(let e=t-1;e>=0;e--)n[e]=r%256,r=Math.floor(r/256);return n[0]|=1<<8-t,n}function A(e,t){return k([Ae(e),je(t.length),t])}function j(e,t){let n=[],r=t;do n.unshift(r%256),r=Math.floor(r/256);while(r>0);return A(e,Uint8Array.from(n))}function Me(e,t){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!1),A(e,n)}function M(e,t){return A(e,new TextEncoder().encode(t))}function Ne(e){let t=new Uint8Array(19),n=new DataView(t.buffer);return t.set(new TextEncoder().encode(`OpusHead`),0),t[8]=1,t[9]=e.channels,n.setUint16(10,e.preSkip,!0),n.setUint32(12,e.sampleRate,!0),n.setInt16(16,0,!0),t[18]=0,t}function Pe(e){return Ne(e)}function Fe(e,t,n,r){let i=A(440786851,k([j(17030,1),j(17143,1),j(17138,4),j(17139,8),M(17026,`webm`),j(17031,4),j(17029,2)])),a=A(357149030,k([j(2807729,1e6),Me(17545,r),M(19840,`formencoder demo`),M(22337,`formencoder demo`)])),o=[];e&&o.push(A(174,k([j(215,1),j(29637,1),j(131,1),j(156,0),M(134,e.codec),A(224,k([j(176,e.width),j(186,e.height)]))]))),t&&o.push(A(174,k([j(215,2),j(29637,2),j(131,2),j(156,0),M(134,`A_OPUS`),j(22186,Math.round(t.preSkip/48e3*1e9)),j(22203,8e7),A(25506,Ne(t)),A(225,k([Me(181,t.sampleRate),j(159,t.channels)]))])));let s=A(374648427,k(o)),c=[...n].sort((e,t)=>e.timeMs-t.timeMs||e.track-t.track),l=[],u=[],d=a.length+s.length,f=[],p=0,m=!1,h=()=>{if(!m)return;let e=A(524531317,k([j(231,Math.round(p)),...f]));l.push(e),d+=e.length,f=[],m=!1};for(let e of c){let t=Math.round(e.timeMs),n=t-Math.round(p);(!m||e.track===1&&e.key&&n>0||n>3e4)&&(h(),p=t,m=!0,e.track===1&&e.key&&u.push({timeMs:t,offset:d}));let r=new Uint8Array(4);r[0]=128|e.track,new DataView(r.buffer).setInt16(1,t-Math.round(p),!1),r[3]=e.key?128:0,f.push(A(163,k([r,e.data])))}h();let g=u.length?A(475249515,k(u.map(e=>A(187,k([j(179,e.timeMs),A(183,k([j(247,1),j(241,e.offset)]))]))))):new Uint8Array,_=A(408125543,k([a,s,...l,g]));return new Blob([i,_],{type:`video/webm`})}var Ie=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t<<24;for(let e=0;e<8;e++)n=n&2147483648?n<<1^79764919:n<<1;e[t]=n>>>0}return e})();function Le(e){let t=0;for(let n=0;n>>24^e[n])&255])>>>0;return t>>>0}function Re(e,t,n,r,i,a=!1){let o=[];for(let t of e){let e=t.length;for(;e>=255;)o.push(255),e-=255;o.push(e)}let s=e.reduce((e,t)=>e+t.length,0),c=new Uint8Array(27+o.length+s),l=new DataView(c.buffer);c.set(new TextEncoder().encode(`OggS`),0),c[4]=0,c[5]=t|+!!a,l.setBigUint64(6,BigInt(n),!0),l.setUint32(14,r,!0),l.setUint32(18,i,!0),c[26]=o.length,c.set(o,27);let u=27+o.length;for(let t of e)c.set(t,u),u+=t.length;return l.setUint32(22,Le(c),!0),c}function ze(e,t,n,r){let i=1178947139,a=[],o=Pe({sampleRate:r,channels:t,preSkip:n}),s=new TextEncoder().encode(`formencoder demo`),c=new Uint8Array(12+s.length+4),l=new DataView(c.buffer);c.set(new TextEncoder().encode(`OpusTags`),0),l.setUint32(8,s.length,!0),c.set(s,12),l.setUint32(12+s.length,0,!0),a.push(Re([o],2,0,i,0)),a.push(Re([c],0,0,i,1));let u=2,d=n,f=[],p=e.length;return e.forEach((e,t)=>{f.push(e),d+=e.samples;let n=t===p-1;(f.length>=40||n)&&(a.push(Re(f.map(e=>e.data),n?4:0,d,i,u++)),f=[])}),new Blob(a,{type:`audio/ogg`})}function Be(e,t){let n=t===16?32767:8388607,r=Math.max(-1,Math.min(1,e));return Math.round(r<0?r*(n+1):r*n)}function Ve(e,t,n){let r=e[0]?.length??0,i=e.length,a=n/8,o=r*i*a,s=new ArrayBuffer(44+o),c=new DataView(s),l=(e,t)=>{for(let n=0;n>8&255),c.setUint8(u+2,i>>16&255)),u+=a}return new Blob([s],{type:`audio/wav`})}function He(e,t,n){let r=e[0]?.length??0,i=e.length,a=n/8,o=r*i*a,s=new ArrayBuffer(54+o),c=new DataView(s),l=(e,t)=>{for(let n=0;n>16&255),c.setUint8(d+1,i>>8&255),c.setUint8(d+2,i&255)),d+=a}return new Blob([s],{type:`audio/aiff`})}var Ue=[[`match-source-high`,`Match Source - High bitrate`,`Web Video`,`h264`,null,null,null,20],[`match-source-medium`,`Match Source - Medium bitrate`,`Web Video`,`h264`,null,null,null,10],[`match-source-adaptive-high`,`Match Source - Adaptive High Bitrate`,`Web Video`,`h264`,null,null,null,null],[`hevc-match-source-high`,`HEVC Match Source - High bitrate`,`Web Video`,`hevc`,null,null,null,14],[`hevc-4k-hdr10`,`HEVC 4K HDR10 (Rec. 2100 PQ)`,`Web Video`,`hevc`,3840,2160,null,40],[`av1-match-source`,`AV1 Match Source`,`Web Video`,`av1`,null,null,null,null],[`webm-vp9-1080p`,`WebM VP9 1080p`,`Web Video`,`webm`,1920,1080,null,null],[`webm-vp9-alpha`,`WebM VP9 with Alpha`,`Web Video`,`webm`,null,null,null,null],[`youtube-1080p`,`YouTube 1080p Full HD`,`Social Media`,`h264`,1920,1080,null,16],[`youtube-1440p`,`YouTube 1440p 2K QHD`,`Social Media`,`h264`,2560,1440,null,24],[`youtube-2160p`,`YouTube 2160p 4K UHD`,`Social Media`,`h264`,3840,2160,null,45],[`youtube-shorts`,`YouTube Shorts 1080x1920`,`Social Media`,`h264`,1080,1920,null,16],[`vimeo-1080p`,`Vimeo 1080p Full HD`,`Social Media`,`h264`,1920,1080,null,20],[`vimeo-2160p`,`Vimeo 2160p 4K UHD`,`Social Media`,`h264`,3840,2160,null,50],[`x-1080p`,`X (Twitter) 1080p`,`Social Media`,`h264`,1920,1080,null,8],[`instagram-reels`,`Instagram Reels and Stories 1080x1920`,`Social Media`,`h264`,1080,1920,30,10],[`instagram-feed-square`,`Instagram Feed 1080x1080`,`Social Media`,`h264`,1080,1080,30,8],[`tiktok`,`TikTok 1080x1920`,`Social Media`,`h264`,1080,1920,null,10],[`facebook-1080p`,`Facebook 1080p`,`Social Media`,`h264`,1920,1080,null,10],[`linkedin-1080p`,`LinkedIn 1080p`,`Social Media`,`h264`,1920,1080,30,8],[`apple-tv-4k`,`Apple TV 4K (HEVC)`,`Devices`,`hevc`,3840,2160,null,25],[`iphone-1080p`,`Apple iPhone and iPad 1080p`,`Devices`,`h264`,1920,1080,null,10],[`android-1080p`,`Android Phone and Tablet 1080p`,`Devices`,`h264`,1920,1080,null,10],[`android-720p`,`Android Phone 720p`,`Devices`,`h264`,1280,720,null,5],[`prores-proxy`,`Apple ProRes 422 Proxy`,`Mezzanine`,`prores`,null,null,null,null],[`prores-lt`,`Apple ProRes 422 LT`,`Mezzanine`,`prores`,null,null,null,null],[`prores-422`,`Apple ProRes 422`,`Mezzanine`,`prores`,null,null,null,null],[`prores-hq`,`Apple ProRes 422 HQ`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444`,`Apple ProRes 4444`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444-alpha`,`Apple ProRes 4444 with Alpha`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444xq`,`Apple ProRes 4444 XQ`,`Mezzanine`,`prores`,null,null,null,null],[`dnxhr-lb`,`DNxHR LB`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-sq`,`DNxHR SQ`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-hq`,`DNxHR HQ`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-hqx`,`DNxHR HQX 10-bit`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-444`,`DNxHR 444 10-bit`,`Mezzanine`,`quicktime`,null,null,null,null],[`cineform-high`,`GoPro CineForm YUV 10-bit`,`Mezzanine`,`cineform`,null,null,null,null],[`cineform-alpha`,`GoPro CineForm RGBA 12-bit with Alpha`,`Mezzanine`,`cineform`,null,null,null,null],[`animation-alpha`,`QuickTime Animation with Alpha`,`Mezzanine`,`quicktime`,null,null,null,null],[`uncompressed-10bit`,`Uncompressed 10-bit 4:2:2 (v210)`,`Mezzanine`,`quicktime`,null,null,null,null],[`xdcam-hd422-1080i50`,`XDCAM HD 422 1080i 25 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1920,1080,25,null],[`xdcam-hd422-1080i5994`,`XDCAM HD 422 1080i 29.97 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1920,1080,29.97,null],[`xdcam-hd422-720p50`,`XDCAM HD 422 720p 50 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1280,720,50,null],[`dnxhr-hq-mxf`,`DNxHR HQ MXF OP1a`,`Broadcast`,`dnxhr_mxf`,null,null,null,null],[`dnxhd-145-mxf`,`DNxHD 145 MXF OP1a 1080`,`Broadcast`,`dnxhr_mxf`,1920,1080,null,null],[`prores-hq-mxf`,`Apple ProRes 422 HQ MXF OP1a`,`Broadcast`,`prores_mxf`,null,null,null,null],[`jpeg2000-mxf`,`JPEG 2000 MXF OP1a`,`Broadcast`,`jpeg2000_mxf`,null,null,null,null],[`mpeg2-1080i`,`MPEG-2 1080i 29.97 Broadcast`,`Broadcast`,`mpeg2`,1920,1080,29.97,25],[`h264-broadcast-ebu`,`H.264 Broadcast, EBU R128 loudness`,`Broadcast`,`h264`,1920,1080,null,30],[`h264-broadcast-atsc`,`H.264 Broadcast, ATSC A/85 loudness`,`Broadcast`,`h264`,1920,1080,null,30],[`mpeg2-dvd-ntsc`,`NTSC DV Widescreen DVD`,`DVD`,`mpeg2_dvd`,720,480,29.97,6],[`bluray-mpeg2-1080i`,`Blu-ray MPEG-2 1080i 29.97`,`DVD`,`mpeg2_bluray`,1920,1080,29.97,25],[`bluray-h264-1080p24`,`Blu-ray H.264 1080p 23.976`,`DVD`,`h264_bluray`,1920,1080,23.976,25],[`as10-high-hd-1080i50`,`AS-10 HIGH_HD_2014 1080i 25`,`Broadcast`,`as10`,null,null,25,null],[`as10-high-hd-1080i5994`,`AS-10 HIGH_HD_2014 1080i 29.97`,`Broadcast`,`as10`,null,null,29.97,null],[`as11-mpeg2-1080i50`,`AS-11 OP1a MPEG-2 HD422 1080i 25`,`Broadcast`,`as11`,null,null,25,null],[`as11-d10-imx50-625`,`AS-11 D10 IMX 50 625 (UK DPP SD)`,`Broadcast`,`as11_d10`,null,null,null,null],[`p2-dvcprohd-1080i50`,`P2 DVCPRO HD 1080i 25`,`Broadcast`,`p2`,null,null,null,null],[`p2-dvcprohd-720p50`,`P2 DVCPRO HD 720p 50`,`Broadcast`,`p2`,null,null,null,null],[`dcp-2k-flat-24`,`DCP 2K Flat 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-2k-scope-24`,`DCP 2K Scope 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-2k-flat-24-interop`,`DCP 2K Flat 24 (Interop)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-4k-flat-24`,`DCP 4K Flat 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`mpeg2-dvd-pal`,`PAL DV Widescreen DVD`,`DVD`,`mpeg2_dvd`,720,576,25,6],[`png-sequence`,`PNG Sequence`,`Image Sequence`,`png`,null,null,null,null],[`png-sequence-alpha`,`PNG Sequence with Alpha`,`Image Sequence`,`png`,null,null,null,null],[`tiff-sequence-16`,`TIFF Sequence 16-bit`,`Image Sequence`,`tiff`,null,null,null,null],[`dpx-sequence-10`,`DPX Sequence 10-bit`,`Image Sequence`,`dpx`,null,null,null,null],[`exr-sequence-half`,`OpenEXR Sequence (half float)`,`Image Sequence`,`exr`,null,null,null,null],[`jpeg-sequence`,`JPEG Sequence`,`Image Sequence`,`jpeg`,null,null,null,null],[`targa-sequence`,`Targa Sequence`,`Image Sequence`,`targa`,null,null,null,null],[`png-still`,`PNG Still (first frame of the range)`,`Image`,`png`,null,null,null,null],[`jpeg-still`,`JPEG Still`,`Image`,`jpeg`,null,null,null,null],[`gif-480`,`Animated GIF 480 px`,`Animated GIF`,`gif`,null,null,15,null],[`gif-720`,`Animated GIF 720 px`,`Animated GIF`,`gif`,null,null,20,null],[`wav-48-24`,`Waveform Audio 48 kHz 24-bit`,`Audio Only`,`wav`,null,null,null,null],[`wav-48-16`,`Waveform Audio 48 kHz 16-bit`,`Audio Only`,`wav`,null,null,null,null],[`bwf-ebu`,`Broadcast WAV, EBU R128 loudness`,`Audio Only`,`bwf`,null,null,null,null],[`aiff-48-24`,`AIFF 48 kHz 24-bit`,`Audio Only`,`aiff`,null,null,null,null],[`mp3-320`,`MP3 320 kb/s`,`Audio Only`,`mp3`,null,null,null,null],[`mp3-podcast`,`MP3 Podcast, -16 LUFS`,`Audio Only`,`mp3`,null,null,null,null],[`aac-256`,`AAC Audio 256 kb/s`,`Audio Only`,`aac`,null,null,null,null],[`aac-streaming`,`AAC Streaming, -14 LUFS`,`Audio Only`,`aac`,null,null,null,null],[`flac-48-24`,`FLAC 48 kHz 24-bit`,`Audio Only`,`flac`,null,null,null,null],[`ogg-opus`,`Ogg Opus 160 kb/s`,`Audio Only`,`ogg`,null,null,null,null],[`ffv1-archive`,`FFV1 Lossless Archive (Matroska)`,`Archive`,`matroska`,null,null,null,null],[`proxy-prores`,`ProRes Proxy, quarter size (proxy)`,`Proxy`,`prores`,960,540,null,null],[`proxy-h264-540`,`H.264 Proxy 960x540`,`Proxy`,`h264`,960,540,null,3],[`proxy-h264-720`,`H.264 Proxy 1280x720 (formcut)`,`Proxy`,`h264`,1280,720,null,5],[`proxy-cineform`,`CineForm Proxy 1280x720`,`Proxy`,`cineform`,1280,720,null,null],[`family-formcut-mezzanine`,`formcut mezzanine (ProRes 422 HQ)`,`Form Family`,`prores`,null,null,null,null],[`family-formwav-audio`,`formwav session audio (WAV 48 kHz 24-bit)`,`Form Family`,`wav`,null,null,null,null],[`family-formvis-stills`,`formvis stills (PNG Sequence)`,`Form Family`,`png`,null,null,null,null]],We=new Set([`h264`,`hevc`,`av1`,`webm`,`mpeg2`,`mpeg2_dvd`,`mpeg2_bluray`,`h264_bluray`,`matroska`]);function Ge(e,t){return e===`webm-vp9-alpha`||e===`ffv1-archive`?null:We.has(t)?`webm`:t===`gif`?`gif`:t===`wav`||t===`bwf`?`wav`:t===`aiff`?`aiff`:t===`ogg`?`ogg`:e===`png-still`?`png`:e===`jpeg-still`?`jpeg`:null}function Ke(e){if(/EBU R128/.test(e))return-23;if(/ATSC A\/85/.test(e))return-24;let t=/(-\d+) LUFS/.exec(e);return t?Number(t[1]):null}var N=Ue.map(([e,t,n,r,i,a,o,s])=>({id:e,name:t,category:n,format:r,width:i,height:a,fps:o,mbps:s,target:Ge(e,r),lufs:Ke(t),bits:/-16\b|16-bit/.test(t)?16:24})),P=new Map(N.map(e=>[e.id,e])),F={webm:`WebM`,gif:`GIF`,wav:`WAV`,aiff:`AIFF`,ogg:`Ogg Opus`,png:`PNG`,jpeg:`JPEG`},I={webm:`webm`,gif:`gif`,wav:`wav`,aiff:`aiff`,ogg:`opus`,png:`png`,jpeg:`jpg`},L={webm:`video/webm`,gif:`image/gif`,wav:`audio/wav`,aiff:`audio/aiff`,ogg:`audio/ogg`,png:`image/png`,jpeg:`image/jpeg`},qe={h264:`H.264`,hevc:`HEVC`,av1:`AV1`,webm:`WebM`,prores:`ProRes`,quicktime:`QuickTime`,cineform:`CineForm`,mxf_op1a:`MXF OP1a`,dnxhr_mxf:`DNx MXF`,prores_mxf:`ProRes MXF`,jpeg2000_mxf:`J2K MXF`,mpeg2:`MPEG-2`,mpeg2_dvd:`DVD`,mpeg2_bluray:`Blu-ray`,h264_bluray:`Blu-ray`,as10:`AS-10`,as11:`AS-11`,as11_d10:`AS-11 D10`,p2:`P2`,dcp:`DCP`,png:`PNG`,tiff:`TIFF`,dpx:`DPX`,exr:`EXR`,jpeg:`JPEG`,targa:`Targa`,gif:`GIF`,wav:`WAV`,bwf:`BWF`,aiff:`AIFF`,mp3:`MP3`,aac:`AAC`,flac:`FLAC`,ogg:`Ogg`,matroska:`Matroska`},Je=new Set([`wav`,`aiff`,`ogg`]);function Ye(e){return e.width&&e.height?`${e.width}x${e.height}`:``}function Xe(e){return e.fps?`${Number(e.fps.toFixed(3))}`:``}function Ze(e){return e.mbps?`${e.mbps} Mb/s`:``}var Qe=0,$e=()=>`src${++Qe}`,R=48e3;function et(e,t,n,r=8e3){return new Promise((i,a)=>{let o=window.setTimeout(()=>{l(),a(Error(`timed out waiting for ${t}`))},r),s=()=>{l(),i()},c=()=>{l(),a(Error(`the browser cannot decode this file`))},l=()=>{window.clearTimeout(o),e.removeEventListener(t,s),e.removeEventListener(n,c)};e.addEventListener(t,s),e.addEventListener(n,c)})}async function tt(e){if(Number.isFinite(e.duration))return e.duration;e.currentTime=1e101,await et(e,`durationchange`,`error`,4e3).catch(()=>void 0);let t=Number.isFinite(e.duration)?e.duration:0;return e.currentTime=0,t}async function nt(e){let t=e.requestVideoFrameCallback?.bind(e);if(!t)return 30;let n=[];return new Promise(r=>{let i=()=>{e.pause(),e.currentTime=0;let t=[];for(let e=1;en[e-1]&&t.push(n[e]-n[e-1]);t.sort((e,t)=>e-t);let i=1/(t.length?t[t.length>>1]:1/30),a=[12,15,23.976,24,25,29.97,30,50,59.94,60].reduce((e,t)=>Math.abs(t-i){n.push(r.mediaTime),n.length>=14?i():t(a)};t(a),e.muted=!0,e.play().catch(()=>i()),window.setTimeout(()=>{n.length<14&&i()},1500)})}async function rt(e,t){let n=URL.createObjectURL(e),r=document.createElement(`video`);r.muted=!0,r.preload=`auto`,r.playsInline=!0,r.src=n;try{await et(r,`loadedmetadata`,`error`)}catch(e){throw URL.revokeObjectURL(n),e}let i=await tt(r),a=r.videoWidth>0&&r.videoHeight>0,o=a?t??await nt(r):0;a&&await it(r,0);let s=null;return{id:$e(),name:e.name,kind:a?`video`:`audio`,sample:!1,size:e.size,width:r.videoWidth,height:r.videoHeight,fps:o,duration:i,async frame(e){return await it(r,Math.max(0,Math.min(e,Math.max(0,i-.001)))),r},audio(){return s||=(async()=>{if(e.size>629145600)return null;try{return await new OfflineAudioContext(2,1,R).decodeAudioData(await e.arrayBuffer())}catch{return null}})(),s},dispose(){r.removeAttribute(`src`),r.load(),URL.revokeObjectURL(n)}}}async function it(e,t){if(Math.abs(e.currentTime-t)<1e-4&&e.readyState>=2)return;let n=et(e,`seeked`,`error`,6e3);e.currentTime=t,await n}var at=640,ot=360,z=24,B=8;function st(){let e=R*B,t=new AudioBuffer({length:e,numberOfChannels:2,sampleRate:R}),n=t.getChannelData(0),r=t.getChannelData(1),i=[261.63,329.63,392,523.25,392,329.63,293.66,349.23],a=12345,o=()=>(a=a*1664525+1013904223>>>0,a/4294967296-.5);for(let t=0;t{e.fillStyle=t,e.fillRect(n/o.length*r,0,n/o.length+1,34)}),e.strokeStyle=`rgba(255,255,255,0.12)`,e.lineWidth=1;for(let i=-(t*40)%40;i=0;r--){let i=t-r*.035,a=n/2+Math.sin(i*1.7)*190,o=190+Math.cos(i*2.3)*70;e.fillStyle=`rgba(242, 84, 91, ${.9-r*.09})`,e.beginPath(),e.arc(a,o,26-r*1.6,0,Math.PI*2),e.fill()}e.strokeStyle=`rgba(255,255,255,0.8)`,e.lineWidth=3,e.beginPath(),e.arc(s,c,48,t*3,t*3+Math.PI*1.3),e.stroke();let l=.5+.5*Math.sin(t*6);e.fillStyle=`rgba(0,0,0,0.45)`,e.fillRect(18,300,604,14),e.fillStyle=`#f2545b`,e.fillRect(18,300,t/B*604,14),e.fillStyle=`rgba(255,255,255,${.5+l*.4})`,e.fillRect(18+t/B*604-2,296,4,22);let u=Math.floor(t*z),d=Math.floor(u/z),f=u%z;e.fillStyle=`#fff`,e.font=`600 44px ui-monospace, Menlo, monospace`,e.textBaseline=`alphabetic`,e.fillText(`00:00:${String(d).padStart(2,`0`)}:${String(f).padStart(2,`0`)}`,20,96),e.font=`500 15px system-ui, sans-serif`,e.fillStyle=`rgba(255,255,255,0.8)`,e.fillText(`formencoder sample · generated in this page · 640x360 · 24 fps`,20,344)}function lt(){let e=document.createElement(`canvas`);e.width=at,e.height=ot;let t=e.getContext(`2d`,{willReadFrequently:!1}),n=null;return{id:$e(),name:`formencoder-sample`,kind:`video`,sample:!0,size:0,width:at,height:ot,fps:z,duration:B,async frame(n){return ct(t,Math.max(0,Math.min(n,B))),e},async audio(){return n||=st(),n},dispose(){n=null}}}var ut=1280;function dt(e){return{size:`preset`,fps:null,mbps:null,codec:`auto`,audio:!0,lufs:e.lufs,start:0,end:null}}var V=e=>Math.max(2,Math.round(e/2)*2);function H(e,t,n){let r=Math.max(0,Math.min(n.start,e.duration)),i=Math.max(r+.05,Math.min(n.end??e.duration,e.duration)),a=e.width||640,o=e.height||360,s=!1,c=t.target===`gif`?Number(/(\d+) px/.exec(t.name)?.[1]??0):0;typeof n.size==`number`?(a=n.size,o=e.height/e.width*n.size):n.size===`preset`&&t.width&&t.height?(a=t.width,o=t.height,s=!0):n.size===`preset`&&c&&(a=c,o=e.height/e.width*c);let l=!1,u=Math.max(a,o);if(u>1280){let e=ut/u;a*=e,o*=e,l=!0}let d=V(a),f=V(o),p=d,m=f;if(s&&e.width&&e.height){let t=Math.min(d/e.width,f/e.height);p=V(e.width*t),m=V(e.height*t)}let h=n.fps??t.fps??(e.fps||30),g=Math.max(1,Math.min(60,t.target===`gif`?Math.min(h,25):h)),_=n.mbps??0;_||=t.mbps&&t.width&&t.height?t.mbps*(d*f/(t.width*t.height))*(g/(t.fps||30)):t.mbps?t.mbps*.25:.09*d*f*g/1e6,_=Math.max(.15,Math.min(14,_));let v=Math.max(1,Math.floor((i-r)*g));return{width:d,height:f,innerWidth:p,innerHeight:m,fps:g,mbps:_,start:r,end:i,frames:v,capped:l}}function ft(){let e=[];return e.push(typeof VideoEncoder>`u`?`VideoEncoder missing`:`VideoEncoder ready`),e.push(typeof AudioEncoder>`u`?`AudioEncoder missing`:`AudioEncoder ready`),e.join(`, `)}function U(e){if(e.aborted)throw new DOMException(`stopped`,`AbortError`)}function pt(){return new Promise(e=>window.setTimeout(e,0))}function mt(e,t,n,r,i){e.fillStyle=`#000`,e.fillRect(0,0,t.width,t.height);let a=(t.width-t.innerWidth)/2,o=(t.height-t.innerHeight)/2;e.drawImage(n,0,0,r,i,a,o,t.innerWidth,t.innerHeight)}function ht(e,t){return e instanceof HTMLVideoElement?{w:e.videoWidth,h:e.videoHeight}:e instanceof HTMLCanvasElement?{w:e.width,h:e.height}:{w:t.width,h:t.height}}async function gt(e,t){let n=await e.source.audio();if(!n)return null;let r=Math.floor(t.start*n.sampleRate),i=Math.min(n.length,Math.ceil(t.end*n.sampleRate)),a=[];for(let e=0;e=0?`+`:``}${t.gainDb.toFixed(1)} dB${t.limited?`, held at -1 dBTP`:``})`}else r=`Loudness ${O(i)}`;return{channels:n.channels,rate:n.rate,note:r}}async function yt(e,t,n,r){if(typeof AudioEncoder>`u`)throw Error(`this browser has no AudioEncoder`);if(t!==48e3)throw Error(`audio at ${t} Hz needs resampling; the demo expects ${R} Hz`);let i={codec:`opus`,sampleRate:R,numberOfChannels:e.length,bitrate:n};if(!(await AudioEncoder.isConfigSupported(i)).supported)throw Error(`Opus encoding is not available in this browser`);let a=[],o=null,s=new AudioEncoder({output:e=>{let t=new Uint8Array(e.byteLength);e.copyTo(t),a.push({data:t,timeUs:e.timestamp,samples:Math.round((e.duration??2e4)/1e6*R)})},error:e=>{o=e}});s.configure(i);let c=e[0].length;for(let t=0;ti.set(e.subarray(t,t+n),r*960));let a=new AudioData({format:`f32-planar`,sampleRate:R,numberOfFrames:960,numberOfChannels:e.length,timestamp:Math.round(t/R*1e6),data:i});s.encode(a),a.close(),s.encodeQueueSize>12&&await pt()}if(await s.flush(),s.close(),o)throw o;return a}async function bt(e){if(typeof VideoEncoder>`u`)throw Error(`this browser has no WebCodecs VideoEncoder`);let{source:t,preset:n,settings:r}=e;if(t.kind!==`video`)throw Error(`this source has no picture`);let i=H(t,n,r),a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`),s=r.codec===`vp8`?[`vp8`]:r.codec===`vp9`?[`vp09.00.10.08`]:[`vp09.00.10.08`,`vp8`],c=``,l=null;for(let e of s){let t={codec:e,width:i.width,height:i.height,bitrate:Math.round(i.mbps*1e6),framerate:i.fps,latencyMode:`quality`,bitrateMode:`variable`};if((await VideoEncoder.isConfigSupported(t)).supported){c=e,l=t;break}}if(!l)throw Error(`neither VP9 nor VP8 encoding is available in this browser`);let u=[],d=null,f=new VideoEncoder({output:e=>{let t=new Uint8Array(e.byteLength);e.copyTo(t),u.push({track:1,timeMs:e.timestamp/1e3,key:e.type===`key`,data:t})},error:e=>{d=e}});f.configure(l);let p=performance.now(),m=Math.max(1,Math.round(i.fps*2)),h=0;for(let n=0;n6;)await pt();let u=performance.now();u-h>160&&(h=u,e.onPreview(a));let g=(u-p)/1e3;e.onProgress({fraction:(n+1)/i.frames*.92,frame:n+1,frames:i.frames,message:`${((n+1)/Math.max(g,.001)).toFixed(1)} fps`})}if(await f.flush(),f.close(),e.onPreview(a),d)throw d;let g=i.capped?`Frame size capped at ${ut} px in the browser demo`:``,_=null;if(r.audio){e.onProgress({fraction:.93,frame:i.frames,frames:i.frames,message:`Encoding audio`});let t=await vt(e,i);if(t)try{let n=await yt(t.channels,t.rate,128e3,e.signal);for(let e of n)u.push({track:2,timeMs:e.timeUs/1e3,key:!0,data:e.data});_={sampleRate:R,channels:t.channels.length,preSkip:312},g=[g,t.note].filter(Boolean).join(`. `)}catch(e){g=[g,`Audio left out: ${e.message}`].filter(Boolean).join(`. `)}}return e.onProgress({fraction:.98,frame:i.frames,frames:i.frames,message:`Writing WebM`}),{blob:Fe({codec:c===`vp8`?`V_VP8`:`V_VP9`,width:i.width,height:i.height},_,u,(i.end-i.start)*1e3),ext:I.webm,mime:L.webm,encoder:`WebCodecs ${c===`vp8`?`VP8`:`VP9`}${_?` + Opus`:``} · ${i.width}x${i.height} · ${i.fps} fps · ${i.mbps.toFixed(1)} Mb/s`,note:g}}async function xt(e){let{source:t,preset:n,settings:r}=e;if(t.kind!==`video`)throw Error(`this source has no picture`);let i=H(t,n,r),a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`,{willReadFrequently:!0}),s=new ve(i.width,i.height),c=Math.max(2,Math.round(100/i.fps));for(let n=0;n({data:e.data,samples:e.samples})),a.channels.length,312,a.rate),ext:I.ogg,mime:L.ogg,encoder:`WebCodecs Opus · ${a.channels.length} ch · 160 kb/s`,note:a.note}:{blob:t===`aiff`?He(a.channels,a.rate,r.bits):Ve(a.channels,a.rate,r.bits),ext:I[t],mime:L[t],encoder:`PCM ${r.bits}-bit · ${a.rate} Hz · ${a.channels.length} ch`,note:a.note}}async function Ct(e,t){let{source:n,preset:r,settings:i}=e;if(n.kind!==`video`)throw Error(`this source has no picture`);let a=H(n,r,i),o=document.createElement(`canvas`);o.width=a.width,o.height=a.height;let s=o.getContext(`2d`),c=await n.frame(a.start),l=ht(c,n);return mt(s,a,c,l.w,l.h),e.onPreview(o),{blob:await new Promise((e,n)=>o.toBlob(t=>t?e(t):n(Error(`the canvas could not be saved`)),L[t],.92)),ext:I[t],mime:L[t],encoder:`${t.toUpperCase()} still · ${a.width}x${a.height}`,note:``}}async function wt(e){let t=e.preset.target;if(!t)throw Error(`needs the desktop engine`);return t===`webm`?bt(e):t===`gif`?xt(e):Je.has(t)?St(e,t):Ct(e,t)}function Tt(e){return e==null||!Number.isFinite(e)?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function Et(e){if(e==null||!Number.isFinite(e)||e<0)return`--:--`;let t=Math.round(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n?`${n}:${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`:`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`}function Dt(e){return!e||!Number.isFinite(e)?``:e<60?`${e.toFixed(e<10?2:1)} s`:Et(e)}var Ot={ready:`Ready`,preparing:`Preparing`,encoding:`Encoding`,paused:`Paused`,done:`Done`,failed:`Failed`,stopped:`Stopped`,skipped:`Skipped`},W=new TextDecoder(`latin1`);async function G(e,t,n){let r=await e.slice(t,t+n).arrayBuffer();return new DataView(r)}var K=(e,t)=>W.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),kt={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},At={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},jt={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function Mt(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=K(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=K(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=K(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=K(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${kt[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=K(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=Mt(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:Nt(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Pt(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:jt[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function It(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await G(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function Vt(e){let t=await G(e,0,Math.min(e.size,64));if(t.byteLength<26||K(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Ht=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Ut=[44100,48e3,32e3];async function Wt(e){let t=await G(e,0,Math.min(e.size,65536)),n=0;if(K(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Ht[t.getUint8(r+2)>>4],o=Ut[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Gt(e){let t=[Ft,Rt,zt,Bt,Vt,Wt];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Kt=[{pack:`open-water`,file:`open-water-1280x720-30fps.mp4`,mime:`video/mp4`,kind:`video`,width:1280,height:720,fps:29.97,duration:8.008,bytes:6819433,outputs:[{preset:`match-source-medium`},{preset:`gif-480`},{preset:`png-still`}]},{pack:`coast-aerial`,file:`coast-aerial-1280x720-25fps.mp4`,mime:`video/mp4`,kind:`video`,width:1280,height:720,fps:25,duration:7,bytes:6637734,outputs:[{preset:`match-source-medium`},{preset:`gif-480`}]},{pack:`shoreline-vertical`,file:`shoreline-vertical-404x720-60fps.mp4`,mime:`video/mp4`,kind:`video`,width:404,height:720,fps:59.94,duration:7.858,bytes:4235966,outputs:[{preset:`match-source-medium`},{preset:`gif-480`,size:`source`}]},{pack:`on-the-sea-reading`,file:`on-the-sea-reading.mp3`,mime:`audio/mpeg`,kind:`audio`,width:0,height:0,fps:0,duration:21.133,bytes:211755,outputs:[{preset:`ogg-opus`,lufs:-16},{preset:`bwf-ebu`},{preset:`wav-48-24`}]}];function qt(){let e=window;return e.FE_MEDIA||={},e.FE_MEDIA}function Jt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}async function Yt(e){await Jt(e.pack);let t=qt(),n=t[e.file];if(delete t[e.file],!n)throw Error(`the media pack ${e.pack} holds no ${e.file}`);let r=atob(n),i=new Uint8Array(r.length);for(let e=0;ePromise.reject(Error(`the source is still loading`)),audio:()=>Promise.resolve(null),dispose:()=>void 0}}var Qt=0,q=new class{items=[];selectedItem=``;selectedOutput=``;running=!1;logs=[];listeners=new Map;abort=null;previews=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e)?.add(t)}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}log(e,t=!1){let n=new Date,r=[n.getHours(),n.getMinutes(),n.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`);this.logs.push({time:r,text:e,error:t}),this.logs.length>400&&this.logs.shift(),this.emit(`log`)}previewFor(e){return this.previews.get(e)}item(e){return this.items.find(t=>t.id===e)}outputOf(e){for(let t of this.items){let n=t.outputs.find(t=>t.id===e);if(n)return{item:t,output:n}}}select(e,t=``){(this.selectedItem!==e||this.selectedOutput!==t)&&(this.selectedItem=e,this.selectedOutput=t,this.emit(`select`))}makeOutput(e){let t=P.get(e);if(!t)throw Error(`unknown preset ${e}`);return{id:`out${++Qt}`,presetId:e,settings:dt(t),status:`ready`,progress:0,message:``,encoder:``,note:``,blob:null,mime:``,fileName:``,elapsed:0,fps:0,frame:0,frames:0,eta:0,speed:0}}stem(e){return e.source.name.replace(/\.[^.]+$/,``).replace(/[^A-Za-z0-9._-]+/g,`_`)||`source`}nameFor(e,t){let n=P.get(t.presetId),r=n?.target?I[n.target]:`out`;return`${this.stem(e)}_${t.presetId}.${r}`}addOutput(e,t){let n=this.item(e);if(!n)return;let r=this.makeOutput(t);return r.fileName=this.nameFor(n,r),n.outputs.push(r),n.collapsed=!1,this.log(`Added output ${P.get(t)?.name??t} to ${n.source.name}`),this.emit(`items`),r}async addSource(e,t){let n={id:e.id,source:e,probe:{container:``,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[]},loudness:null,loudnessState:`pending`,poster:null,outputs:[],collapsed:!1,loading:!1};this.items.push(n);for(let e of t){let t=this.makeOutput(e);t.fileName=this.nameFor(n,t),n.outputs.push(t)}return this.selectedItem=n.id,this.selectedOutput=``,this.log(`Added source ${e.name}`),this.emit(`items`),this.emit(`select`),n}async analyse(e,t){if(e.probe=t?await Gt(t):{container:`generated in this page (no file)`,duration:e.source.duration,size:0,bitrate:null,video:{codec:`canvas RGB`,profile:``,width:e.source.width,height:e.source.height,fps:e.source.fps,frames:Math.round(e.source.duration*e.source.fps),bitrate:null,pixels:`rgb24`},audio:[{codec:`PCM f32 (synthesised)`,sampleRate:48e3,channels:2,bitDepth:32,bitrate:null}],notes:[]},e.source.kind===`video`)try{let t=await e.source.frame(Math.min(1,e.source.duration/2)),n=document.createElement(`canvas`);n.width=640,n.height=Math.max(2,Math.round(640*e.source.height/e.source.width)),n.getContext(`2d`)?.drawImage(t,0,0,n.width,n.height),e.poster=n}catch(e){this.log(`No preview frame: ${e.message}`,!0)}this.emit(`items`),this.emit(`select`);try{let t=await e.source.audio();if(!t)e.loudnessState=`none`;else{e.probe.audio.length||e.probe.audio.push({codec:`decoded by the browser`,sampleRate:t.sampleRate,channels:t.numberOfChannels,bitDepth:null,bitrate:null}),await new Promise(e=>window.setTimeout(e,0));let n=[];for(let e=0;e{let r=this.addCuratedRow(t);e.push({item:r,index:n})}),this.selectedItem=e[0].item.id,this.emit(`select`);let t=0;for(let{item:n,index:r}of e){let e=Kt[r];try{let r=await Yt(e),i=await rt(r,e.fps||null);i.id=n.id,n.source.dispose(),n.source=i,n.loading=!1,this.emit(`items`),await this.analyse(n,r),t++}catch(t){this.log(`Could not load ${e.file}: ${t.message}`,!0),this.items=this.items.filter(e=>e.id!==n.id),this.selectedItem===n.id&&(this.selectedItem=this.items[0]?.id??``),this.emit(`items`),this.emit(`select`)}}t||(this.log(`The curated media did not load; adding the built-in sample instead`,!0),await this.addSample())}addCuratedRow(e){let t=Zt(e),n={id:t.id,source:t,probe:{container:``,duration:e.duration,size:e.bytes,bitrate:null,video:null,audio:[],notes:[]},loudness:null,loudnessState:`pending`,poster:null,outputs:[],collapsed:!1,loading:!0};this.items.push(n);for(let t of e.outputs){let e=this.makeOutput(t.preset);t.lufs!==void 0&&(e.settings.lufs=t.lufs),t.size&&(e.settings.size=t.size),e.fileName=this.nameFor(n,e),n.outputs.push(e)}return this.log(`Added source ${e.file}`),this.emit(`items`),n}async addSample(){let e=lt(),t=await this.addSource(e,[`match-source-medium`,`gif-480`,`bwf-ebu`]);await this.analyse(t,null)}removeSelected(){if(!this.running){if(this.selectedOutput){let e=this.outputOf(this.selectedOutput);e&&(e.item.outputs=e.item.outputs.filter(e=>e.id!==this.selectedOutput),this.selectedOutput=``)}else this.selectedItem&&=(this.item(this.selectedItem)?.source.dispose(),this.items=this.items.filter(e=>e.id!==this.selectedItem),this.items[0]?.id??``);this.emit(`items`),this.emit(`select`)}}resetOutput(e){e.status=`ready`,e.progress=0,e.message=``,e.blob=null,e.note=``,e.encoder=``,this.emit(`items`)}async start(){if(this.running)return;let e=[];for(let t of this.items)for(let n of t.outputs)(!t.loading&&n.status===`ready`||n.status===`failed`||n.status===`stopped`)&&e.push({item:t,out:n});if(!e.length)this.log(`Nothing to encode: every output is done`);else{this.running=!0,this.abort=new AbortController,this.emit(`run`),this.log(`Queue started: ${e.length} output${e.length===1?``:`s`}`);for(let{item:t,out:n}of e){if(this.abort.signal.aborted)break;await this.runOne(t,n,this.abort.signal)}this.running=!1,this.abort=null,this.log(`Queue finished`),this.emit(`run`)}}stop(){this.abort?.abort()}async runOne(e,t,n){let r=P.get(t.presetId);if(!r)return;if(!r.target){t.status=`skipped`,t.message=`Needs the desktop engine`,this.log(`Skipped ${t.fileName}: ${r.name} needs the desktop engine`),this.emit(`progress`,t);return}t.status=`preparing`,t.progress=0,t.message=`Preparing`,t.blob=null,t.note=``,this.emit(`progress`,t);let i=performance.now();this.log(`Encoding ${t.fileName} with ${r.name}`);try{let a=()=>{let e=this.previews.get(t.id);return e||(e=document.createElement(`canvas`),this.previews.set(t.id,e)),e},o=await wt({source:e.source,preset:r,settings:t.settings,signal:n,onProgress:n=>{let r=(performance.now()-i)/1e3;t.status=`encoding`,t.progress=n.fraction,t.frame=n.frame,t.frames=n.frames,t.elapsed=r,t.eta=n.fraction>.02?r/n.fraction*(1-n.fraction):0,t.fps=r>0?n.frame/r:0,t.speed=r>0&&e.source.fps?n.frame/e.source.fps/r:0,t.message=n.message,this.emit(`progress`,t)},onPreview:e=>{let n=a();(n.width!==e.width||n.height!==e.height)&&(n.width=e.width,n.height=e.height),n.getContext(`2d`)?.drawImage(e,0,0),this.emit(`progress`,t)}});t.blob=o.blob,t.mime=o.mime,t.fileName=t.fileName.replace(/\.[^.]+$/,`.${o.ext}`),t.encoder=o.encoder,t.note=o.note,t.status=`done`,t.progress=1,t.elapsed=(performance.now()-i)/1e3,t.eta=0,t.message=Tt(o.blob.size),this.log(`Done ${t.fileName}: ${o.encoder}${o.note?`. `+o.note:``}`)}catch(e){let n=e;n.name===`AbortError`?(t.status=`stopped`,t.message=`Stopped`,this.log(`Stopped ${t.fileName}`)):(t.status=`failed`,t.message=n.message,this.log(`Failed ${t.fileName}: ${n.message}`,!0))}this.emit(`progress`,t),this.emit(`items`)}},$t=new WeakMap;function J(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout($t.get(a)),$t.set(a,window.setTimeout(()=>a.remove(),r));return}let o=s(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();$t.set(o,window.setTimeout(()=>o.remove(),r))}var en=null,tn,nn,rn=``;function an(){let e=new _(`Preview`,760);return tn=s(`
`),nn=s(`

`),e.body.appendChild(tn),e.body.appendChild(nn),e.button(`Save`,`ghost`,()=>{rn&&on(rn)}),e.button(`Close`,`primary`,()=>e.close()),e.onClose=()=>{tn.replaceChildren(),rn=``},e}function on(e){let t=q.outputOf(e);if(!t?.output.blob){J(`This output has not been encoded yet`);return}let n=URL.createObjectURL(t.output.blob),r=document.createElement(`a`);r.href=n,r.download=t.output.fileName,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>URL.revokeObjectURL(n),4e3)}function sn(e){let n=q.outputOf(e);if(!n?.output.blob){J(`This output has not been encoded yet`);return}en??=an();let{output:r}=n,i=URL.createObjectURL(n.output.blob),a;r.mime.startsWith(`video/`)?(a=s(``),a.src=i):r.mime.startsWith(`audio/`)?(a=s(``),a.src=i):(a=s(``),a.src=i),tn.replaceChildren(a),rn=e,en.setTitle(r.fileName),t(nn,[r.encoder,r.note].filter(Boolean).join(`. `)),en.open(c(en.scrim,`.cv-btn-primary`))}var cn=class{id=`encoding`;title=`Encoding`;el;list;constructor(){this.el=s(`
+
`),this.areas=Object.fromEntries(ne.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,r=>{r.preventDefault(),e.setPointerCapture(r.pointerId),n(e,`is-dragging`,!0);let i={x:r.clientX,y:r.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},a=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,i.l+e.clientX-i.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,i.r-(e.clientX-i.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,i.b-(e.clientY-i.y)))),this.applySizes()},o=()=>{n(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,a),e.removeEventListener(`pointerup`,o),this.save()};e.addEventListener(`pointermove`,a),e.addEventListener(`pointerup`,o)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,r=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${r}px`),n(this.el,`no-left`,!e),n(this.el,`no-right`,!t),n(this.el,`no-bottom`,!r);for(let e of te){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ne){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new re(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(T);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??w[e]??w.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(T),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(T,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(T)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(T)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??w[e]??w.Default,e),this.save()}resetWorkspace(){this.applyLayout(w[this.workspace]??w.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(T)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(T,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ne)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new re(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,n(this.el,`is-maximized`,!1),n(e.el,`is-max`,!1)):(this.maximized&&n(this.maximized.el,`is-max`,!1),this.maximized=e,n(this.el,`is-maximized`,!0),n(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&n(t.el,`is-focused`,!1),this.focused=e;let r=this.find(e);r&&n(r.el,`is-focused`,!0),this.onFocus?.(e)}},E={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},ae=`studio`,oe=`#f2545b`,se=`formencoder_ui_settings`,ce=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function le(){try{let e=localStorage.getItem(se);if(e){let t=JSON.parse(e);return{theme:t.theme&&E[t.theme]?t.theme:ae,accentColor:t.accentColor||`#f2545b`,intensity:ce(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:ae,accentColor:oe,intensity:1}}function ue(e){try{let t=localStorage.getItem(se),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(se,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function de(e=le()){let t=document.documentElement,n=E[e.theme]||E.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(ce(e.intensity))),t.style.setProperty(`--accent-tint`,pe(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,pe(e.accentColor,.1))}function fe(e){let t={...le(),theme:e};ue(t),de(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function pe(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var me=`0.10.0`;function he(e,t){let n=(e,t)=>e>>16-t*8&255,r=Array.from(e.keys()),i=[{lo:0,hi:r.length}],a=r,o=t=>{let r=0,i=-1;for(let o=0;o<3;o++){let s=255,c=0;for(let r=t.lo;rc&&(c=t)}c-s>i&&(i=c-s,r=o)}return{c:r,span:i}};for(;i.length{if(e.hi-e.lo<2)return;let i=o(e),a=i.span*Math.sqrt(e.hi-e.lo);a>r&&(r=a,t=n,s=i.c)}),t<0)break;let c=i[t],l=a.slice(c.lo,c.hi).sort((t,r)=>n(e[t],s)-n(e[r],s));for(let e=0;e>1);i.splice(t,1,{lo:c.lo,hi:u},{lo:u,hi:c.hi})}let s=new Uint8Array(768);return i.forEach((t,r)=>{let i=0,o=0,c=0,l=Math.max(1,t.hi-t.lo);for(let r=t.lo;r{for(a|=e<=8;)t.push(a&255),a>>>=8,o-=8};s(256);let c=e[0];for(let t=1;t1<0&&t.push(a&255),Uint8Array.from(t)}var ve=class{width;height;parts=[];constructor(e,t){this.width=e,this.height=t;let n=new Uint8Array(13),r=new DataView(n.buffer);n.set(new TextEncoder().encode(`GIF89a`),0),r.setUint16(6,e,!0),r.setUint16(8,t,!0),n[10]=0,n[11]=0,n[12]=0,this.parts.push(n),this.parts.push(Uint8Array.from([33,255,11,...new TextEncoder().encode(`NETSCAPE2.0`),3,1,0,0,0]))}addFrame(e,t){let n=this.width*this.height,r=Math.max(1,Math.floor(n/12e3)),i=[];for(let t=0;t{let r=e>>3<<10|t>>3<<5|n>>3,i=o.get(r);if(i!==void 0)return i;let s=e>>3<<3|4,c=t>>3<<3|4,l=n>>3<<3|4,u=0,d=1/0;for(let e=0;e<256;e++){let t=a[e*3]-s,n=a[e*3+1]-c,r=a[e*3+2]-l,i=t*t*2+n*n*4+r*r*3;i>8&255,0,0]));let l=new Uint8Array(10),u=new DataView(l.buffer);l[0]=44,u.setUint16(5,this.width,!0),u.setUint16(7,this.height,!0),l[9]=135,this.parts.push(l),this.parts.push(a),this.parts.push(Uint8Array.from([8]));let d=_e(c);for(let e=0;ee>0?-.691+10*Math.log10(e):-1/0;function Ce(e,t){if(!e.length)return-1/0;let n=(e.length-1)*t,r=Math.floor(n),i=Math.min(e.length-1,r+1);return e[r]+(e[i]-e[r])*(n-r)}function we(e,t){let n=[];for(let r=0;r+t<=e.length;r++){let i=0;for(let n=0;n=e.length)continue;let o=i-n,s=Math.abs(o)<1e-9?1:Math.sin(Math.PI*o)/(Math.PI*o),c=.5+.5*Math.cos(Math.PI*o/9);r+=e[a]*s*c}return r}function Ee(e){let t=0;for(let n of e)for(let e=0;et&&(t=r)}let n=t,r=t*.55;for(let t of e)for(let e=0;en&&(n=i)}return{sample:t,truePeak:n}}function De(e,t){let n=e=>e>0?20*Math.log10(e):-1/0,r=e[0]?.length??0,i=Ee(e),a=Math.round(t*.1),o=Math.floor(r/a),s=Se(e.length),c=new Float64Array(o);e.forEach((e,n)=>{if(!s[n])return;let r=xe(e,t);for(let e=0;eD(e)>-70),d=-1/0;if(u.length){let e=D(u.reduce((e,t)=>e+t,0)/u.length)-10,t=l.filter(t=>D(t)>-70&&D(t)>e);t.length&&(d=D(t.reduce((e,t)=>e+t,0)/t.length))}let f=we(c,30).filter(e=>D(e)>-70),p=0,m=-1/0;if(f.length){let e=D(f.reduce((e,t)=>e+t,0)/f.length)-20,t=f.map(D).filter(t=>t>e).sort((e,t)=>e-t);t.length&&(p=Ce(t,.95)-Ce(t,.1),m=t[t.length-1])}return{integrated:d,lra:p,samplePeak:n(i.sample),truePeak:n(i.truePeak),shortTermMax:m}}function Oe(e){return Number.isFinite(e)?e.toFixed(1):`-inf`}function O(e){return`${Oe(e.integrated)} LUFS, LRA ${e.lra.toFixed(1)} LU, peak ${Oe(e.truePeak)} dBTP`}function ke(e,t,n=-1){if(!Number.isFinite(e.integrated))return{gainDb:0,limited:!1};let r=t-e.integrated,i=n-e.truePeak;return Number.isFinite(i)&&r>i?{gainDb:i,limited:!0}:{gainDb:r,limited:!1}}function k(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Ae(e){let t=[],n=e;for(;n>0;)t.unshift(n&255),n=Math.floor(n/256);return Uint8Array.from(t)}function je(e){let t=1;for(;t<8&&e>=2**(7*t)-1;)t++;let n=new Uint8Array(t),r=e;for(let e=t-1;e>=0;e--)n[e]=r%256,r=Math.floor(r/256);return n[0]|=1<<8-t,n}function A(e,t){return k([Ae(e),je(t.length),t])}function j(e,t){let n=[],r=t;do n.unshift(r%256),r=Math.floor(r/256);while(r>0);return A(e,Uint8Array.from(n))}function Me(e,t){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!1),A(e,n)}function M(e,t){return A(e,new TextEncoder().encode(t))}function Ne(e){let t=new Uint8Array(19),n=new DataView(t.buffer);return t.set(new TextEncoder().encode(`OpusHead`),0),t[8]=1,t[9]=e.channels,n.setUint16(10,e.preSkip,!0),n.setUint32(12,e.sampleRate,!0),n.setInt16(16,0,!0),t[18]=0,t}function Pe(e){return Ne(e)}function Fe(e,t,n,r){let i=A(440786851,k([j(17030,1),j(17143,1),j(17138,4),j(17139,8),M(17026,`webm`),j(17031,4),j(17029,2)])),a=A(357149030,k([j(2807729,1e6),Me(17545,r),M(19840,`formencoder demo`),M(22337,`formencoder demo`)])),o=[];e&&o.push(A(174,k([j(215,1),j(29637,1),j(131,1),j(156,0),M(134,e.codec),A(224,k([j(176,e.width),j(186,e.height)]))]))),t&&o.push(A(174,k([j(215,2),j(29637,2),j(131,2),j(156,0),M(134,`A_OPUS`),j(22186,Math.round(t.preSkip/48e3*1e9)),j(22203,8e7),A(25506,Ne(t)),A(225,k([Me(181,t.sampleRate),j(159,t.channels)]))])));let s=A(374648427,k(o)),c=[...n].sort((e,t)=>e.timeMs-t.timeMs||e.track-t.track),l=[],u=[],d=a.length+s.length,f=[],p=0,m=!1,h=()=>{if(!m)return;let e=A(524531317,k([j(231,Math.round(p)),...f]));l.push(e),d+=e.length,f=[],m=!1};for(let e of c){let t=Math.round(e.timeMs),n=t-Math.round(p);(!m||e.track===1&&e.key&&n>0||n>3e4)&&(h(),p=t,m=!0,e.track===1&&e.key&&u.push({timeMs:t,offset:d}));let r=new Uint8Array(4);r[0]=128|e.track,new DataView(r.buffer).setInt16(1,t-Math.round(p),!1),r[3]=e.key?128:0,f.push(A(163,k([r,e.data])))}h();let g=u.length?A(475249515,k(u.map(e=>A(187,k([j(179,e.timeMs),A(183,k([j(247,1),j(241,e.offset)]))]))))):new Uint8Array,_=A(408125543,k([a,s,...l,g]));return new Blob([i,_],{type:`video/webm`})}var Ie=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t<<24;for(let e=0;e<8;e++)n=n&2147483648?n<<1^79764919:n<<1;e[t]=n>>>0}return e})();function Le(e){let t=0;for(let n=0;n>>24^e[n])&255])>>>0;return t>>>0}function Re(e,t,n,r,i,a=!1){let o=[];for(let t of e){let e=t.length;for(;e>=255;)o.push(255),e-=255;o.push(e)}let s=e.reduce((e,t)=>e+t.length,0),c=new Uint8Array(27+o.length+s),l=new DataView(c.buffer);c.set(new TextEncoder().encode(`OggS`),0),c[4]=0,c[5]=t|+!!a,l.setBigUint64(6,BigInt(n),!0),l.setUint32(14,r,!0),l.setUint32(18,i,!0),c[26]=o.length,c.set(o,27);let u=27+o.length;for(let t of e)c.set(t,u),u+=t.length;return l.setUint32(22,Le(c),!0),c}function ze(e,t,n,r){let i=1178947139,a=[],o=Pe({sampleRate:r,channels:t,preSkip:n}),s=new TextEncoder().encode(`formencoder demo`),c=new Uint8Array(12+s.length+4),l=new DataView(c.buffer);c.set(new TextEncoder().encode(`OpusTags`),0),l.setUint32(8,s.length,!0),c.set(s,12),l.setUint32(12+s.length,0,!0),a.push(Re([o],2,0,i,0)),a.push(Re([c],0,0,i,1));let u=2,d=n,f=[],p=e.length;return e.forEach((e,t)=>{f.push(e),d+=e.samples;let n=t===p-1;(f.length>=40||n)&&(a.push(Re(f.map(e=>e.data),n?4:0,d,i,u++)),f=[])}),new Blob(a,{type:`audio/ogg`})}function Be(e,t){let n=t===16?32767:8388607,r=Math.max(-1,Math.min(1,e));return Math.round(r<0?r*(n+1):r*n)}function Ve(e,t,n){let r=e[0]?.length??0,i=e.length,a=n/8,o=r*i*a,s=new ArrayBuffer(44+o),c=new DataView(s),l=(e,t)=>{for(let n=0;n>8&255),c.setUint8(u+2,i>>16&255)),u+=a}return new Blob([s],{type:`audio/wav`})}function He(e,t,n){let r=e[0]?.length??0,i=e.length,a=n/8,o=r*i*a,s=new ArrayBuffer(54+o),c=new DataView(s),l=(e,t)=>{for(let n=0;n>16&255),c.setUint8(d+1,i>>8&255),c.setUint8(d+2,i&255)),d+=a}return new Blob([s],{type:`audio/aiff`})}var Ue=[[`match-source-high`,`Match Source - High bitrate`,`Web Video`,`h264`,null,null,null,20],[`match-source-medium`,`Match Source - Medium bitrate`,`Web Video`,`h264`,null,null,null,10],[`match-source-adaptive-high`,`Match Source - Adaptive High Bitrate`,`Web Video`,`h264`,null,null,null,null],[`hevc-match-source-high`,`HEVC Match Source - High bitrate`,`Web Video`,`hevc`,null,null,null,14],[`hevc-4k-hdr10`,`HEVC 4K HDR10 (Rec. 2100 PQ)`,`Web Video`,`hevc`,3840,2160,null,40],[`av1-match-source`,`AV1 Match Source`,`Web Video`,`av1`,null,null,null,null],[`webm-vp9-1080p`,`WebM VP9 1080p`,`Web Video`,`webm`,1920,1080,null,null],[`webm-vp9-alpha`,`WebM VP9 with Alpha`,`Web Video`,`webm`,null,null,null,null],[`youtube-1080p`,`YouTube 1080p Full HD`,`Social Media`,`h264`,1920,1080,null,16],[`youtube-1440p`,`YouTube 1440p 2K QHD`,`Social Media`,`h264`,2560,1440,null,24],[`youtube-2160p`,`YouTube 2160p 4K UHD`,`Social Media`,`h264`,3840,2160,null,45],[`youtube-shorts`,`YouTube Shorts 1080x1920`,`Social Media`,`h264`,1080,1920,null,16],[`vimeo-1080p`,`Vimeo 1080p Full HD`,`Social Media`,`h264`,1920,1080,null,20],[`vimeo-2160p`,`Vimeo 2160p 4K UHD`,`Social Media`,`h264`,3840,2160,null,50],[`x-1080p`,`X (Twitter) 1080p`,`Social Media`,`h264`,1920,1080,null,8],[`instagram-reels`,`Instagram Reels and Stories 1080x1920`,`Social Media`,`h264`,1080,1920,30,10],[`instagram-feed-square`,`Instagram Feed 1080x1080`,`Social Media`,`h264`,1080,1080,30,8],[`tiktok`,`TikTok 1080x1920`,`Social Media`,`h264`,1080,1920,null,10],[`facebook-1080p`,`Facebook 1080p`,`Social Media`,`h264`,1920,1080,null,10],[`linkedin-1080p`,`LinkedIn 1080p`,`Social Media`,`h264`,1920,1080,30,8],[`apple-tv-4k`,`Apple TV 4K (HEVC)`,`Devices`,`hevc`,3840,2160,null,25],[`iphone-1080p`,`Apple iPhone and iPad 1080p`,`Devices`,`h264`,1920,1080,null,10],[`android-1080p`,`Android Phone and Tablet 1080p`,`Devices`,`h264`,1920,1080,null,10],[`android-720p`,`Android Phone 720p`,`Devices`,`h264`,1280,720,null,5],[`prores-proxy`,`Apple ProRes 422 Proxy`,`Mezzanine`,`prores`,null,null,null,null],[`prores-lt`,`Apple ProRes 422 LT`,`Mezzanine`,`prores`,null,null,null,null],[`prores-422`,`Apple ProRes 422`,`Mezzanine`,`prores`,null,null,null,null],[`prores-hq`,`Apple ProRes 422 HQ`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444`,`Apple ProRes 4444`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444-alpha`,`Apple ProRes 4444 with Alpha`,`Mezzanine`,`prores`,null,null,null,null],[`prores-4444xq`,`Apple ProRes 4444 XQ`,`Mezzanine`,`prores`,null,null,null,null],[`dnxhr-lb`,`DNxHR LB`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-sq`,`DNxHR SQ`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-hq`,`DNxHR HQ`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-hqx`,`DNxHR HQX 10-bit`,`Mezzanine`,`quicktime`,null,null,null,null],[`dnxhr-444`,`DNxHR 444 10-bit`,`Mezzanine`,`quicktime`,null,null,null,null],[`cineform-high`,`GoPro CineForm YUV 10-bit`,`Mezzanine`,`cineform`,null,null,null,null],[`cineform-alpha`,`GoPro CineForm RGBA 12-bit with Alpha`,`Mezzanine`,`cineform`,null,null,null,null],[`animation-alpha`,`QuickTime Animation with Alpha`,`Mezzanine`,`quicktime`,null,null,null,null],[`uncompressed-10bit`,`Uncompressed 10-bit 4:2:2 (v210)`,`Mezzanine`,`quicktime`,null,null,null,null],[`xdcam-hd422-1080i50`,`XDCAM HD 422 1080i 25 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1920,1080,25,null],[`xdcam-hd422-1080i5994`,`XDCAM HD 422 1080i 29.97 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1920,1080,29.97,null],[`xdcam-hd422-720p50`,`XDCAM HD 422 720p 50 (50 Mb/s)`,`Broadcast`,`mxf_op1a`,1280,720,50,null],[`dnxhr-hq-mxf`,`DNxHR HQ MXF OP1a`,`Broadcast`,`dnxhr_mxf`,null,null,null,null],[`dnxhd-145-mxf`,`DNxHD 145 MXF OP1a 1080`,`Broadcast`,`dnxhr_mxf`,1920,1080,null,null],[`prores-hq-mxf`,`Apple ProRes 422 HQ MXF OP1a`,`Broadcast`,`prores_mxf`,null,null,null,null],[`jpeg2000-mxf`,`JPEG 2000 MXF OP1a`,`Broadcast`,`jpeg2000_mxf`,null,null,null,null],[`mpeg2-1080i`,`MPEG-2 1080i 29.97 Broadcast`,`Broadcast`,`mpeg2`,1920,1080,29.97,25],[`h264-broadcast-ebu`,`H.264 Broadcast, EBU R128 loudness`,`Broadcast`,`h264`,1920,1080,null,30],[`h264-broadcast-atsc`,`H.264 Broadcast, ATSC A/85 loudness`,`Broadcast`,`h264`,1920,1080,null,30],[`mpeg2-dvd-ntsc`,`NTSC DV Widescreen DVD`,`DVD`,`mpeg2_dvd`,720,480,29.97,6],[`bluray-mpeg2-1080i`,`Blu-ray MPEG-2 1080i 29.97`,`DVD`,`mpeg2_bluray`,1920,1080,29.97,25],[`bluray-h264-1080p24`,`Blu-ray H.264 1080p 23.976`,`DVD`,`h264_bluray`,1920,1080,23.976,25],[`as10-high-hd-1080i50`,`AS-10 HIGH_HD_2014 1080i 25`,`Broadcast`,`as10`,null,null,25,null],[`as10-high-hd-1080i5994`,`AS-10 HIGH_HD_2014 1080i 29.97`,`Broadcast`,`as10`,null,null,29.97,null],[`as11-mpeg2-1080i50`,`AS-11 OP1a MPEG-2 HD422 1080i 25`,`Broadcast`,`as11`,null,null,25,null],[`as11-d10-imx50-625`,`AS-11 D10 IMX 50 625 (UK DPP SD)`,`Broadcast`,`as11_d10`,null,null,null,null],[`p2-dvcprohd-1080i50`,`P2 DVCPRO HD 1080i 25`,`Broadcast`,`p2`,null,null,null,null],[`p2-dvcprohd-720p50`,`P2 DVCPRO HD 720p 50`,`Broadcast`,`p2`,null,null,null,null],[`dcp-2k-flat-24`,`DCP 2K Flat 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-2k-scope-24`,`DCP 2K Scope 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-2k-flat-24-interop`,`DCP 2K Flat 24 (Interop)`,`Cinema`,`dcp`,null,null,24,null],[`dcp-4k-flat-24`,`DCP 4K Flat 24 (SMPTE)`,`Cinema`,`dcp`,null,null,24,null],[`mpeg2-dvd-pal`,`PAL DV Widescreen DVD`,`DVD`,`mpeg2_dvd`,720,576,25,6],[`png-sequence`,`PNG Sequence`,`Image Sequence`,`png`,null,null,null,null],[`png-sequence-alpha`,`PNG Sequence with Alpha`,`Image Sequence`,`png`,null,null,null,null],[`tiff-sequence-16`,`TIFF Sequence 16-bit`,`Image Sequence`,`tiff`,null,null,null,null],[`dpx-sequence-10`,`DPX Sequence 10-bit`,`Image Sequence`,`dpx`,null,null,null,null],[`exr-sequence-half`,`OpenEXR Sequence (half float)`,`Image Sequence`,`exr`,null,null,null,null],[`jpeg-sequence`,`JPEG Sequence`,`Image Sequence`,`jpeg`,null,null,null,null],[`targa-sequence`,`Targa Sequence`,`Image Sequence`,`targa`,null,null,null,null],[`png-still`,`PNG Still (first frame of the range)`,`Image`,`png`,null,null,null,null],[`jpeg-still`,`JPEG Still`,`Image`,`jpeg`,null,null,null,null],[`gif-480`,`Animated GIF 480 px`,`Animated GIF`,`gif`,null,null,15,null],[`gif-720`,`Animated GIF 720 px`,`Animated GIF`,`gif`,null,null,20,null],[`wav-48-24`,`Waveform Audio 48 kHz 24-bit`,`Audio Only`,`wav`,null,null,null,null],[`wav-48-16`,`Waveform Audio 48 kHz 16-bit`,`Audio Only`,`wav`,null,null,null,null],[`bwf-ebu`,`Broadcast WAV, EBU R128 loudness`,`Audio Only`,`bwf`,null,null,null,null],[`aiff-48-24`,`AIFF 48 kHz 24-bit`,`Audio Only`,`aiff`,null,null,null,null],[`mp3-320`,`MP3 320 kb/s`,`Audio Only`,`mp3`,null,null,null,null],[`mp3-podcast`,`MP3 Podcast, -16 LUFS`,`Audio Only`,`mp3`,null,null,null,null],[`aac-256`,`AAC Audio 256 kb/s`,`Audio Only`,`aac`,null,null,null,null],[`aac-streaming`,`AAC Streaming, -14 LUFS`,`Audio Only`,`aac`,null,null,null,null],[`flac-48-24`,`FLAC 48 kHz 24-bit`,`Audio Only`,`flac`,null,null,null,null],[`ogg-opus`,`Ogg Opus 160 kb/s`,`Audio Only`,`ogg`,null,null,null,null],[`ffv1-archive`,`FFV1 Lossless Archive (Matroska)`,`Archive`,`matroska`,null,null,null,null],[`proxy-prores`,`ProRes Proxy, quarter size (proxy)`,`Proxy`,`prores`,960,540,null,null],[`proxy-h264-540`,`H.264 Proxy 960x540`,`Proxy`,`h264`,960,540,null,3],[`proxy-h264-720`,`H.264 Proxy 1280x720 (formcut)`,`Proxy`,`h264`,1280,720,null,5],[`proxy-cineform`,`CineForm Proxy 1280x720`,`Proxy`,`cineform`,1280,720,null,null],[`family-formcut-mezzanine`,`formcut mezzanine (ProRes 422 HQ)`,`Form Family`,`prores`,null,null,null,null],[`family-formwav-audio`,`formwav session audio (WAV 48 kHz 24-bit)`,`Form Family`,`wav`,null,null,null,null],[`family-formvis-stills`,`formvis stills (PNG Sequence)`,`Form Family`,`png`,null,null,null,null]],We=new Set([`h264`,`hevc`,`av1`,`webm`,`mpeg2`,`mpeg2_dvd`,`mpeg2_bluray`,`h264_bluray`,`matroska`]);function Ge(e,t){return e===`webm-vp9-alpha`||e===`ffv1-archive`?null:We.has(t)?`webm`:t===`gif`?`gif`:t===`wav`||t===`bwf`?`wav`:t===`aiff`?`aiff`:t===`ogg`?`ogg`:e===`png-still`?`png`:e===`jpeg-still`?`jpeg`:null}function Ke(e){if(/EBU R128/.test(e))return-23;if(/ATSC A\/85/.test(e))return-24;let t=/(-\d+) LUFS/.exec(e);return t?Number(t[1]):null}var N=Ue.map(([e,t,n,r,i,a,o,s])=>({id:e,name:t,category:n,format:r,width:i,height:a,fps:o,mbps:s,target:Ge(e,r),lufs:Ke(t),bits:/-16\b|16-bit/.test(t)?16:24})),P=new Map(N.map(e=>[e.id,e])),F={webm:`WebM`,gif:`GIF`,wav:`WAV`,aiff:`AIFF`,ogg:`Ogg Opus`,png:`PNG`,jpeg:`JPEG`},I={webm:`webm`,gif:`gif`,wav:`wav`,aiff:`aiff`,ogg:`opus`,png:`png`,jpeg:`jpg`},L={webm:`video/webm`,gif:`image/gif`,wav:`audio/wav`,aiff:`audio/aiff`,ogg:`audio/ogg`,png:`image/png`,jpeg:`image/jpeg`},qe={h264:`H.264`,hevc:`HEVC`,av1:`AV1`,webm:`WebM`,prores:`ProRes`,quicktime:`QuickTime`,cineform:`CineForm`,mxf_op1a:`MXF OP1a`,dnxhr_mxf:`DNx MXF`,prores_mxf:`ProRes MXF`,jpeg2000_mxf:`J2K MXF`,mpeg2:`MPEG-2`,mpeg2_dvd:`DVD`,mpeg2_bluray:`Blu-ray`,h264_bluray:`Blu-ray`,as10:`AS-10`,as11:`AS-11`,as11_d10:`AS-11 D10`,p2:`P2`,dcp:`DCP`,png:`PNG`,tiff:`TIFF`,dpx:`DPX`,exr:`EXR`,jpeg:`JPEG`,targa:`Targa`,gif:`GIF`,wav:`WAV`,bwf:`BWF`,aiff:`AIFF`,mp3:`MP3`,aac:`AAC`,flac:`FLAC`,ogg:`Ogg`,matroska:`Matroska`},Je=new Set([`wav`,`aiff`,`ogg`]);function Ye(e){return e.width&&e.height?`${e.width}x${e.height}`:``}function Xe(e){return e.fps?`${Number(e.fps.toFixed(3))}`:``}function Ze(e){return e.mbps?`${e.mbps} Mb/s`:``}var Qe=0,$e=()=>`src${++Qe}`,R=48e3;function et(e,t,n,r=8e3){return new Promise((i,a)=>{let o=window.setTimeout(()=>{l(),a(Error(`timed out waiting for ${t}`))},r),s=()=>{l(),i()},c=()=>{l(),a(Error(`the browser cannot decode this file`))},l=()=>{window.clearTimeout(o),e.removeEventListener(t,s),e.removeEventListener(n,c)};e.addEventListener(t,s),e.addEventListener(n,c)})}async function tt(e){if(Number.isFinite(e.duration))return e.duration;e.currentTime=1e101,await et(e,`durationchange`,`error`,4e3).catch(()=>void 0);let t=Number.isFinite(e.duration)?e.duration:0;return e.currentTime=0,t}async function nt(e){let t=e.requestVideoFrameCallback?.bind(e);if(!t)return 30;let n=[];return new Promise(r=>{let i=()=>{e.pause(),e.currentTime=0;let t=[];for(let e=1;en[e-1]&&t.push(n[e]-n[e-1]);t.sort((e,t)=>e-t);let i=1/(t.length?t[t.length>>1]:1/30),a=[12,15,23.976,24,25,29.97,30,50,59.94,60].reduce((e,t)=>Math.abs(t-i){n.push(r.mediaTime),n.length>=14?i():t(a)};t(a),e.muted=!0,e.play().catch(()=>i()),window.setTimeout(()=>{n.length<14&&i()},1500)})}async function rt(e,t){let n=URL.createObjectURL(e),r=document.createElement(`video`);r.muted=!0,r.preload=`auto`,r.playsInline=!0,r.src=n;try{await et(r,`loadedmetadata`,`error`)}catch(e){throw URL.revokeObjectURL(n),e}let i=await tt(r),a=r.videoWidth>0&&r.videoHeight>0,o=a?t??await nt(r):0;a&&await it(r,0);let s=null;return{id:$e(),name:e.name,kind:a?`video`:`audio`,sample:!1,size:e.size,width:r.videoWidth,height:r.videoHeight,fps:o,duration:i,async frame(e){return await it(r,Math.max(0,Math.min(e,Math.max(0,i-.001)))),r},audio(){return s||=(async()=>{if(e.size>629145600)return null;try{return await new OfflineAudioContext(2,1,R).decodeAudioData(await e.arrayBuffer())}catch{return null}})(),s},dispose(){r.removeAttribute(`src`),r.load(),URL.revokeObjectURL(n)}}}async function it(e,t){if(Math.abs(e.currentTime-t)<1e-4&&e.readyState>=2)return;let n=et(e,`seeked`,`error`,6e3);e.currentTime=t,await n}var at=640,ot=360,z=24,B=8;function st(){let e=R*B,t=new AudioBuffer({length:e,numberOfChannels:2,sampleRate:R}),n=t.getChannelData(0),r=t.getChannelData(1),i=[261.63,329.63,392,523.25,392,329.63,293.66,349.23],a=12345,o=()=>(a=a*1664525+1013904223>>>0,a/4294967296-.5);for(let t=0;t{e.fillStyle=t,e.fillRect(n/o.length*r,0,n/o.length+1,34)}),e.strokeStyle=`rgba(255,255,255,0.12)`,e.lineWidth=1;for(let i=-(t*40)%40;i=0;r--){let i=t-r*.035,a=n/2+Math.sin(i*1.7)*190,o=190+Math.cos(i*2.3)*70;e.fillStyle=`rgba(242, 84, 91, ${.9-r*.09})`,e.beginPath(),e.arc(a,o,26-r*1.6,0,Math.PI*2),e.fill()}e.strokeStyle=`rgba(255,255,255,0.8)`,e.lineWidth=3,e.beginPath(),e.arc(s,c,48,t*3,t*3+Math.PI*1.3),e.stroke();let l=.5+.5*Math.sin(t*6);e.fillStyle=`rgba(0,0,0,0.45)`,e.fillRect(18,300,604,14),e.fillStyle=`#f2545b`,e.fillRect(18,300,t/B*604,14),e.fillStyle=`rgba(255,255,255,${.5+l*.4})`,e.fillRect(18+t/B*604-2,296,4,22);let u=Math.floor(t*z),d=Math.floor(u/z),f=u%z;e.fillStyle=`#fff`,e.font=`600 44px ui-monospace, Menlo, monospace`,e.textBaseline=`alphabetic`,e.fillText(`00:00:${String(d).padStart(2,`0`)}:${String(f).padStart(2,`0`)}`,20,96),e.font=`500 15px system-ui, sans-serif`,e.fillStyle=`rgba(255,255,255,0.8)`,e.fillText(`formencoder sample · generated in this page · 640x360 · 24 fps`,20,344)}function lt(){let e=document.createElement(`canvas`);e.width=at,e.height=ot;let t=e.getContext(`2d`,{willReadFrequently:!1}),n=null;return{id:$e(),name:`formencoder-sample`,kind:`video`,sample:!0,size:0,width:at,height:ot,fps:z,duration:B,async frame(n){return ct(t,Math.max(0,Math.min(n,B))),e},async audio(){return n||=st(),n},dispose(){n=null}}}var ut=1280;function dt(e){return{size:`preset`,fps:null,mbps:null,codec:`auto`,audio:!0,lufs:e.lufs,start:0,end:null}}var V=e=>Math.max(2,Math.round(e/2)*2);function H(e,t,n){let r=Math.max(0,Math.min(n.start,e.duration)),i=Math.max(r+.05,Math.min(n.end??e.duration,e.duration)),a=e.width||640,o=e.height||360,s=!1,c=t.target===`gif`?Number(/(\d+) px/.exec(t.name)?.[1]??0):0;typeof n.size==`number`?(a=n.size,o=e.height/e.width*n.size):n.size===`preset`&&t.width&&t.height?(a=t.width,o=t.height,s=!0):n.size===`preset`&&c&&(a=c,o=e.height/e.width*c);let l=!1,u=Math.max(a,o);if(u>1280){let e=ut/u;a*=e,o*=e,l=!0}let d=V(a),f=V(o),p=d,m=f;if(s&&e.width&&e.height){let t=Math.min(d/e.width,f/e.height);p=V(e.width*t),m=V(e.height*t)}let h=n.fps??t.fps??(e.fps||30),g=Math.max(1,Math.min(60,t.target===`gif`?Math.min(h,25):h)),_=n.mbps??0;_||=t.mbps&&t.width&&t.height?t.mbps*(d*f/(t.width*t.height))*(g/(t.fps||30)):t.mbps?t.mbps*.25:.09*d*f*g/1e6,_=Math.max(.15,Math.min(14,_));let v=Math.max(1,Math.floor((i-r)*g));return{width:d,height:f,innerWidth:p,innerHeight:m,fps:g,mbps:_,start:r,end:i,frames:v,capped:l}}function ft(){let e=[];return e.push(typeof VideoEncoder>`u`?`VideoEncoder missing`:`VideoEncoder ready`),e.push(typeof AudioEncoder>`u`?`AudioEncoder missing`:`AudioEncoder ready`),e.join(`, `)}function U(e){if(e.aborted)throw new DOMException(`stopped`,`AbortError`)}function pt(){return new Promise(e=>window.setTimeout(e,0))}function mt(e,t,n,r,i){e.fillStyle=`#000`,e.fillRect(0,0,t.width,t.height);let a=(t.width-t.innerWidth)/2,o=(t.height-t.innerHeight)/2;e.drawImage(n,0,0,r,i,a,o,t.innerWidth,t.innerHeight)}function ht(e,t){return e instanceof HTMLVideoElement?{w:e.videoWidth,h:e.videoHeight}:e instanceof HTMLCanvasElement?{w:e.width,h:e.height}:{w:t.width,h:t.height}}async function gt(e,t){let n=await e.source.audio();if(!n)return null;let r=Math.floor(t.start*n.sampleRate),i=Math.min(n.length,Math.ceil(t.end*n.sampleRate)),a=[];for(let e=0;e=0?`+`:``}${t.gainDb.toFixed(1)} dB${t.limited?`, held at -1 dBTP`:``})`}else r=`Loudness ${O(i)}`;return{channels:n.channels,rate:n.rate,note:r}}async function yt(e,t,n,r){if(typeof AudioEncoder>`u`)throw Error(`this browser has no AudioEncoder`);if(t!==48e3)throw Error(`audio at ${t} Hz needs resampling; the demo expects ${R} Hz`);let i={codec:`opus`,sampleRate:R,numberOfChannels:e.length,bitrate:n};if(!(await AudioEncoder.isConfigSupported(i)).supported)throw Error(`Opus encoding is not available in this browser`);let a=[],o=null,s=new AudioEncoder({output:e=>{let t=new Uint8Array(e.byteLength);e.copyTo(t),a.push({data:t,timeUs:e.timestamp,samples:Math.round((e.duration??2e4)/1e6*R)})},error:e=>{o=e}});s.configure(i);let c=e[0].length;for(let t=0;ti.set(e.subarray(t,t+n),r*960));let a=new AudioData({format:`f32-planar`,sampleRate:R,numberOfFrames:960,numberOfChannels:e.length,timestamp:Math.round(t/R*1e6),data:i});s.encode(a),a.close(),s.encodeQueueSize>12&&await pt()}if(await s.flush(),s.close(),o)throw o;return a}async function bt(e){if(typeof VideoEncoder>`u`)throw Error(`this browser has no WebCodecs VideoEncoder`);let{source:t,preset:n,settings:r}=e;if(t.kind!==`video`)throw Error(`this source has no picture`);let i=H(t,n,r),a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`),s=r.codec===`vp8`?[`vp8`]:r.codec===`vp9`?[`vp09.00.10.08`]:[`vp09.00.10.08`,`vp8`],c=``,l=null;for(let e of s){let t={codec:e,width:i.width,height:i.height,bitrate:Math.round(i.mbps*1e6),framerate:i.fps,latencyMode:`quality`,bitrateMode:`variable`};if((await VideoEncoder.isConfigSupported(t)).supported){c=e,l=t;break}}if(!l)throw Error(`neither VP9 nor VP8 encoding is available in this browser`);let u=[],d=null,f=new VideoEncoder({output:e=>{let t=new Uint8Array(e.byteLength);e.copyTo(t),u.push({track:1,timeMs:e.timestamp/1e3,key:e.type===`key`,data:t})},error:e=>{d=e}});f.configure(l);let p=performance.now(),m=Math.max(1,Math.round(i.fps*2)),h=0;for(let n=0;n6;)await pt();let u=performance.now();u-h>160&&(h=u,e.onPreview(a));let g=(u-p)/1e3;e.onProgress({fraction:(n+1)/i.frames*.92,frame:n+1,frames:i.frames,message:`${((n+1)/Math.max(g,.001)).toFixed(1)} fps`})}if(await f.flush(),f.close(),e.onPreview(a),d)throw d;let g=i.capped?`Frame size capped at ${ut} px in the browser demo`:``,_=null;if(r.audio){e.onProgress({fraction:.93,frame:i.frames,frames:i.frames,message:`Encoding audio`});let t=await vt(e,i);if(t)try{let n=await yt(t.channels,t.rate,128e3,e.signal);for(let e of n)u.push({track:2,timeMs:e.timeUs/1e3,key:!0,data:e.data});_={sampleRate:R,channels:t.channels.length,preSkip:312},g=[g,t.note].filter(Boolean).join(`. `)}catch(e){g=[g,`Audio left out: ${e.message}`].filter(Boolean).join(`. `)}}return e.onProgress({fraction:.98,frame:i.frames,frames:i.frames,message:`Writing WebM`}),{blob:Fe({codec:c===`vp8`?`V_VP8`:`V_VP9`,width:i.width,height:i.height},_,u,(i.end-i.start)*1e3),ext:I.webm,mime:L.webm,encoder:`WebCodecs ${c===`vp8`?`VP8`:`VP9`}${_?` + Opus`:``} · ${i.width}x${i.height} · ${i.fps} fps · ${i.mbps.toFixed(1)} Mb/s`,note:g}}async function xt(e){let{source:t,preset:n,settings:r}=e;if(t.kind!==`video`)throw Error(`this source has no picture`);let i=H(t,n,r),a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`,{willReadFrequently:!0}),s=new ve(i.width,i.height),c=Math.max(2,Math.round(100/i.fps));for(let n=0;n({data:e.data,samples:e.samples})),a.channels.length,312,a.rate),ext:I.ogg,mime:L.ogg,encoder:`WebCodecs Opus · ${a.channels.length} ch · 160 kb/s`,note:a.note}:{blob:t===`aiff`?He(a.channels,a.rate,r.bits):Ve(a.channels,a.rate,r.bits),ext:I[t],mime:L[t],encoder:`PCM ${r.bits}-bit · ${a.rate} Hz · ${a.channels.length} ch`,note:a.note}}async function Ct(e,t){let{source:n,preset:r,settings:i}=e;if(n.kind!==`video`)throw Error(`this source has no picture`);let a=H(n,r,i),o=document.createElement(`canvas`);o.width=a.width,o.height=a.height;let s=o.getContext(`2d`),c=await n.frame(a.start),l=ht(c,n);return mt(s,a,c,l.w,l.h),e.onPreview(o),{blob:await new Promise((e,n)=>o.toBlob(t=>t?e(t):n(Error(`the canvas could not be saved`)),L[t],.92)),ext:I[t],mime:L[t],encoder:`${t.toUpperCase()} still · ${a.width}x${a.height}`,note:``}}async function wt(e){let t=e.preset.target;if(!t)throw Error(`needs the desktop engine`);return t===`webm`?bt(e):t===`gif`?xt(e):Je.has(t)?St(e,t):Ct(e,t)}function Tt(e){return e==null||!Number.isFinite(e)?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function Et(e){if(e==null||!Number.isFinite(e)||e<0)return`--:--`;let t=Math.round(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n?`${n}:${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`:`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`}function Dt(e){return!e||!Number.isFinite(e)?``:e<60?`${e.toFixed(e<10?2:1)} s`:Et(e)}var Ot={ready:`Ready`,preparing:`Preparing`,encoding:`Encoding`,paused:`Paused`,done:`Done`,failed:`Failed`,stopped:`Stopped`,skipped:`Skipped`},W=new TextDecoder(`latin1`);async function G(e,t,n){let r=await e.slice(t,t+n).arrayBuffer();return new DataView(r)}var K=(e,t)=>W.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),kt={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},At={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},jt={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function Mt(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=K(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=K(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=K(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=K(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${kt[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=K(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=Mt(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:Nt(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Pt(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:jt[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function It(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await G(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function Vt(e){let t=await G(e,0,Math.min(e.size,64));if(t.byteLength<26||K(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Ht=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Ut=[44100,48e3,32e3];async function Wt(e){let t=await G(e,0,Math.min(e.size,65536)),n=0;if(K(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Ht[t.getUint8(r+2)>>4],o=Ut[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Gt(e){let t=[Ft,Rt,zt,Bt,Vt,Wt];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Kt=[{pack:`open-water`,file:`open-water-1280x720-30fps.mp4`,mime:`video/mp4`,kind:`video`,width:1280,height:720,fps:29.97,duration:8.008,bytes:6819433,outputs:[{preset:`match-source-medium`},{preset:`gif-480`},{preset:`png-still`}]},{pack:`coast-aerial`,file:`coast-aerial-1280x720-25fps.mp4`,mime:`video/mp4`,kind:`video`,width:1280,height:720,fps:25,duration:7,bytes:6637734,outputs:[{preset:`match-source-medium`},{preset:`gif-480`}]},{pack:`shoreline-vertical`,file:`shoreline-vertical-404x720-60fps.mp4`,mime:`video/mp4`,kind:`video`,width:404,height:720,fps:59.94,duration:7.858,bytes:4235966,outputs:[{preset:`match-source-medium`},{preset:`gif-480`,size:`source`}]},{pack:`on-the-sea-reading`,file:`on-the-sea-reading.mp3`,mime:`audio/mpeg`,kind:`audio`,width:0,height:0,fps:0,duration:21.133,bytes:211755,outputs:[{preset:`ogg-opus`,lufs:-16},{preset:`bwf-ebu`},{preset:`wav-48-24`}]}];function qt(){let e=window;return e.FE_MEDIA||={},e.FE_MEDIA}function Jt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}async function Yt(e){await Jt(e.pack);let t=qt(),n=t[e.file];if(delete t[e.file],!n)throw Error(`the media pack ${e.pack} holds no ${e.file}`);let r=atob(n),i=new Uint8Array(r.length);for(let e=0;ePromise.reject(Error(`the source is still loading`)),audio:()=>Promise.resolve(null),dispose:()=>void 0}}var Qt=0,q=new class{items=[];selectedItem=``;selectedOutput=``;running=!1;logs=[];listeners=new Map;abort=null;previews=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e)?.add(t)}emit(e,t){for(let n of this.listeners.get(e)??[])n(t)}log(e,t=!1){let n=new Date,r=[n.getHours(),n.getMinutes(),n.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`);this.logs.push({time:r,text:e,error:t}),this.logs.length>400&&this.logs.shift(),this.emit(`log`)}previewFor(e){return this.previews.get(e)}item(e){return this.items.find(t=>t.id===e)}outputOf(e){for(let t of this.items){let n=t.outputs.find(t=>t.id===e);if(n)return{item:t,output:n}}}select(e,t=``){(this.selectedItem!==e||this.selectedOutput!==t)&&(this.selectedItem=e,this.selectedOutput=t,this.emit(`select`))}makeOutput(e){let t=P.get(e);if(!t)throw Error(`unknown preset ${e}`);return{id:`out${++Qt}`,presetId:e,settings:dt(t),status:`ready`,progress:0,message:``,encoder:``,note:``,blob:null,mime:``,fileName:``,elapsed:0,fps:0,frame:0,frames:0,eta:0,speed:0}}stem(e){return e.source.name.replace(/\.[^.]+$/,``).replace(/[^A-Za-z0-9._-]+/g,`_`)||`source`}nameFor(e,t){let n=P.get(t.presetId),r=n?.target?I[n.target]:`out`;return`${this.stem(e)}_${t.presetId}.${r}`}addOutput(e,t){let n=this.item(e);if(!n)return;let r=this.makeOutput(t);return r.fileName=this.nameFor(n,r),n.outputs.push(r),n.collapsed=!1,this.log(`Added output ${P.get(t)?.name??t} to ${n.source.name}`),this.emit(`items`),r}async addSource(e,t){let n={id:e.id,source:e,probe:{container:``,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[]},loudness:null,loudnessState:`pending`,poster:null,outputs:[],collapsed:!1,loading:!1};this.items.push(n);for(let e of t){let t=this.makeOutput(e);t.fileName=this.nameFor(n,t),n.outputs.push(t)}return this.selectedItem=n.id,this.selectedOutput=``,this.log(`Added source ${e.name}`),this.emit(`items`),this.emit(`select`),n}async analyse(e,t){if(e.probe=t?await Gt(t):{container:`generated in this page (no file)`,duration:e.source.duration,size:0,bitrate:null,video:{codec:`canvas RGB`,profile:``,width:e.source.width,height:e.source.height,fps:e.source.fps,frames:Math.round(e.source.duration*e.source.fps),bitrate:null,pixels:`rgb24`},audio:[{codec:`PCM f32 (synthesised)`,sampleRate:48e3,channels:2,bitDepth:32,bitrate:null}],notes:[]},e.source.kind===`video`)try{let t=await e.source.frame(Math.min(1,e.source.duration/2)),n=document.createElement(`canvas`);n.width=640,n.height=Math.max(2,Math.round(640*e.source.height/e.source.width)),n.getContext(`2d`)?.drawImage(t,0,0,n.width,n.height),e.poster=n}catch(e){this.log(`No preview frame: ${e.message}`,!0)}this.emit(`items`),this.emit(`select`);try{let t=await e.source.audio();if(!t)e.loudnessState=`none`;else{e.probe.audio.length||e.probe.audio.push({codec:`decoded by the browser`,sampleRate:t.sampleRate,channels:t.numberOfChannels,bitDepth:null,bitrate:null}),await new Promise(e=>window.setTimeout(e,0));let n=[];for(let e=0;e{let r=this.addCuratedRow(t);e.push({item:r,index:n})}),this.selectedItem=e[0].item.id,this.emit(`select`);let t=0;for(let{item:n,index:r}of e){let e=Kt[r];try{let r=await Yt(e),i=await rt(r,e.fps||null);i.id=n.id,n.source.dispose(),n.source=i,n.loading=!1,this.emit(`items`),await this.analyse(n,r),t++}catch(t){this.log(`Could not load ${e.file}: ${t.message}`,!0),this.items=this.items.filter(e=>e.id!==n.id),this.selectedItem===n.id&&(this.selectedItem=this.items[0]?.id??``),this.emit(`items`),this.emit(`select`)}}t||(this.log(`The curated media did not load; adding the built-in sample instead`,!0),await this.addSample())}addCuratedRow(e){let t=Zt(e),n={id:t.id,source:t,probe:{container:``,duration:e.duration,size:e.bytes,bitrate:null,video:null,audio:[],notes:[]},loudness:null,loudnessState:`pending`,poster:null,outputs:[],collapsed:!1,loading:!0};this.items.push(n);for(let t of e.outputs){let e=this.makeOutput(t.preset);t.lufs!==void 0&&(e.settings.lufs=t.lufs),t.size&&(e.settings.size=t.size),e.fileName=this.nameFor(n,e),n.outputs.push(e)}return this.log(`Added source ${e.file}`),this.emit(`items`),n}async addSample(){let e=lt(),t=await this.addSource(e,[`match-source-medium`,`gif-480`,`bwf-ebu`]);await this.analyse(t,null)}removeSelected(){if(!this.running){if(this.selectedOutput){let e=this.outputOf(this.selectedOutput);e&&(e.item.outputs=e.item.outputs.filter(e=>e.id!==this.selectedOutput),this.selectedOutput=``)}else this.selectedItem&&=(this.item(this.selectedItem)?.source.dispose(),this.items=this.items.filter(e=>e.id!==this.selectedItem),this.items[0]?.id??``);this.emit(`items`),this.emit(`select`)}}resetOutput(e){e.status=`ready`,e.progress=0,e.message=``,e.blob=null,e.note=``,e.encoder=``,this.emit(`items`)}async start(){if(this.running)return;let e=[];for(let t of this.items)for(let n of t.outputs)(!t.loading&&n.status===`ready`||n.status===`failed`||n.status===`stopped`)&&e.push({item:t,out:n});if(!e.length)this.log(`Nothing to encode: every output is done`);else{this.running=!0,this.abort=new AbortController,this.emit(`run`),this.log(`Queue started: ${e.length} output${e.length===1?``:`s`}`);for(let{item:t,out:n}of e){if(this.abort.signal.aborted)break;await this.runOne(t,n,this.abort.signal)}this.running=!1,this.abort=null,this.log(`Queue finished`),this.emit(`run`)}}stop(){this.abort?.abort()}async runOne(e,t,n){let r=P.get(t.presetId);if(!r)return;if(!r.target){t.status=`skipped`,t.message=`Needs the desktop engine`,this.log(`Skipped ${t.fileName}: ${r.name} needs the desktop engine`),this.emit(`progress`,t);return}t.status=`preparing`,t.progress=0,t.message=`Preparing`,t.blob=null,t.note=``,this.emit(`progress`,t);let i=performance.now();this.log(`Encoding ${t.fileName} with ${r.name}`);try{let a=()=>{let e=this.previews.get(t.id);return e||(e=document.createElement(`canvas`),this.previews.set(t.id,e)),e},o=await wt({source:e.source,preset:r,settings:t.settings,signal:n,onProgress:n=>{let r=(performance.now()-i)/1e3;t.status=`encoding`,t.progress=n.fraction,t.frame=n.frame,t.frames=n.frames,t.elapsed=r,t.eta=n.fraction>.02?r/n.fraction*(1-n.fraction):0,t.fps=r>0?n.frame/r:0,t.speed=r>0&&e.source.fps?n.frame/e.source.fps/r:0,t.message=n.message,this.emit(`progress`,t)},onPreview:e=>{let n=a();(n.width!==e.width||n.height!==e.height)&&(n.width=e.width,n.height=e.height),n.getContext(`2d`)?.drawImage(e,0,0),this.emit(`progress`,t)}});t.blob=o.blob,t.mime=o.mime,t.fileName=t.fileName.replace(/\.[^.]+$/,`.${o.ext}`),t.encoder=o.encoder,t.note=o.note,t.status=`done`,t.progress=1,t.elapsed=(performance.now()-i)/1e3,t.eta=0,t.message=Tt(o.blob.size),this.log(`Done ${t.fileName}: ${o.encoder}${o.note?`. `+o.note:``}`)}catch(e){let n=e;n.name===`AbortError`?(t.status=`stopped`,t.message=`Stopped`,this.log(`Stopped ${t.fileName}`)):(t.status=`failed`,t.message=n.message,this.log(`Failed ${t.fileName}: ${n.message}`,!0))}this.emit(`progress`,t),this.emit(`items`)}},$t=new WeakMap;function J(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout($t.get(a)),$t.set(a,window.setTimeout(()=>a.remove(),r));return}let o=s(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();$t.set(o,window.setTimeout(()=>o.remove(),r))}var en=null,tn,nn,rn=``;function an(){let e=new _(`Preview`,760);return tn=s(`
`),nn=s(`

`),e.body.appendChild(tn),e.body.appendChild(nn),e.button(`Save`,`ghost`,()=>{rn&&on(rn)}),e.button(`Close`,`primary`,()=>e.close()),e.onClose=()=>{tn.replaceChildren(),rn=``},e}function on(e){let t=q.outputOf(e);if(!t?.output.blob){J(`This output has not been encoded yet`);return}let n=URL.createObjectURL(t.output.blob),r=document.createElement(`a`);r.href=n,r.download=t.output.fileName,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>URL.revokeObjectURL(n),4e3)}function sn(e){let n=q.outputOf(e);if(!n?.output.blob){J(`This output has not been encoded yet`);return}en??=an();let{output:r}=n,i=URL.createObjectURL(n.output.blob),a;r.mime.startsWith(`video/`)?(a=s(``),a.src=i):r.mime.startsWith(`audio/`)?(a=s(``),a.src=i):(a=s(``),a.src=i),tn.replaceChildren(a),rn=e,en.setTitle(r.fileName),t(nn,[r.encoder,r.note].filter(Boolean).join(`. `)),en.open(c(en.scrim,`.cv-btn-primary`))}var cn=class{id=`encoding`;title=`Encoding`;el;list;constructor(){this.el=s(`
${h(`film`,26)}Nothing has run yet. Press Start in the Queue.
diff --git a/demos/broadcast/assets/broadcast.js b/demos/broadcast/assets/broadcast.js index f1b7e61..44fe969 100644 --- a/demos/broadcast/assets/broadcast.js +++ b/demos/broadcast/assets/broadcast.js @@ -10,7 +10,7 @@
-
`),this.areas=Object.fromEntries(ot.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,n=>{n.preventDefault(),e.setPointerCapture(n.pointerId),k(e,`is-dragging`,!0);let r={x:n.clientX,y:n.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},i=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,r.l+e.clientX-r.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,r.r-(e.clientX-r.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,r.b-(e.clientY-r.y)))),this.applySizes()},a=()=>{k(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,i),e.removeEventListener(`pointerup`,a),this.save()};e.addEventListener(`pointermove`,i),e.addEventListener(`pointerup`,a)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,n=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${n}px`),k(this.el,`no-left`,!e),k(this.el,`no-right`,!t),k(this.el,`no-bottom`,!n);for(let e of at){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ot){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new st(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(R);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??L[e]??L.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(R),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(R,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(R)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(R)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??L[e]??L.Default,e),this.save()}resetWorkspace(){this.applyLayout(L[this.workspace]??L.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(R)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(R,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ot)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new st(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,k(this.el,`is-maximized`,!1),k(e.el,`is-max`,!1)):(this.maximized&&k(this.maximized.el,`is-max`,!1),this.maximized=e,k(this.el,`is-maximized`,!0),k(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&k(t.el,`is-focused`,!1),this.focused=e;let n=this.find(e);n&&k(n.el,`is-focused`,!0),this.onFocus?.(e)}},lt={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},ut=`studio`,dt=`#f2545b`,ft=`formencoder_ui_settings`,pt=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function mt(){try{let e=localStorage.getItem(ft);if(e){let t=JSON.parse(e);return{theme:t.theme&<[t.theme]?t.theme:ut,accentColor:t.accentColor||`#f2545b`,intensity:pt(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:ut,accentColor:dt,intensity:1}}function ht(e){try{let t=localStorage.getItem(ft),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(ft,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function gt(e=mt()){let t=document.documentElement,n=lt[e.theme]||lt.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(pt(e.intensity))),t.style.setProperty(`--accent-tint`,vt(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,vt(e.accentColor,.1))}function _t(e){let t={...mt(),theme:e};ht(t),gt(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function vt(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var yt=new WeakMap;function bt(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout(yt.get(a)),yt.set(a,window.setTimeout(()=>a.remove(),r));return}let o=A(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();yt.set(o,window.setTimeout(()=>o.remove(),r))}var xt=`0.9.0`;function St(e){let t=.7071752369554196,n=Math.tan(Math.PI*1681.974450955533/e),r=10**(3.999843853973347/20),i=r**.4996667741545416,a=1+n/t+n*n;return{b0:(r+i*n/t+n*n)/a,b1:2*(n*n-r)/a,b2:(r-i*n/t+n*n)/a,a1:2*(n*n-1)/a,a2:(1-n/t+n*n)/a}}function Ct(e){let t=.5003270373238773,n=Math.tan(Math.PI*38.13547087602444/e),r=1+n/t+n*n;return{b0:1,b1:-2,b2:1,a1:2*(n*n-1)/r,a2:(1-n/t+n*n)/r}}function wt(e,t){let n=St(t),r=Ct(t),i=new Float64Array(e.length),a=0,o=0,s=0,c=0;for(let t=0;te>0?-.691+10*Math.log10(e):-1/0,Et=e=>e>0?20*Math.log10(e):-1/0;function Dt(e,t,n){let r=0;for(let i=-7;i<=8;i++){let a=t+i;if(a<0||a>=e.length)continue;let o=i-n,s=Math.abs(o)<1e-9?1:Math.sin(Math.PI*o)/(Math.PI*o);r+=e[a]*s*(.5+.5*Math.cos(Math.PI*o/9))}return r}function Ot(e){let t=0;for(let n of e)for(let e=0;et&&(t=r)}let n=t,r=t*.5;for(let t of e)for(let e=0;en&&(n=i)}return{sample:t,truePeak:n}}function kt(e,t){let n=(e.length-1)*t,r=Math.floor(n),i=Math.min(e.length-1,r+1);return e[r]+(e[i]-e[r])*(n-r)}function At(e,t){let n=new Float32Array(e.length).fill(NaN),r=0;for(let i=0;i=t&&(r-=e[i-t]),i>=t-1&&(n[i]=Tt(r/t));return n}function z(e,t){let n=e[0]?.length??0,r=Math.round(t*.1),i=Math.floor(n/r),a=new Float64Array(i);for(let n of e){let e=wt(n,t);for(let t=0;t10**((e+.691)/10),l=Array.from(o).filter(e=>Number.isFinite(e)&&e>-70),u=-1/0;if(l.length){let e=Tt(l.reduce((e,t)=>e+c(t),0)/l.length)-10,t=l.filter(t=>t>e);t.length&&(u=Tt(t.reduce((e,t)=>e+c(t),0)/t.length))}let d=Array.from(s).filter(e=>Number.isFinite(e)&&e>-70),f=0;if(d.length){let e=Tt(d.reduce((e,t)=>e+c(t),0)/d.length)-20,t=d.filter(t=>t>e).sort((e,t)=>e-t);t.length&&(f=kt(t,.95)-kt(t,.1))}let p=Ot(e),m=e=>e.reduce((e,t)=>Number.isFinite(t)&&t>e?t:e,-1/0);return{integrated:u,lra:f,samplePeak:Et(p.sample),truePeak:Et(p.truePeak),momentary:o,short:s,momentaryMax:m(o),shortMax:m(s),step:.1,duration:n/t}}function B(e,t=1){let n=Number(e.toFixed(t));return`${n>0?`+`:``}${n.toFixed(t)}`}function V(e,t=1){return Number.isFinite(e)?e.toFixed(t):`-inf`}function jt(){let e=window;return e.FE_MEDIA||={},e.FE_MEDIA}function Mt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}async function Nt(e){await Mt(e.pack);let t=jt(),n=t[e.file];if(delete t[e.file],!n)throw Error(`the media pack ${e.pack} holds no ${e.file}`);let r=atob(n),i=new Uint8Array(r.length);for(let e=0;ePt.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),Ft={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},It={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},Lt={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function Rt(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=U(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=U(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=U(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=U(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${Ft[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=U(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=Rt(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:zt(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Bt(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:Lt[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function Ht(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await H(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function qt(e){let t=await H(e,0,Math.min(e.size,64));if(t.byteLength<26||U(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Jt=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Yt=[44100,48e3,32e3];async function Xt(e){let t=await H(e,0,Math.min(e.size,65536)),n=0;if(U(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Jt[t.getUint8(r+2)>>4],o=Yt[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Zt(e){let t=[Vt,Wt,Gt,Kt,qt,Xt];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Qt=`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAACa7klEQVR42u39aZgt2XUdBq59Iu6Uw5vrvRoeUKhCASBATCIBkBRFgDMJUpIhCqJEUaREkZJMWa22P8ndn9WDZXf7k9vdbbcttU1qFk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8wDMTPay3COpgMRLBYBdGAyudL2tc0xlEzMiBYwBhntLnqcpEyWeKwVmKK/stA+0pmz5rMz1K7vA3bcjFpIEJUdrOJbBw1zLHtv8Xdz0YnvYuTtgAMx6nxpnq8hSJl1JoXN0aS9e7L1lvQNR136s3i14+Zewt8Jnb4mejnZ96Ob2/lXf8wBQAtG/ADgcQJ5FdfZAp98d/191Q8j/EMTIwHShplnMV06n8fHTdSb/Di9kbEXy3uT+b7VMrvVlnwmXCykos89/4t6/tcsfG6ZXd9HNKbVWYBmsioXyakYqHLwCB/XwePxMsQ6uclJQhEZtuOFv4+C5UF8N7SRP2uAGAjnBL5JVP2zPt3pvxcpvdFZOEfqJLv79cAoJUFUMoDGRQSz5Uo9RZ7ogQRf/GbjsVPtziYym/SINLhHx64mdqOr1wJCrmXzvtfVknzcRjS/TdLAMCChSi5BL4AadqR6ieRlN8sWPS079G63z9pf5ebIC03PtQpBxwLAloW4M+X+KVAoezqfubgL/Il7JCPAsAbGQxICQpaWt9V72tfvIRWFi/p2kH7rJlv5G+WI8e/Nt5PVxp/M4IOd5QEVskO/GAgvxdK8HjTLHq8yetW6qjRu75MpL6PPc9BX78bpdq8GVP/ZYPaMkbmsVKBOxb3m2rR4/cRcEUdi5YWPA4duzwdgX63ZBDgJX4eyxa6ggm/2RfI77eja8G/GbolfAQmdp7zogX/+24hHB2vbxDoSt9vtH5fxKtdBKS9lvOmJbRIDkor8qADwNFxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx614/P8BURHlBMXY6sIAAAAASUVORK5CYII=`,$t=`1 +
`),this.areas=Object.fromEntries(ot.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,n=>{n.preventDefault(),e.setPointerCapture(n.pointerId),k(e,`is-dragging`,!0);let r={x:n.clientX,y:n.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},i=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,r.l+e.clientX-r.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,r.r-(e.clientX-r.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,r.b-(e.clientY-r.y)))),this.applySizes()},a=()=>{k(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,i),e.removeEventListener(`pointerup`,a),this.save()};e.addEventListener(`pointermove`,i),e.addEventListener(`pointerup`,a)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,n=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${n}px`),k(this.el,`no-left`,!e),k(this.el,`no-right`,!t),k(this.el,`no-bottom`,!n);for(let e of at){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ot){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new st(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(R);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??L[e]??L.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(R),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(R,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(R)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(R)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??L[e]??L.Default,e),this.save()}resetWorkspace(){this.applyLayout(L[this.workspace]??L.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(R)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(R,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ot)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new st(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,k(this.el,`is-maximized`,!1),k(e.el,`is-max`,!1)):(this.maximized&&k(this.maximized.el,`is-max`,!1),this.maximized=e,k(this.el,`is-maximized`,!0),k(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&k(t.el,`is-focused`,!1),this.focused=e;let n=this.find(e);n&&k(n.el,`is-focused`,!0),this.onFocus?.(e)}},lt={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},ut=`studio`,dt=`#f2545b`,ft=`formencoder_ui_settings`,pt=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function mt(){try{let e=localStorage.getItem(ft);if(e){let t=JSON.parse(e);return{theme:t.theme&<[t.theme]?t.theme:ut,accentColor:t.accentColor||`#f2545b`,intensity:pt(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:ut,accentColor:dt,intensity:1}}function ht(e){try{let t=localStorage.getItem(ft),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(ft,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function gt(e=mt()){let t=document.documentElement,n=lt[e.theme]||lt.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(pt(e.intensity))),t.style.setProperty(`--accent-tint`,vt(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,vt(e.accentColor,.1))}function _t(e){let t={...mt(),theme:e};ht(t),gt(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function vt(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var yt=new WeakMap;function bt(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout(yt.get(a)),yt.set(a,window.setTimeout(()=>a.remove(),r));return}let o=A(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();yt.set(o,window.setTimeout(()=>o.remove(),r))}var xt=`0.10.0`;function St(e){let t=.7071752369554196,n=Math.tan(Math.PI*1681.974450955533/e),r=10**(3.999843853973347/20),i=r**.4996667741545416,a=1+n/t+n*n;return{b0:(r+i*n/t+n*n)/a,b1:2*(n*n-r)/a,b2:(r-i*n/t+n*n)/a,a1:2*(n*n-1)/a,a2:(1-n/t+n*n)/a}}function Ct(e){let t=.5003270373238773,n=Math.tan(Math.PI*38.13547087602444/e),r=1+n/t+n*n;return{b0:1,b1:-2,b2:1,a1:2*(n*n-1)/r,a2:(1-n/t+n*n)/r}}function wt(e,t){let n=St(t),r=Ct(t),i=new Float64Array(e.length),a=0,o=0,s=0,c=0;for(let t=0;te>0?-.691+10*Math.log10(e):-1/0,Et=e=>e>0?20*Math.log10(e):-1/0;function Dt(e,t,n){let r=0;for(let i=-7;i<=8;i++){let a=t+i;if(a<0||a>=e.length)continue;let o=i-n,s=Math.abs(o)<1e-9?1:Math.sin(Math.PI*o)/(Math.PI*o);r+=e[a]*s*(.5+.5*Math.cos(Math.PI*o/9))}return r}function Ot(e){let t=0;for(let n of e)for(let e=0;et&&(t=r)}let n=t,r=t*.5;for(let t of e)for(let e=0;en&&(n=i)}return{sample:t,truePeak:n}}function kt(e,t){let n=(e.length-1)*t,r=Math.floor(n),i=Math.min(e.length-1,r+1);return e[r]+(e[i]-e[r])*(n-r)}function At(e,t){let n=new Float32Array(e.length).fill(NaN),r=0;for(let i=0;i=t&&(r-=e[i-t]),i>=t-1&&(n[i]=Tt(r/t));return n}function z(e,t){let n=e[0]?.length??0,r=Math.round(t*.1),i=Math.floor(n/r),a=new Float64Array(i);for(let n of e){let e=wt(n,t);for(let t=0;t10**((e+.691)/10),l=Array.from(o).filter(e=>Number.isFinite(e)&&e>-70),u=-1/0;if(l.length){let e=Tt(l.reduce((e,t)=>e+c(t),0)/l.length)-10,t=l.filter(t=>t>e);t.length&&(u=Tt(t.reduce((e,t)=>e+c(t),0)/t.length))}let d=Array.from(s).filter(e=>Number.isFinite(e)&&e>-70),f=0;if(d.length){let e=Tt(d.reduce((e,t)=>e+c(t),0)/d.length)-20,t=d.filter(t=>t>e).sort((e,t)=>e-t);t.length&&(f=kt(t,.95)-kt(t,.1))}let p=Ot(e),m=e=>e.reduce((e,t)=>Number.isFinite(t)&&t>e?t:e,-1/0);return{integrated:u,lra:f,samplePeak:Et(p.sample),truePeak:Et(p.truePeak),momentary:o,short:s,momentaryMax:m(o),shortMax:m(s),step:.1,duration:n/t}}function B(e,t=1){let n=Number(e.toFixed(t));return`${n>0?`+`:``}${n.toFixed(t)}`}function V(e,t=1){return Number.isFinite(e)?e.toFixed(t):`-inf`}function jt(){let e=window;return e.FE_MEDIA||={},e.FE_MEDIA}function Mt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}async function Nt(e){await Mt(e.pack);let t=jt(),n=t[e.file];if(delete t[e.file],!n)throw Error(`the media pack ${e.pack} holds no ${e.file}`);let r=atob(n),i=new Uint8Array(r.length);for(let e=0;ePt.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),Ft={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},It={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},Lt={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function Rt(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=U(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=U(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=U(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=U(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${Ft[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=U(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=Rt(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:zt(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Bt(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:Lt[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function Ht(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await H(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function qt(e){let t=await H(e,0,Math.min(e.size,64));if(t.byteLength<26||U(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Jt=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Yt=[44100,48e3,32e3];async function Xt(e){let t=await H(e,0,Math.min(e.size,65536)),n=0;if(U(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Jt[t.getUint8(r+2)>>4],o=Yt[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Zt(e){let t=[Vt,Wt,Gt,Kt,qt,Xt];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Qt=`data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAACa7klEQVR42u39aZgt2XUdBq59Iu6Uw5vrvRoeUKhCASBATCIBkBRFgDMJUpIhCqJEUaREkZJMWa22P8ndn9WDZXf7k9vdbbcttU1qFkXZ1mdJptykKFIkAYKYUShUFQo1z1Wv6s053ykizu4fMe1zzj5xb76qfPWymIEvka8yb94bN26cffZee+21gKPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODqOjqPj6Dg6jo6j4+g4Oo6Oo+PoODpu6kFHl2Dp63F0rQ7XwTf4u6Mb/vfJ+yblGtBRQDjUC54ii5s7/pvFdz4KAG/O90fKvwm4j+6+O6OiKJrrIP9trSVrLRljGAAuXQKAS0eL/5YOAudw7lz7+RljuP78ACBJEuffL7zQY+BpFgFACwh8FAAO3+4uF725G3cb3A30ej1++umnCwCF98Ea8TfGey4DIKm+G++5l7mmLH7Ob/AO6e+W9BquM0f+m16n19hP+l4vWFt9FdV3uZCt9zh57sl9992XZFlGeAF4AS9Y8RgtQBwFgFt40RMAc/78eTMcDu3TTz+dVR8mAVgFcGY4XL/j9Okz5/v90dnV0cpbjUnX0jQZkTE9Q0gJMIAhIgIzJwBSBidgNkRkAAJ71894d5W6TLzDlL9mf/k0K4er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gJX4eyxa6ggm/2RfI77eja8G/GbolfAQmdp7zogX/+24hHB2vbxDoSt9vtH5fxKtdBKS9lvOmJbRIDkor8qADwNFxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx9FxdBwdR8fRcXQcHUfH0XF0HB1Hx614/P8BURHlBMXY6sIAAAAASUVORK5CYII=`,$t=`1 00:00:00,340 --> 00:00:03,850 She was fastened by a light chain to one of the seats on deck, diff --git a/demos/inspect/assets/inspect.js b/demos/inspect/assets/inspect.js index 1c5dea9..4bd0a15 100644 --- a/demos/inspect/assets/inspect.js +++ b/demos/inspect/assets/inspect.js @@ -10,7 +10,7 @@
-
`),this.areas=Object.fromEntries(ae.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,r=>{r.preventDefault(),e.setPointerCapture(r.pointerId),n(e,`is-dragging`,!0);let i={x:r.clientX,y:r.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},a=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,i.l+e.clientX-i.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,i.r-(e.clientX-i.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,i.b-(e.clientY-i.y)))),this.applySizes()},o=()=>{n(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,a),e.removeEventListener(`pointerup`,o),this.save()};e.addEventListener(`pointermove`,a),e.addEventListener(`pointerup`,o)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,r=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${r}px`),n(this.el,`no-left`,!e),n(this.el,`no-right`,!t),n(this.el,`no-bottom`,!r);for(let e of ie){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ae){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new oe(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(C);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??S[e]??S.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(C),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(C,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(C)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(C)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??S[e]??S.Default,e),this.save()}resetWorkspace(){this.applyLayout(S[this.workspace]??S.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(C)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(C,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ae)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new oe(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,n(this.el,`is-maximized`,!1),n(e.el,`is-max`,!1)):(this.maximized&&n(this.maximized.el,`is-max`,!1),this.maximized=e,n(this.el,`is-maximized`,!0),n(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&n(t.el,`is-focused`,!1),this.focused=e;let r=this.find(e);r&&n(r.el,`is-focused`,!0),this.onFocus?.(e)}},ce={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},le=`studio`,ue=`#f2545b`,de=`formencoder_ui_settings`,fe=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function pe(){try{let e=localStorage.getItem(de);if(e){let t=JSON.parse(e);return{theme:t.theme&&ce[t.theme]?t.theme:le,accentColor:t.accentColor||`#f2545b`,intensity:fe(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:le,accentColor:ue,intensity:1}}function me(e){try{let t=localStorage.getItem(de),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(de,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function he(e=pe()){let t=document.documentElement,n=ce[e.theme]||ce.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(fe(e.intensity))),t.style.setProperty(`--accent-tint`,_e(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,_e(e.accentColor,.1))}function ge(e){let t={...pe(),theme:e};me(t),he(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function _e(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var ve=`0.9.0`,ye=new WeakMap;function w(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout(ye.get(a)),ye.set(a,window.setTimeout(()=>a.remove(),r));return}let o=s(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();ye.set(o,window.setTimeout(()=>o.remove(),r))}var be=new TextDecoder(`latin1`);async function T(e,t,n){let r=await e.slice(t,t+n).arrayBuffer();return new DataView(r)}var E=(e,t)=>be.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),xe={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},Se={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},Ce={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function we(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=E(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=E(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=E(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=E(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${xe[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=E(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=we(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:Te(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Ee(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:Ce[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function Oe(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await T(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function Ne(e){let t=await T(e,0,Math.min(e.size,64));if(t.byteLength<26||E(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Pe=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Fe=[44100,48e3,32e3];async function Ie(e){let t=await T(e,0,Math.min(e.size,65536)),n=0;if(E(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Pe[t.getUint8(r+2)>>4],o=Fe[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Le(e){let t=[De,Ae,je,Me,Ne,Ie];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Re=0,ze=()=>`src${++Re}`,D=48e3;function Be(e,t,n,r=8e3){return new Promise((i,a)=>{let o=window.setTimeout(()=>{l(),a(Error(`timed out waiting for ${t}`))},r),s=()=>{l(),i()},c=()=>{l(),a(Error(`the browser cannot decode this file`))},l=()=>{window.clearTimeout(o),e.removeEventListener(t,s),e.removeEventListener(n,c)};e.addEventListener(t,s),e.addEventListener(n,c)})}async function Ve(e){if(Number.isFinite(e.duration))return e.duration;e.currentTime=1e101,await Be(e,`durationchange`,`error`,4e3).catch(()=>void 0);let t=Number.isFinite(e.duration)?e.duration:0;return e.currentTime=0,t}async function He(e){let t=e.requestVideoFrameCallback?.bind(e);if(!t)return 30;let n=[];return new Promise(r=>{let i=()=>{e.pause(),e.currentTime=0;let t=[];for(let e=1;en[e-1]&&t.push(n[e]-n[e-1]);t.sort((e,t)=>e-t);let i=1/(t.length?t[t.length>>1]:1/30),a=[12,15,23.976,24,25,29.97,30,50,59.94,60].reduce((e,t)=>Math.abs(t-i){n.push(r.mediaTime),n.length>=14?i():t(a)};t(a),e.muted=!0,e.play().catch(()=>i()),window.setTimeout(()=>{n.length<14&&i()},1500)})}async function Ue(e,t){let n=URL.createObjectURL(e),r=document.createElement(`video`);r.muted=!0,r.preload=`auto`,r.playsInline=!0,r.src=n;try{await Be(r,`loadedmetadata`,`error`)}catch(e){throw URL.revokeObjectURL(n),e}let i=await Ve(r),a=r.videoWidth>0&&r.videoHeight>0,o=a?t??await He(r):0;a&&await We(r,0);let s=null;return{id:ze(),name:e.name,kind:a?`video`:`audio`,sample:!1,size:e.size,width:r.videoWidth,height:r.videoHeight,fps:o,duration:i,async frame(e){return await We(r,Math.max(0,Math.min(e,Math.max(0,i-.001)))),r},audio(){return s||=(async()=>{if(e.size>629145600)return null;try{return await new OfflineAudioContext(2,1,D).decodeAudioData(await e.arrayBuffer())}catch{return null}})(),s},dispose(){r.removeAttribute(`src`),r.load(),URL.revokeObjectURL(n)}}}async function We(e,t){if(Math.abs(e.currentTime-t)<1e-4&&e.readyState>=2)return;let n=Be(e,`seeked`,`error`,6e3);e.currentTime=t,await n}function O(e){return e==null||!Number.isFinite(e)?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function Ge(e){if(e==null||!Number.isFinite(e)||e<0)return`--:--`;let t=Math.round(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n?`${n}:${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`:`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`}function k(e){return!e||!Number.isFinite(e)?``:e<60?`${e.toFixed(e<10?2:1)} s`:Ge(e)}function Ke(e){return Math.abs(e-29.97)<.02||Math.abs(e-59.94)<.03}function qe(e,t){let n=Math.max(1,Math.round(t)),r=Ke(t)?Math.round(n/15):0,i=Math.max(0,Math.floor(e));if(r){let e=Math.round(t*600),a=n*60-r,o=Math.floor(i/e),s=i%e;i+=r*9*o+(s>r?r*Math.floor((s-r)/a):0)}let a=i%n,o=Math.floor(i/n),s=e=>String(e).padStart(2,`0`);return`${s(Math.floor(o/3600))}:${s(Math.floor(o/60)%60)}:${s(o%60)}${r?`;`:`:`}${s(a)}`}function A(e){let t=[[23.976,`23.976`],[24,`24`],[25,`25`],[29.97,`29.97`],[30,`30`],[50,`50`],[59.94,`59.94`],[60,`60`]].find(([t])=>Math.abs(t-e)<.02);return t?t[1]:String(Number(e.toFixed(3)))}function j(e,t){if(!e||!t)return``;let n=e/t,r=[[16/9,`16:9`],[2,`2:1`],[9/16,`9:16`],[4/3,`4:3`],[1,`1:1`],[3/4,`3:4`],[21/9,`21:9`]].find(([e])=>Math.abs(e-n)/e<.01);return r?r[1]:n.toFixed(2)}function Je(e,t,n,r){return{id:e,name:t,role:n,form:r,parent:``,origin:`included`,label:``,state:`loading`,progress:0,message:``,blob:null,size:0,source:null,probe:null,gif:null,seq:null,frameBlobs:null,names:[],thumb:``,md5:``,md5State:`idle`,width:0,height:0,fps:0,frames:0,duration:0,offset:0,expect:null,checks:null,url:``}}var M=e=>e.replace(/\.[^.]+$/,``).replace(/_%0\dd$/,``),N=e=>(e.form===`video`||e.form===`sequence`)&&!!e.source&&e.state!==`loading`,P=new class{items=[];slotA=``;slotB=``;view=`compare`;zoom=`fit`;frame=0;markIn=null;markOut=null;working=``;logs=[];listeners=new Map;seq=0;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e)?.add(t)}emit(e){for(let t of this.listeners.get(e)??[])t()}log(e,t=!1){let n=new Date,r=[n.getHours(),n.getMinutes(),n.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`);this.logs.push({time:r,text:e,error:t}),this.logs.length>400&&this.logs.shift(),this.emit(`log`)}nextId(){return this.seq+=1,`m${this.seq}`}get(e){return this.items.find(t=>t.id===e)}a(){return this.get(this.slotA)}b(){return this.get(this.slotB)}master(){let e=this.a();return e&&e.fps>0?e:this.b()}sources(){return this.items.filter(e=>e.role===`source`)}outputs(){return this.items.filter(e=>e.role!==`source`)}add(e){return this.items.push(e),this.emit(`items`),e}make(e,t,n){return Je(this.nextId(),e,t,n)}setSlots(e,t){(e!==this.slotA||t!==this.slotB)&&(this.slotA=e,this.slotB=t,this.emit(`slots`))}setView(e){e!==this.view&&(this.view=e,this.emit(`view`))}setZoom(e){e!==this.zoom&&(this.zoom=e,this.emit(`view`))}setFrame(e){let t=this.master(),n=t?Math.max(0,t.frames-1):0,r=Math.max(0,Math.min(n,Math.round(e)));r!==this.frame&&(this.frame=r,this.emit(`frame`))}setMarks(e,t){this.markIn=e,this.markOut=t,this.emit(`marks`)}},Ye=e=>e?`${(e/1e6).toFixed(2)} Mb/s`:``;function Xe(e){return e.form===`sequence`?`Image sequence`:e.form===`animation`?`Animated GIF`:e.form===`archive`?`Numbered frames (ZIP)`:e.role===`proxy`?`Video, proxy`:`Video`}function Ze(e,t){let n=[],r=(e,t,r)=>{r&&n.push({key:e,label:t,value:r})};r(`kind`,`Kind`,Xe(e));let i=e.probe;if(e.form===`sequence`&&e.seq)r(`container`,`Container`,`Numbered ${e.seq.ext.slice(1).toUpperCase()} files`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.duration)),r(`vcodec`,`Video`,e.seq.ext.slice(1).toUpperCase()===`JPG`?`JPEG, intra only`:e.seq.ext.slice(1).toUpperCase()),r(`frame`,`Frame`,`${e.width}x${e.height}`),r(`shape`,`Shape`,j(e.width,e.height)),r(`rate`,`Rate`,`${A(e.fps)} fps (set when added)`),r(`frames`,`Frames`,`${e.seq.count}, ${String(e.seq.first).padStart(e.seq.digits,`0`)} to ${String(e.seq.last).padStart(e.seq.digits,`0`)}${e.seq.gaps.length?`, ${e.seq.gaps.length} missing`:`, no gaps`}`),r(`audio`,`Audio`,`None`);else if(e.form===`animation`&&e.gif)r(`container`,`Container`,`GIF89a`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.gif.duration)),r(`vcodec`,`Video`,`GIF, 256 colours`),r(`frame`,`Frame`,`${e.gif.width}x${e.gif.height}`),r(`shape`,`Shape`,j(e.gif.width,e.gif.height)),r(`rate`,`Rate`,e.gif.duration?`${A(e.gif.frames/e.gif.duration)} fps`:``),r(`frames`,`Frames`,String(e.gif.frames)),r(`audio`,`Audio`,`None`),r(`loop`,`Loop`,e.gif.loops?`Forever`:`Once`);else if(e.form===`archive`)r(`container`,`Container`,`ZIP, stored`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.duration)),r(`vcodec`,`Video`,e.seq?.ext.slice(1).toUpperCase()??``),r(`frame`,`Frame`,e.width?`${e.width}x${e.height}`:``),r(`shape`,`Shape`,j(e.width,e.height)),r(`rate`,`Rate`,e.fps?`${A(e.fps)} fps`:``),e.seq&&r(`frames`,`Frames`,`${e.seq.count}, ${String(e.seq.first).padStart(e.seq.digits,`0`)} to ${String(e.seq.last).padStart(e.seq.digits,`0`)}${e.seq.gaps.length?`, ${e.seq.gaps.length} missing`:`, no gaps`}`),r(`audio`,`Audio`,`None`);else if(i){r(`container`,`Container`,i.container),r(`size`,`Size`,O(i.size)),r(`duration`,`Duration`,k(i.duration??e.duration)),r(`bitrate`,`Bit rate`,Ye(i.bitrate)),i.video&&(r(`vcodec`,`Video`,[i.video.codec,i.video.profile].filter(Boolean).join(` `)),r(`frame`,`Frame`,`${i.video.width}x${i.video.height}`),r(`shape`,`Shape`,j(i.video.width,i.video.height)),r(`rate`,`Rate`,i.video.fps?`${A(i.video.fps)} fps`:``),r(`frames`,`Frames`,i.video.frames?String(i.video.frames):``),r(`vbit`,`Video rate`,Ye(i.video.bitrate)));let n=i.audio[0];r(`audio`,`Audio`,n?[n.codec,n.sampleRate?`${n.sampleRate} Hz`:``,n.channels?`${n.channels} ch`:``].filter(Boolean).join(`, `):`None`),r(`loud`,`Loudness`,t)}return r(`md5`,`MD5`,e.md5?`${e.md5.slice(0,12)}...`:e.md5State===`running`?`Reading`:``),n}var F=(e,t,n)=>Math.abs(e-t)<=n;function Qe(e){let t=e.expect,n=[];if(!t)return n;if(e.form===`archive`&&e.seq){let r=e.width===t.width&&e.height===t.height;return n.push({label:`Frame count`,want:String(t.frames),got:String(e.seq.count),ok:e.seq.count===t.frames}),n.push({label:`Numbers`,want:`1 to ${t.frames}`,got:`${e.seq.first} to ${e.seq.last}`,ok:e.seq.first===1&&e.seq.last===t.frames&&e.seq.gaps.length===0}),n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${e.width}x${e.height}`,ok:r}),n}if(e.form===`animation`&&e.gif)return n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${e.gif.width}x${e.gif.height}`,ok:e.gif.width===t.width&&e.gif.height===t.height}),n.push({label:`Frame rate`,want:`${A(t.fps)}`,got:e.gif.duration?`${A(e.gif.frames/e.gif.duration)}`:``,ok:e.gif.duration>0&&F(e.gif.frames/e.gif.duration,t.fps,1.6)}),n.push({label:`Duration`,want:`${t.duration.toFixed(2)} s`,got:`${e.gif.duration.toFixed(2)} s`,ok:F(e.gif.duration,t.duration,Math.max(.1,1/t.fps))}),n;let r=e.probe?.video;if(!r)return n;n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${r.width}x${r.height}`,ok:r.width===t.width&&r.height===t.height}),n.push({label:`Frame rate`,want:A(t.fps),got:r.fps?A(r.fps):``,ok:!!r.fps&&F(r.fps,t.fps,.05)});let i=e.probe?.duration??e.duration;n.push({label:`Duration`,want:`${t.duration.toFixed(2)} s`,got:`${i.toFixed(2)} s`,ok:F(i,t.duration,Math.max(.06,1.5/t.fps))}),n.push({label:`Video codec`,want:t.codec,got:r.codec,ok:r.codec.toLowerCase().replace(/\W/g,``).includes(t.codec.toLowerCase().replace(/\W/g,``))});let a=(e.probe?.audio.length??0)>0;return n.push({label:`Audio`,want:t.audio?`present`:`none`,got:a?`present`:`none`,ok:a===t.audio}),r.frames&&t.frames&&n.push({label:`Frames`,want:String(t.frames),got:String(r.frames),ok:Math.abs(r.frames-t.frames)<=1}),n}function $e(e,t){let n=e.probe?.video,r=t.probe?.video;if(!n||!r)return[];let i=(e.probe?.audio.length??0)>0,a=(t.probe?.audio.length??0)>0,o=n.frames??Math.round((e.probe?.duration??e.duration)*(n.fps??e.fps)),s=r.frames??Math.round((t.probe?.duration??t.duration)*(r.fps??t.fps));return[{label:`Same frame rate`,want:r.fps?A(r.fps):``,got:n.fps?A(n.fps):``,ok:!!n.fps&&!!r.fps&&F(n.fps,r.fps,.05)},{label:`Same frame count`,want:String(s),got:String(o),ok:!!o&&Math.abs(o-s)<=1},{label:`Same duration`,want:`${(t.probe?.duration??t.duration).toFixed(2)} s`,got:`${(e.probe?.duration??e.duration).toFixed(2)} s`,ok:F(e.probe?.duration??e.duration,t.probe?.duration??t.duration,.08)},{label:`Same shape`,want:j(r.width,r.height),got:j(n.width,n.height),ok:j(r.width,r.height)===j(n.width,n.height)},{label:`Same audio`,want:a?`present`:`none`,got:i?`present`:`none`,ok:i===a}]}function et(){let e=P.sources().filter(e=>e.state!==`loading`&&e.fps>0);if(e.length<2)return[];let t=[...new Set(e.map(e=>A(e.fps)))],n=[...new Set(e.map(e=>j(e.width,e.height)))],r=[];return r.push(`${e.length} sources, ${t.length} frame rate${t.length===1?``:`s`} (${t.join(`, `)})`),r.push(`${n.length} frame shape${n.length===1?``:`s`} (${n.join(`, `)})`),r}async function tt(e){let t=new Uint8Array(await e.arrayBuffer()),n=String.fromCharCode(...t.subarray(0,6));if(n!==`GIF89a`&&n!==`GIF87a`)return null;let r=new DataView(t.buffer),i=r.getUint16(6,!0),a=r.getUint16(8,!0),o=13+(t[10]&128?3*2**((t[10]&7)+1):0),s=0,c=0,l=!1,u=()=>{for(;o>>0;var it=class{a=1732584193;b=-271733879;c=-1732584194;d=271733878;tail=new Uint8Array(64);fill=0;total=0;w=new Int32Array(16);update(e){this.total+=e.length;let t=0;if(this.fill){let n=Math.min(64-this.fill,e.length);this.tail.set(e.subarray(0,n),this.fill),this.fill+=n,t=n,this.fill===64&&(this.block(this.tail,0),this.fill=0)}for(;t+64<=e.length;t+=64)this.block(e,t);t>4)*4+(e&3)],l=r+t+rt[e]+n[s]|0,u=i+(l<>>32-c)|0;r=o,o=a,a=i,i=u}this.a=this.a+r|0,this.b=this.b+i|0,this.c=this.c+a|0,this.d=this.d+o|0}hex(){let e=this.total*8,t=new Uint8Array((this.fill<56?56:120)-this.fill+8);t[0]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,e>>>0,!0),n.setUint32(t.length-4,Math.floor(e/4294967296),!0),this.update(t);let r=new Uint8Array(16),i=new DataView(r.buffer);return i.setInt32(0,this.a,!0),i.setInt32(4,this.b,!0),i.setInt32(8,this.c,!0),i.setInt32(12,this.d,!0),Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``)}},I=2097152;function at(){return new Promise(e=>window.setTimeout(e,0))}async function L(e,t){let n=new it;for(let r=0;rvoid 0).then(async()=>{let e=await r.frame(t);return n(e,e instanceof HTMLVideoElement?e.videoWidth:e.width,e instanceof HTMLVideoElement?e.videoHeight:e.height)});return ot.set(e.id,i),i}async function st(e,t){return(await fetch(`data:${t};base64,${e}`)).blob()}function ct(){let e=window;return e.INSPECT_MEDIA||={},e.INSPECT_MEDIA}function lt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}var ut=/^(.*?)(\d+)(\.[A-Za-z0-9]+)$/;function dt(e){let t=new Map;for(let n of e){let e=ut.exec(n.name);if(!e)continue;let r=`${e[1]}|${e[2].length}|${e[3].toLowerCase()}`;t.has(r)||t.set(r,[]),t.get(r)?.push({...n,n:Number(e[2])})}let n=null,r=``;for(let[e,i]of t)(!n||i.length>n.length)&&(n=i,r=e);if(!n||n.length<2)return null;n.sort((e,t)=>e.n-t.n);let[i,a,o]=r.split(`|`),s=new Set(n.map(e=>e.n)),c=n[0].n,l=n[n.length-1].n,u=[];for(let e=c;e<=l;e++)s.has(e)||u.push(e);return{files:n,info:{pattern:`${i}%0${a}d${o}`,first:c,last:l,count:n.length,gaps:u,digits:Number(a),ext:o}}}var ft=0;async function pt(e,t){let n=dt(e);if(!n)throw Error(`these files are not a numbered image sequence`);let r=await Promise.all(n.files.map(e=>createImageBitmap(e.blob))),i=r[0].width,a=r[0].height,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`),c=r.length/t;return{source:{id:`seq${++ft}`,name:n.info.pattern,kind:`video`,sample:!1,size:n.files.reduce((e,t)=>e+t.blob.size,0),width:i,height:a,fps:t,duration:c,async frame(e){let n=Math.max(0,Math.min(r.length-1,Math.floor(e*t+1e-6)));return s.clearRect(0,0,i,a),s.drawImage(r[n],0,0,i,a),o},audio:()=>Promise.resolve(null),dispose:()=>void 0},info:n.info,names:n.files.map(e=>e.name),width:i,height:a}}var mt=3e4/1001,ht=[{pack:`autumn-stream`,file:`autumn-stream.mp4`,role:`source`,form:`video`,parent:``,label:`Camera original, trimmed`,width:1280,height:720,fps:mt,duration:8.008,frames:240,size:6525912,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`waterfall`,file:`waterfall.mp4`,role:`source`,form:`video`,parent:``,label:`Camera original, trimmed`,width:1280,height:640,fps:24e3/1001,duration:6.006,frames:144,size:2898071,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`river-vertical`,file:`river-vertical.mp4`,role:`source`,form:`video`,parent:``,label:`Phone original, vertical`,width:404,height:720,fps:60,duration:6.15,frames:369,size:1501308,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`clouds-sequence`,file:`clouds_%04d.jpg`,role:`source`,form:`sequence`,parent:``,label:`Numbered stills, 24 fps`,width:960,height:540,fps:24,duration:1.5,frames:36,size:17e5,codec:`JPEG`,audio:!1,offset:0,type:`image/jpeg`},{pack:`autumn-stream_high`,file:`autumn-stream_high.mp4`,role:`output`,form:`video`,parent:`autumn-stream.mp4`,label:`Match Source, high: H.264 3.5 Mb/s`,width:1280,height:720,fps:mt,duration:3.003,frames:90,size:1514869,codec:`H.264`,audio:!0,offset:2.002,type:`video/mp4`},{pack:`autumn-stream_low`,file:`autumn-stream_low.mp4`,role:`output`,form:`video`,parent:`autumn-stream.mp4`,label:`Match Source, low: H.264 0.45 Mb/s`,width:1280,height:720,fps:mt,duration:3.003,frames:90,size:220648,codec:`H.264`,audio:!0,offset:2.002,type:`video/mp4`},{pack:`autumn-stream_Proxy`,file:`autumn-stream_Proxy.mp4`,role:`proxy`,form:`video`,parent:`autumn-stream.mp4`,label:`H.264 Proxy 960x540`,width:960,height:540,fps:mt,duration:8.008,frames:240,size:2922345,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`autumn-stream_480`,file:`autumn-stream_480.gif`,role:`output`,form:`animation`,parent:`autumn-stream.mp4`,label:`Animated GIF 480 px`,width:480,height:270,fps:15,duration:3,frames:45,size:892598,codec:`GIF`,audio:!1,offset:2.002,type:`image/gif`}],gt={markIn:60,markOut:149};function _t(){let e=new Map;for(let t of ht){let n=P.make(t.file,t.role,t.form);n.label=t.label,n.width=t.width,n.height=t.height,n.fps=t.fps,n.duration=t.duration,n.frames=t.frames,n.size=t.size,n.offset=t.offset,n.origin=`included`,t.role!==`source`&&(n.expect={width:t.width,height:t.height,fps:t.fps,duration:t.duration,frames:t.frames,codec:t.codec,audio:t.audio},n.parent=e.get(t.parent)?.id??``),e.set(t.file,n),P.items.push(n)}return e}async function vt(e){return R(e,e.form===`sequence`?e.duration/2:Math.min(e.duration/2,2.5),(e,t,n)=>{let r=document.createElement(`canvas`);return r.width=240,r.height=Math.max(2,Math.round(240*n/t)),r.getContext(`2d`)?.drawImage(e,0,0,r.width,r.height),r.toDataURL(`image/jpeg`,.72)})}async function yt(e,t){await lt(e.pack);let n=ct(),r=e.form===`sequence`?e.pack:e.file,i=n[r];if(delete n[r],!i)throw Error(`the pack ${e.pack} holds no ${e.file}`);if(e.form===`sequence`){let n=await Promise.all(Object.entries(i).map(async([e,t])=>({name:e,blob:await st(t,`image/jpeg`)}))),r=await pt(n,e.fps);t.source=r.source,t.seq=r.info,t.names=r.names,t.size=r.source.size,t.width=r.width,t.height=r.height,t.frames=r.info.count,t.duration=r.info.count/e.fps,t.frameBlobs=n.sort((e,t)=>e.name.localeCompare(t.name)).map(e=>e.blob)}else{let n=await st(i,e.type);if(t.blob=n,t.size=n.size,e.form===`animation`)t.gif=await tt(n),t.url=URL.createObjectURL(n);else{let r=new File([n],e.file,{type:e.type}),i=await Le(r);t.probe=i;let a=i.video?.fps&&Number.isFinite(i.video.fps)?i.video.fps:e.fps;t.source=await Ue(r,a),t.fps=a,t.width=i.video?.width??e.width,t.height=i.video?.height??e.height,t.duration=i.duration??t.source.duration,t.frames=i.video?.frames??Math.round(t.duration*a)}}t.state=`ready`}async function bt(e){if(e.source)try{e.thumb=await vt(e)}catch(t){P.log(`No thumbnail for ${e.name}: ${t.message}`,!0)}}function z(e){if(!e.expect)return;let t=Qe(e),n=P.get(e.parent);e.checks=e.role===`proxy`&&n?.probe?[...t,...$e(e,n)]:t}async function xt(){for(let e of P.items){if(!e.blob&&!e.frameBlobs||e.md5State===`done`)continue;e.md5State=`running`,P.emit(`items`);let t=performance.now();try{e.md5=e.blob?await L(e.blob):await L(new Blob(e.frameBlobs)),e.md5State=`done`,P.log(`MD5 ${e.md5} ${e.name} (${((performance.now()-t)/1e3).toFixed(1)} s)`)}catch(t){e.md5State=`idle`,P.log(`MD5 failed for ${e.name}: ${t.message}`,!0)}P.emit(`items`)}}async function St(){let e=_t();P.emit(`items`);let t=e.get(`autumn-stream.mp4`),n=e.get(`autumn-stream_low.mp4`);P.setSlots(t.id,n.id);let r=[`autumn-stream.mp4`,`autumn-stream_low.mp4`,`autumn-stream_high.mp4`,`waterfall.mp4`,`river-vertical.mp4`,`clouds_%04d.jpg`,`autumn-stream_Proxy.mp4`,`autumn-stream_480.gif`],i=0;for(let n of r){let r=ht.find(e=>e.file===n),a=e.get(n);try{await yt(r,a),i+=1,z(a),P.emit(`items`),a===t&&P.setFrame(gt.markIn+24),bt(a).then(()=>P.emit(`items`)),P.log(`Loaded ${a.name}`)}catch(e){a.state=`failed`,a.message=e.message,P.log(`Could not load ${n}: ${a.message}`,!0),P.emit(`items`)}}for(let e of P.items)e.role===`proxy`&&z(e);P.emit(`items`),i||P.log(`No curated media loaded`,!0),xt()}function B(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>URL.revokeObjectURL(n),4e3)}function Ct(e,t=`image/png`,n){return new Promise((r,i)=>e.toBlob(e=>e?r(e):i(Error(`the canvas could not be saved`)),t,n))}var wt=new Map,Tt=`md5`,Et=!1,Dt=!1,Ot={size:`Size`,md5:`MD5`,bit:`Bit for bit`};function kt(e){return e.blob?e.blob:e.frameBlobs?new Blob(e.frameBlobs):null}async function At(e,t,n){let r=kt(e);if(!r)return;let i={mode:t,srcMd5:``,copyMd5:``,ok:!1,detail:``,progress:0,running:!0,flipped:n};wt.set(e.id,i),P.emit(`items`);let a=new it,o=[],s=Math.floor(r.size*.37);for(let e=0;e=e&&s{i.progress=.5+e*.5,P.emit(`items`)}),i.ok=i.copyMd5===i.srcMd5,i.detail=i.ok?`Copy read back from storage matches`:`${i.srcMd5.slice(0,8)} against ${i.copyMd5.slice(0,8)}`;else{let e=-1;for(let t=0;te.md5).map(e=>`${e.md5} ${e.name}`).join(` + `),this.areas=Object.fromEntries(ae.map(e=>[e,this.el.querySelector(`[data-area="${e}"]`)]));for(let e of Array.from(this.el.querySelectorAll(`.fx-split`)))this.bindSplit(e);window.addEventListener(`resize`,()=>this.resized())}register(e,t,n){this.factories.set(e,n),this.titles.set(e,t)}titleOf(e){return this.titles.get(e)??e}panelIds(){return[...this.factories.keys()]}peek(e){return this.made.get(e)}panel(e){let t=this.made.get(e);if(!t){let n=this.factories.get(e);if(!n)return;t=n(),t.el.classList.add(`fx-panel`),t.el.dataset.panel=e,t.el.dataset.automationId=`panel.${e}`,this.made.set(e,t)}return t}bindSplit(e){let t=e.dataset.split;e.addEventListener(`pointerdown`,r=>{r.preventDefault(),e.setPointerCapture(r.pointerId),n(e,`is-dragging`,!0);let i={x:r.clientX,y:r.clientY,l:this.layout.leftW,r:this.layout.rightW,b:this.layout.bottomH},a=e=>{t===`left`&&(this.layout.leftW=Math.max(160,Math.min(900,i.l+e.clientX-i.x))),t===`right`&&(this.layout.rightW=Math.max(160,Math.min(1100,i.r-(e.clientX-i.x)))),t===`bottom`&&(this.layout.bottomH=Math.max(120,Math.min(window.innerHeight-220,i.b-(e.clientY-i.y)))),this.applySizes()},o=()=>{n(e,`is-dragging`,!1),e.removeEventListener(`pointermove`,a),e.removeEventListener(`pointerup`,o),this.save()};e.addEventListener(`pointermove`,a),e.addEventListener(`pointerup`,o)})}applySizes(){let e=this.groups.left.length?this.layout.leftW:0,t=this.groups.right.length?this.layout.rightW:0,r=this.groups.bottom.length?this.layout.bottomH:0;this.el.style.setProperty(`--fx-left`,`${e}px`),this.el.style.setProperty(`--fx-right`,`${t}px`),this.el.style.setProperty(`--fx-bottom`,`${r}px`),n(this.el,`no-left`,!e),n(this.el,`no-right`,!t),n(this.el,`no-bottom`,!r);for(let e of ie){let t=this.groups[e],n=t.reduce((e,t)=>e+t.size,0)||1;for(let e of t)e.el.style.flex=`${e.size/n} 1 0`}this.resized()}resized(){for(let e of this.made.values())e.el.hidden||e.resized?.()}applyLayout(e,t){this.workspace=t,this.layout=structuredClone(e);for(let t of ae){for(let e of this.groups[t]){for(let t of e.panels){let e=this.made.get(t);e&&(e.el.hidden=!0,e.hidden?.())}e.el.remove()}this.groups[t]=[];let n=(t===`float`?e.float:e[t])??[];for(let e of n){let n=new oe(this,t);n.size=e.size??1,e.w!==void 0&&(n.rect={x:e.x??120,y:e.y??90,w:e.w,h:e.h??340}),this.areas[t].appendChild(n.el),this.groups[t].push(n);for(let t of e.panels)this.factories.has(t)&&n.add(t,!1);t===`float`&&!n.panels.length?(n.el.remove(),this.groups[t].pop()):(n.activate(e.active&&e.panels.includes(e.active)?e.active:n.panels[0]),t===`float`&&n.place())}}this.applySizes(),this.onWorkspace?.(t)}load(){let e=`Default`,t=null;try{let n=localStorage.getItem(C);if(n){let r=JSON.parse(n);e=r.workspace||`Default`,t=r.layouts?.[e]??null}}catch{t=null}this.applyLayout(t??S[e]??S.Default,e)}snapshot(){let e={left:[],center:[],right:[],bottom:[],leftW:this.layout.leftW,rightW:this.layout.rightW,bottomH:this.layout.bottomH};for(let t of[`left`,`center`,`right`,`bottom`])e[t]=this.groups[t].map(e=>({panels:[...e.panels],active:e.active,size:e.size}));return e.float=this.groups.float.map(e=>({panels:[...e.panels],active:e.active,...e.rect})),e}save(){try{let e=localStorage.getItem(C),t=e?JSON.parse(e):{};t.workspace=this.workspace,t.layouts={...t.layouts||{},[this.workspace]:this.snapshot()},localStorage.setItem(C,JSON.stringify(t))}catch{return}}savedNames(){try{let e=JSON.parse(localStorage.getItem(C)||`{}`);return Object.keys(e.custom||{})}catch{return[]}}switchTo(e){let t=null;try{let n=JSON.parse(localStorage.getItem(C)||`{}`);t=n.layouts?.[e]??n.custom?.[e]??null}catch{t=null}this.applyLayout(t??S[e]??S.Default,e),this.save()}resetWorkspace(){this.applyLayout(S[this.workspace]??S.Default,this.workspace),this.save()}saveAs(e){try{let t=JSON.parse(localStorage.getItem(C)||`{}`);t.custom={...t.custom||{},[e]:this.snapshot()},localStorage.setItem(C,JSON.stringify(t))}catch{return}this.workspace=e,this.save(),this.onWorkspace?.(e)}find(e){for(let t of ae)for(let n of this.groups[t])if(n.panels.includes(e))return n}home(e){let t=e===`essential`?this.find(`effectsPresets`):void 0;if(t&&t.area!==`float`)return t;let n=e===`composition`?`center`:[`timeline`,`renderQueue`,`terminal`,`agents`,`graph`,`flowchart`].includes(e)?`bottom`:`right`;return this.groups[n][0]??this.groups.right[0]??this.groups.bottom[0]??this.groups.center[0]}show(e){if(!this.factories.has(e))return;let t=this.find(e);if(!t){if(t=this.home(e),!t)return;t.add(e,!0),this.applySizes()}t.activate(e),this.focus(e)}undock(e){let t=this.find(e);if(!t||t.area===`float`)return;let n=this.el.getBoundingClientRect(),r=new oe(this,`float`),i=this.groups.float.length;r.rect={x:Math.max(0,n.width/2-260+i*28),y:Math.max(0,n.height/2-200+i*28),w:520,h:400},this.areas.float.appendChild(r.el),this.groups.float.push(r),r.place(),this.move(e,r),this.focus(e)}redock(e){let t=this.find(e);if(!t||t.area!==`float`)return;let n=this.home(e);n?this.move(e,n):this.close(e)}isVisible(e){let t=this.made.get(e);return!!t&&!t.el.hidden}close(e){let t=this.find(e);t&&(t.remove(e),t.panels.length||(t.el.remove(),this.groups[t.area]=this.groups[t.area].filter(e=>e!==t),this.applySizes()),this.save())}move(e,t){let n=this.find(e);n!==t&&(n?.remove(e),n&&!n.panels.length&&(n.el.remove(),this.groups[n.area]=this.groups[n.area].filter(e=>e!==n)),t.add(e,!0),this.applySizes(),this.save())}raise(e){let t=this.groups.float;e.area===`float`&&t[t.length-1]!==e&&(this.groups.float=[...t.filter(t=>t!==e),e],this.groups.float.forEach((e,t)=>e.el.style.zIndex=String(t+1)))}maximize(e){e.area!==`float`&&(this.maximized===e?(this.maximized=null,n(this.el,`is-maximized`,!1),n(e.el,`is-max`,!1)):(this.maximized&&n(this.maximized.el,`is-max`,!1),this.maximized=e,n(this.el,`is-maximized`,!0),n(e.el,`is-max`,!0)),this.resized())}toggleMaximizeFocused(){let e=this.find(this.focused);e&&this.maximize(e)}focused=`queue`;focus(e){if(!e||this.focused===e)return;let t=this.find(this.focused);t&&n(t.el,`is-focused`,!1),this.focused=e;let r=this.find(e);r&&n(r.el,`is-focused`,!0),this.onFocus?.(e)}},ce={studio:{label:`Studio Dark`,vars:{"--bg-primary":`#111111`,"--bg-secondary":`#17151b`,"--bg-tertiary":`#222127`,"--border-color":`#2a2a2a`,"--border-light":`#34333a`,"--text-primary":`#f7f7f7`,"--text-secondary":`#a4a4a4`,"--text-muted":`#717072`,"--canvas-bg":`#1c1b1d`,"--grid-color":`#5e5e60`,"--bg-node":`#191919`}},"nodemode-dark":{label:`NodeMode Dark`,vars:{"--bg-primary":`#0a0a0a`,"--bg-secondary":`#121218`,"--bg-tertiary":`#1a1a24`,"--border-color":`#2a2a35`,"--border-light":`#3a3a48`,"--text-primary":`#e8e8ee`,"--text-secondary":`#a8a8b8`,"--text-muted":`#6a6a7a`,"--canvas-bg":`#0a0a0a`,"--grid-color":`rgba(255,255,255,0.04)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.45)`}},light:{label:`Light`,light:!0,vars:{"--bg-primary":`#ecebe6`,"--bg-secondary":`#f7f6f1`,"--bg-tertiary":`#e2e0d8`,"--bg-node":`#f4f3ed`,"--border-color":`#d1cdc1`,"--border-light":`#beb9aa`,"--text-primary":`#26241d`,"--text-secondary":`#4c4a40`,"--text-muted":`#8b887a`,"--canvas-bg":`#e7e5dd`,"--grid-color":`rgba(70,60,30,0.10)`,"--node-shadow":`0 5px 14px rgba(96,90,70,0.15)`}},"github-dark":{label:`GitHub Dark`,vars:{"--bg-primary":`#0d1117`,"--bg-secondary":`#161b22`,"--bg-tertiary":`#21262d`,"--border-color":`#30363d`,"--border-light":`#3d444d`,"--text-primary":`#e6edf3`,"--text-secondary":`#9198a1`,"--text-muted":`#656c76`,"--canvas-bg":`#0d1117`,"--grid-color":`rgba(230,237,243,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},midnight:{label:`Midnight Blue`,vars:{"--bg-primary":`#0b1020`,"--bg-secondary":`#101830`,"--bg-tertiary":`#182242`,"--border-color":`#25325c`,"--border-light":`#324274`,"--text-primary":`#e4e9f7`,"--text-secondary":`#9fabd0`,"--text-muted":`#63709a`,"--canvas-bg":`#0b1020`,"--grid-color":`rgba(160,180,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,0,20,0.55)`}},forest:{label:`Forest`,vars:{"--bg-primary":`#0c130e`,"--bg-secondary":`#121c15`,"--bg-tertiary":`#1a281e`,"--border-color":`#2a4030`,"--border-light":`#375441`,"--text-primary":`#e4efe7`,"--text-secondary":`#a4bdac`,"--text-muted":`#6a8674`,"--canvas-bg":`#0c130e`,"--grid-color":`rgba(180,230,190,0.05)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.5)`}},ember:{label:`Ember`,vars:{"--bg-primary":`#140d0a`,"--bg-secondary":`#1d1310`,"--bg-tertiary":`#2a1c16`,"--border-color":`#452e22`,"--border-light":`#5a3d2e`,"--text-primary":`#f2e8e2`,"--text-secondary":`#c7ab9c`,"--text-muted":`#8f7263`,"--canvas-bg":`#140d0a`,"--grid-color":`rgba(255,200,160,0.05)`,"--node-shadow":`0 6px 18px rgba(20,5,0,0.55)`}},violet:{label:`Violet Haze`,vars:{"--bg-primary":`#100b1c`,"--bg-secondary":`#171129`,"--bg-tertiary":`#221a3c`,"--border-color":`#382c5e`,"--border-light":`#493b78`,"--text-primary":`#ece6f9`,"--text-secondary":`#b3a6d8`,"--text-muted":`#7a6da3`,"--canvas-bg":`#100b1c`,"--grid-color":`rgba(210,190,255,0.06)`,"--node-shadow":`0 8px 22px rgba(10,0,30,0.55)`}},slate:{label:`Slate`,vars:{"--bg-primary":`#101418`,"--bg-secondary":`#171d23`,"--bg-tertiary":`#212a32`,"--border-color":`#32404c`,"--border-light":`#415260`,"--text-primary":`#e7edf2`,"--text-secondary":`#a3b2bf`,"--text-muted":`#6b7a87`,"--canvas-bg":`#101418`,"--grid-color":`rgba(200,220,240,0.05)`,"--node-shadow":`0 6px 18px rgba(0,5,10,0.5)`}},mono:{label:`Mono Ink`,vars:{"--bg-primary":`#0e0e0e`,"--bg-secondary":`#161616`,"--bg-tertiary":`#202020`,"--border-color":`#333333`,"--border-light":`#454545`,"--text-primary":`#f0f0f0`,"--text-secondary":`#ababab`,"--text-muted":`#6e6e6e`,"--canvas-bg":`#0e0e0e`,"--grid-color":`rgba(255,255,255,0.05)`,"--node-shadow":`0 6px 18px rgba(0,0,0,0.5)`}},sand:{label:`Sand (light)`,light:!0,vars:{"--bg-primary":`#efe8da`,"--bg-secondary":`#f8f3e9`,"--bg-tertiary":`#e6dcc8`,"--bg-node":`#f5efe2`,"--border-color":`#d4c7ab`,"--border-light":`#c2b28e`,"--text-primary":`#2a2418`,"--text-secondary":`#59503c`,"--text-muted":`#8d8168`,"--canvas-bg":`#eae2d1`,"--grid-color":`rgba(80,60,10,0.10)`,"--node-shadow":`0 5px 14px rgba(100,80,30,0.16)`}},ocean:{label:`Deep Ocean`,vars:{"--bg-primary":`#06131c`,"--bg-secondary":`#0a1c29`,"--bg-tertiary":`#10293c`,"--border-color":`#1d425e`,"--border-light":`#285578`,"--text-primary":`#e2eef7`,"--text-secondary":`#96b6cc`,"--text-muted":`#5b7d94`,"--canvas-bg":`#06131c`,"--grid-color":`rgba(150,210,255,0.06)`,"--node-shadow":`0 8px 22px rgba(0,10,20,0.6)`}},rose:{label:`Rose Noir`,vars:{"--bg-primary":`#170b10`,"--bg-secondary":`#211117`,"--bg-tertiary":`#301a22`,"--border-color":`#4d2b38`,"--border-light":`#653a49`,"--text-primary":`#f5e7ec`,"--text-secondary":`#cfa5b3`,"--text-muted":`#966b7b`,"--canvas-bg":`#170b10`,"--grid-color":`rgba(255,190,215,0.05)`,"--node-shadow":`0 6px 18px rgba(25,0,10,0.55)`}},terminal:{label:`Terminal Green`,vars:{"--bg-primary":`#050d05`,"--bg-secondary":`#0a140a`,"--bg-tertiary":`#102010`,"--border-color":`#1f3d1f`,"--border-light":`#2b522b`,"--text-primary":`#d8f5d8`,"--text-secondary":`#8fce8f`,"--text-muted":`#568a56`,"--canvas-bg":`#050d05`,"--grid-color":`rgba(120,255,120,0.06)`,"--node-shadow":`0 6px 18px rgba(0,10,0,0.6)`}},contrast:{label:`High Contrast`,vars:{"--bg-primary":`#000000`,"--bg-secondary":`#0a0a0a`,"--bg-tertiary":`#161616`,"--border-color":`#555555`,"--border-light":`#777777`,"--text-primary":`#ffffff`,"--text-secondary":`#d8d8d8`,"--text-muted":`#9a9a9a`,"--canvas-bg":`#000000`,"--grid-color":`rgba(255,255,255,0.10)`,"--node-shadow":`0 0 0 1px #666`}}},le=`studio`,ue=`#f2545b`,de=`formencoder_ui_settings`,fe=e=>typeof e==`number`&&Number.isFinite(e)?Math.min(1.5,Math.max(0,e)):1;function pe(){try{let e=localStorage.getItem(de);if(e){let t=JSON.parse(e);return{theme:t.theme&&ce[t.theme]?t.theme:le,accentColor:t.accentColor||`#f2545b`,intensity:fe(t.intensity)}}}catch(e){console.error(`[theme] read failed:`,e)}return{theme:le,accentColor:ue,intensity:1}}function me(e){try{let t=localStorage.getItem(de),n={...t?JSON.parse(t):{},...e,appearance:1};localStorage.setItem(de,JSON.stringify(n))}catch(e){console.error(`[theme] save failed:`,e)}}function he(e=pe()){let t=document.documentElement,n=ce[e.theme]||ce.studio;for(let[e,r]of Object.entries(n.vars))t.style.setProperty(e,r);document.body.classList.toggle(`theme-light`,!!n.light),t.style.setProperty(`--bg-node`,n.vars[`--bg-node`]||n.vars[`--bg-secondary`]),t.style.setProperty(`--shadow-lg`,n.light?`0 4px 14px rgba(96, 90, 70, 0.16)`:`0 8px 32px rgba(0, 0, 0, 0.5)`),t.style.setProperty(`--accent-color`,e.accentColor),t.style.setProperty(`--accent-color-dim`,e.accentColor+`33`),t.style.setProperty(`--accent-color-hover`,`color-mix(in srgb, ${e.accentColor} 82%, #ffffff)`),t.style.setProperty(`--accent-intensity`,String(fe(e.intensity))),t.style.setProperty(`--accent-tint`,_e(e.accentColor,.06)),t.style.setProperty(`--accent-tint-strong`,_e(e.accentColor,.1))}function ge(e){let t={...pe(),theme:e};me(t),he(t),document.dispatchEvent(new CustomEvent(`nm:ui-settings-changed`,{detail:{key:`theme`}}))}function _e(e,t){let n=e.replace(`#`,``),r=n.length===3?n.split(``).map(e=>e+e).join(``):n,i=parseInt(r.slice(0,6),16);return Number.isNaN(i)?`rgba(171,160,211,${t})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${t})`}var ve=`0.10.0`,ye=new WeakMap;function w(e,t=`info`){let n=document.getElementById(`toast-root`);if(!n)return;let r=t===`error`?6e3:3600,i=`cv-toast${t===`error`?` is-error`:t===`ok`?` is-ok`:``}`,a=Array.from(n.children).find(t=>t.textContent===e&&t.className===i);if(a){window.clearTimeout(ye.get(a)),ye.set(a,window.setTimeout(()=>a.remove(),r));return}let o=s(`
`);for(o.textContent=e,n.appendChild(o);n.children.length>4;)n.firstElementChild?.remove();ye.set(o,window.setTimeout(()=>o.remove(),r))}var be=new TextDecoder(`latin1`);async function T(e,t,n){let r=await e.slice(t,t+n).arrayBuffer();return new DataView(r)}var E=(e,t)=>be.decode(new Uint8Array(e.buffer,e.byteOffset+t,4)),xe={66:`Baseline`,77:`Main`,88:`Extended`,100:`High`,110:`High 10`,122:`High 4:2:2`,244:`High 4:4:4`},Se={apco:`ProRes 422 Proxy`,apcs:`ProRes 422 LT`,apcn:`ProRes 422`,apch:`ProRes 422 HQ`,ap4h:`ProRes 4444`,ap4x:`ProRes 4444 XQ`},Ce={sowt:`PCM s16le`,twos:`PCM s16be`,in24:`PCM s24`,in32:`PCM s32`,lpcm:`PCM`,fl32:`PCM f32`,fl64:`PCM f64`,raw:`PCM u8`};function we(e,t,n){let r={type:``,timescale:0,duration:0,width:0,height:0,format:``,profile:``,samples:0,stts:0,bytes:0,channels:0,bits:0,rate:0,esObject:0},i=(t,n)=>{let a=t;for(;a+8<=n;){let t=e.getUint32(a),o=E(e,a+4),s=8;if(t===1&&(t=Number(e.getBigUint64(a+8)),s=16),t===0&&(t=n-a),tn)break;let c=a+s,l=a+t;if(o===`mdia`||o===`minf`||o===`stbl`)i(c,l);else if(o===`tkhd`){let t=c+(e.getUint8(c)===1?88:76);r.width=e.getUint32(t)/65536,r.height=e.getUint32(t+4)/65536}else if(o===`mdhd`){let t=e.getUint8(c);r.timescale=e.getUint32(c+(t===1?20:12)),r.duration=t===1?Number(e.getBigUint64(c+24)):e.getUint32(c+16)}else if(o===`hdlr`)r.type=E(e,c+8);else if(o===`stsd`){let t=c+8;if(r.format=E(e,t+4),r.type===`vide`){let n=e.getUint16(t+32),i=e.getUint16(t+34);n&&(r.width=n),i&&(r.height=i);let a=t+86,o=e.getUint32(t);for(;a+8<=t+o;){let t=e.getUint32(a),n=E(e,a+4);if(t<8)break;n===`avcC`&&(r.profile=`${xe[e.getUint8(a+9)]??`profile `+e.getUint8(a+9)} L${(e.getUint8(a+11)/10).toFixed(1)}`),n===`hvcC`&&(r.profile={1:`Main`,2:`Main 10`}[e.getUint8(a+9)&31]??``),a+=t}}else if(r.type===`soun`){r.channels=e.getUint16(t+24),r.bits=e.getUint16(t+26),r.rate=e.getUint16(t+32);let n=e.getUint32(t),i=t+36;for(;i+8<=t+n;){let t=e.getUint32(i),n=E(e,i+4);if(t<8)break;if(n===`esds`){for(let n=i+12;nr.byteLength)break;if(t===`mvhd`){let e=r.getUint8(s+8);a=r.getUint32(s+8+(e===1?20:12)),o=e===1?Number(r.getBigUint64(s+8+24)):r.getUint32(s+8+16)}else if(t===`trak`){let t=we(r,s+8,s+e),n=t.timescale?t.duration/t.timescale:0;if(t.type===`vide`&&!i.video){let e=t.stts&&t.samples?t.samples*t.timescale/t.stts:null;i.video={codec:Te(t.format),profile:t.profile,width:Math.round(t.width),height:Math.round(t.height),fps:e,frames:t.samples||null,bitrate:n&&t.bytes?t.bytes*8/n:null,pixels:``}}else t.type===`soun`&&i.audio.push({codec:Ee(t),sampleRate:t.rate||null,channels:t.channels||null,bitDepth:Ce[t.format]?t.bits:null,bitrate:n&&t.bytes?t.bytes*8/n:null})}s+=e}return i.duration=a?o/a:null,i.duration&&(i.bitrate=e.size*8/i.duration),i}function Oe(e,t,n){let r=e[t];if(r===void 0||r===0)return null;let i=1;for(;!(r&128>>i-1);)i++;if(t+i>e.length)return null;let a=n?r:r&255>>i,o=(r&255>>i)==255>>i;for(let n=1;n{if(!o)return;let e=o.codec===`V_VP9`?`VP9`:o.codec===`V_VP8`?`VP8`:o.codec===`V_AV1`?`AV1`:o.codec===`V_MPEG4/ISO/AVC`?`H.264`:o.codec===`V_MPEGH/ISO/HEVC`?`HEVC`:o.codec;o.type===1&&!r.video&&(r.video={codec:e,profile:``,width:o.w,height:o.h,fps:o.dur?1e9/o.dur:null,frames:null,bitrate:null,pixels:``}),o.type===2&&r.audio.push({codec:o.codec===`A_OPUS`?`Opus`:o.codec===`A_VORBIS`?`Vorbis`:o.codec===`A_AAC`?`AAC`:o.codec===`A_FLAC`?`FLAC`:o.codec,sampleRate:o.rate||null,channels:o.ch||null,bitDepth:o.bits||null,bitrate:null}),o=null},c=(e,t)=>{let r=0;for(let i=0;in===4?t.getFloat32(e):n===8?t.getFloat64(e):0,u=(e,t,d)=>{let f=e;for(;f=0?i={codec:`Opus`,sampleRate:48e3,channels:n[a+9],bitDepth:null,bitrate:null}:o>=0&&(i={codec:`Vorbis`,sampleRate:t.getUint32(o+12,!0),channels:n[o+11],bitDepth:null,bitrate:null});let s=await T(e,Math.max(0,e.size-65536),Math.min(e.size,65536)),c=new Uint8Array(s.buffer),l=null;for(let e=c.length-27;e>=0;e--)if(c[e]===79&&c[e+1]===103&&c[e+2]===103&&c[e+3]===83){l=Number(s.getBigUint64(e+6,!0));break}let u=i.sampleRate??48e3,d=l!==null&&l>0?l/(i.codec===`Opus`?48e3:u):null;return{container:`Ogg`,duration:d,size:e.size,bitrate:d?e.size*8/d:null,video:null,audio:[i],notes:[]}}async function Ne(e){let t=await T(e,0,Math.min(e.size,64));if(t.byteLength<26||E(t,0)!==`fLaC`)return null;let n=t.getUint8(18)<<12|t.getUint8(19)<<4|t.getUint8(20)>>4,r=(t.getUint8(20)>>1&7)+1,i=((t.getUint8(20)&1)<<4|t.getUint8(21)>>4)+1,a=(t.getUint8(21)&15)*2**32+t.getUint32(22),o=n&&a?a/n:null;return{container:`FLAC`,duration:o,size:e.size,bitrate:o?e.size*8/o:null,video:null,audio:[{codec:`FLAC`,sampleRate:n,channels:r,bitDepth:i,bitrate:null}],notes:[]}}var Pe=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320],Fe=[44100,48e3,32e3];async function Ie(e){let t=await T(e,0,Math.min(e.size,65536)),n=0;if(E(t,0).startsWith(`ID3`)&&(n=10+(t.getUint8(6)<<21|t.getUint8(7)<<14|t.getUint8(8)<<7|t.getUint8(9))),n+4>t.byteLength)return null;for(let r=n;r+4>3&3,i=t.getUint8(r+1)>>1&3,a=Pe[t.getUint8(r+2)>>4],o=Fe[t.getUint8(r+2)>>2&3];if(n!==3||i!==1||!a||!o)continue;let s=t.getUint8(r+3)>>6==3?1:2;return{container:`MPEG audio`,duration:(e.size-r)*8/(a*1e3),size:e.size,bitrate:a*1e3,video:null,audio:[{codec:`MP3`,sampleRate:o,channels:s,bitDepth:null,bitrate:a*1e3}],notes:[`duration assumes constant bitrate`]}}return null}async function Le(e){let t=[De,Ae,je,Me,Ne,Ie];for(let n of t)try{let t=await n(e);if(t)return t}catch{continue}return{container:e.type||`unknown`,duration:null,size:e.size,bitrate:null,video:null,audio:[],notes:[`container not recognised, showing what the browser reports`]}}var Re=0,ze=()=>`src${++Re}`,D=48e3;function Be(e,t,n,r=8e3){return new Promise((i,a)=>{let o=window.setTimeout(()=>{l(),a(Error(`timed out waiting for ${t}`))},r),s=()=>{l(),i()},c=()=>{l(),a(Error(`the browser cannot decode this file`))},l=()=>{window.clearTimeout(o),e.removeEventListener(t,s),e.removeEventListener(n,c)};e.addEventListener(t,s),e.addEventListener(n,c)})}async function Ve(e){if(Number.isFinite(e.duration))return e.duration;e.currentTime=1e101,await Be(e,`durationchange`,`error`,4e3).catch(()=>void 0);let t=Number.isFinite(e.duration)?e.duration:0;return e.currentTime=0,t}async function He(e){let t=e.requestVideoFrameCallback?.bind(e);if(!t)return 30;let n=[];return new Promise(r=>{let i=()=>{e.pause(),e.currentTime=0;let t=[];for(let e=1;en[e-1]&&t.push(n[e]-n[e-1]);t.sort((e,t)=>e-t);let i=1/(t.length?t[t.length>>1]:1/30),a=[12,15,23.976,24,25,29.97,30,50,59.94,60].reduce((e,t)=>Math.abs(t-i){n.push(r.mediaTime),n.length>=14?i():t(a)};t(a),e.muted=!0,e.play().catch(()=>i()),window.setTimeout(()=>{n.length<14&&i()},1500)})}async function Ue(e,t){let n=URL.createObjectURL(e),r=document.createElement(`video`);r.muted=!0,r.preload=`auto`,r.playsInline=!0,r.src=n;try{await Be(r,`loadedmetadata`,`error`)}catch(e){throw URL.revokeObjectURL(n),e}let i=await Ve(r),a=r.videoWidth>0&&r.videoHeight>0,o=a?t??await He(r):0;a&&await We(r,0);let s=null;return{id:ze(),name:e.name,kind:a?`video`:`audio`,sample:!1,size:e.size,width:r.videoWidth,height:r.videoHeight,fps:o,duration:i,async frame(e){return await We(r,Math.max(0,Math.min(e,Math.max(0,i-.001)))),r},audio(){return s||=(async()=>{if(e.size>629145600)return null;try{return await new OfflineAudioContext(2,1,D).decodeAudioData(await e.arrayBuffer())}catch{return null}})(),s},dispose(){r.removeAttribute(`src`),r.load(),URL.revokeObjectURL(n)}}}async function We(e,t){if(Math.abs(e.currentTime-t)<1e-4&&e.readyState>=2)return;let n=Be(e,`seeked`,`error`,6e3);e.currentTime=t,await n}function O(e){return e==null||!Number.isFinite(e)?``:e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(0)} KB`:e<1073741824?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(2)} GB`}function Ge(e){if(e==null||!Number.isFinite(e)||e<0)return`--:--`;let t=Math.round(e),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n?`${n}:${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`:`${String(r).padStart(2,`0`)}:${String(i).padStart(2,`0`)}`}function k(e){return!e||!Number.isFinite(e)?``:e<60?`${e.toFixed(e<10?2:1)} s`:Ge(e)}function Ke(e){return Math.abs(e-29.97)<.02||Math.abs(e-59.94)<.03}function qe(e,t){let n=Math.max(1,Math.round(t)),r=Ke(t)?Math.round(n/15):0,i=Math.max(0,Math.floor(e));if(r){let e=Math.round(t*600),a=n*60-r,o=Math.floor(i/e),s=i%e;i+=r*9*o+(s>r?r*Math.floor((s-r)/a):0)}let a=i%n,o=Math.floor(i/n),s=e=>String(e).padStart(2,`0`);return`${s(Math.floor(o/3600))}:${s(Math.floor(o/60)%60)}:${s(o%60)}${r?`;`:`:`}${s(a)}`}function A(e){let t=[[23.976,`23.976`],[24,`24`],[25,`25`],[29.97,`29.97`],[30,`30`],[50,`50`],[59.94,`59.94`],[60,`60`]].find(([t])=>Math.abs(t-e)<.02);return t?t[1]:String(Number(e.toFixed(3)))}function j(e,t){if(!e||!t)return``;let n=e/t,r=[[16/9,`16:9`],[2,`2:1`],[9/16,`9:16`],[4/3,`4:3`],[1,`1:1`],[3/4,`3:4`],[21/9,`21:9`]].find(([e])=>Math.abs(e-n)/e<.01);return r?r[1]:n.toFixed(2)}function Je(e,t,n,r){return{id:e,name:t,role:n,form:r,parent:``,origin:`included`,label:``,state:`loading`,progress:0,message:``,blob:null,size:0,source:null,probe:null,gif:null,seq:null,frameBlobs:null,names:[],thumb:``,md5:``,md5State:`idle`,width:0,height:0,fps:0,frames:0,duration:0,offset:0,expect:null,checks:null,url:``}}var M=e=>e.replace(/\.[^.]+$/,``).replace(/_%0\dd$/,``),N=e=>(e.form===`video`||e.form===`sequence`)&&!!e.source&&e.state!==`loading`,P=new class{items=[];slotA=``;slotB=``;view=`compare`;zoom=`fit`;frame=0;markIn=null;markOut=null;working=``;logs=[];listeners=new Map;seq=0;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e)?.add(t)}emit(e){for(let t of this.listeners.get(e)??[])t()}log(e,t=!1){let n=new Date,r=[n.getHours(),n.getMinutes(),n.getSeconds()].map(e=>String(e).padStart(2,`0`)).join(`:`);this.logs.push({time:r,text:e,error:t}),this.logs.length>400&&this.logs.shift(),this.emit(`log`)}nextId(){return this.seq+=1,`m${this.seq}`}get(e){return this.items.find(t=>t.id===e)}a(){return this.get(this.slotA)}b(){return this.get(this.slotB)}master(){let e=this.a();return e&&e.fps>0?e:this.b()}sources(){return this.items.filter(e=>e.role===`source`)}outputs(){return this.items.filter(e=>e.role!==`source`)}add(e){return this.items.push(e),this.emit(`items`),e}make(e,t,n){return Je(this.nextId(),e,t,n)}setSlots(e,t){(e!==this.slotA||t!==this.slotB)&&(this.slotA=e,this.slotB=t,this.emit(`slots`))}setView(e){e!==this.view&&(this.view=e,this.emit(`view`))}setZoom(e){e!==this.zoom&&(this.zoom=e,this.emit(`view`))}setFrame(e){let t=this.master(),n=t?Math.max(0,t.frames-1):0,r=Math.max(0,Math.min(n,Math.round(e)));r!==this.frame&&(this.frame=r,this.emit(`frame`))}setMarks(e,t){this.markIn=e,this.markOut=t,this.emit(`marks`)}},Ye=e=>e?`${(e/1e6).toFixed(2)} Mb/s`:``;function Xe(e){return e.form===`sequence`?`Image sequence`:e.form===`animation`?`Animated GIF`:e.form===`archive`?`Numbered frames (ZIP)`:e.role===`proxy`?`Video, proxy`:`Video`}function Ze(e,t){let n=[],r=(e,t,r)=>{r&&n.push({key:e,label:t,value:r})};r(`kind`,`Kind`,Xe(e));let i=e.probe;if(e.form===`sequence`&&e.seq)r(`container`,`Container`,`Numbered ${e.seq.ext.slice(1).toUpperCase()} files`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.duration)),r(`vcodec`,`Video`,e.seq.ext.slice(1).toUpperCase()===`JPG`?`JPEG, intra only`:e.seq.ext.slice(1).toUpperCase()),r(`frame`,`Frame`,`${e.width}x${e.height}`),r(`shape`,`Shape`,j(e.width,e.height)),r(`rate`,`Rate`,`${A(e.fps)} fps (set when added)`),r(`frames`,`Frames`,`${e.seq.count}, ${String(e.seq.first).padStart(e.seq.digits,`0`)} to ${String(e.seq.last).padStart(e.seq.digits,`0`)}${e.seq.gaps.length?`, ${e.seq.gaps.length} missing`:`, no gaps`}`),r(`audio`,`Audio`,`None`);else if(e.form===`animation`&&e.gif)r(`container`,`Container`,`GIF89a`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.gif.duration)),r(`vcodec`,`Video`,`GIF, 256 colours`),r(`frame`,`Frame`,`${e.gif.width}x${e.gif.height}`),r(`shape`,`Shape`,j(e.gif.width,e.gif.height)),r(`rate`,`Rate`,e.gif.duration?`${A(e.gif.frames/e.gif.duration)} fps`:``),r(`frames`,`Frames`,String(e.gif.frames)),r(`audio`,`Audio`,`None`),r(`loop`,`Loop`,e.gif.loops?`Forever`:`Once`);else if(e.form===`archive`)r(`container`,`Container`,`ZIP, stored`),r(`size`,`Size`,O(e.size)),r(`duration`,`Duration`,k(e.duration)),r(`vcodec`,`Video`,e.seq?.ext.slice(1).toUpperCase()??``),r(`frame`,`Frame`,e.width?`${e.width}x${e.height}`:``),r(`shape`,`Shape`,j(e.width,e.height)),r(`rate`,`Rate`,e.fps?`${A(e.fps)} fps`:``),e.seq&&r(`frames`,`Frames`,`${e.seq.count}, ${String(e.seq.first).padStart(e.seq.digits,`0`)} to ${String(e.seq.last).padStart(e.seq.digits,`0`)}${e.seq.gaps.length?`, ${e.seq.gaps.length} missing`:`, no gaps`}`),r(`audio`,`Audio`,`None`);else if(i){r(`container`,`Container`,i.container),r(`size`,`Size`,O(i.size)),r(`duration`,`Duration`,k(i.duration??e.duration)),r(`bitrate`,`Bit rate`,Ye(i.bitrate)),i.video&&(r(`vcodec`,`Video`,[i.video.codec,i.video.profile].filter(Boolean).join(` `)),r(`frame`,`Frame`,`${i.video.width}x${i.video.height}`),r(`shape`,`Shape`,j(i.video.width,i.video.height)),r(`rate`,`Rate`,i.video.fps?`${A(i.video.fps)} fps`:``),r(`frames`,`Frames`,i.video.frames?String(i.video.frames):``),r(`vbit`,`Video rate`,Ye(i.video.bitrate)));let n=i.audio[0];r(`audio`,`Audio`,n?[n.codec,n.sampleRate?`${n.sampleRate} Hz`:``,n.channels?`${n.channels} ch`:``].filter(Boolean).join(`, `):`None`),r(`loud`,`Loudness`,t)}return r(`md5`,`MD5`,e.md5?`${e.md5.slice(0,12)}...`:e.md5State===`running`?`Reading`:``),n}var F=(e,t,n)=>Math.abs(e-t)<=n;function Qe(e){let t=e.expect,n=[];if(!t)return n;if(e.form===`archive`&&e.seq){let r=e.width===t.width&&e.height===t.height;return n.push({label:`Frame count`,want:String(t.frames),got:String(e.seq.count),ok:e.seq.count===t.frames}),n.push({label:`Numbers`,want:`1 to ${t.frames}`,got:`${e.seq.first} to ${e.seq.last}`,ok:e.seq.first===1&&e.seq.last===t.frames&&e.seq.gaps.length===0}),n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${e.width}x${e.height}`,ok:r}),n}if(e.form===`animation`&&e.gif)return n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${e.gif.width}x${e.gif.height}`,ok:e.gif.width===t.width&&e.gif.height===t.height}),n.push({label:`Frame rate`,want:`${A(t.fps)}`,got:e.gif.duration?`${A(e.gif.frames/e.gif.duration)}`:``,ok:e.gif.duration>0&&F(e.gif.frames/e.gif.duration,t.fps,1.6)}),n.push({label:`Duration`,want:`${t.duration.toFixed(2)} s`,got:`${e.gif.duration.toFixed(2)} s`,ok:F(e.gif.duration,t.duration,Math.max(.1,1/t.fps))}),n;let r=e.probe?.video;if(!r)return n;n.push({label:`Frame size`,want:`${t.width}x${t.height}`,got:`${r.width}x${r.height}`,ok:r.width===t.width&&r.height===t.height}),n.push({label:`Frame rate`,want:A(t.fps),got:r.fps?A(r.fps):``,ok:!!r.fps&&F(r.fps,t.fps,.05)});let i=e.probe?.duration??e.duration;n.push({label:`Duration`,want:`${t.duration.toFixed(2)} s`,got:`${i.toFixed(2)} s`,ok:F(i,t.duration,Math.max(.06,1.5/t.fps))}),n.push({label:`Video codec`,want:t.codec,got:r.codec,ok:r.codec.toLowerCase().replace(/\W/g,``).includes(t.codec.toLowerCase().replace(/\W/g,``))});let a=(e.probe?.audio.length??0)>0;return n.push({label:`Audio`,want:t.audio?`present`:`none`,got:a?`present`:`none`,ok:a===t.audio}),r.frames&&t.frames&&n.push({label:`Frames`,want:String(t.frames),got:String(r.frames),ok:Math.abs(r.frames-t.frames)<=1}),n}function $e(e,t){let n=e.probe?.video,r=t.probe?.video;if(!n||!r)return[];let i=(e.probe?.audio.length??0)>0,a=(t.probe?.audio.length??0)>0,o=n.frames??Math.round((e.probe?.duration??e.duration)*(n.fps??e.fps)),s=r.frames??Math.round((t.probe?.duration??t.duration)*(r.fps??t.fps));return[{label:`Same frame rate`,want:r.fps?A(r.fps):``,got:n.fps?A(n.fps):``,ok:!!n.fps&&!!r.fps&&F(n.fps,r.fps,.05)},{label:`Same frame count`,want:String(s),got:String(o),ok:!!o&&Math.abs(o-s)<=1},{label:`Same duration`,want:`${(t.probe?.duration??t.duration).toFixed(2)} s`,got:`${(e.probe?.duration??e.duration).toFixed(2)} s`,ok:F(e.probe?.duration??e.duration,t.probe?.duration??t.duration,.08)},{label:`Same shape`,want:j(r.width,r.height),got:j(n.width,n.height),ok:j(r.width,r.height)===j(n.width,n.height)},{label:`Same audio`,want:a?`present`:`none`,got:i?`present`:`none`,ok:i===a}]}function et(){let e=P.sources().filter(e=>e.state!==`loading`&&e.fps>0);if(e.length<2)return[];let t=[...new Set(e.map(e=>A(e.fps)))],n=[...new Set(e.map(e=>j(e.width,e.height)))],r=[];return r.push(`${e.length} sources, ${t.length} frame rate${t.length===1?``:`s`} (${t.join(`, `)})`),r.push(`${n.length} frame shape${n.length===1?``:`s`} (${n.join(`, `)})`),r}async function tt(e){let t=new Uint8Array(await e.arrayBuffer()),n=String.fromCharCode(...t.subarray(0,6));if(n!==`GIF89a`&&n!==`GIF87a`)return null;let r=new DataView(t.buffer),i=r.getUint16(6,!0),a=r.getUint16(8,!0),o=13+(t[10]&128?3*2**((t[10]&7)+1):0),s=0,c=0,l=!1,u=()=>{for(;o>>0;var it=class{a=1732584193;b=-271733879;c=-1732584194;d=271733878;tail=new Uint8Array(64);fill=0;total=0;w=new Int32Array(16);update(e){this.total+=e.length;let t=0;if(this.fill){let n=Math.min(64-this.fill,e.length);this.tail.set(e.subarray(0,n),this.fill),this.fill+=n,t=n,this.fill===64&&(this.block(this.tail,0),this.fill=0)}for(;t+64<=e.length;t+=64)this.block(e,t);t>4)*4+(e&3)],l=r+t+rt[e]+n[s]|0,u=i+(l<>>32-c)|0;r=o,o=a,a=i,i=u}this.a=this.a+r|0,this.b=this.b+i|0,this.c=this.c+a|0,this.d=this.d+o|0}hex(){let e=this.total*8,t=new Uint8Array((this.fill<56?56:120)-this.fill+8);t[0]=128;let n=new DataView(t.buffer);n.setUint32(t.length-8,e>>>0,!0),n.setUint32(t.length-4,Math.floor(e/4294967296),!0),this.update(t);let r=new Uint8Array(16),i=new DataView(r.buffer);return i.setInt32(0,this.a,!0),i.setInt32(4,this.b,!0),i.setInt32(8,this.c,!0),i.setInt32(12,this.d,!0),Array.from(r,e=>e.toString(16).padStart(2,`0`)).join(``)}},I=2097152;function at(){return new Promise(e=>window.setTimeout(e,0))}async function L(e,t){let n=new it;for(let r=0;rvoid 0).then(async()=>{let e=await r.frame(t);return n(e,e instanceof HTMLVideoElement?e.videoWidth:e.width,e instanceof HTMLVideoElement?e.videoHeight:e.height)});return ot.set(e.id,i),i}async function st(e,t){return(await fetch(`data:${t};base64,${e}`)).blob()}function ct(){let e=window;return e.INSPECT_MEDIA||={},e.INSPECT_MEDIA}function lt(e){return new Promise((t,n)=>{let r=document.createElement(`script`);r.async=!0,r.src=`media/${e}.js`,r.onload=()=>{r.remove(),t()},r.onerror=()=>{r.remove(),n(Error(`the media pack ${e} did not load`))},document.head.appendChild(r)})}var ut=/^(.*?)(\d+)(\.[A-Za-z0-9]+)$/;function dt(e){let t=new Map;for(let n of e){let e=ut.exec(n.name);if(!e)continue;let r=`${e[1]}|${e[2].length}|${e[3].toLowerCase()}`;t.has(r)||t.set(r,[]),t.get(r)?.push({...n,n:Number(e[2])})}let n=null,r=``;for(let[e,i]of t)(!n||i.length>n.length)&&(n=i,r=e);if(!n||n.length<2)return null;n.sort((e,t)=>e.n-t.n);let[i,a,o]=r.split(`|`),s=new Set(n.map(e=>e.n)),c=n[0].n,l=n[n.length-1].n,u=[];for(let e=c;e<=l;e++)s.has(e)||u.push(e);return{files:n,info:{pattern:`${i}%0${a}d${o}`,first:c,last:l,count:n.length,gaps:u,digits:Number(a),ext:o}}}var ft=0;async function pt(e,t){let n=dt(e);if(!n)throw Error(`these files are not a numbered image sequence`);let r=await Promise.all(n.files.map(e=>createImageBitmap(e.blob))),i=r[0].width,a=r[0].height,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`),c=r.length/t;return{source:{id:`seq${++ft}`,name:n.info.pattern,kind:`video`,sample:!1,size:n.files.reduce((e,t)=>e+t.blob.size,0),width:i,height:a,fps:t,duration:c,async frame(e){let n=Math.max(0,Math.min(r.length-1,Math.floor(e*t+1e-6)));return s.clearRect(0,0,i,a),s.drawImage(r[n],0,0,i,a),o},audio:()=>Promise.resolve(null),dispose:()=>void 0},info:n.info,names:n.files.map(e=>e.name),width:i,height:a}}var mt=3e4/1001,ht=[{pack:`autumn-stream`,file:`autumn-stream.mp4`,role:`source`,form:`video`,parent:``,label:`Camera original, trimmed`,width:1280,height:720,fps:mt,duration:8.008,frames:240,size:6525912,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`waterfall`,file:`waterfall.mp4`,role:`source`,form:`video`,parent:``,label:`Camera original, trimmed`,width:1280,height:640,fps:24e3/1001,duration:6.006,frames:144,size:2898071,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`river-vertical`,file:`river-vertical.mp4`,role:`source`,form:`video`,parent:``,label:`Phone original, vertical`,width:404,height:720,fps:60,duration:6.15,frames:369,size:1501308,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`clouds-sequence`,file:`clouds_%04d.jpg`,role:`source`,form:`sequence`,parent:``,label:`Numbered stills, 24 fps`,width:960,height:540,fps:24,duration:1.5,frames:36,size:17e5,codec:`JPEG`,audio:!1,offset:0,type:`image/jpeg`},{pack:`autumn-stream_high`,file:`autumn-stream_high.mp4`,role:`output`,form:`video`,parent:`autumn-stream.mp4`,label:`Match Source, high: H.264 3.5 Mb/s`,width:1280,height:720,fps:mt,duration:3.003,frames:90,size:1514869,codec:`H.264`,audio:!0,offset:2.002,type:`video/mp4`},{pack:`autumn-stream_low`,file:`autumn-stream_low.mp4`,role:`output`,form:`video`,parent:`autumn-stream.mp4`,label:`Match Source, low: H.264 0.45 Mb/s`,width:1280,height:720,fps:mt,duration:3.003,frames:90,size:220648,codec:`H.264`,audio:!0,offset:2.002,type:`video/mp4`},{pack:`autumn-stream_Proxy`,file:`autumn-stream_Proxy.mp4`,role:`proxy`,form:`video`,parent:`autumn-stream.mp4`,label:`H.264 Proxy 960x540`,width:960,height:540,fps:mt,duration:8.008,frames:240,size:2922345,codec:`H.264`,audio:!0,offset:0,type:`video/mp4`},{pack:`autumn-stream_480`,file:`autumn-stream_480.gif`,role:`output`,form:`animation`,parent:`autumn-stream.mp4`,label:`Animated GIF 480 px`,width:480,height:270,fps:15,duration:3,frames:45,size:892598,codec:`GIF`,audio:!1,offset:2.002,type:`image/gif`}],gt={markIn:60,markOut:149};function _t(){let e=new Map;for(let t of ht){let n=P.make(t.file,t.role,t.form);n.label=t.label,n.width=t.width,n.height=t.height,n.fps=t.fps,n.duration=t.duration,n.frames=t.frames,n.size=t.size,n.offset=t.offset,n.origin=`included`,t.role!==`source`&&(n.expect={width:t.width,height:t.height,fps:t.fps,duration:t.duration,frames:t.frames,codec:t.codec,audio:t.audio},n.parent=e.get(t.parent)?.id??``),e.set(t.file,n),P.items.push(n)}return e}async function vt(e){return R(e,e.form===`sequence`?e.duration/2:Math.min(e.duration/2,2.5),(e,t,n)=>{let r=document.createElement(`canvas`);return r.width=240,r.height=Math.max(2,Math.round(240*n/t)),r.getContext(`2d`)?.drawImage(e,0,0,r.width,r.height),r.toDataURL(`image/jpeg`,.72)})}async function yt(e,t){await lt(e.pack);let n=ct(),r=e.form===`sequence`?e.pack:e.file,i=n[r];if(delete n[r],!i)throw Error(`the pack ${e.pack} holds no ${e.file}`);if(e.form===`sequence`){let n=await Promise.all(Object.entries(i).map(async([e,t])=>({name:e,blob:await st(t,`image/jpeg`)}))),r=await pt(n,e.fps);t.source=r.source,t.seq=r.info,t.names=r.names,t.size=r.source.size,t.width=r.width,t.height=r.height,t.frames=r.info.count,t.duration=r.info.count/e.fps,t.frameBlobs=n.sort((e,t)=>e.name.localeCompare(t.name)).map(e=>e.blob)}else{let n=await st(i,e.type);if(t.blob=n,t.size=n.size,e.form===`animation`)t.gif=await tt(n),t.url=URL.createObjectURL(n);else{let r=new File([n],e.file,{type:e.type}),i=await Le(r);t.probe=i;let a=i.video?.fps&&Number.isFinite(i.video.fps)?i.video.fps:e.fps;t.source=await Ue(r,a),t.fps=a,t.width=i.video?.width??e.width,t.height=i.video?.height??e.height,t.duration=i.duration??t.source.duration,t.frames=i.video?.frames??Math.round(t.duration*a)}}t.state=`ready`}async function bt(e){if(e.source)try{e.thumb=await vt(e)}catch(t){P.log(`No thumbnail for ${e.name}: ${t.message}`,!0)}}function z(e){if(!e.expect)return;let t=Qe(e),n=P.get(e.parent);e.checks=e.role===`proxy`&&n?.probe?[...t,...$e(e,n)]:t}async function xt(){for(let e of P.items){if(!e.blob&&!e.frameBlobs||e.md5State===`done`)continue;e.md5State=`running`,P.emit(`items`);let t=performance.now();try{e.md5=e.blob?await L(e.blob):await L(new Blob(e.frameBlobs)),e.md5State=`done`,P.log(`MD5 ${e.md5} ${e.name} (${((performance.now()-t)/1e3).toFixed(1)} s)`)}catch(t){e.md5State=`idle`,P.log(`MD5 failed for ${e.name}: ${t.message}`,!0)}P.emit(`items`)}}async function St(){let e=_t();P.emit(`items`);let t=e.get(`autumn-stream.mp4`),n=e.get(`autumn-stream_low.mp4`);P.setSlots(t.id,n.id);let r=[`autumn-stream.mp4`,`autumn-stream_low.mp4`,`autumn-stream_high.mp4`,`waterfall.mp4`,`river-vertical.mp4`,`clouds_%04d.jpg`,`autumn-stream_Proxy.mp4`,`autumn-stream_480.gif`],i=0;for(let n of r){let r=ht.find(e=>e.file===n),a=e.get(n);try{await yt(r,a),i+=1,z(a),P.emit(`items`),a===t&&P.setFrame(gt.markIn+24),bt(a).then(()=>P.emit(`items`)),P.log(`Loaded ${a.name}`)}catch(e){a.state=`failed`,a.message=e.message,P.log(`Could not load ${n}: ${a.message}`,!0),P.emit(`items`)}}for(let e of P.items)e.role===`proxy`&&z(e);P.emit(`items`),i||P.log(`No curated media loaded`,!0),xt()}function B(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>URL.revokeObjectURL(n),4e3)}function Ct(e,t=`image/png`,n){return new Promise((r,i)=>e.toBlob(e=>e?r(e):i(Error(`the canvas could not be saved`)),t,n))}var wt=new Map,Tt=`md5`,Et=!1,Dt=!1,Ot={size:`Size`,md5:`MD5`,bit:`Bit for bit`};function kt(e){return e.blob?e.blob:e.frameBlobs?new Blob(e.frameBlobs):null}async function At(e,t,n){let r=kt(e);if(!r)return;let i={mode:t,srcMd5:``,copyMd5:``,ok:!1,detail:``,progress:0,running:!0,flipped:n};wt.set(e.id,i),P.emit(`items`);let a=new it,o=[],s=Math.floor(r.size*.37);for(let e=0;e=e&&s{i.progress=.5+e*.5,P.emit(`items`)}),i.ok=i.copyMd5===i.srcMd5,i.detail=i.ok?`Copy read back from storage matches`:`${i.srcMd5.slice(0,8)} against ${i.copyMd5.slice(0,8)}`;else{let e=-1;for(let t=0;te.md5).map(e=>`${e.md5} ${e.name}`).join(` `)+` `}async function Nt(e){let n=await e.text(),r=[];for(let e of n.split(/\r?\n/)){let t=/^([a-fA-F0-9]{32})\s+\*?(.+?)\s*$/.exec(e);if(!t)continue;let n=P.items.find(e=>e.name===t[2]);n?n.md5?n.md5===t[1].toLowerCase()?r.push([`ok`,t[2],`OK`]):r.push([`bad`,t[2],`FAILED, listed ${t[1].slice(0,8)}, file ${n.md5.slice(0,8)}`]):r.push([`missing`,t[2],`not read yet`]):r.push([`missing`,t[2],`no file of that name is loaded`])}let i=new v(`Check ${e.name}`,560),a=s(`
`);r.length||a.appendChild(s(`

No MD5 lines were found. Each line is a 32 character hash, two spaces and a file name.

`));for(let[e,n,i]of r){let r=s(`
`);t(c(r,`.ins-report-name`),n),t(c(r,`.ins-report-text`),i),a.appendChild(r)}i.body.appendChild(a);let o=r.filter(e=>e[0]!==`ok`).length;P.log(`Checked ${e.name}: ${r.length-o} of ${r.length} match`,o>0),i.button(`Close`,`primary`,()=>i.close()),i.open()}var Pt=class{id=`checksums`;title=`Ingest and Checksums`;el;list;constructor(){this.el=s(`
diff --git a/form-functions.json b/form-functions.json index b64a8f1..23d52b6 100644 --- a/form-functions.json +++ b/form-functions.json @@ -2,7 +2,7 @@ "format": "form-functions", "format_version": 1, "app": "formencoder", - "app_version": "0.9.0", + "app_version": "0.10.0", "functions": [ { "id": "encode", diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 0e13edd..b2aa7a8 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formencoder", - "version": "0.9.0", + "version": "0.10.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formencoder", - "version": "0.9.0", + "version": "0.10.0", "license": "Apache-2.0", "dependencies": { "@fontsource/inter": "5.3.0", diff --git a/frontend/package.json b/frontend/package.json index 5340036..cab93ee 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formencoder", "private": true, - "version": "0.9.0", + "version": "0.10.0", "description": "formencoder · the media encoder of the form family", "license": "Apache-2.0", "type": "module", diff --git a/frontend/src/version.ts b/frontend/src/version.ts index b336f57..699451e 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.9.0'; +export const VERSION = '0.10.0'; diff --git a/native/Cargo.lock b/native/Cargo.lock index c5ed463..f6beb7c 100644 --- a/native/Cargo.lock +++ b/native/Cargo.lock @@ -157,7 +157,7 @@ dependencies = [ [[package]] name = "fencoder-commands" -version = "0.9.0" +version = "0.10.0" dependencies = [ "fencoder-core", "fencoder-engine", @@ -170,7 +170,7 @@ dependencies = [ [[package]] name = "fencoder-core" -version = "0.9.0" +version = "0.10.0" dependencies = [ "ab_glyph", "chrono", @@ -183,7 +183,7 @@ dependencies = [ [[package]] name = "fencoder-engine" -version = "0.9.0" +version = "0.10.0" dependencies = [ "fencoder-core", "fencoder-io", @@ -194,7 +194,7 @@ dependencies = [ [[package]] name = "fencoder-io" -version = "0.9.0" +version = "0.10.0" dependencies = [ "chrono", "fencoder-core", @@ -207,7 +207,7 @@ dependencies = [ [[package]] name = "fencoder-plan" -version = "0.9.0" +version = "0.10.0" dependencies = [ "chrono", "fencoder-core", @@ -218,7 +218,7 @@ dependencies = [ [[package]] name = "fencoder-py" -version = "0.9.0" +version = "0.10.0" dependencies = [ "fencoder-commands", "fencoder-core", @@ -232,7 +232,7 @@ dependencies = [ [[package]] name = "fencoder-run" -version = "0.9.0" +version = "0.10.0" dependencies = [ "fencoder-core", "fencoder-io", diff --git a/native/Cargo.toml b/native/Cargo.toml index 77cae2f..c89ef17 100644 --- a/native/Cargo.toml +++ b/native/Cargo.toml @@ -11,7 +11,7 @@ members = [ ] [workspace.package] -version = "0.9.0" +version = "0.10.0" edition = "2024" rust-version = "1.95" license = "Apache-2.0" diff --git a/native/fencoder-py/pyproject.toml b/native/fencoder-py/pyproject.toml index 4196a0c..a169151 100644 --- a/native/fencoder-py/pyproject.toml +++ b/native/fencoder-py/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "fe-core" -version = "0.9.0" +version = "0.10.0" description = "formencoder's own encoding engine for the formencoder engine service" license = { text = "Apache-2.0" } requires-python = ">=3.10" diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index b87538c..246918c 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -893,7 +893,7 @@ dependencies = [ [[package]] name = "formencoder" -version = "0.9.0" +version = "0.10.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index c1ea6b7..d059b69 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formencoder" -version = "0.9.0" +version = "0.10.0" description = "formencoder desktop shell" authors = ["NodeAgentc, Inc."] license = "Apache-2.0" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index b301fef..fbfa5e1 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormEncoder", - "version": "0.9.0", + "version": "0.10.0", "identifier": "dev.formai.formencoder", "build": { "frontendDist": "../frontend/dist" From 0ce1120db7a8f0bff9e3e8739f791cecef6837ea Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 19 Nov 2026 23:30:03 -0500 Subject: [PATCH 30/30] fix(functions): a function call refuses a pixel aspect value with anything but a ratio whichever engine command carries it Three cases of test_the_engine_side_guard_refuses_metacharacters_and_inner_paths failed in the pull request's test job (3 failed, 261 passed). They queue an output with such a value and expect guard.before to refuse it. Since 0.8.2 (584fe9b, 11 November) the engine replaces the value with 1:1 when it is set, so the queued output never held it and guard.before, which read only the engine's merged settings, had nothing to refuse; the test, written the day before (c91e8e8), has failed since then. The function session now keeps every settings patch it carries to the engine, and guard.before, after its checks of the merged settings, applies the patch rule to each of them. encode already applied that rule before queueing, so its answers are the same. Seen with a headless session: the three values were held by the engine as 1:1 and refused by guard.before with the setting's name; 4:3 and source were held as sent and allowed. Run: tests/test_functions.py, 42 passed (39 passed and 3 failed before). Not changed: the engine (no Rust change, not rebuilt), and the window's and agents' own commands, where the engine still corrects such a value to 1:1. --- backend/HASHOUT_LOG.md | 10 ++++++++++ backend/app/functions/guard.py | 2 ++ backend/app/functions/session.py | 3 +++ 3 files changed, 15 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index d08fd02..c42b716 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -350,3 +350,13 @@ Refers to `backend/formencoder_engine.py` (the first lines) · kind: fix · logg - Checked on Linux: started with `>&- 2>&-` on port 4743 the engine gave no answer on its health route before this change and answered `{"status":"ok",...}` after it; started normally it still printed `Uvicorn running on http://127.0.0.1:4741`. - Not run: Windows, a frozen engine. +## A function call refuses a setting it was sent even when the engine has already corrected it (unreleased, after 0.10.0) + +Refers to `backend/app/functions/session.py` (`Session.run`, `Session.sent`), `backend/app/functions/guard.py` (`before`) · kind: fix · logged: unreleased · 2026-11-19 + +- Why: three cases of `test_the_engine_side_guard_refuses_metacharacters_and_inner_paths` failed in the pull request's test job. They queue an output with a pixel aspect value that is not a ratio and expect `guard.before` to refuse it. Since 0.8.2 (584fe9b, 11 November) `settings::normalize` replaces such a value with `1:1`, so the queued output never held it, and `guard.before`, which read only the engine's merged settings, had nothing to refuse: the call would have gone on with a value the caller did not send. The test was written the day before that change (c91e8e8, 10 November) and has failed since it. +- `Session.run` keeps every `settings` patch it carries to the engine in `Session.sent`. After its checks of the merged settings, `guard.before` runs `guard.patch` on each of them, so a pixel aspect value with anything but a ratio, and any other string the patch rule refuses, is refused whichever engine command carried it, whether the engine kept it or corrected it. +- The new check comes last, so a path the engine did keep is still refused with its own "outside" sentence. `encode` already ran `guard.patch` before queueing, so its answers are the same. +- Seen with a headless session before any test was run again: queued with `1:1,movie=...`, `1:1;x` and `1:1 /...` the engine held `1:1` each time and `guard.before` refused with `params.settings.video.pixelAspect ... holds a filtergraph, option or path character`; `4:3` and `source` were held as sent and allowed. Then `tests/test_functions.py`: 42 passed (39 passed, 3 failed before). +- Not changed: the engine (no Rust change, not rebuilt) and the commands the window and agents use, where such a value is still corrected to `1:1` and not refused. + diff --git a/backend/app/functions/guard.py b/backend/app/functions/guard.py index 23fded1..e0d77e1 100644 --- a/backend/app/functions/guard.py +++ b/backend/app/functions/guard.py @@ -71,6 +71,8 @@ def before(s: Session, oid: str, out: Path, planned: str) -> None: for m in _PATH_INSIDE.finditer(value): if not _within(value[m.start(1):], allowed): raise FunctionError(f"{where} names {value[m.start(1):]}, outside the inputs, the install and out_dir") + for sent in s.sent: + patch(sent) def patch(settings: object) -> None: diff --git a/backend/app/functions/session.py b/backend/app/functions/session.py index 0dd1aac..9b08fc9 100644 --- a/backend/app/functions/session.py +++ b/backend/app/functions/session.py @@ -29,8 +29,11 @@ class FunctionError(Exception): class Session: def __init__(self, engine: Any) -> None: self.engine = engine + self.sent: list = [] def run(self, command: str, **params: Any) -> Any: + if params.get("settings"): + self.sent.append(params["settings"]) try: return json.loads(self.engine.execute(command, json.dumps(params), "function")) except ValueError as exc: