diff --git a/.docs/wiki/GoF.md b/.docs/wiki/GoF.md index 0e94e1e..5bb4f64 100644 --- a/.docs/wiki/GoF.md +++ b/.docs/wiki/GoF.md @@ -67,7 +67,7 @@ An agent can do the same with `POST /api/agent {"command":"apply_return","path": ## Agent link -Another app can push a file into an open FormRig with `POST /api/agent {"command":"load_rig","path":...}`. It is accepted when the request carries the window token, or when Agent link is on (a switch stored in `/agent_link.json`). Only `load_rig` exists; a `.frig` opens as a project and anything else imports. +Another app can push a file into an open FormRig with `POST /api/agent {"command":"load_rig","path":...}`. It is accepted when the request carries the window token, or when Agent link is on (a switch stored in `/agent_link.json`). Only `load_rig` exists; a `.frig` opens as a project and anything else imports. Without the window token, a `.frig` is refused with 409 while the open project has unsaved changes, because opening a project clears the undo history; an import is kept in undo and is not refused. ## Limits diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index fdf1e1d..8ea3c86 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,18 @@ Living context for the FastAPI engine service. What would be comments in `backend/` lives here, newest first. Read before editing. +## 2026-11-29 · unreleased (services/agent_lookup.py 1.0.2, services/claude_code.py, services/agent_programs.py, setup/agents.py) + +- Windows start of a `.cmd` or `.bat` program: `start_argv` reads the script (64 KiB at most) and, when its last `%*` line names a file under `%dp0%` or `%~dp0`, runs that file directly: an `.exe` as itself, a `.js`, `.cjs` or `.mjs` with the `node.exe` beside the script or the first `node.exe` in a full-path folder of the child PATH (quotes around an entry are dropped, relative entries and the current folder are skipped, and a `node.cmd` or `node.bat` is never used, since Windows would start it through the command interpreter). This is the npm shim case and needs no command interpreter, so prompt words reach the program unchanged. A script ending is matched without case and with trailing dots and spaces dropped, as Windows does when it opens the file. +- Any other script still goes through `COMSPEC /c`, and `_cmd_words` raises `Unsafe` (an `OSError`, so `check` reports broken and the open routes answer 500 with the text) for any word, the script path included, holding a control character (`\x00`-`\x1f`, `\x7f`) or any of `&|<>^()!%"`, with or without spaces, since the script re-reads `%*` and the command interpreter acts on these even inside quotes. The message tells the caller to pass long text through standard input or a file. It also refuses a script path that gets quoted while another word is quoted too, because `cmd /c` then drops the first and last quote of the line. The earlier exemption for special characters inside a quoted word is removed. +- `claude_code.tab_argv` and `agent_programs.open_tab` hand the child environment to `start_argv`, so the node lookup sees the same PATH the tab runs with. +- The finder is 1.0.2 with its hash in `setup/agents.py`; other Form engines carrying 1.0.1 need the same file and hash. +- `routers/agent.py`: a `load_rig` of a `.frig` without the window token asks `doc.summary` first and answers 409 `UNSAVED` while `dirty` is true (or the summary fails), since `file.open` runs `Session::reset` and clears history. The window keeps its own `mayReplace()` prompt and is not checked here. `file.import` goes through `Session::replace`, which records an undo step, so it is left as it was. +- `services/clip_library.py` holds the clip folder lookup (`FORMRIG_CLIPS`, then `_MEIPASS/clips` in a frozen engine, then `assets/clips`) and the checked listing that `/api/library/clips` used. The MCP resource `formrig://library/clips` now returns that same listing (`name`, `path`, `licence`, `credit`, `skeleton` for a paired `.amc`), so the installed app's MCP server finds the bundled clips. The resource no longer carries the raw `file` field. +- `formrig_engine.py`: the parent watch (`wait_for_parent`) calls `tidy()` before `os._exit(0)`, which runs `app.main.shutdown()` (the lifespan teardown: GoF watcher stop and `engine.json` retract, terminals, agent config files) when the service module is loaded, and ignores any error so the exit still happens. The Windows quit in `src-tauri/src/main.rs` is still a hard kill; nothing in the engine runs after it, so `engine.json` can still be left behind there. +- Integrations: with a left-over `engine.json`, Unreal `_hop` and Unity `Hop` read a refused connection (`ConnectionRefusedError`, `WebExceptionStatus.ConnectFailure`) as FormRig not running and go on to start the configured app or say it is not open. Any other failure (a refusal by the engine, a timeout) keeps the "will show the return in a moment" message. The Unity change was not compiled here. +- Removed code: `routers/library.py` `_clips_dir` and its loop, moved whole into `services/clip_library.py`; the MCP resource's own read of `config.REPO/assets/clips/index.json`. + ## 2026-11-28 · v0.14.3 (routers/gof.py, services/engine.py) - `routers/gof.py` sends `overwrite: True` to `export.run`: a second send to the same sister app writes over the file the first send left in the send folder, which the engine now refuses without the argument. diff --git a/backend/app/main.py b/backend/app/main.py index 00afe11..f28d6b5 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -30,6 +30,10 @@ async def lifespan(_: FastAPI): claude_code.sweep() terminals.bind(asyncio.get_running_loop()) yield + shutdown() + + +def shutdown() -> None: gof_return.stop() terminals.close_all() claude_code.revoke_all() diff --git a/backend/app/mcp_stdio.py b/backend/app/mcp_stdio.py index 428e29f..4b12d69 100644 --- a/backend/app/mcp_stdio.py +++ b/backend/app/mcp_stdio.py @@ -11,7 +11,7 @@ from app import __version__ from app.core import config -from app.services import engine +from app.services import clip_library, engine PROTOCOLS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") TEXT_LIMIT = 60000 @@ -262,14 +262,7 @@ def read_resource(req_id, uri) -> dict: return failure(req_id, -32603, reply.get("error", {}).get("message", "doc_summary failed")) body, mime = json.dumps(slim(reply["result"]), separators=(",", ":")), "application/json" elif uri == "formrig://library/clips": - folder = config.REPO / "assets" / "clips" - try: - entries = json.loads((folder / "index.json").read_text(encoding="utf-8")) - except (OSError, ValueError): - entries = [] - for entry in entries: - entry["path"] = str(folder / entry.get("file", "")) - body, mime = json.dumps(entries, separators=(",", ":")), "application/json" + body, mime = json.dumps(clip_library.listing(), separators=(",", ":")), "application/json" elif uri == "formrig://guide/rigging": body, mime = GUIDE, "text/markdown" else: diff --git a/backend/app/routers/agent.py b/backend/app/routers/agent.py index 8835945..58fc101 100644 --- a/backend/app/routers/agent.py +++ b/backend/app/routers/agent.py @@ -13,6 +13,7 @@ RIGS = {".glb", ".gltf", ".fbx", ".vrm", ".frig"} REFUSAL = "turn on Agent link in FormRig, or send the window token, to push a file to an open FormRig" +UNSAVED = "FormRig has unsaved changes; save or close the open project in the window before opening another .frig" def _link_path() -> Path: @@ -44,7 +45,12 @@ def link_set(body: Link) -> dict: return {"link": body.on} -def _load_rig(args: dict) -> dict: +def _unsaved() -> bool: + reply = engine.dispatch("doc.summary", {}, notify=False) + return not reply.get("ok") or bool((reply.get("result") or {}).get("dirty")) + + +def _load_rig(args: dict, window: bool = False) -> dict: raw = args.get("path") if not isinstance(raw, str) or not raw: raise HTTPException(status_code=400, detail="load_rig needs a path") @@ -58,6 +64,8 @@ def _load_rig(args: dict) -> dict: if not engine.available(): raise HTTPException(status_code=503, detail=engine.UNAVAILABLE) command = "file.open" if path.suffix.lower() == ".frig" else "file.import" + if command == "file.open" and not window and _unsaved(): + raise HTTPException(status_code=409, detail=UNSAVED) reply = engine.dispatch(command, {"path": str(path)}) if not reply.get("ok"): error = reply.get("error") or {} @@ -76,7 +84,8 @@ def _apply_return(args: dict) -> dict: @router.post("/agent") async def agent(request: Request) -> dict: - if not (from_window(request.headers) or link_on()): + window = from_window(request.headers) + if not (window or link_on()): raise HTTPException(status_code=403, detail=REFUSAL) try: body = await request.json() @@ -90,4 +99,4 @@ async def agent(request: Request) -> dict: return {"command": command, "result": await run_in_threadpool(_apply_return, args)} if command != "load_rig": raise HTTPException(status_code=400, detail="the command must be load_rig or apply_return") - return {"command": command, "result": await run_in_threadpool(_load_rig, args)} + return {"command": command, "result": await run_in_threadpool(_load_rig, args, window)} diff --git a/backend/app/routers/library.py b/backend/app/routers/library.py index 3912c22..c2cefc8 100644 --- a/backend/app/routers/library.py +++ b/backend/app/routers/library.py @@ -1,44 +1,11 @@ -import json -import os -import sys -from pathlib import Path - from fastapi import APIRouter, Depends -from app.core import config from app.core.window_guard import require_window_read +from app.services import clip_library router = APIRouter() -def _clips_dir() -> Path | None: - configured = os.environ.get("FORMRIG_CLIPS") - candidates = [Path(configured)] if configured else [] - bundle = getattr(sys, "_MEIPASS", None) - if bundle: - candidates.append(Path(bundle) / "clips") - candidates.append(config.REPO / "assets" / "clips") - return next((c for c in candidates if (c / "index.json").is_file()), None) - - @router.get("/clips", dependencies=[Depends(require_window_read)]) def clips() -> dict: - folder = _clips_dir() - if folder is None: - return {"clips": []} - try: - entries = json.loads((folder / "index.json").read_text(encoding="utf-8")) - except (OSError, ValueError): - return {"clips": []} - out = [] - for entry in entries if isinstance(entries, list) else []: - file = folder / str(entry.get("file", "")) - skeleton = folder / str(entry["skeleton"]) if entry.get("skeleton") else None - root = folder.resolve() - paired = file.suffix == ".amc" and skeleton is not None and skeleton.suffix == ".asf" and skeleton.is_file() and skeleton.resolve().is_relative_to(root) - if file.resolve().is_relative_to(root) and file.is_file() and (file.suffix == ".bvh" or paired): - item = {"name": entry.get("name", file.stem), "path": str(file.resolve()), "licence": entry.get("licence", ""), "credit": entry.get("credit", "")} - if paired: - item["skeleton"] = str(skeleton.resolve()) - out.append(item) - return {"clips": out} + return {"clips": clip_library.listing()} diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index ea34eba..c2e2671 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -26,7 +26,7 @@ from dataclasses import dataclass, field from pathlib import Path -VERSION = "1.0.1" +VERSION = "1.0.2" PROGRAMS: dict = { "claude": {"title": "Claude Code", "names": ("claude",), "setting": "claudeBin", "install": "curl -fsSL https://claude.ai/install.sh | bash", "install_windows": "irm https://claude.ai/install.ps1 | iex", @@ -45,6 +45,9 @@ 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 +CMD_SPECIAL = frozenset('&|<>^()!%"') +SHIM_WORD = re.compile(r'"%(?:~dp0|dp0%)\\?([^"%]+)"') +SHIM_LIMIT = 65536 _lock = threading.RLock() _shell: dict = {} @@ -359,13 +362,60 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +class Unsafe(OSError): + """A word that the Windows command interpreter would read as part of a command instead of passing it on.""" + + +def _shim_target(words: list[str], env: dict) -> list[str] | None: + shim = Path(words[0]) + try: + if shim.stat().st_size > SHIM_LIMIT: + return None + text = shim.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + line = next((one for one in reversed(text.splitlines()) if "%*" in one), "") + named = SHIM_WORD.findall(line) + if not named: + return None + target = Path(os.path.normpath(shim.parent.joinpath(*[p for p in re.split(r"[\\/]", named[-1]) if p]))) + if not target.is_file(): + return None + if target.suffix.lower() == ".exe": + return [str(target), *words[1:]] + if target.suffix.lower() not in (".js", ".cjs", ".mjs"): + return None + entries = [p.strip().strip('"') for p in env.get("PATH", "").split(";")] + places = [shim.parent, *(Path(p) for p in entries if p and Path(p).is_absolute())] + node = next((str(p / "node.exe") for p in places if (p / "node.exe").is_file()), None) + return [node, str(target), *words[1:]] if node else None + + +def _cmd_words(words: list[str]) -> list[str]: + name = Path(words[0]).name + hint = "; pass long text through standard input or a file if the program supports it" + for word in words: + if re.search(r"[\x00-\x1f\x7f]", word): + raise Unsafe(f"{name} is a command script and a word for it holds a control character, such as a line break{hint}") + if CMD_SPECIAL & set(word): + raise Unsafe(f"{name} is a command script and a word for it holds one of {''.join(sorted(CMD_SPECIAL))}, which the command interpreter reads even inside quotes{hint}") + quoted = [not w or " " in w for w in words] + if quoted[0] and any(quoted[1:]): + raise Unsafe(f"{name} is a command script in a folder whose path the command interpreter cannot keep quoted together with these words") + return words + + def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]: """How a program is started, the same for a tab, Chat and a check: through the person's login shell on macOS and Linux - (exec, so the process is the program), directly on Windows with the command interpreter in front of a .cmd or .bat.""" + (exec, so the process is the program), directly on Windows. A .cmd or .bat that only starts a program (an npm shim) is + replaced by that program; any other goes through the command interpreter, and words it would read as commands are + refused with Unsafe.""" words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words + if not words[0].lower().rstrip(" .").endswith((".cmd", ".bat")): + return words + return _shim_target(words, env) or [env.get("COMSPEC") or "cmd.exe", "/c", *_cmd_words(words)] shell = login_shell(env, platform) fish = Path(shell).name == "fish" return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py index 49f7c9f..319407f 100644 --- a/backend/app/services/agent_programs.py +++ b/backend/app/services/agent_programs.py @@ -142,7 +142,8 @@ def open_tab(kind: str, cols: int = 100, rows: int = 30) -> dict: if own: write_tab_entry(own, mark) wrote = True if own else write_config(kind, folder) - session = terminal.open_session(str(folder), cols, rows, program["title"], agent_lookup.start_argv([found.path]), claude_code.child_env(found.path), kind) + env = claude_code.child_env(found.path) + session = terminal.open_session(str(folder), cols, rows, program["title"], agent_lookup.start_argv([found.path], env), env, kind) except BaseException: if own: remove_tab_entry(own, mark) diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index 8e3cfce..bc7ec32 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -110,13 +110,13 @@ def workdir() -> Path: return folder -def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None) -> list[str]: +def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None, env: dict | None = None) -> list[str]: cmd = [path, "--mcp-config", mcp_file, "--allowedTools", f"mcp__{TAB_ENTRY}", "--append-system-prompt", NOTE] if resume: cmd += ["--resume", resume] if prompt: cmd.append(prompt) - return agent_lookup.start_argv(cmd) + return agent_lookup.start_argv(cmd, env) def status() -> dict: @@ -140,7 +140,8 @@ def open_tab(prompt: str | None = None, cols: int = 100, rows: int = 30, fresh: raise LookupError(said(found)) mcp_file = issue() try: - session = terminal.open_session(str(workdir()), cols, rows, "Claude Code",tab_argv(found.path, mcp_file, prompt, resume), child_env(found.path), "claude") + env = child_env(found.path) + session = terminal.open_session(str(workdir()), cols, rows, "Claude Code", tab_argv(found.path, mcp_file, prompt, resume, env), env, "claude") except BaseException: revoke(mcp_file) raise diff --git a/backend/app/services/clip_library.py b/backend/app/services/clip_library.py new file mode 100644 index 0000000..79ca383 --- /dev/null +++ b/backend/app/services/clip_library.py @@ -0,0 +1,40 @@ +import json +import os +import sys +from pathlib import Path + +from app.core import config + + +def folder() -> Path | None: + configured = os.environ.get("FORMRIG_CLIPS") + candidates = [Path(configured)] if configured else [] + bundle = getattr(sys, "_MEIPASS", None) + if bundle: + candidates.append(Path(bundle) / "clips") + candidates.append(config.REPO / "assets" / "clips") + return next((c for c in candidates if (c / "index.json").is_file()), None) + + +def listing() -> list[dict]: + base = folder() + if base is None: + return [] + try: + entries = json.loads((base / "index.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return [] + root = base.resolve() + out = [] + for entry in entries if isinstance(entries, list) else []: + if not isinstance(entry, dict): + continue + file = base / str(entry.get("file", "")) + skeleton = base / str(entry["skeleton"]) if entry.get("skeleton") else None + paired = file.suffix == ".amc" and skeleton is not None and skeleton.suffix == ".asf" and skeleton.is_file() and skeleton.resolve().is_relative_to(root) + if file.resolve().is_relative_to(root) and file.is_file() and (file.suffix == ".bvh" or paired): + item = {"name": entry.get("name", file.stem), "path": str(file.resolve()), "licence": entry.get("licence", ""), "credit": entry.get("credit", "")} + if paired: + item["skeleton"] = str(skeleton.resolve()) + out.append(item) + return out diff --git a/backend/formrig_engine.py b/backend/formrig_engine.py index 9d2714e..93108b4 100644 --- a/backend/formrig_engine.py +++ b/backend/formrig_engine.py @@ -59,20 +59,31 @@ def parent_alive(pid: int) -> bool: return True +def tidy() -> None: + service = sys.modules.get("app.main") + try: + if service is not None: + service.shutdown() + except Exception: + pass + + +def wait_for_parent(pid: int) -> None: + import time + + while parent_alive(pid): + time.sleep(1.5) + tidy() + os._exit(0) + + def watch_parent() -> None: raw = os.environ.get("FORMRIG_PARENT_PID", "") if not raw.isdigit(): return - pid = int(raw) import threading - import time - - def loop() -> None: - while parent_alive(pid): - time.sleep(1.5) - os._exit(0) - threading.Thread(target=loop, name="parent-watch", daemon=True).start() + threading.Thread(target=wait_for_parent, args=(int(raw),), name="parent-watch", daemon=True).start() def free_port() -> int: diff --git a/backend/tests/rb02/test_engine_parent_watch.py b/backend/tests/rb02/test_engine_parent_watch.py new file mode 100644 index 0000000..5475ab9 --- /dev/null +++ b/backend/tests/rb02/test_engine_parent_watch.py @@ -0,0 +1,53 @@ +import json +import os +import sys +import types + +import formrig_engine +from app.core import config +from app.services import gof_return + + +class Exited(Exception): + pass + + +def test_engine_tidies_up_before_it_exits_when_the_app_is_gone(monkeypatch): + order = [] + monkeypatch.setattr(formrig_engine, "parent_alive", lambda pid: False) + monkeypatch.setitem(sys.modules, "app.main", types.SimpleNamespace(shutdown=lambda: order.append("shutdown"))) + + def leave(code): + order.append(("exit", code)) + raise Exited + + monkeypatch.setattr(formrig_engine.os, "_exit", leave) + try: + formrig_engine.wait_for_parent(1234) + except Exited: + pass + assert order == ["shutdown", ("exit", 0)] + + +def test_engine_still_exits_when_tidying_up_fails(monkeypatch): + def broken(): + raise RuntimeError("busy") + + monkeypatch.setitem(sys.modules, "app.main", types.SimpleNamespace(shutdown=broken)) + formrig_engine.tidy() + + +def test_engine_exits_without_tidying_when_the_service_never_started(monkeypatch): + monkeypatch.delitem(sys.modules, "app.main", raising=False) + formrig_engine.tidy() + + +def test_shutdown_removes_the_engine_file(data_dir, monkeypatch): + from app import main + + gof_return.publish_engine() + path = data_dir / "engine.json" + assert json.loads(path.read_text())["pid"] == os.getpid() + main.shutdown() + assert not path.exists() + assert config.data_dir() == data_dir diff --git a/backend/tests/rb02/test_mcp_stdio_clips.py b/backend/tests/rb02/test_mcp_stdio_clips.py new file mode 100644 index 0000000..0a0ccac --- /dev/null +++ b/backend/tests/rb02/test_mcp_stdio_clips.py @@ -0,0 +1,48 @@ +import json +import sys + +import pytest + +from app import mcp_stdio +from app.core import config + + +def clips_of(reply): + return json.loads(reply["result"]["contents"][0]["text"]) + + +@pytest.fixture +def no_override(monkeypatch): + monkeypatch.delenv("FORMRIG_CLIPS", raising=False) + + +def bundle(root): + folder = root / "clips" + folder.mkdir(parents=True) + (folder / "walk.bvh").write_text("x") + (folder / "index.json").write_text(json.dumps([{"file": "walk.bvh", "name": "Walk", "licence": "CC0", "credit": "me"}])) + return folder + + +def test_clip_resource_reads_the_clips_bundled_into_a_frozen_engine(tmp_path, monkeypatch, no_override): + folder = bundle(tmp_path / "meipass") + monkeypatch.setattr(sys, "_MEIPASS", str(tmp_path / "meipass"), raising=False) + monkeypatch.setattr(config, "REPO", tmp_path / "nowhere") + out = clips_of(mcp_stdio.read_resource(1, "formrig://library/clips")) + assert out == [{"name": "Walk", "path": str((folder / "walk.bvh").resolve()), "licence": "CC0", "credit": "me"}] + + +def test_clip_resource_matches_the_window_listing(tmp_path, monkeypatch): + folder = bundle(tmp_path) + (folder / "index.json").write_text(json.dumps([{"file": "walk.bvh"}, {"file": "../outside.bvh"}, {"file": "missing.bvh"}])) + (tmp_path / "outside.bvh").write_text("x") + monkeypatch.setenv("FORMRIG_CLIPS", str(folder)) + out = clips_of(mcp_stdio.read_resource(1, "formrig://library/clips")) + assert [c["path"] for c in out] == [str((folder / "walk.bvh").resolve())] + + +def test_clip_resource_survives_a_damaged_index(tmp_path, monkeypatch): + folder = bundle(tmp_path) + (folder / "index.json").write_text('{"file": "walk.bvh"}') + monkeypatch.setenv("FORMRIG_CLIPS", str(folder)) + assert clips_of(mcp_stdio.read_resource(1, "formrig://library/clips")) == [] diff --git a/backend/tests/rb02/test_routers_agent.py b/backend/tests/rb02/test_routers_agent.py new file mode 100644 index 0000000..f2aeecb --- /dev/null +++ b/backend/tests/rb02/test_routers_agent.py @@ -0,0 +1,72 @@ +import json + +import pytest + +from app.routers import agent +from app.services import engine + + +@pytest.fixture +def fake_engine(monkeypatch): + state = {"dirty": False, "calls": []} + + def dispatch(name, args, notify=True): + state["calls"].append(name) + if name == "doc.summary": + return {"ok": True, "result": {"dirty": state["dirty"]}} + return {"ok": True, "result": {"name": "other"}} + + monkeypatch.setattr(engine, "available", lambda: True) + monkeypatch.setattr(engine, "dispatch", dispatch) + return state + + +@pytest.fixture +def rig(tmp_path): + path = tmp_path / "other.frig" + path.write_bytes(b"x") + return path + + +def link(data_dir, on=True): + (data_dir / "agent_link.json").write_text(json.dumps({"link": on})) + + +def test_linked_caller_cannot_open_a_project_over_unsaved_work(anon_client, data_dir, fake_engine, rig): + link(data_dir) + fake_engine["dirty"] = True + reply = anon_client.post("/api/agent", json={"command": "load_rig", "path": str(rig)}) + assert reply.status_code == 409 + assert reply.json()["detail"] == agent.UNSAVED + assert "file.open" not in fake_engine["calls"] + + +def test_linked_caller_opens_a_project_when_nothing_is_unsaved(anon_client, data_dir, fake_engine, rig): + link(data_dir) + reply = anon_client.post("/api/agent", json={"command": "load_rig", "path": str(rig)}) + assert reply.status_code == 200 + assert fake_engine["calls"][-1] == "file.open" + + +def test_linked_caller_still_imports_a_model_over_unsaved_work(anon_client, data_dir, fake_engine, tmp_path): + link(data_dir) + fake_engine["dirty"] = True + model = tmp_path / "hero.glb" + model.write_bytes(b"x") + reply = anon_client.post("/api/agent", json={"command": "load_rig", "path": str(model)}) + assert reply.status_code == 200 + assert fake_engine["calls"][-1] == "file.import" + + +def test_the_window_opens_a_project_after_its_own_prompt(client, fake_engine, rig): + fake_engine["dirty"] = True + reply = client.post("/api/agent", json={"command": "load_rig", "path": str(rig)}) + assert reply.status_code == 200 + assert fake_engine["calls"] == ["file.open"] + + +def test_without_link_or_window_key_the_route_refuses(anon_client, data_dir, fake_engine, rig): + link(data_dir, on=False) + reply = anon_client.post("/api/agent", json={"command": "load_rig", "path": str(rig)}) + assert reply.status_code == 403 + assert fake_engine["calls"] == [] diff --git a/backend/tests/rb02/test_services_agent_lookup.py b/backend/tests/rb02/test_services_agent_lookup.py index 1267e49..3d89438 100644 --- a/backend/tests/rb02/test_services_agent_lookup.py +++ b/backend/tests/rb02/test_services_agent_lookup.py @@ -110,6 +110,110 @@ def test_start_argv_on_windows_wraps_only_cmd_and_bat_files(): assert al.start_argv(["C:/x/claude.exe", "-v"], {}, "win32") == ["C:/x/claude.exe", "-v"] +NPM_SHIM = ('@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\n' + 'IF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\n' + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js" %*\r\n') + + +def npm_install(folder: Path, node_beside: bool = True) -> tuple[Path, Path]: + script = folder / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("") + if node_beside: + (folder / "node.exe").write_text("") + shim = folder / "claude.cmd" + shim.write_text(NPM_SHIM) + return shim, script + + +def test_start_argv_on_windows_runs_an_npm_shim_through_node_without_the_command_interpreter(tmp_path): + shim, script = npm_install(tmp_path) + name = 'hero & sidekick (copy)' + argv = al.start_argv([str(shim), "-p", f'rig it (FormRig window: character "{name}")'], {"COMSPEC": "C:/cmd.exe", "PATH": ""}, "win32") + assert argv == [str(tmp_path / "node.exe"), str(script), "-p", f'rig it (FormRig window: character "{name}")'] + + +def test_start_argv_on_windows_finds_node_on_path_for_an_npm_shim(tmp_path): + shim, script = npm_install(tmp_path / "npm", node_beside=False) + node = program(tmp_path / "nodejs", "node.exe") + argv = al.start_argv([str(shim), "--version"], {"PATH": f'"{node.parent}";{tmp_path / "other"}'}, "win32") + assert argv == [str(node), str(script), "--version"] + + +def test_start_argv_on_windows_runs_node_only_as_a_program_from_a_full_path_folder(tmp_path, monkeypatch): + shim, _ = npm_install(tmp_path / "npm", node_beside=False) + program(tmp_path / "scripts", "node.cmd") + program(tmp_path / "scripts", "node.bat") + program(tmp_path / "here", "node.exe") + monkeypatch.chdir(tmp_path) + env = {"PATH": f"{tmp_path / 'scripts'};here"} + assert al.start_argv([str(shim), "--version"], env, "win32") == ["cmd.exe", "/c", str(shim), "--version"] + with pytest.raises(al.Unsafe): + al.start_argv([str(shim), "-p", "a&b"], env, "win32") + + +@pytest.mark.parametrize("ending", [".cmd.", ".CMD ", ".Bat"]) +def test_start_argv_on_windows_treats_any_spelling_of_a_script_ending_as_a_script(ending): + with pytest.raises(al.Unsafe): + al.start_argv([f"C:/x/claude{ending}", "-p", "a&b"], {}, "win32") + + +def test_start_argv_on_windows_runs_the_program_a_shim_names_directly(tmp_path): + exe = tmp_path / "bin" / "agent.exe" + exe.parent.mkdir() + exe.write_text("") + shim = tmp_path / "agent.cmd" + shim.write_text('@ECHO off\r\n"%~dp0\\bin\\agent.exe" %*\r\n') + assert al.start_argv([str(shim), "a & b"], {}, "win32") == [str(exe), "a & b"] + + +@pytest.mark.parametrize("word", ["a&b", "x|y", "out>f", "in