diff --git a/.agents/skills/formcraft-driving/references/tools-by-task.md b/.agents/skills/formcraft-driving/references/tools-by-task.md index cb19440..4fc2bb2 100644 --- a/.agents/skills/formcraft-driving/references/tools-by-task.md +++ b/.agents/skills/formcraft-driving/references/tools-by-task.md @@ -76,7 +76,7 @@ To turn a shot into media, use `command_run` with the scene's generate-from-came ## Projects -`projects_list` and `projects_get` read; `projects_create` and `projects_update` write; `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. A project open in the window reloads when changed under it. +`projects_list` and `projects_get` read; `projects_create` and `projects_update` write, and replacing a project's document asks every time (that answer is never remembered); `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. `folders_delete`, `tags_delete` and `characters_delete` ask too. A project open in the window reloads when changed under it. ## Catalogue of commands diff --git a/.agents/skills/formcraft-harness/references/tool-map.md b/.agents/skills/formcraft-harness/references/tool-map.md index 877b982..8aeced2 100644 --- a/.agents/skills/formcraft-harness/references/tool-map.md +++ b/.agents/skills/formcraft-harness/references/tool-map.md @@ -44,18 +44,18 @@ These run in the engine and work with the window closed. Code: `backend/app/serv | `folders_list` | R | `GET /api/folders` | | | `folders_create` | W | `POST /api/folders` | | | `folders_update` | W | `PATCH /api/folders/{id}` | | -| `folders_delete` | D | `DELETE /api/folders/{id}` | | +| `folders_delete` | D | `DELETE /api/folders/{id}` | asks | | `folders_add_items` | W | `POST /api/folders/{id}/items` | | | `tags_list` | R | `GET /api/tags` | | | `tags_apply` | W | `POST /api/tags/apply` | | | `tags_rename` | W | `PATCH /api/tags/{name}` | | -| `tags_delete` | D | `DELETE /api/tags/{name}` | | +| `tags_delete` | D | `DELETE /api/tags/{name}` | asks | | `characters_list`, `characters_get` | R | `GET /api/characters`, `/{id}` | | | `characters_create`, `characters_update` | W | `POST`, `PATCH /api/characters` | | -| `characters_delete` | D | `DELETE /api/characters/{id}` | | +| `characters_delete` | D | `DELETE /api/characters/{id}` | asks | | `prompt_history` | R | `GET /api/prompts` | | | `projects_list`, `projects_get` | R | `GET /api/projects`, `/{id}` | kinds storyboard, scene, canvas, board, edit | -| `projects_create`, `projects_update` | W | `POST`, `PUT`, `PATCH /api/projects` | a project open in the window reloads through its changed-under-it path | +| `projects_create`, `projects_update` | W | `POST`, `PUT`, `PATCH /api/projects` | a project open in the window reloads through its changed-under-it path; replacing the document asks | | `projects_export` | W | `POST /api/projects/{id}/export` | overwriting a file asks | | `projects_import` | W | `POST /api/projects/import` | | | `projects_delete` | D | `DELETE /api/projects/{id}` | asks | diff --git a/.claude/skills/formcraft-driving/references/tools-by-task.md b/.claude/skills/formcraft-driving/references/tools-by-task.md index cb19440..4fc2bb2 100644 --- a/.claude/skills/formcraft-driving/references/tools-by-task.md +++ b/.claude/skills/formcraft-driving/references/tools-by-task.md @@ -76,7 +76,7 @@ To turn a shot into media, use `command_run` with the scene's generate-from-came ## Projects -`projects_list` and `projects_get` read; `projects_create` and `projects_update` write; `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. A project open in the window reloads when changed under it. +`projects_list` and `projects_get` read; `projects_create` and `projects_update` write, and replacing a project's document asks every time (that answer is never remembered); `projects_export` writes a `.fcrft` file; `projects_import` reads one; `projects_delete` asks. `folders_delete`, `tags_delete` and `characters_delete` ask too. A project open in the window reloads when changed under it. ## Catalogue of commands diff --git a/.claude/skills/formcraft-harness/references/tool-map.md b/.claude/skills/formcraft-harness/references/tool-map.md index 877b982..8aeced2 100644 --- a/.claude/skills/formcraft-harness/references/tool-map.md +++ b/.claude/skills/formcraft-harness/references/tool-map.md @@ -44,18 +44,18 @@ These run in the engine and work with the window closed. Code: `backend/app/serv | `folders_list` | R | `GET /api/folders` | | | `folders_create` | W | `POST /api/folders` | | | `folders_update` | W | `PATCH /api/folders/{id}` | | -| `folders_delete` | D | `DELETE /api/folders/{id}` | | +| `folders_delete` | D | `DELETE /api/folders/{id}` | asks | | `folders_add_items` | W | `POST /api/folders/{id}/items` | | | `tags_list` | R | `GET /api/tags` | | | `tags_apply` | W | `POST /api/tags/apply` | | | `tags_rename` | W | `PATCH /api/tags/{name}` | | -| `tags_delete` | D | `DELETE /api/tags/{name}` | | +| `tags_delete` | D | `DELETE /api/tags/{name}` | asks | | `characters_list`, `characters_get` | R | `GET /api/characters`, `/{id}` | | | `characters_create`, `characters_update` | W | `POST`, `PATCH /api/characters` | | -| `characters_delete` | D | `DELETE /api/characters/{id}` | | +| `characters_delete` | D | `DELETE /api/characters/{id}` | asks | | `prompt_history` | R | `GET /api/prompts` | | | `projects_list`, `projects_get` | R | `GET /api/projects`, `/{id}` | kinds storyboard, scene, canvas, board, edit | -| `projects_create`, `projects_update` | W | `POST`, `PUT`, `PATCH /api/projects` | a project open in the window reloads through its changed-under-it path | +| `projects_create`, `projects_update` | W | `POST`, `PUT`, `PATCH /api/projects` | a project open in the window reloads through its changed-under-it path; replacing the document asks | | `projects_export` | W | `POST /api/projects/{id}/export` | overwriting a file asks | | `projects_import` | W | `POST /api/projects/import` | | | `projects_delete` | D | `DELETE /api/projects/{id}` | asks | diff --git a/agents/manifest.json b/agents/manifest.json index afbbc6b..e4a4bcd 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -76,6 +76,10 @@ "library_import", "library_save_copy", "library_delete", + "folders_delete", + "tags_delete", + "characters_delete", + "projects_update", "projects_export", "projects_delete", "starter_pack_install", diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index acff4bd..5d3138e 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2247,6 +2247,17 @@ From VERIFY_v0.8.0_E2E.md. A closed page's long poll could take a queued call: t - **CI.** The `install` job runs `./formcraft install` and the self-check. `install-desktop`, the freeze and the desktop build still run in no job. - Removed code: none. +## 2026-11-28 · agent controls, approvals, the Windows prompt and dev origins {#agents-hardening} + +- refers-to: app/routers/agents.py :: WINDOW; app/routers/settings.py :: write_settings; app/services/mcp_tools.py :: folders_delete, tags_delete, characters_delete, projects_update; app/services/claude_code.py :: located, checked_script, through_interpreter, interpreter_safe, direct, launch_words, interpreter_argv, run, tab_argv, open_tab; app/services/command_script.py :: safe, resolve; app/services/agent_programs.py :: open_tab, claude_signed_in; app/services/agents.py :: NEVER_REMEMBERED, rememberable, approval_key, remember, remembered, Bridge.ask; frontend src/automation/approvals.ts; app/core/config.py :: window_origins; app/core/local_guard.py :: LocalGuard.allowed; app/main.py; tests/cb01/test_core_local_guard.py, tests/cb02/test_services_mcp_tools_approval.py, tests/cb03/test_routers_agents_window_key.py, tests/cb03/test_services_claude_code_prompt.py, tests/cb03/test_services_command_script.py, tests/cb02/test_services_agents_replace_doc.py +- **Window key on agent routes.** Every `/api/agents/*` route except `POST /api/agents/bridge/bye` now depends on `window_key.require`, and so does `PUT /api/settings` (it carries `agentsAllowed`). These are the window's controls: the bridge queue, results, approvals, policies, the token, activity and stop. The window's patched `fetch` adds the key to every `/api/` call, so it is unaffected. `bye` stays open because the window sends it with `sendBeacon`, which cannot set a header; it only shortens the connected grace period. `GET /api/settings` stays open. +- **Approvals for changes that cannot be undone.** `folders_delete`, `tags_delete` and `characters_delete` are `risky=True`, and `projects_update` is risky when `doc` is given (the document is replaced and no earlier version is kept). They ask whatever the client policy, like `projects_delete` and `library_delete`. Renames and cover changes still follow the policy. `agents.approval_key` keys a `projects_update` with `doc` as `projects_update:doc` and every other `projects_update` as `projects_update`, so a remembered rename or cover change never covers a document replacement. `projects_update:doc` is in `agents.NEVER_REMEMBERED` with the bare `generate`: `remember` never stores it, `remembered` never honours a stored copy, and the approval item carries `rememberable: false` so the window hides the remember box. +- **Command scripts on Windows.** `claude_code.launch_words` is the one place a Windows `.cmd` or `.bat` start is decided, used by `interpreter_argv` (the Claude Code tab and the other agent tabs), `claude_code.run` (the sign-in check) and `checked_script` (the `--version` check `located` uses for a script instead of `agent_lookup.check`, which would start it through cmd.exe). First `command_script.resolve` reads an npm-style shim (at most 64 KiB): the last line holding `%*`, its last quoted word that starts with `%dp0%` or `%~dp0` and is not `node.exe`, with no other `%` left. The target must be an existing file inside the shim's folder (its parent for a `.bin` folder). A `.js`, `.cjs` or `.mjs` target runs as `[node.exe, script, ...]`, with `node.exe` from the shim's folder or else the child PATH; an `.exe` target runs as itself. Then no cmd.exe is involved, the words are an argv list and the prompt goes on the command line again. When the shim does not resolve, cmd.exe is still used and every word, the program path included, must be text with none of `& | < > ^ ( ) ! % "` and no control character (`\x00` to `\x1f`, `\x7f`), with or without spaces: the `/c` line is read by cmd.exe and again by the shim's `%*`, so quoting protects nothing. Otherwise a `LookupError` with `command_script.REFUSED` (the router's 409 path), which says to pass long text through standard input or a file; the checks report broken or unknown without running anything. The earlier exception for `(` and `)` inside a quoted word is gone. Open: the shim formats are checked against hand-written samples in `tests/cb03/test_services_command_script.py`, not yet on a Windows machine. +- **Windows prompt.** A Claude Code found as a `.cmd` or `.bat` starts as `cmd.exe /c ...`, and cmd.exe reads its command line itself: inner quotes, `& | < > ^` and `%VAR%` are not protected by the MSVC quoting pywinpty applies. `tab_argv` leaves the prompt off that command line (only while the shim does not resolve, see above) and `open_tab` types it into the new tab with a carriage return, as it already did for a running tab. `.exe` and macOS and Linux are unchanged. The check lives in `claude_code.py`, because `agent_lookup.py` is the family's shared finder, held to a recorded hash by `setup/agents.py`. +- **Dev origins.** `config.window_origins()` lists `localhost` and `127.0.0.1` on 5290 and 5291 only when `FORMCRAFT_DEV=1`; otherwise only `tauri://localhost` and `http://tauri.localhost` (the engine's own origin is always admitted by the guard). `LocalGuard` takes the list or a function returning it and evaluates it per request; `main.py` passes the function. Tests that model the Vite page set `FORMCRAFT_DEV=1`. +- **Open.** Client names are still what the client reports (`clientInfo.name` or `X-Formcraft-Client`) and every client shares one bearer token, so remembered approvals and policies are per name, not per credential. New names get `ask`. Binding them to a client would need a token per client. +- Removed code: none. + ## 2026-11-29 · v0.10.0 the usability round {#usable-v0100} - **Binaries (`services/binaries.py`).** One resolver for ffmpeg and ffprobe that follows the formai-binaries record; `ffmpeg_fetch.locate()`, `encoders.selected()` and `encode_sessions.py` go through it. The old formcut-binaries address stays as the fallback, and the shared install folder keeps its name. Adapted from formcut `backend/app/tools.py` and `ffmpeg_fetch.py` and formencoder `backend/app/ffmpeg_fetch.py` (Apache-2.0). @@ -2267,3 +2278,11 @@ From VERIFY_v0.8.0_E2E.md. A closed page's long poll could take a queued call: t - **Starter (`services/starter.py`).** `licence_evidence` may be a string or a list; licences accepted are CC0-1.0 and the public-domain labels; packs carry `material` and `map`, `rigged` and `animations`, `source_page`. - **Starter sourcing rule.** Files come from the publisher's own website, two licence statements read there, and never from a site or path whose robots.txt closes it to AI agents (OpenGameArt, Free Nature Stock, itch.io download links). The older scene pack in `app/pack` (KayKit pieces from GitHub, 0.6.0) is not covered by this round and is left as it was. - Removed code: none. + +## 2026-11-29 · main 0.11.0 merged into the agents hardening branch {#agents-hardening-merge} + +- refers-to: app/routers/agents.py :: WINDOW, bridge_next; app/services/agents.py :: approval_key, remember, remembered, _keepable, Bridge.ask; app/services/mcp_tools.py :: projects_update; frontend src/automation/approvals.ts; frontend src/io/api-agents.ts :: BridgeApproval; tests/cb02/test_services_agents_replace_doc.py +- **Router.** `GET /api/agents/bridge/next` keeps the window key from this branch and takes main's `project` query, which calls `agents.set_window_project`. The `Decision` body keeps main's `scope` and `project`. +- **Approval keys.** Main's risk classes replace this branch's `projects_update:doc` key. A `projects_update` with `doc` is risky through `mcp_tools` (`risky=lambda a: "doc" in a`, from this branch), so `approval_key` gives it `risk:projects_update:`; `_keepable` is false for it, so `remember` never stores it, `remembered` never honours a stored copy, and no session, project or allow grant covers it. A rename or cover change stays a normal key. The approval item says so as main's `keepable: false`, which the window already reads to hide the remember box; the PR's `rememberable` field is gone from the engine, `approvals.ts` and `BridgeApproval`. +- **Test.** The two assertions in `test_services_agents_replace_doc.py` that read the approval item now read `keepable`; nothing else in it changed. +- Removed code: `REPLACE_DOC_KEY = "projects_update:doc"`, `NEVER_REMEMBERED = ("generate", REPLACE_DOC_KEY)`, `def rememberable(key: str) -> bool: return key not in NEVER_REMEMBERED`, in `approval_key` the lines `if tool == "command_run": return f"{tool}:{args.get('id')}"`, `if tool == "projects_update": return REPLACE_DOC_KEY if "doc" in args else tool` and `if callable(mcp_tools.TOOLS.get(tool, {}).get("risky")): return f"{tool}:{args.get('path') or args.get('dir') or ''}"`, and the item field `"rememberable": rememberable(key)`; in `approvals.ts`, `const offered = item.rememberable !== false && (priced || item.tool !== 'generate');`; in `api-agents.ts`, `rememberable?: boolean;`. diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 713378a..9d54d1b 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -76,4 +76,7 @@ def cors_origins() -> list[str]: def window_origins() -> list[str]: preview = FRONTEND_PORT + 1 - return [*cors_origins(), f"http://localhost:{preview}", f"http://127.0.0.1:{preview}", "tauri://localhost", "http://tauri.localhost"] + desktop = ["tauri://localhost", "http://tauri.localhost"] + if not is_dev(): + return desktop + return [*cors_origins(), f"http://localhost:{preview}", f"http://127.0.0.1:{preview}", *desktop] diff --git a/backend/app/core/local_guard.py b/backend/app/core/local_guard.py index 4ef42cd..43925a8 100644 --- a/backend/app/core/local_guard.py +++ b/backend/app/core/local_guard.py @@ -38,9 +38,14 @@ def _loopback_client(client) -> bool: class LocalGuard: - def __init__(self, app, origins: list[str]) -> None: + def __init__(self, app, origins) -> None: self.app = app - self.allowed = {key for key in (_origin_key(o) for o in origins) if key is not None} + self.origins = origins + + @property + def allowed(self) -> set: + origins = self.origins() if callable(self.origins) else self.origins + return {key for key in (_origin_key(o) for o in origins) if key is not None} def _permitted(self, scope, headers: dict[str, str]) -> bool: if not _loopback_client(scope.get("client")): diff --git a/backend/app/main.py b/backend/app/main.py index 88873ab..9521e40 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -71,7 +71,7 @@ async def lifespan(_: FastAPI): errors.install(app) if config.is_dev(): app.add_middleware(CORSMiddleware, allow_origins=config.cors_origins(), allow_methods=["*"], allow_headers=["*"]) -app.add_middleware(LocalGuard, origins=config.window_origins()) +app.add_middleware(LocalGuard, origins=config.window_origins) for _router in (system.router, settings_router.router, keys.router, jobs_router.router, events_router.router, media_router.router, costs.router, models_router.router, plan.router, generate.router, folders.router, tags.router, characters_router.router, prompts.router, projects.router, scene.router, pack_router.router, edit_router.router): app.include_router(_router, prefix="/api") diff --git a/backend/app/routers/agents.py b/backend/app/routers/agents.py index ec02103..d1e8680 100644 --- a/backend/app/routers/agents.py +++ b/backend/app/routers/agents.py @@ -1,12 +1,14 @@ from typing import Literal -from fastapi import APIRouter, Body, Query, Request, Response +from fastapi import APIRouter, Body, Depends, Query, Request, Response from pydantic import BaseModel, StrictBool +from app.core import window_key from app.core.errors import ApiError from app.services import agents, mcp_tools router = APIRouter() +WINDOW = [Depends(window_key.require)] class Decision(BaseModel): @@ -16,12 +18,12 @@ class Decision(BaseModel): project: str | None = None -@router.post("/agents/catalogue") +@router.post("/agents/catalogue", dependencies=WINDOW) def post_catalogue(body: dict = Body(...)): return agents.catalogue.set(body, mcp_tools.names()) -@router.get("/agents/bridge/next") +@router.get("/agents/bridge/next", dependencies=WINDOW) async def bridge_next(request: Request, wait: float = Query(25, ge=0, le=30), project: str | None = Query(None, max_length=200)): if project is not None: agents.set_window_project(project) @@ -40,14 +42,14 @@ def bridge_bye(): return Response(status_code=204) -@router.post("/agents/bridge/{item_id}/result") +@router.post("/agents/bridge/{item_id}/result", dependencies=WINDOW) def bridge_result(item_id: str, body: dict = Body(...)): if not agents.bridge.result(item_id, body): raise ApiError(404, "call_not_found", "No pending call with that id.") return {"ok": True} -@router.post("/agents/approvals/{item_id}") +@router.post("/agents/approvals/{item_id}", dependencies=WINDOW) def approval(item_id: str, body: Decision): if body.project is not None: agents.set_window_project(body.project) @@ -56,26 +58,26 @@ def approval(item_id: str, body: Decision): return {"ok": True} -@router.get("/agents/state") +@router.get("/agents/state", dependencies=WINDOW) def read_state(): return agents.public_state() -@router.put("/agents/state") +@router.put("/agents/state", dependencies=WINDOW) def write_state(body: dict = Body(...)): return agents.put_state(body) -@router.post("/agents/token/rotate") +@router.post("/agents/token/rotate", dependencies=WINDOW) def rotate_token(): return {"tokenPath": str(agents.rotate_token())} -@router.get("/agents/activity") +@router.get("/agents/activity", dependencies=WINDOW) def read_activity(): return {"calls": agents.activity.list(), "max": agents.ACTIVITY_MAX} -@router.post("/agents/stop") +@router.post("/agents/stop", dependencies=WINDOW) def stop(): return {"stopped": agents.bridge.stop()} diff --git a/backend/app/routers/settings.py b/backend/app/routers/settings.py index 3d41694..15dd62c 100644 --- a/backend/app/routers/settings.py +++ b/backend/app/routers/settings.py @@ -1,5 +1,6 @@ -from fastapi import APIRouter, Body +from fastapi import APIRouter, Body, Depends +from app.core import window_key from app.services import settings router = APIRouter() @@ -10,6 +11,6 @@ def read_settings(): return settings.get() -@router.put("/settings") +@router.put("/settings", dependencies=[Depends(window_key.require)]) def write_settings(body: dict = Body(...)): return settings.update(body) diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py index 4d40c22..de9f124 100644 --- a/backend/app/services/agent_programs.py +++ b/backend/app/services/agent_programs.py @@ -26,9 +26,9 @@ def claude_signed_in(path: str) -> bool | None: if os.environ.get("ANTHROPIC_API_KEY") or os.environ.get("CLAUDE_CODE_OAUTH_TOKEN"): return True try: - out = agent_lookup.run([path, "auth", "status"], claude_code.child_env(path), claude_code.CHECK_WAIT) + out = claude_code.run([path, "auth", "status"], claude_code.child_env(path), claude_code.CHECK_WAIT) data = json.loads(out.stdout) - except (OSError, subprocess.SubprocessError, ValueError): + except (OSError, subprocess.SubprocessError, ValueError, LookupError): return None return bool(data.get("loggedIn")) if isinstance(data, dict) and "loggedIn" in data else None @@ -143,7 +143,8 @@ def open_tab(kind: str, cols: int = 100, rows: int = 30) -> dict: if own: write_tab_entry(own, token) 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, {TOKEN_VAR: token}), kind) + env = claude_code.child_env(found.path, {TOKEN_VAR: token}) + session = terminal.open_session(str(folder), cols, rows, program["title"], claude_code.interpreter_argv([found.path], env=env), env, kind) except BaseException: claude_code.revoke(token) if own: diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index 2e36846..1fa5e0f 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -2,11 +2,12 @@ import json import os import secrets +import subprocess import time from pathlib import Path from app.core import config -from app.services import agent_lookup, agents, terminal +from app.services import agent_lookup, agents, command_script, terminal KEEP_ENV = agent_lookup.KEEP_ENV OVERRIDES = {"claude": ("FORMCRAFT_CLAUDE_BIN",), "codex": ("FORMCRAFT_CODEX_BIN",), "cursor": ("FORMCRAFT_CURSOR_BIN",), "antigravity": ("FORMCRAFT_ANTIGRAVITY_BIN",)} @@ -41,7 +42,30 @@ def child_env(path: str | None = None, extra: dict | None = None) -> dict: def located(kind: str, fresh: bool = False) -> agent_lookup.Found: found = agent_lookup.find(kind, setting=setting(kind), override_vars=OVERRIDES.get(kind, ()), shell_timeout=SHELL_WAIT, fresh=fresh) - return agent_lookup.check(found, child_env(found.path), CHECK_WAIT, fresh) + env = child_env(found.path) + if found.path and through_interpreter(found.path): + return checked_script(found, env) + return agent_lookup.check(found, env, CHECK_WAIT, fresh) + + +def checked_script(found: agent_lookup.Found, env: dict, platform: str | None = None) -> agent_lookup.Found: + try: + out = run([found.path, "--version"], env, CHECK_WAIT, platform) + except LookupError as exc: + found.state, found.version, found.error = "broken", None, str(exc) + return found + except subprocess.TimeoutExpired: + found.state, found.version, found.error = "broken", None, f"it gave no answer to --version in {CHECK_WAIT:g} seconds" + return found + except OSError as exc: + found.state, found.version, found.error = "broken", None, exc.strerror or str(exc) + return found + if out.returncode == 0: + found.state, found.version, found.error = "runs", agent_lookup._version(out.stdout), "" + else: + found.state, found.version = "broken", None + found.error = agent_lookup._last_line(out.stderr) or agent_lookup._last_line(out.stdout) or f"it ended with code {out.returncode}" + return found def usable(kind: str) -> agent_lookup.Found: @@ -126,13 +150,42 @@ def workdir() -> Path: return folder -def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None) -> list[str]: +def through_interpreter(path: str, platform: str | None = None) -> bool: + return agent_lookup.windows(platform) and str(path).lower().endswith(command_script.SUFFIXES) + + +def interpreter_safe(words: list) -> bool: + return command_script.safe(words) + + +def direct(path: str, env: dict | None = None, platform: str | None = None) -> list[str]: + if not through_interpreter(path, platform): + return [str(path)] + return command_script.resolve(path, env) or [str(path)] + + +def launch_words(cmd: list, env: dict | None = None, platform: str | None = None) -> list: + words = direct(cmd[0], env, platform) + list(cmd[1:]) if cmd else [] + if words and through_interpreter(words[0], platform) and not interpreter_safe(words): + raise LookupError(command_script.REFUSED) + return words + + +def interpreter_argv(cmd: list, platform: str | None = None, env: dict | None = None) -> list[str]: + return agent_lookup.start_argv(launch_words(cmd, env, platform), platform=platform) + + +def run(cmd: list, env: dict, timeout: float = CHECK_WAIT, platform: str | None = None): + return agent_lookup.run(launch_words(cmd, env, platform), env, timeout, platform) + + +def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None, platform: 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: + if prompt and not through_interpreter(direct(path, env, platform)[0], platform): cmd.append(prompt) - return agent_lookup.start_argv(cmd) + return interpreter_argv(cmd, platform, env) def status() -> dict: @@ -156,12 +209,15 @@ def open_tab(prompt: str | None = None, cols: int = 100, rows: int = 30, fresh: raise LookupError(said(found)) title = "Claude Code (resumed)" if resume else "Claude Code" token, mcp_file = issue() + env = child_env(found.path) try: - session = terminal.open_session(str(workdir()), cols, rows, title, tab_argv(found.path, mcp_file, prompt or None, resume), child_env(found.path), "claude") + session = terminal.open_session(str(workdir()), cols, rows, title, tab_argv(found.path, mcp_file, prompt or None, resume, env=env), env, "claude") except BaseException: revoke(token) raise session.on_close.append(lambda: revoke(token)) + if prompt and through_interpreter(direct(found.path, env)[0]): + terminal.write(session.id, prompt + "\r") return session.describe() diff --git a/backend/app/services/command_script.py b/backend/app/services/command_script.py new file mode 100644 index 0000000..c8a1770 --- /dev/null +++ b/backend/app/services/command_script.py @@ -0,0 +1,66 @@ +import os +import re +from pathlib import Path + +NEVER = re.compile(r'[\x00-\x1f\x7f&|<>^()!%"]') +REFUSED = ("This program is a Windows command script, which starts through the command interpreter, and one of its words holds " + "a character that interpreter reads itself (& | < > ^ ( ) ! % \" or a control character), so it was not started. " + "Pass long or free text through standard input or a file if the program supports it.") +SUFFIXES = (".cmd", ".bat") +SCRIPTS = (".js", ".cjs", ".mjs") +HERE = re.compile(r"^%~?dp0%?[\\/]?", re.IGNORECASE) +QUOTED = re.compile(r'"([^"]*)"') +MAX_BYTES = 64 * 1024 + + +def safe(words: list) -> bool: + return all(isinstance(word, (str, Path)) and not NEVER.search(str(word)) for word in words) + + +def _text(shim: Path) -> str | None: + try: + if not shim.is_file() or shim.stat().st_size > MAX_BYTES: + return None + return shim.read_bytes().decode("utf-8", errors="replace") + except OSError: + return None + + +def _target(text: str) -> str | None: + line = next((ln for ln in reversed(text.splitlines()) if "%*" in ln), None) + if line is None: + return None + named = [HERE.sub("", word) for word in QUOTED.findall(line) if HERE.match(word)] + named = [word for word in named if word.lower() != "node.exe"] + return named[-1] if named and "%" not in named[-1] else None + + +def _inside(target: Path, shim: Path) -> bool: + folder = shim.parent.resolve() + root = folder.parent if folder.name.lower() == ".bin" else folder + return target.is_relative_to(root) + + +def _node(shim: Path, env: dict) -> str | None: + folders = [str(shim.parent)] + [p for p in (env.get("PATH") or "").split(";") if p] + return next((str(Path(f) / "node.exe") for f in folders if (Path(f) / "node.exe").is_file()), None) + + +def resolve(path: str | os.PathLike, env: dict | None = None) -> list[str] | None: + """The program an npm-style command script starts, as words to run without the command interpreter: [node, script] + for a JavaScript target, [program] for an .exe target. None when the script is not of that form or its target is + missing or outside the script's folder.""" + shim = Path(path) + text = _text(shim) if shim.suffix.lower() in SUFFIXES else None + rel = _target(text) if text else None + if not rel: + return None + target = Path(shim.parent, *[part for part in re.split(r"[\\/]+", rel) if part]).resolve() + if not target.is_file() or not _inside(target, shim): + return None + if target.suffix.lower() == ".exe": + return [str(target)] + if target.suffix.lower() in SCRIPTS: + node = _node(shim, os.environ if env is None else env) + return [node, str(target)] if node else None + return None diff --git a/backend/app/services/mcp_tools.py b/backend/app/services/mcp_tools.py index 291f9c9..48dd5ec 100644 --- a/backend/app/services/mcp_tools.py +++ b/backend/app/services/mcp_tools.py @@ -566,7 +566,7 @@ async def folders_update(a, ctx): return await _t(svc.library.update_folder, a["id"], fields) -@tool("folders_delete", "Delete a folder", "Delete a folder; its items stay in the library.", {"id": _s("Folder id.")}, ("id",), hint="D") +@tool("folders_delete", "Delete a folder", "Delete a folder; its items stay in the library. The owner is asked to approve.", {"id": _s("Folder id.")}, ("id",), hint="D", risky=True) async def folders_delete(a, ctx): await _t(svc.library.delete_folder, a["id"]) return {"deleted": True} @@ -592,7 +592,7 @@ async def tags_rename(a, ctx): return await _t(svc.library.rename_tag, a["name"], a["newName"]) -@tool("tags_delete", "Delete a tag", "Remove a tag from every item.", {"name": _s("Tag name.")}, ("name",), hint="D") +@tool("tags_delete", "Delete a tag", "Remove a tag from every item. The owner is asked to approve.", {"name": _s("Tag name.")}, ("name",), hint="D", risky=True) async def tags_delete(a, ctx): await _t(svc.library.delete_tag, a["name"]) return {"deleted": True} @@ -621,7 +621,7 @@ async def characters_update(a, ctx): return await _t(svc.characters.update, a["id"], fields) -@tool("characters_delete", "Delete a character", "Delete a character.", {"id": _s("Character id.")}, ("id",), hint="D") +@tool("characters_delete", "Delete a character", "Delete a character. The owner is asked to approve.", {"id": _s("Character id.")}, ("id",), hint="D", risky=True) async def characters_delete(a, ctx): await _t(svc.characters.delete, a["id"]) return {"deleted": True} @@ -649,7 +649,7 @@ async def projects_create(a, ctx): return await _t(svc.projects.create, a["kind"], a["name"], a["doc"]) -@tool("projects_update", "Update a project", "Replace a project's document, rename it or set its cover image. A project open in the window reloads.", {"id": _s("Project id."), "name": _s("New name."), "doc": _o("A new document."), "coverId": _null("string", "Cover library id.")}, ("id",), hint="U") +@tool("projects_update", "Update a project", "Replace a project's document, rename it or set its cover image. A project open in the window reloads. Replacing the document asks the owner to approve.", {"id": _s("Project id."), "name": _s("New name."), "doc": _o("A new document."), "coverId": _null("string", "Cover library id.")}, ("id",), hint="U", risky=lambda a: "doc" in a) async def projects_update(a, ctx): if "doc" in a: name = a.get("name") or (await _t(svc.projects.get_summary, a["id"]))["name"] diff --git a/backend/tests/cb01/test_core_local_guard.py b/backend/tests/cb01/test_core_local_guard.py index 55276b9..ea359ea 100644 --- a/backend/tests/cb01/test_core_local_guard.py +++ b/backend/tests/cb01/test_core_local_guard.py @@ -147,3 +147,27 @@ def test_a_rebound_host_header_is_refused_even_for_the_window(client): def test_a_cross_site_fetch_without_origin_is_refused(anon_client): assert anon_client.get("/api/health", headers={"sec-fetch-site": "cross-site"}).status_code == 403 assert anon_client.get("/api/health", headers={"sec-fetch-site": "same-origin"}).status_code == 200 + + +DEV_SERVER_ORIGINS = [f"http://{host}:{port}" for host in ("localhost", "127.0.0.1") for port in (config.FRONTEND_PORT, config.FRONTEND_PORT + 1)] + + +@pytest.mark.parametrize("origin", DEV_SERVER_ORIGINS) +def test_a_release_engine_refuses_the_dev_server_origins(monkeypatch, origin): + monkeypatch.delenv("FORMCRAFT_DEV", raising=False) + assert origin not in config.window_origins() + assert not LocalGuard(None, config.window_origins)._permitted(scope(), {"host": HOST, "origin": origin}) + + +@pytest.mark.parametrize("origin", DEV_SERVER_ORIGINS) +def test_a_dev_engine_admits_the_dev_server_origins(monkeypatch, origin): + monkeypatch.setenv("FORMCRAFT_DEV", "1") + assert origin in config.window_origins() + assert LocalGuard(None, config.window_origins)._permitted(scope(), {"host": HOST, "origin": origin}) + + +def test_the_desktop_window_origins_are_admitted_in_both_modes(monkeypatch): + for dev in ("1", "0"): + monkeypatch.setenv("FORMCRAFT_DEV", dev) + for origin in ("tauri://localhost", "http://tauri.localhost"): + assert LocalGuard(None, config.window_origins)._permitted(scope(), {"host": HOST, "origin": origin}) diff --git a/backend/tests/cb02/test_services_agents_replace_doc.py b/backend/tests/cb02/test_services_agents_replace_doc.py new file mode 100644 index 0000000..d68ed07 --- /dev/null +++ b/backend/tests/cb02/test_services_agents_replace_doc.py @@ -0,0 +1,60 @@ +import asyncio +import time + +from app.services import agents + +RENAME = {"id": "p", "name": "New"} +REPLACE = {"id": "p", "doc": {}} + + +def test_replacing_a_document_has_its_own_approval_key(): + assert agents.approval_key("projects_update", RENAME) != agents.approval_key("projects_update", REPLACE) + assert agents.approval_key("projects_update", {"id": "p", "coverId": None}) == agents.approval_key("projects_update", RENAME) + + +def test_a_remembered_rename_does_not_cover_replacing_the_document(data_dir): + agents.remember("client", agents.approval_key("projects_update", RENAME)) + assert agents.remembered("client", agents.approval_key("projects_update", RENAME)) + assert not agents.remembered("client", agents.approval_key("projects_update", REPLACE)) + + +def test_approval_to_replace_a_document_is_never_remembered(data_dir): + key = agents.approval_key("projects_update", REPLACE) + agents.remember("client", key) + assert not agents.remembered("client", key) + assert all(key not in c["remembered"] for c in agents.public_state()["clients"]) + + +def test_a_stored_replace_entry_is_not_honoured(data_dir): + key = agents.approval_key("projects_update", REPLACE) + state = agents._load() + agents._save({**state, "remembered": {"client": [key]}}) + assert not agents.remembered("client", key) + + +def _asked(args: dict) -> tuple[dict, bool]: + async def run(): + bridge = agents.Bridge() + bridge.until = time.monotonic() + 60 + task = asyncio.create_task(bridge.ask("client", "projects_update", args, None)) + while not bridge.queue: + await asyncio.sleep(0) + item = bridge.queue.popleft() + bridge.decide(item["id"], True, True) + await task + return item + + item = asyncio.run(run()) + return item, agents.remembered("client", agents.approval_key("projects_update", args)) + + +def test_the_window_is_told_a_document_replacement_cannot_be_remembered(data_dir): + item, kept = _asked(REPLACE) + assert item["keepable"] is False + assert not kept + + +def test_an_ordinary_update_can_still_be_remembered(data_dir): + item, kept = _asked(RENAME) + assert item["keepable"] is True + assert kept diff --git a/backend/tests/cb02/test_services_mcp_tools_approval.py b/backend/tests/cb02/test_services_mcp_tools_approval.py new file mode 100644 index 0000000..486ebc3 --- /dev/null +++ b/backend/tests/cb02/test_services_mcp_tools_approval.py @@ -0,0 +1,35 @@ +import pytest + +from app.services import mcp_tools + +ALWAYS_ASK = [ + ("projects_delete", {"id": "p"}), + ("library_delete", {"ids": ["m"]}), + ("characters_delete", {"id": "c"}), + ("folders_delete", {"id": "f"}), + ("tags_delete", {"name": "t"}), + ("projects_update", {"id": "p", "doc": {}}), +] + +NO_ASK = [ + ("projects_update", {"id": "p", "name": "New"}), + ("projects_update", {"id": "p", "coverId": None}), + ("characters_update", {"id": "c", "name": "New"}), + ("folders_update", {"id": "f", "name": "New"}), + ("tags_rename", {"name": "t", "newName": "u"}), +] + + +@pytest.mark.parametrize(("name", "args"), ALWAYS_ASK) +def test_calls_that_cannot_be_undone_ask_the_owner_whatever_the_policy(name, args): + assert mcp_tools.is_risky(name, args) + + +@pytest.mark.parametrize(("name", "args"), NO_ASK) +def test_renames_and_covers_follow_the_client_policy(name, args): + assert not mcp_tools.is_risky(name, args) + + +@pytest.mark.parametrize("name", sorted({n for n, _ in ALWAYS_ASK})) +def test_tools_that_ask_say_so_in_their_description(name): + assert "approve" in mcp_tools.get(name)["description"] diff --git a/backend/tests/cb03/test_routers_agents_window_key.py b/backend/tests/cb03/test_routers_agents_window_key.py new file mode 100644 index 0000000..6f07256 --- /dev/null +++ b/backend/tests/cb03/test_routers_agents_window_key.py @@ -0,0 +1,52 @@ +import pytest + +from app.services import agents + +WINDOW_ONLY = [ + ("post", "/api/agents/catalogue", {"tools": [], "commands": []}), + ("get", "/api/agents/bridge/next?wait=0", None), + ("post", "/api/agents/bridge/none/result", {"ok": True, "result": {"text": "x"}}), + ("post", "/api/agents/approvals/none", {"allow": True, "remember": True}), + ("get", "/api/agents/state", None), + ("put", "/api/agents/state", {"allowed": True, "policies": {"someone": "allow"}}), + ("post", "/api/agents/token/rotate", None), + ("get", "/api/agents/activity", None), + ("post", "/api/agents/stop", None), + ("put", "/api/settings", {"agentsAllowed": True}), +] + + +def _send(client, method: str, path: str, body): + return getattr(client, method)(path, json=body) if body is not None else getattr(client, method)(path) + + +@pytest.mark.parametrize(("method", "path", "body"), WINDOW_ONLY) +def test_agent_controls_refuse_a_caller_without_the_window_key(anon_client, method, path, body): + response = _send(anon_client, method, path, body) + assert response.status_code == 403 + assert response.json()["error"]["code"] == "window_key_required" + + +@pytest.mark.parametrize(("method", "path", "body"), WINDOW_ONLY) +def test_agent_controls_answer_the_window(client, method, path, body): + response = _send(client, method, path, body) + assert response.status_code != 403 + + +def test_a_caller_without_the_window_key_cannot_turn_agents_on(anon_client, client): + client.put("/api/agents/state", json={"allowed": False}) + anon_client.put("/api/agents/state", json={"allowed": True, "policies": {"someone": "allow"}}) + anon_client.put("/api/settings", json={"agentsAllowed": True}) + state = client.get("/api/agents/state").json() + assert state["allowed"] is False + assert "someone" not in state["policies"] + + +def test_a_caller_without_the_window_key_cannot_take_queued_approvals(anon_client, monkeypatch): + monkeypatch.setattr(agents.bridge, "queue", agents.deque([{"kind": "approval", "id": "kept"}])) + assert anon_client.get("/api/agents/bridge/next?wait=0").status_code == 403 + assert [item["id"] for item in agents.bridge.queue] == ["kept"] + + +def test_the_window_can_still_say_goodbye_without_headers(anon_client): + assert anon_client.post("/api/agents/bridge/bye").status_code == 204 diff --git a/backend/tests/cb03/test_routers_terminal_window_key.py b/backend/tests/cb03/test_routers_terminal_window_key.py index 46cfb73..55a1ea6 100644 --- a/backend/tests/cb03/test_routers_terminal_window_key.py +++ b/backend/tests/cb03/test_routers_terminal_window_key.py @@ -18,7 +18,8 @@ def test_the_adapter_header_is_the_one_the_engine_reads(): @pytest.mark.parametrize("origin", [engine_origin(), vite_origin()]) -def test_a_dock_list_built_like_the_adapter_is_accepted(fresh, origin): +def test_a_dock_list_built_like_the_adapter_is_accepted(fresh, monkeypatch, origin): + monkeypatch.setenv("FORMCRAFT_DEV", "1") client = page(origin) key = claim(client) response = client.get("/api/terminal", headers=adapter_headers(key)) @@ -27,7 +28,8 @@ def test_a_dock_list_built_like_the_adapter_is_accepted(fresh, origin): @pytest.mark.parametrize("origin", [engine_origin(), vite_origin()]) -def test_a_dock_list_without_the_key_is_refused(fresh, origin): +def test_a_dock_list_without_the_key_is_refused(fresh, monkeypatch, origin): + monkeypatch.setenv("FORMCRAFT_DEV", "1") client = page(origin) claim(client) response = client.get("/api/terminal", headers={"Accept": "application/json"}) diff --git a/backend/tests/cb03/test_services_claude_code_prompt.py b/backend/tests/cb03/test_services_claude_code_prompt.py new file mode 100644 index 0000000..ff4def4 --- /dev/null +++ b/backend/tests/cb03/test_services_claude_code_prompt.py @@ -0,0 +1,98 @@ +from types import SimpleNamespace + +import pytest + +from app.services import agent_lookup, claude_code, terminal + +PROMPT = 'make a "red & blue" poster at 100% | then stop' + + +def test_a_windows_command_script_never_carries_the_prompt_on_its_command_line(): + argv = claude_code.tab_argv(r"C:\npm\claude.cmd", "mcp.json", PROMPT, platform="win32") + assert argv[1] == "/c" + assert PROMPT not in argv + assert not any("red & blue" in word for word in argv) + + +def test_a_windows_batch_file_never_carries_the_prompt_either(): + argv = claude_code.tab_argv(r"C:\tools\CLAUDE.BAT", "mcp.json", PROMPT, platform="win32") + assert PROMPT not in argv + + +def test_a_windows_program_still_takes_the_prompt_as_its_last_word(): + argv = claude_code.tab_argv(r"C:\bin\claude.exe", "mcp.json", PROMPT, platform="win32") + assert argv[0] == r"C:\bin\claude.exe" + assert argv[-1] == PROMPT + + +def test_macos_and_linux_still_pass_the_prompt_to_the_program(monkeypatch): + monkeypatch.setattr(agent_lookup, "login_shell", lambda env=None, platform=None: "/bin/sh") + argv = claude_code.tab_argv("/usr/local/bin/claude", "mcp.json", PROMPT, platform="darwin") + assert "'make a \"red & blue\" poster at 100% | then stop'" in argv[-1] + + +@pytest.mark.parametrize(("path", "typed"), [(r"C:\npm\claude.cmd", True), (r"C:\bin\claude.exe", False)]) +def test_a_prompt_left_off_the_command_line_is_typed_into_the_new_tab(monkeypatch, path, typed): + session = SimpleNamespace(id="s1", on_close=[], describe=lambda: {"id": "s1"}) + started = [] + written = [] + monkeypatch.setattr(terminal, "SESSIONS", {}) + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + monkeypatch.setattr(agent_lookup, "login_shell", lambda env=None, platform=None: "/bin/sh") + monkeypatch.setattr(claude_code, "usable", lambda kind: SimpleNamespace(state="runs", path=path)) + monkeypatch.setattr(claude_code, "issue", lambda: ("token", "mcp.json")) + monkeypatch.setattr(claude_code, "child_env", lambda p=None, extra=None: {}) + monkeypatch.setattr(claude_code, "workdir", lambda: "here") + monkeypatch.setattr(terminal, "open_session", lambda cwd, cols, rows, title, argv, env, kind: started.append(argv) or session) + monkeypatch.setattr(terminal, "write", lambda sid, data: written.append((sid, data))) + claude_code.open_tab(PROMPT) + assert written == ([("s1", PROMPT + "\r")] if typed else []) + assert (PROMPT in started[0]) is not typed + + +@pytest.mark.parametrize("word", ["a\nb", "a\rb", "a\x00b", "a\x1bb", "a\x7fb", "%PATH%", "a b %c", 'say "hi"', "a&b", "a b & c", "a|b", "ab", "a^b", "a!b", "(a)"]) +def test_a_command_script_refuses_words_the_interpreter_would_read(word): + with pytest.raises(LookupError): + claude_code.tab_argv(r"C:\npm\claude.cmd", "mcp.json", None, word, platform="win32") + + +def test_a_command_script_refuses_a_word_that_is_not_text(): + assert not claude_code.interpreter_safe([r"C:\npm\claude.cmd", 3]) + assert not claude_code.interpreter_safe([r"C:\npm\claude.cmd", None]) + + +@pytest.mark.parametrize("word", ["a (b)", "(a b)", "a b)", "say \"a b\"", "a b !c", "a\tb^c"]) +def test_a_command_script_refuses_those_words_even_when_they_hold_a_space(word): + with pytest.raises(LookupError, match="standard input or a file"): + claude_code.tab_argv(r"C:\npm\claude.cmd", "mcp.json", None, word, platform="win32") + + +def test_a_command_script_whose_own_path_holds_parentheses_is_refused(): + with pytest.raises(LookupError): + claude_code.tab_argv(r"C:\Program Files (x86)\npm\claude.cmd", "mcp.json", None, platform="win32") + + +@pytest.mark.parametrize("path", [r"C:\Program Files\npm\claude.cmd", r"C:\Users\me\AppData\Roaming\npm\claude.cmd"]) +def test_a_command_script_still_starts_with_ordinary_words(path): + argv = claude_code.tab_argv(path, r"C:\Users\me\data\mcp-1.json", None, "abc-123", platform="win32") + assert argv[1] == "/c" + assert argv[2] == path + + +def test_a_windows_program_keeps_any_characters_in_its_words(): + argv = claude_code.tab_argv(r"C:\bin\claude.exe", "mcp.json", None, "a&b%c", platform="win32") + assert "a&b%c" in argv + + +def test_another_agent_started_as_a_command_script_is_refused_too(monkeypatch): + from app.services import agent_programs + + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False) + ran = [] + monkeypatch.setattr(agent_lookup, "run", lambda *a, **k: ran.append(a)) + with pytest.raises(LookupError): + claude_code.interpreter_argv([r"C:\npm\a&b\codex.cmd"]) + assert agent_programs.claude_signed_in(r"C:\npm\a&b\claude.cmd") is None + assert ran == [] diff --git a/backend/tests/cb03/test_services_command_script.py b/backend/tests/cb03/test_services_command_script.py new file mode 100644 index 0000000..64e0a7a --- /dev/null +++ b/backend/tests/cb03/test_services_command_script.py @@ -0,0 +1,136 @@ +from types import SimpleNamespace + +import pytest + +from app.services import agent_lookup, agent_programs, claude_code, command_script, terminal + +JS_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)\r\n\r\n' + 'endLocal & "%_prog%" "%dp0%\\node_modules\\tool\\cli.js" %*\r\n' +) +EXE_SHIM = '@ECHO off\r\nSETLOCAL\r\nSET dp0=%~dp0\r\nendLocal & "%dp0%\\node_modules\\tool\\bin\\tool.exe" %*\r\n' +OLD_SHIM = '@IF EXIST "%~dp0\\node.exe" (\r\n "%~dp0\\node.exe" "%~dp0\\node_modules\\tool\\cli.js" %*\r\n) ELSE (\r\n node "%~dp0\\node_modules\\tool\\cli.js" %*\r\n)\r\n' +PROMPT = 'make a "red & blue" poster at 100% | then (stop) !' + + +def make(folder, text, name="claude.cmd", target=("node_modules", "tool", "cli.js"), node=True): + folder.mkdir(parents=True, exist_ok=True) + shim = folder / name + shim.write_text(text, encoding="utf-8") + if target: + file = folder.joinpath(*target) + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text("", encoding="utf-8") + if node: + (folder / "node.exe").write_text("", encoding="utf-8") + return shim + + +def test_a_script_shim_resolves_to_node_and_its_script(tmp_path): + shim = make(tmp_path / "npm", JS_SHIM) + words = command_script.resolve(shim, {"PATH": ""}) + assert words == [str((tmp_path / "npm" / "node.exe")), str((tmp_path / "npm" / "node_modules" / "tool" / "cli.js").resolve())] + + +def test_an_older_script_shim_resolves_the_same_way(tmp_path): + shim = make(tmp_path / "npm", OLD_SHIM) + assert command_script.resolve(shim, {"PATH": ""})[1].endswith("cli.js") + + +def test_node_is_taken_from_the_path_when_the_shim_folder_has_none(tmp_path): + shim = make(tmp_path / "npm", JS_SHIM, node=False) + (tmp_path / "nodejs").mkdir() + (tmp_path / "nodejs" / "node.exe").write_text("", encoding="utf-8") + words = command_script.resolve(shim, {"PATH": str(tmp_path / "nodejs")}) + assert words[0] == str(tmp_path / "nodejs" / "node.exe") + + +def test_a_shim_without_any_node_is_not_resolved(tmp_path): + shim = make(tmp_path / "npm", JS_SHIM, node=False) + assert command_script.resolve(shim, {"PATH": ""}) is None + + +def test_a_program_shim_resolves_to_the_program(tmp_path): + shim = make(tmp_path / "npm", EXE_SHIM, target=("node_modules", "tool", "bin", "tool.exe"), node=False) + assert command_script.resolve(shim, {"PATH": ""}) == [str((tmp_path / "npm" / "node_modules" / "tool" / "bin" / "tool.exe").resolve())] + + +@pytest.mark.parametrize("text", [ + "@echo off\r\necho hello\r\n", + '@echo off\r\n"%dp0%\\node_modules\\tool\\cli.js"\r\n', + '@echo off\r\n"%dp0%\\..\\elsewhere\\cli.js" %*\r\n', + '@echo off\r\n"%dp0%\\%OTHER%\\cli.js" %*\r\n', + '@echo off\r\n"%dp0%\\node_modules\\tool\\run.bat" %*\r\n', +]) +def test_other_command_scripts_are_not_resolved(tmp_path, text): + (tmp_path / "elsewhere").mkdir() + (tmp_path / "elsewhere" / "cli.js").write_text("", encoding="utf-8") + shim = make(tmp_path / "npm", text, target=("node_modules", "tool", "run.bat")) + assert command_script.resolve(shim, {"PATH": ""}) is None + + +def test_a_missing_target_is_not_resolved(tmp_path): + shim = make(tmp_path / "npm", JS_SHIM, target=None) + assert command_script.resolve(shim, {"PATH": ""}) is None + + +def test_a_resolved_shim_starts_without_the_interpreter_and_keeps_every_word(tmp_path): + shim = make(tmp_path / "npm", JS_SHIM) + argv = claude_code.tab_argv(str(shim), "mcp.json", PROMPT, platform="win32", env={"PATH": ""}) + assert argv[0] == str(tmp_path / "npm" / "node.exe") + assert "/c" not in argv + assert argv[-1] == PROMPT + + +def test_an_unresolved_shim_still_refuses_words_the_interpreter_would_read(tmp_path): + shim = make(tmp_path / "npm", "@echo off\r\necho hello\r\n", target=None) + with pytest.raises(LookupError): + claude_code.interpreter_argv([str(shim), "a&b"], platform="win32", env={"PATH": ""}) + + +def test_a_resolved_tab_gets_its_prompt_on_the_command_line_not_typed(monkeypatch, tmp_path): + shim = make(tmp_path / "npm", JS_SHIM) + session = SimpleNamespace(id="s1", on_close=[], describe=lambda: {"id": "s1"}) + started, written = [], [] + monkeypatch.setattr(terminal, "SESSIONS", {}) + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + monkeypatch.setattr(claude_code, "usable", lambda kind: SimpleNamespace(state="runs", path=str(shim))) + monkeypatch.setattr(claude_code, "issue", lambda: ("token", "mcp.json")) + monkeypatch.setattr(claude_code, "child_env", lambda p=None, extra=None: {"PATH": ""}) + monkeypatch.setattr(claude_code, "workdir", lambda: "here") + monkeypatch.setattr(terminal, "open_session", lambda cwd, cols, rows, title, argv, env, kind: started.append(argv) or session) + monkeypatch.setattr(terminal, "write", lambda sid, data: written.append((sid, data))) + claude_code.open_tab(PROMPT) + assert written == [] + assert started[0][-1] == PROMPT + + +def test_the_version_check_of_an_unresolved_unsafe_script_runs_nothing(monkeypatch): + ran = [] + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + monkeypatch.setattr(agent_lookup, "run", lambda *a, **k: ran.append(a)) + found = claude_code.checked_script(agent_lookup.Found("claude", "Claude Code", path=r"C:\a&b\claude.cmd"), {"PATH": ""}) + assert found.state == "broken" + assert "standard input or a file" in found.error + assert ran == [] + + +def test_the_version_check_and_sign_in_check_run_the_resolved_program(monkeypatch, tmp_path): + shim = make(tmp_path / "a&b" / "npm", JS_SHIM) + ran = [] + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + monkeypatch.setattr(claude_code, "child_env", lambda p=None, extra=None: {"PATH": ""}) + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False) + + def fake_run(cmd, env, timeout=15.0, platform=None): + ran.append(cmd) + return SimpleNamespace(returncode=0, stdout='{"loggedIn": true}' if "auth" in cmd else "2.0.1 (tool)", stderr="") + + monkeypatch.setattr(agent_lookup, "run", fake_run) + found = claude_code.checked_script(agent_lookup.Found("claude", "Claude Code", path=str(shim)), {"PATH": ""}) + assert (found.state, found.version) == ("runs", "2.0.1") + assert agent_programs.claude_signed_in(str(shim)) is True + assert [cmd[0] for cmd in ran] == [str(tmp_path / "a&b" / "npm" / "node.exe")] * 2 + assert ran[0][2:] == ["--version"] and ran[1][2:] == ["auth", "status"] diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 11c98ee..08a8744 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -7152,6 +7152,12 @@ Checked in a real Chrome against the engine: a reload keeps the dock working (th - **Remember box.** The approval dialog is built once and reused, so with no estimate the label stays in place with `visibility: hidden` and a disabled checkbox, and `finish` ignores a disabled box. Removing the label would shift the dialog. - **Source maps (`vite.config.ts`).** Production builds emit none; `npm run dev` still serves them. `setup/freeze_backend` rebuilds a `dist` that still has `.map` files and stops if any remain. +## 2026-11-28 · approvals that are never remembered {#approvals-never-remembered} + +- refers-to: src/automation/approvals.ts :: ApprovalDialog; src/io/api-agents.ts :: BridgeApproval +- **Remember box.** An approval item may carry `rememberable: false` (the engine sends it for replacing a project's document). The dialog then hides and disables the remember box the same way it does for an unpriced generate, so the layout does not move. An item without the field behaves as before. +- Removed code: none. + ## 2026-11-29 · v0.10.0 the usability round {#usable-v0100} - **Why Record hung.** `ui/scene/output` tried the window's WebCodecs encoder first. Its `add` waits for a `dequeue` event once four frames are queued and that wait has no time limit; the macOS webview may never send the event, and Stop only set a flag the stuck loop never read. The engine sink is now first, the window sink is the fallback, and every wait has a limit. Reproduced in headless Chrome by dropping `dequeue` events. Not run on a Mac. @@ -7179,3 +7185,9 @@ Checked in a real Chrome against the engine: a reload keeps the dock working (th - **Tours.** `ui/help/tour.ts` takes Esc only while its card is visible. - **Edit open.** `activeProjectId()` must not start a studio; it did, and the Edit opener kept the blank studio. - Removed code: `ui/key-setup.ts`, `ui/canvas/generate/extend.ts`, the Media pop-up panel in `ui/panels/media-drawer.ts`, `.fc-ed-dots` and `.fc-ed-ob-actions`. + +## 2026-11-29 · main 0.11.0 merged into the agents hardening branch {#agents-hardening-merge} + +- refers-to: src/automation/approvals.ts :: ApprovalDialog; src/io/api-agents.ts :: BridgeApproval +- **Remember box.** The dialog reads main's `keepable` only. The engine now sends `keepable: false` for replacing a project's document (see the backend log, `agents-hardening-merge`), so the box is hidden and disabled for it as the entry of 2026-11-28 above describes; the `rememberable` field that entry names is gone. +- Removed code: `const offered = item.rememberable !== false && (priced || item.tool !== 'generate');` in `approvals.ts` and `rememberable?: boolean;` in `BridgeApproval`.