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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .docs/wiki/Agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ Generated by `./formvis agents sync` and never edited by hand: `formvis-editing/
- Only this computer can connect; `/mcp` checks the Origin header.
- Only the formvis window can change what agents may do, answer a question or an approval, or use the terminal dock. The engine makes a window key at each start (`backend/app/core/window_key.py`); every POST, PUT and DELETE except `/mcp`, `/api/window/key` and the two merge routes needs it in `X-Formvis-Window-Key` and is refused with 403 "Only the formvis window can do this" without it, and the terminal, Claude Code and agent sockets must send it as their first message. Run from source, the first page to ask gets the key; the desktop app hands it to its own window.
- The saved choice (`agents.json` in the data folder) is sealed. Changed outside formvis, it reads as Ask again, and Agent Connect and Preferences say so once.
- formvis's own command line (`./formvis cli`, `./formvis headless`, `./formvis mcp`) goes in through `/mcp` as an outside agent and is asked about like any other. A script that used to change the agent setting through the engine must now have the person set Outside agents to Allowed in the window (Preferences > Plugins) first.
- formvis's own command line (`./formvis cli`, `./formvis headless`, `./formvis mcp`) goes in through `/mcp` as an outside agent and is asked about like any other, with one exception: `./formvis cli` sends the key the engine writes to `cli.key` in its data folder on each start (`backend/app/core/cli_key.py`, readable by this user only, removed on stop), and a request with that key is not asked about `convert_file` (the command line names the files and `--overwrite`) or `run_command` (a command undo cannot reverse needs `--yes`). The `X-Formvis-Client` header only names the caller and skips nothing. A script that used to change the agent setting through the engine must now have the person set Outside agents to Allowed in the window (Preferences > Plugins) first.
- After changing the tools in `mcp.py` or the commands in the window, run `./formvis agents sync` (with `backend/venv/bin` first on the path); the engine tests run `--check`.
11 changes: 11 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@

Living log for the engine service side, _v0.1.0. Read the map and the TOC first; entries are anchored by file and symbol, and removed code is quoted in full.

## The command line is known by a key the engine writes, not by its name · after 2.8.3, unreleased (core/cli_key.py new; main.py lifespan; routers/mcp.py _from_cli; setup/cli.py ROOT, KEY_FILE, KEY_HEADER, engine_setting, data_folder, cli_key, headers, call, serve_request; tests/test_cli_key.py new; docs/MANUAL.md; .docs/wiki/Agents.md)

- Kind: fix · logged 2026-11-29.
- Why: `_from_cli` took any plain HTTP call with `X-Formvis-Client: formvis-cli` as the command line, and that skips the Ask question for `convert_file` and `run_command`. Any local program can send that header.
- Now: `lifespan` calls `cli_key.issue(data)`, which makes a new `secrets.token_urlsafe(32)` on each start, removes any `cli.key` already in the data folder and creates the file again with `O_CREAT | O_EXCL | O_NOFOLLOW` at mode 0600 (no file is written through, a symbolic link included); when the file cannot be made there is no key and the command line is asked like any agent. Shutdown calls `cli_key.revoke()`, which forgets the key and removes the file while it still holds this run's value. `_from_cli` is `cli_key.valid(header x-formvis-cli-key)` (compared with `hmac.compare_digest`) with no clientInfo and no session id. The `X-Formvis-Client` header still names the caller and skips nothing.
- Command line: `headers()` reads `cli.key` on each call from `data_folder()`, which follows `config.data_dir` for an engine run from the repo (FORMVIS_DATA_DIR, FORMVIS_PORTABLE=1, ~/Formvis when there, the platform folder) without making anything, accepts only a value of the key's shape, and sends it only when FORMVIS_URL is a loopback address. `serve`'s `tool.call` with `run_command` now goes through `command_result`, so a risky command needs `"yes": true` there as in `command.run`.
- Replaced, quoted exactly: `mcp.py` `_from_cli`: ` return request.headers.get("x-formvis-client") == "formvis-cli" and not info and not sid`; `cli.py` `call`: `headers={"Content-Type": "application/json", "X-Formvis-Client": "formvis-cli"}`.
- Then: `data_folder()` reads FORMVIS_DATA_DIR and FORMVIS_PORTABLE through `engine_setting(name)`, the environment first and else `backend/.env` with the rules of `config._load_env_file`, because the engine takes them from that file too (`backend/.env.example` names FORMVIS_DATA_DIR); before, a data folder set only there left the command line without its key. Replaced, quoted exactly: ` raw = os.environ.get("FORMVIS_DATA_DIR")` and ` if os.environ.get("FORMVIS_PORTABLE") == "1":`. The wiki's Agents page says what the key skips.
- Not covered: a frozen portable engine (FormvisData beside the installed program) is found by the command line only through FORMVIS_DATA_DIR. On Windows the file mode is not an access list; the key relies on the per-user data folder there.
- Seen: tests/test_cli_key.py here on macOS; two of its tests fail on the earlier `_from_cli`. Not run: Windows.

## Hardening of the ComfyUI reads, the agent seal, the agent file writes, the library move and the Windows starter · after 2.8.4, unreleased (routers/comfyui.py status, last_graph, upscale_models_route, job, image; core/seal.py SEALED, EARLIER, VERSION, check, sign; services/agents.py _load; routers/mcp.py _convert, _run; routers/projects.py _free_beside, set_folder; services/agent_lookup.py shim_target, cmd_safe, start_argv, VERSION; setup/agents.py LOOKUP_HASHES)

- Kind: fix · logged 2026-11-29.
Expand Down
64 changes: 64 additions & 0 deletions backend/app/core/cli_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""The command line's key: a random value the engine makes on each start and writes into cli.key in its data folder,
readable by this user only. `./formvis cli` reads the file and sends the value in a header; a request carrying it is
the command line's own, which names its files and confirms risky commands itself. A caller that only names itself
formvis-cli is an outside agent like any other. The file is always made new (a file already there is removed first,
never written through), and it is removed when the engine stops."""

import hmac
import logging
import os
import secrets
from pathlib import Path

FILE_NAME = "cli.key"
HEADER = "x-formvis-cli-key"
_held: dict = {"value": None, "file": None}
log = logging.getLogger("formvis")


def path(data: Path) -> Path:
return data / FILE_NAME


def _create(target: Path, value: str) -> None:
"""Writes value into a file that must not exist yet (O_EXCL, and no symbolic link followed), mode 0600."""
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)
fd = os.open(target, flags, 0o600)
try:
os.write(fd, value.encode("ascii"))
finally:
os.close(fd)


def issue(data: Path) -> str | None:
"""A new key for this run, written to the data folder; None (no key, so the command line is asked like any agent)
when the file cannot be made."""
value = secrets.token_urlsafe(32)
target = path(data)
_held.update(value=None, file=None)
try:
target.unlink(missing_ok=True)
_create(target, value)
except OSError as exc:
log.warning("the command line key could not be written to %s: %s", target, exc)
return None
_held.update(value=value, file=target)
return value


def valid(given) -> bool:
held = _held["value"]
return isinstance(given, str) and bool(given) and bool(held) and hmac.compare_digest(given.encode("utf-8"), held.encode("ascii"))


def revoke() -> None:
"""Forgets this run's key and removes its file, when the file still holds it."""
value, target = _held["value"], _held["file"]
_held.update(value=None, file=None)
if not value or target is None:
return
try:
if target.read_text(encoding="ascii") == value:
target.unlink()
except (OSError, ValueError):
pass
4 changes: 3 additions & 1 deletion backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from starlette.datastructures import MutableHeaders

from app import ffmpeg_fetch
from app.core import config, runtime
from app.core import cli_key, config, runtime
from app.core.local_guard import LocalGuard
from app.core import window_key
from app.routers import fal as _fal_router
Expand All @@ -26,9 +26,11 @@
async def lifespan(_: FastAPI):
data = config.data_dir()
runtime.start_logging(data)
cli_key.issue(data)
asyncio.get_running_loop().run_in_executor(None, sessions.prune)
_terminal_service.bind(asyncio.get_running_loop())
yield
cli_key.revoke()
_claude_service.stop(quiet=True)
_terminal_service.close_all()
runtime.stop_logging()
Expand Down
7 changes: 4 additions & 3 deletions backend/app/routers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import time
import urllib.parse

from app.core import config, window_key
from app.core import cli_key, config, window_key
from fastapi import APIRouter, Request, Response
from fastapi.responses import StreamingResponse

Expand Down Expand Up @@ -1286,9 +1286,10 @@ def _client_of(request: Request, params: dict, sid: str | None) -> tuple[str, st


def _from_cli(request: Request, params: dict, sid: str | None) -> bool:
"""The command line's own HTTP call: named formvis-cli by its header, with no MCP session or clientInfo, through which any agent can claim that name."""
"""The command line's own HTTP call: it carries this run's command line key (core/cli_key.py, read from the data
folder) and no MCP session or clientInfo. A name alone, in a header or in clientInfo, is any agent's claim."""
info = (params.get("_meta") or {}).get("io.modelcontextprotocol/clientInfo") or params.get("clientInfo")
return request.headers.get("x-formvis-client") == "formvis-cli" and not info and not sid
return cli_key.valid(request.headers.get(cli_key.HEADER)) and not info and not sid


# Live resources: the same state the read tools give, as documents a client can attach.
Expand Down
158 changes: 158 additions & 0 deletions backend/tests/test_cli_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
"""The command line's key: the engine writes a new one on each start into a file only this user can read, the
command line sends it, and only a request carrying it skips the Ask question for convert_file and run_command."""
import os
import stat
import sys
from pathlib import Path

import pytest
from fastapi.testclient import TestClient

from app.core import cli_key, config, window_key
from app.main import app
from app.routers import mcp as M
from app.services import agents

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "setup"))
import cli # noqa: E402

BASE = "http://127.0.0.1:8190"


class Asked:
def __init__(self, headers: dict):
self.headers = {k.lower(): v for k, v in headers.items()}


@pytest.fixture(autouse=True)
def no_key_left():
yield
cli_key.revoke()


def test_each_issue_writes_a_new_key_only_this_user_can_read(tmp_path):
first = cli_key.issue(tmp_path)
second = cli_key.issue(tmp_path)
assert first and second and first != second
target = tmp_path / cli_key.FILE_NAME
assert target.read_text() == second
if os.name == "posix":
assert stat.S_IMODE(target.stat().st_mode) == 0o600
assert cli_key.valid(second) and not cli_key.valid(first) and not cli_key.valid("") and not cli_key.valid(None)


def test_a_file_already_there_is_replaced_and_never_written_through(tmp_path):
outside = tmp_path / "outside.txt"
outside.write_text("keep")
target = tmp_path / cli_key.FILE_NAME
target.symlink_to(outside)
value = cli_key.issue(tmp_path)
assert outside.read_text() == "keep"
assert not target.is_symlink() and target.read_text() == value


def test_no_key_when_the_file_cannot_be_made(tmp_path):
missing = tmp_path / "not-a-folder"
assert cli_key.issue(missing) is None
assert not cli_key.valid("anything")


def test_the_engine_rotates_the_key_on_each_start_and_removes_it_on_stop(tmp_path, monkeypatch):
monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path))
target = tmp_path / cli_key.FILE_NAME
with TestClient(app, base_url=BASE):
first = target.read_text()
assert cli_key.valid(first)
assert not target.exists() and not cli_key.valid(first)
with TestClient(app, base_url=BASE):
assert target.read_text() != first


def test_only_the_key_marks_a_call_as_the_command_lines(tmp_path):
value = cli_key.issue(tmp_path)
named = {"X-Formvis-Client": "formvis-cli"}
assert not M._from_cli(Asked(named), {}, None)
assert not M._from_cli(Asked({**named, cli_key.HEADER: "x" * 43}), {}, None)
assert M._from_cli(Asked({cli_key.HEADER: value}), {}, None)
assert not M._from_cli(Asked({cli_key.HEADER: value}), {"clientInfo": {"name": "formvis-cli"}}, None)
assert not M._from_cli(Asked({cli_key.HEADER: value}), {}, "a-session")


def _convert(c, src, dst, extra: dict):
body = {"jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": {"name": "convert_file", "arguments": {"path": str(src), "output_path": str(dst), "overwrite": True}}}
return c.post("/mcp", json=body, headers={"X-Formvis-Client": "formvis-cli", **extra}).json()["result"]


def test_a_name_alone_is_asked_and_the_key_is_not(tmp_path, monkeypatch):
from PIL import Image

data = tmp_path / "data"
monkeypatch.setenv("FORMVIS_DATA_DIR", str(data))
monkeypatch.setattr(M, "_live", lambda: False)
monkeypatch.setattr(agents, "policy_of", lambda client: "ask")
monkeypatch.setattr(agents, "admit", lambda client: None)
src, dst = tmp_path / "in.png", tmp_path / "out.jpg"
Image.new("RGB", (4, 3), (200, 10, 10)).save(src)
dst.write_bytes(b"old")
with TestClient(app, base_url=BASE, headers={window_key.HEADER: window_key.KEY}) as c:
named = _convert(c, src, dst, {})
assert named["isError"] and "no formvis window is open" in named["content"][0]["text"]
assert dst.read_bytes() == b"old"
keyed = _convert(c, src, dst, {"X-Formvis-Cli-Key": (data / cli_key.FILE_NAME).read_text()})
assert not keyed.get("isError"), keyed
assert dst.read_bytes()[:2] == b"\xff\xd8"


def test_the_command_line_finds_the_data_folder_the_engine_uses(tmp_path, monkeypatch):
for name in ("FORMVIS_DATA_DIR", "FORMVIS_PORTABLE"):
monkeypatch.delenv(name, raising=False)
home = tmp_path / "home"
home.mkdir()
monkeypatch.setenv("HOME", str(home))
monkeypatch.setenv("USERPROFILE", str(home))
monkeypatch.setenv("APPDATA", str(home / "AppData" / "Roaming"))
monkeypatch.setenv("XDG_DATA_HOME", str(home / ".local" / "share"))
assert cli.data_folder() == config.data_dir()
(home / "Formvis").mkdir()
assert cli.data_folder() == config.data_dir() == home / "Formvis"
monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path / "chosen"))
assert cli.data_folder() == config.data_dir()


def test_the_command_line_sends_the_key_it_reads(tmp_path, monkeypatch):
monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path))
value = cli_key.issue(tmp_path)
assert cli.headers()[cli.KEY_HEADER] == value
monkeypatch.setattr(cli, "URL", "http://192.0.2.1:8190")
assert cli.KEY_HEADER not in cli.headers()
monkeypatch.setattr(cli, "URL", BASE)
(tmp_path / cli_key.FILE_NAME).unlink()
(tmp_path / cli_key.FILE_NAME).write_text("not a key\n")
assert cli.KEY_HEADER not in cli.headers()


def test_a_risky_command_through_tool_call_still_needs_yes(monkeypatch):
sent = []
monkeypatch.setattr(cli, "call", lambda method, path, body=None: (200, {"risky": True}))
monkeypatch.setattr(cli, "tool", lambda name, args: sent.append(name) or (True, "", {}))
with pytest.raises(RuntimeError, match="--yes"):
cli.serve_request("tool.call", {"name": "run_command", "arguments": {"id": "file.revert"}}, None)
assert sent == []
cli.serve_request("tool.call", {"name": "run_command", "arguments": {"id": "file.revert"}, "yes": True}, None)
assert sent == ["run_command"]


def test_the_command_line_reads_the_data_folder_set_in_the_engine_env_file(tmp_path, monkeypatch):
for name in ("FORMVIS_DATA_DIR", "FORMVIS_PORTABLE"):
monkeypatch.delenv(name, raising=False)
root = tmp_path / "repo"
(root / "backend").mkdir(parents=True)
chosen = tmp_path / "chosen"
(root / "backend" / ".env").write_text(f"# local settings\nFORMVIS_PORTABLE=\nFORMVIS_DATA_DIR = {chosen}\n", encoding="utf-8")
monkeypatch.setattr(cli, "ROOT", root)
assert cli.data_folder() == chosen
monkeypatch.setenv("FORMVIS_DATA_DIR", str(tmp_path / "from-env"))
assert cli.data_folder() == tmp_path / "from-env"
monkeypatch.delenv("FORMVIS_DATA_DIR")
(root / "backend" / ".env").write_text("FORMVIS_PORTABLE=1\n", encoding="utf-8")
assert cli.data_folder() == root / "backend" / "FormvisData"
14 changes: 12 additions & 2 deletions docs/MANUAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,8 @@ other modes and depths its menu items are off, with the reason as their tooltip.
formvis window can do this"). The saved choice is sealed; if the file is changed outside formvis, the choice reads as
Ask again and formvis says so once. A choice saved in the older sealed format is sealed again the first time a
newer formvis starts, with Outside agents set to Blocked; set it back in Preferences > Plugins if you had it open.
formvis's own command line (`./formvis cli`, `./formvis headless`) is asked about like any other outside agent.
formvis's own command line (`./formvis cli`, `./formvis headless`) is asked about like any other outside agent,
except for the steps it confirms itself (see The command line below).

## Terminal

Expand Down Expand Up @@ -689,8 +690,17 @@ other modes and depths its menu items are off, with the reason as their tooltip.
commands (`--group Filter` narrows by menu), `./formvis cli describe <id>` says what one does and what it takes,
and `./formvis cli run <id> key=value ...` runs it in the open window as an undoable step. A command whose result
undo cannot reverse (a file overwritten, say) runs only with `--yes`.
- What the command line is asked about. Each time the engine starts it makes a new command line key and writes it to
`cli.key` in its data folder, a file only your account can read; it is removed when the engine stops. `./formvis cli`
reads it and sends it with each request. A request with that key is not asked about in the window for `convert` (you
name the files, and a file is replaced only with `--overwrite`) or for running a command (a command that undo cannot
reverse runs only with `--yes`, from `run`, `process` and `serve` alike). Everything else it does is asked about as
for any other program, and Blocked and Deny still refuse it. A program that only calls itself formvis-cli, without
the key, is treated like any other. The key is sent only to an engine on this computer and is found in the data
folder the engine uses (`FORMVIS_DATA_DIR` when you set one, in the environment or in `backend/.env`); with no key
the command line still works and is asked about like any other program.
- The window has to be open (`./formvis boot`); with Outside agents on Ask (Preferences > Plugins) formvis asks you in
the window when a command arrives. Or add `--headless` to
the window when a command arrives that needs it. Or add `--headless` to
`list`, `describe`, `run`, `process`, `batch`, `droplet`, `serve` or `convert`: a window with no screen (Playwright's Chromium,
as `./formvis bench` uses) is started for that run and is closed when the command ends. It follows the choice you saved
in formvis and cannot change it: set Outside agents to Allowed in the window first, because with no screen nobody can
Expand Down
Loading
Loading