diff --git a/.agents/skills/formpath-harness/references/tools.md b/.agents/skills/formpath-harness/references/tools.md index 72fb901..e1c4058 100644 --- a/.agents/skills/formpath-harness/references/tools.md +++ b/.agents/skills/formpath-harness/references/tools.md @@ -84,13 +84,14 @@ Opens a file at an absolute path: a formpath project (.fpth), SVG, PDF or a PDF- ## save_project -Saves the document as a formpath project (.fpth) at an absolute path; everything stays editable. +Saves the document as a formpath project (.fpth) at an absolute path; everything stays editable. A path that already exists is refused unless replace is true. - `path`: string; required +- `replace`: boolean; default false; true replaces a file already at path. Without it a path that already exists is refused and nothing is written: choose a new path, or pass true only when the person wants that file replaced. ## export_file -Exports the art to an absolute path; the extension chooses the format: .svg, .pdf (every artboard a page), .ai (PDF-compatible Illustrator file, every artboard a page, reopens fully editable in formpath), .eps (Level 3 PostScript; all_artboards gives a zip of one EPS per artboard), .dxf (AutoCAD 2000 or R12, layers kept), .dwg (AutoCAD 2000 binary drawing, layers kept, written natively), .png (with colors it writes an indexed PNG-8), .jpg, .webp, .gif (2 to 256 colors, transparency with a matte, optional interlace), .bmp (24-bit or 32-bit with alpha), .psd (flattened composite plus layers, RGB or CMYK: with psd_edit, layers and groups become Photoshop groups, point and area type become editable type layers and filled paths become shape layers; otherwise one pixel layer per top-level layer) or .tiff. Every raster format takes ppi (any resolution) and anti_aliasing. +Exports the art to an absolute path; the extension chooses the format: .svg, .pdf (every artboard a page), .ai (PDF-compatible Illustrator file, every artboard a page, reopens fully editable in formpath), .eps (Level 3 PostScript; all_artboards gives a zip of one EPS per artboard), .dxf (AutoCAD 2000 or R12, layers kept), .dwg (AutoCAD 2000 binary drawing, layers kept, written natively), .png (with colors it writes an indexed PNG-8), .jpg, .webp, .gif (2 to 256 colors, transparency with a matte, optional interlace), .bmp (24-bit or 32-bit with alpha), .psd (flattened composite plus layers, RGB or CMYK: with psd_edit, layers and groups become Photoshop groups, point and area type become editable type layers and filled paths become shape layers; otherwise one pixel layer per top-level layer) or .tiff. Every raster format takes ppi (any resolution) and anti_aliasing. A path that already exists is refused unless replace is true. - `path`: string; required - `scope`: string (artboard | document | selection | all_artboards); default "artboard" @@ -126,6 +127,7 @@ Exports the art to an absolute path; the extension chooses the format: .svg, .pd - `bmp_bits`: integer (24 | 32); default 24; BMP only: 24 writes RGB, 32 writes RGBA (alpha when transparent is true). - `psd_layers`: boolean; default true; PSD only: write one pixel layer per top-level layer (name, visibility and opacity kept) under the flattened composite; false writes the composite only. The color parameter (rgb or cmyk) chooses 8-bit RGB or CMYK. - `psd_edit`: boolean; default true; PSD only, with psd_layers: maximum editability. Sublayers and groups become Photoshop layer groups, point and area type become editable type layers, filled paths become shape layers (solid or gradient fill, vector mask, vector stroke); anything Photoshop cannot hold that way (effects, type on a path, patterns, images) stays a pixel layer. false writes one pixel layer per top-level layer. +- `replace`: boolean; default false; true replaces a file already at path. Without it a path that already exists is refused and nothing is written: choose a new path, or pass true only when the person wants that file replaced. ## switch_document diff --git a/.agents/skills/formpath-harness/sub-skills/files-and-export/SUB-SKILL.md b/.agents/skills/formpath-harness/sub-skills/files-and-export/SUB-SKILL.md index df3d4c6..6ae6d95 100644 --- a/.agents/skills/formpath-harness/sub-skills/files-and-export/SUB-SKILL.md +++ b/.agents/skills/formpath-harness/sub-skills/files-and-export/SUB-SKILL.md @@ -22,6 +22,8 @@ Paths are absolute, and the folder exists. When the person names a folder like D 2. **Place**: `place_image` with x, y and width to put a PNG, JPEG, WebP, GIF, or SVG, EPS or DXF art into the open document. A PDF or .ai takes `page` and `crop` (bounding, art, crop, trim, bleed, media) and arrives as editable art, or with `link` true as a linked picture of the page; a PSD takes `psd_import` (objects or flatten); a TIFF takes `page`. 3. **Save editable**: `save_project` to a .fpth path; everything stays editable. Do this before outlining type or expanding. 4. **Export**: `export_file`; the extension picks the format. + - A path that already exists is refused and nothing is written. Choose a new name, or pass `replace` true only when the person asked for that file to be replaced. + - Every `save_project`, `export_file`, `actions` batch, `variables` export, `links` unembed and `run_command` or `run_commands` with `save`, `download-project` or `link-unembed` asks the person in the formpath window, even after they chose Always allow; tell them a question is waiting. - .svg: scope artboard, document or selection; outline_text true when fonts may be missing where it goes. - .pdf: every artboard a page with scope all_artboards; vectors, gradients and transparency kept; formpath reopens it editable. - .eps: Level 3 PostScript of an artboard (all_artboards writes a zip with one EPS per artboard); `color` rgb or cmyk; transparency is flattened against what lies below; formpath reopens it editable. diff --git a/.agents/skills/formpath-harness/sub-skills/troubleshooting/SUB-SKILL.md b/.agents/skills/formpath-harness/sub-skills/troubleshooting/SUB-SKILL.md index dd8bca6..82bcb2d 100644 --- a/.agents/skills/formpath-harness/sub-skills/troubleshooting/SUB-SKILL.md +++ b/.agents/skills/formpath-harness/sub-skills/troubleshooting/SUB-SKILL.md @@ -16,7 +16,7 @@ None: load directly for any failure. ## Procedure 1. **No formpath tools listed**: the MCP server is not connected. Ask the person to run `./formpath mcp` setup (`./formpath agents install`) or check the client's MCP settings, then restart the client. -2. **A call waits, then fails with a consent message**: the formpath window is asking whether to allow the agent, naming it and what it asked for. Tell the person to answer in the formpath window (Allow once covers that one call, Always allow covers every outside agent, Deny refuses; the Preferences > Plugins choice "Outside agents (MCP)" keeps Ask each time, Allowed or Blocked, and only the window can change it), then retry once. +2. **A call waits, then fails with a consent message**: the formpath window is asking whether to allow the agent, naming it and what it asked for. Tell the person to answer in the formpath window (Allow once covers that one call, Always allow covers every outside agent except for writing files, Deny refuses; `save_project`, `export_file`, an `actions` batch, a `variables` export, a `links` unembed and the `save`, `download-project` and `link-unembed` commands ask each time and offer only Deny and Allow once; the Preferences > Plugins choice "Outside agents (MCP)" keeps Ask each time, Allowed or Blocked, and only the window can change it), then retry once. 3. **The engine is not answering**: formpath is not running. `./formpath mcp` starts it; otherwise ask the person to run `./formpath boot` and open http://localhost:5230. 4. **No window open**: tools run in the open formpath window; ask the person to open formpath in a browser or the desktop app. 5. **No object has the id**: ids changed (Pathfinder, expand, outlines, undo, or the person edited). Call `get_document`, match by name or bounds, retry. diff --git a/.agents/skills/formpath-skillset/sub-skills/agent-harness/SUB-SKILL.md b/.agents/skills/formpath-skillset/sub-skills/agent-harness/SUB-SKILL.md index 834092f..8984993 100644 --- a/.agents/skills/formpath-skillset/sub-skills/agent-harness/SUB-SKILL.md +++ b/.agents/skills/formpath-skillset/sub-skills/agent-harness/SUB-SKILL.md @@ -15,7 +15,7 @@ client -> setup/mcp_stdio.py (stdio) -> POST /mcp (backend/app/routers/mcp.py) The window bridge is private to the formpath window: it gets a secret from `POST /api/mcp/bridge/session` (issued only to formpath's own Origin) and sends it in `X-Formpath-Bridge` on every bridge call through `io/api.ts`. Never add a bridge endpoint that skips `_bridge_refusal`, and never make one a GET. -The first call queues `__consent__`; the window asks the person once and remembers the answer in Preferences. File tools (`open_file`, `save_project`, `export_file`, `place_image`) run in the backend, which calls the window's `__open`, `__place`, `__project` and `__export` and writes or reads the absolute path itself. +The first call queues `__consent__`; the window asks the person once and remembers the answer in Preferences. Calls that write files (`save_project`, `export_file`, `actions` batch, `variables` export, `links` unembed, and `run_command` or `run_commands` with an id in `_WRITING_COMMANDS`; `_writes_files`, also checked in `_call` so the `/api/commands` route is covered) queue a `__consent__` with `each: true` and answers `deny`, `once` every time, and the window shows it even when Allowed (`asksEachTime`, `consentOffers` in `io/api.ts`); a yes runs that call only. `save_project` and `export_file` refuse an existing path unless `replace` is true, and write a new file with `files.write_exclusive`. File tools (`open_file`, `save_project`, `export_file`, `place_image`) run in the backend, which calls the window's `__open`, `__place`, `__project` and `__export` and writes or reads the absolute path itself. ## Adding a tool diff --git a/.claude/skills/formpath-harness/references/tools.md b/.claude/skills/formpath-harness/references/tools.md index 72fb901..e1c4058 100644 --- a/.claude/skills/formpath-harness/references/tools.md +++ b/.claude/skills/formpath-harness/references/tools.md @@ -84,13 +84,14 @@ Opens a file at an absolute path: a formpath project (.fpth), SVG, PDF or a PDF- ## save_project -Saves the document as a formpath project (.fpth) at an absolute path; everything stays editable. +Saves the document as a formpath project (.fpth) at an absolute path; everything stays editable. A path that already exists is refused unless replace is true. - `path`: string; required +- `replace`: boolean; default false; true replaces a file already at path. Without it a path that already exists is refused and nothing is written: choose a new path, or pass true only when the person wants that file replaced. ## export_file -Exports the art to an absolute path; the extension chooses the format: .svg, .pdf (every artboard a page), .ai (PDF-compatible Illustrator file, every artboard a page, reopens fully editable in formpath), .eps (Level 3 PostScript; all_artboards gives a zip of one EPS per artboard), .dxf (AutoCAD 2000 or R12, layers kept), .dwg (AutoCAD 2000 binary drawing, layers kept, written natively), .png (with colors it writes an indexed PNG-8), .jpg, .webp, .gif (2 to 256 colors, transparency with a matte, optional interlace), .bmp (24-bit or 32-bit with alpha), .psd (flattened composite plus layers, RGB or CMYK: with psd_edit, layers and groups become Photoshop groups, point and area type become editable type layers and filled paths become shape layers; otherwise one pixel layer per top-level layer) or .tiff. Every raster format takes ppi (any resolution) and anti_aliasing. +Exports the art to an absolute path; the extension chooses the format: .svg, .pdf (every artboard a page), .ai (PDF-compatible Illustrator file, every artboard a page, reopens fully editable in formpath), .eps (Level 3 PostScript; all_artboards gives a zip of one EPS per artboard), .dxf (AutoCAD 2000 or R12, layers kept), .dwg (AutoCAD 2000 binary drawing, layers kept, written natively), .png (with colors it writes an indexed PNG-8), .jpg, .webp, .gif (2 to 256 colors, transparency with a matte, optional interlace), .bmp (24-bit or 32-bit with alpha), .psd (flattened composite plus layers, RGB or CMYK: with psd_edit, layers and groups become Photoshop groups, point and area type become editable type layers and filled paths become shape layers; otherwise one pixel layer per top-level layer) or .tiff. Every raster format takes ppi (any resolution) and anti_aliasing. A path that already exists is refused unless replace is true. - `path`: string; required - `scope`: string (artboard | document | selection | all_artboards); default "artboard" @@ -126,6 +127,7 @@ Exports the art to an absolute path; the extension chooses the format: .svg, .pd - `bmp_bits`: integer (24 | 32); default 24; BMP only: 24 writes RGB, 32 writes RGBA (alpha when transparent is true). - `psd_layers`: boolean; default true; PSD only: write one pixel layer per top-level layer (name, visibility and opacity kept) under the flattened composite; false writes the composite only. The color parameter (rgb or cmyk) chooses 8-bit RGB or CMYK. - `psd_edit`: boolean; default true; PSD only, with psd_layers: maximum editability. Sublayers and groups become Photoshop layer groups, point and area type become editable type layers, filled paths become shape layers (solid or gradient fill, vector mask, vector stroke); anything Photoshop cannot hold that way (effects, type on a path, patterns, images) stays a pixel layer. false writes one pixel layer per top-level layer. +- `replace`: boolean; default false; true replaces a file already at path. Without it a path that already exists is refused and nothing is written: choose a new path, or pass true only when the person wants that file replaced. ## switch_document diff --git a/.claude/skills/formpath-harness/sub-skills/files-and-export/SUB-SKILL.md b/.claude/skills/formpath-harness/sub-skills/files-and-export/SUB-SKILL.md index df3d4c6..6ae6d95 100644 --- a/.claude/skills/formpath-harness/sub-skills/files-and-export/SUB-SKILL.md +++ b/.claude/skills/formpath-harness/sub-skills/files-and-export/SUB-SKILL.md @@ -22,6 +22,8 @@ Paths are absolute, and the folder exists. When the person names a folder like D 2. **Place**: `place_image` with x, y and width to put a PNG, JPEG, WebP, GIF, or SVG, EPS or DXF art into the open document. A PDF or .ai takes `page` and `crop` (bounding, art, crop, trim, bleed, media) and arrives as editable art, or with `link` true as a linked picture of the page; a PSD takes `psd_import` (objects or flatten); a TIFF takes `page`. 3. **Save editable**: `save_project` to a .fpth path; everything stays editable. Do this before outlining type or expanding. 4. **Export**: `export_file`; the extension picks the format. + - A path that already exists is refused and nothing is written. Choose a new name, or pass `replace` true only when the person asked for that file to be replaced. + - Every `save_project`, `export_file`, `actions` batch, `variables` export, `links` unembed and `run_command` or `run_commands` with `save`, `download-project` or `link-unembed` asks the person in the formpath window, even after they chose Always allow; tell them a question is waiting. - .svg: scope artboard, document or selection; outline_text true when fonts may be missing where it goes. - .pdf: every artboard a page with scope all_artboards; vectors, gradients and transparency kept; formpath reopens it editable. - .eps: Level 3 PostScript of an artboard (all_artboards writes a zip with one EPS per artboard); `color` rgb or cmyk; transparency is flattened against what lies below; formpath reopens it editable. diff --git a/.claude/skills/formpath-harness/sub-skills/troubleshooting/SUB-SKILL.md b/.claude/skills/formpath-harness/sub-skills/troubleshooting/SUB-SKILL.md index dd8bca6..82bcb2d 100644 --- a/.claude/skills/formpath-harness/sub-skills/troubleshooting/SUB-SKILL.md +++ b/.claude/skills/formpath-harness/sub-skills/troubleshooting/SUB-SKILL.md @@ -16,7 +16,7 @@ None: load directly for any failure. ## Procedure 1. **No formpath tools listed**: the MCP server is not connected. Ask the person to run `./formpath mcp` setup (`./formpath agents install`) or check the client's MCP settings, then restart the client. -2. **A call waits, then fails with a consent message**: the formpath window is asking whether to allow the agent, naming it and what it asked for. Tell the person to answer in the formpath window (Allow once covers that one call, Always allow covers every outside agent, Deny refuses; the Preferences > Plugins choice "Outside agents (MCP)" keeps Ask each time, Allowed or Blocked, and only the window can change it), then retry once. +2. **A call waits, then fails with a consent message**: the formpath window is asking whether to allow the agent, naming it and what it asked for. Tell the person to answer in the formpath window (Allow once covers that one call, Always allow covers every outside agent except for writing files, Deny refuses; `save_project`, `export_file`, an `actions` batch, a `variables` export, a `links` unembed and the `save`, `download-project` and `link-unembed` commands ask each time and offer only Deny and Allow once; the Preferences > Plugins choice "Outside agents (MCP)" keeps Ask each time, Allowed or Blocked, and only the window can change it), then retry once. 3. **The engine is not answering**: formpath is not running. `./formpath mcp` starts it; otherwise ask the person to run `./formpath boot` and open http://localhost:5230. 4. **No window open**: tools run in the open formpath window; ask the person to open formpath in a browser or the desktop app. 5. **No object has the id**: ids changed (Pathfinder, expand, outlines, undo, or the person edited). Call `get_document`, match by name or bounds, retry. diff --git a/.claude/skills/formpath-skillset/sub-skills/agent-harness/SUB-SKILL.md b/.claude/skills/formpath-skillset/sub-skills/agent-harness/SUB-SKILL.md index 834092f..8984993 100644 --- a/.claude/skills/formpath-skillset/sub-skills/agent-harness/SUB-SKILL.md +++ b/.claude/skills/formpath-skillset/sub-skills/agent-harness/SUB-SKILL.md @@ -15,7 +15,7 @@ client -> setup/mcp_stdio.py (stdio) -> POST /mcp (backend/app/routers/mcp.py) The window bridge is private to the formpath window: it gets a secret from `POST /api/mcp/bridge/session` (issued only to formpath's own Origin) and sends it in `X-Formpath-Bridge` on every bridge call through `io/api.ts`. Never add a bridge endpoint that skips `_bridge_refusal`, and never make one a GET. -The first call queues `__consent__`; the window asks the person once and remembers the answer in Preferences. File tools (`open_file`, `save_project`, `export_file`, `place_image`) run in the backend, which calls the window's `__open`, `__place`, `__project` and `__export` and writes or reads the absolute path itself. +The first call queues `__consent__`; the window asks the person once and remembers the answer in Preferences. Calls that write files (`save_project`, `export_file`, `actions` batch, `variables` export, `links` unembed, and `run_command` or `run_commands` with an id in `_WRITING_COMMANDS`; `_writes_files`, also checked in `_call` so the `/api/commands` route is covered) queue a `__consent__` with `each: true` and answers `deny`, `once` every time, and the window shows it even when Allowed (`asksEachTime`, `consentOffers` in `io/api.ts`); a yes runs that call only. `save_project` and `export_file` refuse an existing path unless `replace` is true, and write a new file with `files.write_exclusive`. File tools (`open_file`, `save_project`, `export_file`, `place_image`) run in the backend, which calls the window's `__open`, `__place`, `__project` and `__export` and writes or reads the absolute path itself. ## Adding a tool diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 4737de0..7344b53 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1069,3 +1069,19 @@ Both launchers expanded `%*` or `%2` to `%9` inside a parenthesised block. `cmd` - logged: v0.63.0 · 2026-11-26 Package copied every font the document uses and said nothing about licences. It now names the copied fonts whose `fsType` restricts embedding and asks the person to check that the licence also lets them pass the font on before they share the package. No font is ever dropped: a package without its fonts opens wrong on the next computer, and whether a licence allows passing the file on is the person's reading to make, not the app's. + +### app/routers/mcp.py, app/core/files.py · file writes ask each time, and an existing file needs replace +- refers-to: app/routers/mcp.py :: _REPLACE, EACH_TIME_ANSWERS, _writes_files, _consent_request, _ask_caller, _call, _taken, _keep_existing, _write, _run, mcp; app/core/files.py :: write_exclusive; frontend/src/io/api.ts :: asksEachTime, consentOffers; frontend/src/automation/agent-bridge.ts :: loop; frontend/src/dock-adapter.ts :: outsideAgents.arrive; tests/test_file_write_consent.py +- kind: decision +- logged: v0.63.0 · 2026-11-29 + +The owner's decision: a standing yes (Always allow, or Outside agents set to Allowed) no longer covers tools that write files on this computer, and saving or exporting never replaces a file the agent did not say it wants replaced. `mcp()` marks a call `writes` when `_writes_files` says so (save_project, export_file, actions with action batch, variables with action export). `_call` then asks even when `_allowed` is set, with `each: true`, answers `["deny", "once"]` and `alwaysCovers: "none"`; any yes runs that one call (the queued item carries `once`) and never sets `_allowed`, and a no refuses only that write, so it sets no ten-minute pause. The window used to answer every question itself while Allowed; it now leaves a question with `each: true` to the person (`asksEachTime`), and `consentOffers` drops `always` from such a question even if the engine listed it. Calls from the in-app Claude Code tab are not asked, as before. `/api/mcp/status` is unchanged, since its shape is shared with the family's consent tests. + +save_project and export_file take `replace` (boolean, default false). Without it a path that already exists (a dangling link counts) is refused before the person is asked and before the window renders anything. With it the file is replaced through `write_atomic` as before. Without it the bytes are written with `write_exclusive` (`open(path, "xb")`), so a file that appears while the person decides is kept and the call says to pass replace true; a write that fails part way removes the new file. `replace` is not passed on to the window's `__export`. + +### app/routers/mcp.py, app/routers/commands.py · menu commands and unembed that write files ask each time +- refers-to: app/routers/mcp.py :: _WRITING_COMMANDS, _command_id, _writing_commands, _writes_files, _what, _call; app/routers/commands.py :: run; tests/test_file_write_consent.py +- kind: decision +- logged: v0.63.0 · 2026-11-29 + +Follows the file writes decision above. Three menu commands write a file without a dialog the person confirms: `save` (into the library under the current name), `download-project` (into the Exports folder on the desktop) and `link-unembed`; the `links` tool's `unembed` writes the same file. `_writes_files` now covers them through `run_command`, every step of `run_commands` (a step id that is not a string counts as writing, since the window turns it into text) and `links` with action unembed. `_call` checks `_writes_files(name, args)` too, so `POST /api/commands/{cid}`, which reaches `_call` without going through `mcp()`, asks each time as well; that route now sets the caller context so the question names the command. `_command_id` picks the command the way the window does (`id` when it is a non-empty string, else `command`), so the question names the command that will run. Commands that open a dialog (Save As, the Export dialogs, Package, Print) are left alone: the person answers the dialog. diff --git a/backend/app/core/files.py b/backend/app/core/files.py index cfd255c..8ac651a 100644 --- a/backend/app/core/files.py +++ b/backend/app/core/files.py @@ -47,3 +47,18 @@ def write_new(path: Path, data: bytes, limit: int = 10_000) -> Path: raise return target raise FileExistsError(f"Every name like {path.name} is taken in {path.parent}.") + + +def write_exclusive(path: Path, data: bytes) -> Path: + """Write data to path only when nothing is there yet; FileExistsError otherwise, and a failed write leaves no file behind.""" + handle = open(path, "xb") + try: + with handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(path) + raise + return path diff --git a/backend/app/routers/commands.py b/backend/app/routers/commands.py index 797662b..d9ba0fd 100644 --- a/backend/app/routers/commands.py +++ b/backend/app/routers/commands.py @@ -82,9 +82,12 @@ async def run(cid: str, request: Request) -> dict: if not isinstance(params, dict): raise HTTPException(status_code=422, detail="the body must be a JSON object of parameters") token = mcp._inapp.set(claude_code.is_inapp(request.headers.get(claude_code.INAPP_HEADER))) + args = {"id": cid, **({"params": params} if params else {})} + asked = mcp._caller.set({"tool": "run_command", "client": "", "what": mcp._what("run_command", args), "writes": mcp._writes_files("run_command", args)}) try: - out = await mcp._call("run_command", {"id": cid, **({"params": params} if params else {})}) + out = await mcp._call("run_command", args) finally: + mcp._caller.reset(asked) mcp._inapp.reset(token) texts = [c.get("text", "") for c in out.get("content", []) if isinstance(c, dict)] if out.get("isError"): diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index ed1a08a..791528f 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -39,7 +39,7 @@ 6. Type: add_text for point, area or on-path type, set_text to change its words and style, create_outlines to turn it into paths. 7. Arrange: group, arrange (stacking order), align (to the selection, the artboard or a key object), transform (move, rotate, scale, reflect, shear, with copy and each), add_layer, move_to_layer and layer_action (duplicate, merge, flatten, release to layers, reverse order, collect). 8. Live looks: apply_effect adds an editable effect (warp.arc, distort.roughen, stylize.drop_shadow, the Effect Gallery's gallery.watercolor and the rest; call it with list true for the catalogue); three_d extrudes, revolves, inflates or turns art in 3D with materials and lighting; make_blend, envelope, repeat, symbol and apply_brush make live objects; expand bakes any of them into plain paths. -9. Deliver: save_project writes a .fpth that keeps everything editable; export_file writes SVG, PDF, EPS, DXF, DWG, PNG, GIF, BMP, PSD, TIFF, JPEG or WebP of an artboard, the whole document or the selection. Paths are absolute and the folder must exist. +9. Deliver: save_project writes a .fpth that keeps everything editable; export_file writes SVG, PDF, EPS, DXF, DWG, PNG, GIF, BMP, PSD, TIFF, JPEG or WebP of an artboard, the whole document or the selection. Paths are absolute and the folder must exist. A path that already exists is refused unless you pass replace true, so pick a new name unless the person asked to replace that file. Every save, export, batch, data set export and unembed, and the save, download-project and link-unembed commands, ask the person in the formpath window, even after they allowed outside agents. 10. Mistakes: undo steps back one change at a time. If a tool fails, its message says what to do next: follow it and retry. """ PROMPTS = [{"name": "draw_strategy", "title": "How to draw in formpath", "description": "The decision tree for formpath's tools: looking, planning in points, shapes and curves, paint, Pathfinder, type, arranging, live effects and delivery.", "arguments": []}] @@ -57,6 +57,7 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = _FILL = {"type": ["string", "object"], "description": _COLOR["description"] + " Or a freeform gradient {type: freeform, mode: points|lines, points: [{x, y, color, spread}]} with x, y and spread as fractions 0..1 of each object's bounds (absolute true for document points), or {type: freeform, colors: [...]} to place the points automatically."} _BLEND = {"type": "string", "enum": ["normal", "darken", "multiply", "color_burn", "lighten", "screen", "color_dodge", "overlay", "soft_light", "hard_light", "difference", "exclusion", "hue", "saturation", "color", "luminosity"]} _SHAPES = ["rectangle", "rounded_rectangle", "ellipse", "polygon", "star", "line", "arc", "spiral", "flare", "rectangular_grid", "polar_grid"] +_REPLACE = {"type": "boolean", "default": False, "description": "true replaces a file already at path. Without it a path that already exists is refused and nothing is written: choose a new path, or pass true only when the person wants that file replaced."} _PF = ["unite", "minus_front", "intersect", "exclude", "divide", "trim", "merge", "crop", "outline", "minus_back"] _GEN_DETAIL = {"type": ["string", "integer"], "minimum": 1, "maximum": 10, "default": "medium", "description": "Detail 1 (minimal) to 10 (richly detailed), or low (3), medium (5), high (8). It sets the prompt and hard limits on element count, gradients, strokes and compound shapes: elements beyond the limit are dropped smallest first, extra gradients become solid colours."} _GEN = { @@ -80,8 +81,8 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = "drawing_scale": {"type": "number", "exclusiveMinimum": 0, "default": 1, "description": "DXF only: multiplies the drawing (0.01 opens a 1:100 plan at one hundredth size)."}, "layout": {"type": "string", "default": "Model", "description": "DXF only: Model, or the name of a paper space layout."}, "merge_layers": {"type": "boolean", "default": False, "description": "DXF only: put every DXF layer into one layer."}, "fit_artboard": {"type": "boolean", "default": False, "description": "DXF only: scale the drawing to fit a Letter artboard instead of using its units."}, "password": {"type": "string", "description": "PDF only: the password of an encrypted PDF. The empty user password is tried automatically; without a password the window asks for one."}}, ["path"]), - _tool("save_project", "Saves the document as a formpath project (.fpth) at an absolute path; everything stays editable.", {"path": {"type": "string"}}, ["path"]), - _tool("export_file", "Exports the art to an absolute path; the extension chooses the format: .svg, .pdf (every artboard a page), .ai (PDF-compatible Illustrator file, every artboard a page, reopens fully editable in formpath), .eps (Level 3 PostScript; all_artboards gives a zip of one EPS per artboard), .dxf (AutoCAD 2000 or R12, layers kept), .dwg (AutoCAD 2000 binary drawing, layers kept, written natively), .png (with colors it writes an indexed PNG-8), .jpg, .webp, .gif (2 to 256 colors, transparency with a matte, optional interlace), .bmp (24-bit or 32-bit with alpha), .psd (flattened composite plus layers, RGB or CMYK: with psd_edit, layers and groups become Photoshop groups, point and area type become editable type layers and filled paths become shape layers; otherwise one pixel layer per top-level layer) or .tiff. Every raster format takes ppi (any resolution) and anti_aliasing.", {"path": {"type": "string"}, "scope": {"type": "string", "enum": ["artboard", "document", "selection", "all_artboards"], "default": "artboard"}, + _tool("save_project", "Saves the document as a formpath project (.fpth) at an absolute path; everything stays editable. A path that already exists is refused unless replace is true.", {"path": {"type": "string"}, "replace": _REPLACE}, ["path"]), + _tool("export_file", "Exports the art to an absolute path; the extension chooses the format: .svg, .pdf (every artboard a page), .ai (PDF-compatible Illustrator file, every artboard a page, reopens fully editable in formpath), .eps (Level 3 PostScript; all_artboards gives a zip of one EPS per artboard), .dxf (AutoCAD 2000 or R12, layers kept), .dwg (AutoCAD 2000 binary drawing, layers kept, written natively), .png (with colors it writes an indexed PNG-8), .jpg, .webp, .gif (2 to 256 colors, transparency with a matte, optional interlace), .bmp (24-bit or 32-bit with alpha), .psd (flattened composite plus layers, RGB or CMYK: with psd_edit, layers and groups become Photoshop groups, point and area type become editable type layers and filled paths become shape layers; otherwise one pixel layer per top-level layer) or .tiff. Every raster format takes ppi (any resolution) and anti_aliasing. A path that already exists is refused unless replace is true.", {"path": {"type": "string"}, "scope": {"type": "string", "enum": ["artboard", "document", "selection", "all_artboards"], "default": "artboard"}, "artboard": {"type": "integer", "minimum": 0, "default": 0}, "scale": {"type": "number", "minimum": 0.1, "maximum": 16, "default": 1}, "quality": {"type": "number", "minimum": 0.1, "maximum": 1, "default": 0.92}, "transparent": {"type": "boolean", "default": False}, "outline_text": {"type": "boolean", "default": False, "description": "SVG, DXF and DWG: type as outlines (DXF and DWG write TEXT otherwise)."}, "live_text": {"type": "boolean", "default": True, "description": "PDF only: write type as selectable, searchable text with the fonts embedded (default). Type with gradients, effects, 3D or an unavailable font is outlined either way; false outlines all type."}, "pdf_standard": {"type": "string", "enum": ["none", "x1a", "x3", "x4", "a2b"], "default": "none", "description": "PDF only: x4 writes PDF/X-4 with the document CMYK profile (set_color_settings) as the output intent, XMP metadata and a document ID, and leaves out formpath editing data. x1a writes PDF/X-1a:2001 (version 1.3, CMYK and spot colours only, transparency flattened into pictures) and x3 writes PDF/X-3:2002 (version 1.3, flattened, RGB stays tagged); both fail with a message naming what could not be flattened. a2b writes PDF/A-2b (sRGB output intent, fonts embedded, XMP identification). The standards cannot be combined with passwords or permissions, and x1a and x3 cannot have layers."}, "pdf_layers": {"type": "boolean", "default": False, "description": "PDF only: Create Acrobat Layers from Top-Level Layers. Each layer becomes an optional content group in the Layers panel (hidden layers start off); needs pdf_standard none, x4 or a2b."}, @@ -106,7 +107,7 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = "interlaced": {"type": "boolean", "default": False, "description": "GIF only: write the rows interlaced."}, "bmp_bits": {"type": "integer", "enum": [24, 32], "default": 24, "description": "BMP only: 24 writes RGB, 32 writes RGBA (alpha when transparent is true)."}, "psd_layers": {"type": "boolean", "default": True, "description": "PSD only: write one pixel layer per top-level layer (name, visibility and opacity kept) under the flattened composite; false writes the composite only. The color parameter (rgb or cmyk) chooses 8-bit RGB or CMYK."}, - "psd_edit": {"type": "boolean", "default": True, "description": "PSD only, with psd_layers: maximum editability. Sublayers and groups become Photoshop layer groups, point and area type become editable type layers, filled paths become shape layers (solid or gradient fill, vector mask, vector stroke); anything Photoshop cannot hold that way (effects, type on a path, patterns, images) stays a pixel layer. false writes one pixel layer per top-level layer."}}, ["path"]), + "psd_edit": {"type": "boolean", "default": True, "description": "PSD only, with psd_layers: maximum editability. Sublayers and groups become Photoshop layer groups, point and area type become editable type layers, filled paths become shape layers (solid or gradient fill, vector mask, vector stroke); anything Photoshop cannot hold that way (effects, type on a path, patterns, images) stays a pixel layer. false writes one pixel layer per top-level layer."}, "replace": _REPLACE}, ["path"]), _tool("switch_document", "Makes another open document the active one, by its index or name from get_document.", {"index": {"type": "integer", "minimum": 0}, "name": {"type": "string"}}), _tool("place_image", "Places an image file (absolute path: PNG, JPEG, WebP, GIF, or SVG, EPS and DXF as editable vector groups) into the document at x, y, embedded; width scales it in proportion. A 3D model (.obj, with the .mtl and texture images beside it, .glb or .gltf) is placed as a live 3D object, width points across, that three_d turns, lights and ray traces and that exports to SVG and PDF as vector faces. A PDF or an Illustrator file (.pdf, .ai) places one page (page, 1-based, default 1) cropped to the crop box (bounding, art, crop, trim, bleed or media; default bounding, the bounds of the page's art): embedded it becomes an editable group of paths, type and images, width points across; with link true it stays a linked high-resolution picture of the page, not vector. A Photoshop file (.psd) places flattened (psd_import flatten) or with each pixel layer as an image object in groups (psd_import objects, the default, with names, opacity, visibility and blend modes); a TIFF (.tif, .tiff; page picks one of several) is placed at its resolution. With link true (raster images, PDF, AI, PSD and TIFF) the image stays linked to its file: formpath reads it again when it changes (see the links tool).", {"path": {"type": "string"}, "x": _NUM, "y": _NUM, "width": {"type": "number", "minimum": 1}, "link": {"type": "boolean", "default": False}, "page": {"type": "integer", "minimum": 1, "description": "PDF, AI or TIFF page, 1-based."}, "crop": {"type": "string", "enum": ["bounding", "art", "crop", "trim", "bleed", "media"], "description": "PDF or AI Crop To box; default bounding."}, "psd_import": {"type": "string", "enum": ["objects", "flatten"], "description": "PSD: layers as objects (default) or one flattened image."}}, ["path"]), _tool("links", "Placed images and their files, as in the Links panel. list gives every placed image with its state (linked, modified when the file changed on disk, missing, embedded) and path. relink points the image in id at another file (path; all true relinks every image sharing its link); relink_folder relinks every missing link to the file of the same name in folder; update reads a modified file again (id, or all true); embed copies a linked image into the document; unembed writes an embedded image to a file next to the project and links it.", { @@ -451,6 +452,31 @@ def _who(request: Request, meta: dict) -> str: _FILE_ASKS = {"open_file": "open the file {}", "place_image": "place the file {}", "save_project": "save the project to {}", "export_file": "export to {}"} _WRITES = {"save_project", "export_file"} +EACH_TIME_ANSWERS = ["deny", "once"] +# Menu commands that write a file without showing the person a dialog first: Save into the library, Download Project and Unembed. +_WRITING_COMMANDS = {"save", "download-project", "link-unembed"} + + +def _command_id(args: dict) -> str: + """The command run_command runs: id when it is a non-empty string, else command, as the window picks it.""" + given, named = args.get("id"), args.get("command") + return given if isinstance(given, str) and given else named if isinstance(named, str) else "" + + +def _writing_commands(tool: str, args: dict) -> list[str]: + if tool == "run_command": + cid = _command_id(args) + return [cid] if cid in _WRITING_COMMANDS else [] + if tool == "run_commands" and isinstance(args.get("steps"), list): + ids = [s.get("id") for s in args["steps"] if isinstance(s, dict)] + return [i if isinstance(i, str) else "a command given in another form" for i in ids if not isinstance(i, str) or i in _WRITING_COMMANDS] + return [] + + +def _writes_files(tool: str, args: dict) -> bool: + """Calls that write files on this computer: the person answers each one, and a standing yes does not cover them.""" + return (tool in _WRITES or (tool == "actions" and args.get("action") == "batch") or (tool == "variables" and args.get("action") == "export") + or (tool == "links" and args.get("action") == "unembed") or bool(_writing_commands(tool, args))) def _real(raw) -> str: @@ -489,8 +515,13 @@ def _folder_what(tool: str, args: dict) -> str: def _what(tool: str, args: dict) -> str: - command = args.get("command") or args.get("id") - if tool == "run_command" and isinstance(command, str) and _client_name(command): + writing = _writing_commands(tool, args) + if writing: + return f"run {', '.join(dict.fromkeys(_client_name(w) for w in writing))}, which writes a file on this computer" + if tool == "links" and args.get("action") == "unembed": + return "write an embedded image to a file and link the image to it" + command = _command_id(args) + if tool == "run_command" and _client_name(command): return f"run the command {_client_name(command)}" shown = _shown_path(args.get("path")) if tool in _FILE_ASKS else "" if shown: @@ -499,10 +530,11 @@ def _what(tool: str, args: dict) -> str: return _folder_what(tool, args) or f"use {tool.replace('_', ' ')}" -def _consent_request() -> dict: +def _consent_request(each: bool = False) -> dict: caller = _caller.get() - return {"tool": caller.get("tool", ""), "client": caller.get("client", ""), "what": caller.get("what", ""), "answers": CONSENT_ANSWERS, - "alwaysCovers": "all", "seconds": CONSENT_SECONDS, "expiresAt": int((time.time() + CONSENT_SECONDS) * 1000)} + asks = {"answers": EACH_TIME_ANSWERS, "alwaysCovers": "none", "each": True} if each else {"answers": CONSENT_ANSWERS, "alwaysCovers": "all"} + return {"tool": caller.get("tool", ""), "client": caller.get("client", ""), "what": caller.get("what", ""), **asks, + "seconds": CONSENT_SECONDS, "expiresAt": int((time.time() + CONSENT_SECONDS) * 1000)} def _withdraw(rid: str, reason: str) -> None: @@ -629,12 +661,24 @@ def _path(raw, kinds: set, reading: bool) -> Path: return path -async def _write(path: Path, out: dict) -> dict: +def _taken(path: Path) -> str: + return f"There is already a file at {path}. Pass replace true to replace it, or choose another path." + + +def _keep_existing(path: Path, args: dict) -> None: + if args.get("replace") is not True and os.path.lexists(path): + raise ValueError(_taken(path)) + + +async def _write(path: Path, out: dict, replace: bool = True) -> dict: data = (out.get("structuredContent") or {}).get("data") if not out.get("isError") else None if not data: return out if out.get("isError") else _fail("formpath gave nothing to write.") blob = base64.b64decode(data) - await asyncio.to_thread(files.write_atomic, path, blob) + try: + await asyncio.to_thread(files.write_atomic if replace else files.write_exclusive, path, blob) + except FileExistsError: + return _fail(_taken(path)) notes = [str(n) for n in (out.get("structuredContent") or {}).get("notes") or [] if str(n).strip()] said = "".join(f" {n}" for n in notes) return {"content": [{"type": "text", "text": f"Wrote {path} ({len(blob):,} bytes).{said}"}], "structuredContent": {"path": str(path), "bytes": len(blob), **({"notes": notes} if notes else {})}} @@ -697,11 +741,13 @@ async def _run(name: str, args: dict) -> dict: return await _call("__open" if name == "open_file" else "__place", {"name": path.name, "data": data, **rest}) if name == "save_project": path = _path(args.get("path"), {".fpth"}, False) - return await _write(path, await _call("__project", {})) + _keep_existing(path, args) + return await _write(path, await _call("__project", {}), args.get("replace") is True) if name == "export_file": path = _path(args.get("path"), set(_EXPORTS), False) - rest = {k: v for k, v in args.items() if k != "path"} - return await _write(path, await _call("__export", {"format": _EXPORTS[path.suffix.lower()], **rest})) + _keep_existing(path, args) + rest = {k: v for k, v in args.items() if k not in ("path", "replace")} + return await _write(path, await _call("__export", {"format": _EXPORTS[path.suffix.lower()], **rest}), args.get("replace") is True) except ValueError as exc: return _fail(str(exc)) except OSError as exc: @@ -709,9 +755,9 @@ async def _run(name: str, args: dict) -> dict: return await _call(name, args) -async def _ask_caller() -> dict | None: +async def _ask_caller(each: bool = False) -> dict | None: gone = _caller.get().get("gone") - ask = asyncio.ensure_future(_ask("__consent__", _consent_request(), CONSENT_SECONDS)) + ask = asyncio.ensure_future(_ask("__consent__", _consent_request(each), CONSENT_SECONDS)) while not ask.done(): await asyncio.wait({ask}, timeout=1.0) if not ask.done() and gone is not None and await gone(): @@ -736,17 +782,20 @@ async def _call(name: str, args: dict) -> dict: break if not _live(): return _fail("formpath is not open. Start it with ./formpath boot (or open the formpath app), then retry.") - if not _allowed and not _inapp.get(): + each = _caller.get().get("writes") is True or _writes_files(name, args) + if (each or not _allowed) and not _inapp.get(): if time.monotonic() < _declined_until: return _fail("The person chose not to allow outside agents in formpath just now. Ask them to set Outside agents to Allowed (Preferences > Plugins), then retry.") - answer = await _ask_caller() + answer = await _ask_caller(each) if (answer or {}).get("gone") is True: return _fail("The agent stopped waiting before the person answered in formpath.") if not (answer or {}).get("allowed"): + if each: + return _fail("The person did not allow this file to be written. Ask them before trying again, or leave the file out.") _declined_until = time.monotonic() + 600 return _fail("The person did not allow outside agents in formpath. Ask them to allow it (the question in the formpath window, or Preferences > Plugins), then retry.") answered = True - if answer.get("once") is not True: + if answer.get("once") is not True and not each: _allowed = True out = await _ask(name, args, 600, answered) return out if out is not None else _fail("formpath did not answer in time: it may be busy with a long task. Check the formpath window, then retry.") @@ -789,7 +838,8 @@ async def mcp(request: Request) -> Response: elif method == "tools/call": name, args = params.get("name"), params.get("arguments") or {} _inapp.set(claude_code.is_inapp(request.headers.get(claude_code.INAPP_HEADER))) - _caller.set({"tool": str(name), "client": _who(request, meta), "what": _what(str(name), args if isinstance(args, dict) else {}), "gone": request.is_disconnected}) + _caller.set({"tool": str(name), "client": _who(request, meta), "what": _what(str(name), args if isinstance(args, dict) else {}), + "writes": isinstance(args, dict) and _writes_files(str(name), args), "gone": request.is_disconnected}) out = _ok(req_id, await _run(name, args), modern) if name in NAMES and isinstance(args, dict) else _err(req_id, -32602, f"No tool named {name}") else: out = _err(req_id, -32601, f"Method not found: {method}") diff --git a/backend/tests/test_file_write_consent.py b/backend/tests/test_file_write_consent.py new file mode 100644 index 0000000..04fa568 --- /dev/null +++ b/backend/tests/test_file_write_consent.py @@ -0,0 +1,236 @@ +import asyncio +import base64 +import importlib +import time + +import pytest + +from app.core import files + +DONE = {"content": [{"type": "text", "text": "done"}]} + + +def mcp(): + return importlib.import_module("app.routers.mcp") + + +def tool(name): + return next(t for t in mcp().TOOLS if t["name"] == name) + + +class Window: + """Stands in for the formpath window: answers questions and hands back the bytes to write.""" + + def __init__(self, answer): + self.answer = answer + self.asked = [] + + async def __call__(self, name, args, timeout, once=False): + self.asked.append((name, args, once)) + if name == "__consent__": + return self.answer + return {"structuredContent": {"data": base64.b64encode(b"new").decode()}} if name in ("__project", "__export") else DONE + + +@pytest.fixture +def window(monkeypatch): + m = mcp() + + def use(answer, allowed): + w = Window(answer) + monkeypatch.setattr(m, "_ask", w) + monkeypatch.setattr(m, "_allowed", allowed) + monkeypatch.setattr(m, "_seen", time.monotonic()) + monkeypatch.setattr(m, "_declined_until", 0.0) + return w + return use + + +def run_as_agent(name, args): + m = mcp() + + async def go(): + m._inapp.set(False) + m._caller.set({"tool": name, "client": "probe-agent", "what": m._what(name, args), "writes": m._writes_files(name, args)}) + return await m._run(name, args) + return asyncio.run(go()) + + +def questions(w): + return [args for name, args, _ in w.asked if name == "__consent__"] + + +@pytest.mark.parametrize("name", ["save_project", "export_file"]) +def test_the_file_tools_take_a_replace_argument_that_is_off_by_default(name): + props = tool(name)["inputSchema"]["properties"] + assert props["replace"]["type"] == "boolean" and props["replace"]["default"] is False + assert "replace" in tool(name)["description"] + + +@pytest.mark.parametrize("name,file", [("save_project", "brand.fpth"), ("export_file", "contract.pdf")]) +def test_a_file_already_there_is_kept_without_replace(window, tmp_path, name, file): + target = tmp_path / file + target.write_bytes(b"kept") + w = window({"allowed": True, "once": True}, True) + out = run_as_agent(name, {"path": str(target)}) + assert out["isError"] and "replace true" in out["content"][0]["text"] + assert target.read_bytes() == b"kept" + assert w.asked == [] + + +@pytest.mark.parametrize("name,file", [("save_project", "brand.fpth"), ("export_file", "contract.pdf")]) +def test_replace_true_replaces_the_file_after_the_person_says_yes(window, tmp_path, name, file): + target = tmp_path / file + target.write_bytes(b"old") + w = window({"allowed": True, "once": True}, True) + out = run_as_agent(name, {"path": str(target), "replace": True}) + assert not out.get("isError"), out + assert target.read_bytes() == b"new" + assert questions(w)[0]["what"].endswith("replacing the file already there") + + +def test_a_link_left_where_the_file_would_go_is_kept_without_replace(window, tmp_path): + link = tmp_path / "art.svg" + link.symlink_to(tmp_path / "missing.svg") + window({"allowed": True, "once": True}, True) + out = run_as_agent("export_file", {"path": str(link)}) + assert out["isError"] and link.is_symlink() and not (tmp_path / "missing.svg").exists() + + +def test_the_window_is_not_sent_the_replace_argument(window, tmp_path): + w = window({"allowed": True, "once": True}, True) + run_as_agent("export_file", {"path": str(tmp_path / "a.svg"), "replace": True}) + sent = next(args for name, args, _ in w.asked if name == "__export") + assert "replace" not in sent and "path" not in sent and sent["format"] == "svg" + + +def test_a_file_that_appears_while_the_person_decides_is_kept(tmp_path): + target = tmp_path / "late.svg" + target.write_bytes(b"theirs") + out = asyncio.run(mcp()._write(target, {"structuredContent": {"data": base64.b64encode(b"new").decode()}}, replace=False)) + assert out["isError"] and "replace true" in out["content"][0]["text"] + assert target.read_bytes() == b"theirs" + + +def test_writing_a_new_file_refuses_a_name_that_is_taken(tmp_path): + target = tmp_path / "a.fpth" + assert files.write_exclusive(target, b"one").read_bytes() == b"one" + with pytest.raises(FileExistsError): + files.write_exclusive(target, b"two") + assert target.read_bytes() == b"one" + + +def test_a_new_file_that_fails_part_way_is_removed(tmp_path, monkeypatch): + target = tmp_path / "a.fpth" + monkeypatch.setattr(files.os, "fsync", lambda *_: (_ for _ in ()).throw(OSError(28, "No space left on device"))) + with pytest.raises(OSError): + files.write_exclusive(target, b"one") + assert not target.exists() + + +WRITES = [ + ("save_project", {"path": "{d}/new.fpth", "replace": True}), + ("export_file", {"path": "{d}/new.png", "replace": True}), + ("actions", {"action": "batch", "folder": "{d}", "out": "{d}/out"}), + ("variables", {"action": "export", "folder": "{d}"}), +] + + +def filled(args, folder): + return {k: v.format(d=folder) if isinstance(v, str) else v for k, v in args.items()} + + +@pytest.mark.parametrize("name,args", WRITES) +def test_a_file_write_asks_each_time_even_when_agents_are_allowed(window, tmp_path, name, args): + w = window({"allowed": True, "once": True}, True) + for _ in range(2): + run_as_agent(name, filled(args, tmp_path)) + asked = questions(w) + assert len(asked) == 2 + assert all(q["answers"] == ["deny", "once"] and q["each"] is True and q["alwaysCovers"] == "none" for q in asked) + assert all(once is True for n, _, once in w.asked if n != "__consent__") + assert mcp()._allowed is True + + +@pytest.mark.parametrize("name,args", WRITES) +def test_a_plain_yes_to_a_file_write_is_not_a_standing_yes(window, tmp_path, name, args): + window({"allowed": True}, False) + run_as_agent(name, filled(args, tmp_path)) + assert mcp()._allowed is False + + +def test_a_no_to_a_file_write_refuses_only_that_write(window, tmp_path): + w = window({"allowed": False}, True) + out = run_as_agent("export_file", {"path": str(tmp_path / "a.svg")}) + assert out["isError"] and "did not allow this file" in out["content"][0]["text"] + assert not (tmp_path / "a.svg").exists() + assert mcp()._declined_until == 0.0 and mcp()._allowed is True + del w.asked[:] + assert not run_as_agent("select", {"all": True}).get("isError") + assert questions(w) == [] + + +@pytest.mark.parametrize("name,args", [("select", {"all": True}), ("actions", {"action": "list"}), ("variables", {"action": "list"})]) +def test_other_tools_still_run_on_the_standing_yes(window, name, args): + w = window({"allowed": False}, True) + run_as_agent(name, args) + assert questions(w) == [] + + +def test_the_app_own_claude_code_tab_is_not_asked(window, tmp_path): + m = mcp() + w = window({"allowed": False}, False) + + async def go(): + m._inapp.set(True) + m._caller.set({"tool": "save_project", "writes": True}) + return await m._run("save_project", {"path": str(tmp_path / "a.fpth")}) + assert not asyncio.run(go()).get("isError") + assert questions(w) == [] + + +COMMAND_WRITES = [ + ("run_command", {"id": "save"}), + ("run_command", {"command": "download-project"}), + ("run_command", {"id": "link-unembed", "command": "zoom-in"}), + ("run_commands", {"steps": [{"id": "select-all"}, {"id": "save"}]}), + ("run_commands", {"steps": [{"id": ["save"]}]}), + ("links", {"action": "unembed", "id": "img1"}), +] + + +@pytest.mark.parametrize("name,args", COMMAND_WRITES) +def test_commands_that_write_a_file_ask_each_time_even_when_agents_are_allowed(window, name, args): + w = window({"allowed": True}, True) + run_as_agent(name, args) + asked = questions(w) + assert len(asked) == 1 and asked[0]["each"] is True and asked[0]["answers"] == ["deny", "once"] + assert "file" in asked[0]["what"] + + +@pytest.mark.parametrize("name,args", [("run_command", {"id": "zoom-in"}), ("run_commands", {"steps": [{"id": "select-all"}]}), ("links", {"action": "list"})]) +def test_commands_that_write_nothing_run_on_the_standing_yes(window, name, args): + w = window({"allowed": False}, True) + run_as_agent(name, args) + assert questions(w) == [] + + +def test_the_question_names_the_command_the_window_runs(): + what = mcp()._what("run_command", {"id": "link-unembed", "command": "zoom-in"}) + assert "link-unembed" in what and "zoom-in" not in what + assert mcp()._what("run_command", {"id": "group", "command": "zoom-in"}) == "run the command group" + + +def test_the_local_command_route_asks_each_time_for_a_writing_command(window, monkeypatch): + commands = importlib.import_module("app.routers.commands") + monkeypatch.setattr(commands, "require_local", lambda request: None) + w = window({"allowed": True}, True) + + class Request: + headers = {} + + async def json(self): + return {} + asyncio.run(commands.run("save", Request())) + asked = questions(w) + assert len(asked) == 1 and asked[0]["each"] is True and "save" in asked[0]["what"] diff --git a/docs/MANUAL.md b/docs/MANUAL.md index fcda51c..bca9d6c 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -756,6 +756,12 @@ ask it questions. - formpath runs an MCP server so agents (Claude Code, Claude Desktop, Codex, Cursor, Antigravity and others) can draw in the open window. Turn it on in Preferences > Plugins (Allow agents); the first call asks your permission. Connect with `./formpath mcp` (a stdio bridge) or the HTTP endpoint the engine prints at boot. +- An outside agent that wants to write a file on your computer asks you every time, even after you chose Always + allow: saving a project, exporting, running an action in a batch, exporting data sets, unembedding an image, and + running the Save, Download Project or Unembed menu commands. The question names the file, folder or command and + offers only Deny and Allow once. Saving and exporting never replace a file that is already + there unless the agent says it wants to replace it, and then the question says the file will be replaced. The + Claude Code tab in formpath's own terminal is not asked. - Only the formpath window hands agent requests to your document. When it opens it gets a private session from the engine, which gives one only to formpath's own page, and every exchange between the window and the engine carries it; a web page or another program cannot pose as the window, answer the permission question or read the requests. diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 7fc32fb..822e54f 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -5441,3 +5441,10 @@ Proof that nothing else moved: 3,608 layouts with no complex script give byte-id - logged: v0.63.0 · 2026-11-26 Two faults found under issue 17 are inside the shared dock module: after a slow start the panel takes focus from a field that is being typed in, and the terminal counts an emoji or a wide sign as one cell. FormPath carries the module byte for byte and never edits it, and this version's work was FormPath's alone, so both are still there. The fix belongs to the module's home; what to change is written up in the planning sidecar's change note. Until a new module version is copied in, `imeEscape` in the adapter stays: it is the guard 0.62.0 added from outside so that an Escape belonging to a composition does not end the guide. + +### src/io/api.ts, src/automation/agent-bridge.ts, src/dock-adapter.ts · a question about writing a file is never answered by the standing choice +- refers-to: src/io/api.ts :: asksEachTime, consentOffers; src/automation/agent-bridge.ts :: AgentBridge.loop; src/dock-adapter.ts :: outsideAgents.arrive; tests/agent-consent.test.ts +- kind: decision +- logged: v0.63.0 · 2026-11-29 + +The engine marks the question for an outside agent's file write with `each: true` (backend HASHOUT, the same date). While Outside agents is Allowed the loop answered every `__consent__` itself; it now hands a question with `each: true` to the dialog. `consentOffers` builds the dialog's buttons from the engine's `answers` and never offers Always allow on such a question, and the dialog's note says that writing files asks each time instead of "Each change is one undoable step.", which a written file is not. The shared dock module is unchanged: it already shows only the offered answers. diff --git a/frontend/src/automation/agent-bridge.ts b/frontend/src/automation/agent-bridge.ts index d3fd327..2cadce3 100644 --- a/frontend/src/automation/agent-bridge.ts +++ b/frontend/src/automation/agent-bridge.ts @@ -35,7 +35,7 @@ import { boundLabel, parseDataFile, VARIABLE_KINDS } from '../engine/variables'; import { exportDataSets, showDataSet } from '../io/data-merge'; import { VERSION } from '../version'; import type { GraphColumnDesign, GraphData, GraphSeriesType, GraphSpec, GraphType, Variable, VariableKind } from '../engine/types'; -import { api, type BridgeItem } from '../io/api'; +import { api, asksEachTime, type BridgeItem } from '../io/api'; import { bakeTraced } from '../io/raster'; import { attachPlace, gridOf, leafPlaneBounds, planeLocalRect, presetGrid, vanishing } from '../engine/perspective'; import type { BrushDef, Doc, PerspPlane } from '../engine/types'; @@ -117,7 +117,7 @@ export class AgentBridge { if (status === 200 && item) { if (item.name === '__withdrawn__') { this.deps.consent.gone(String(item.arguments?.request ?? '')); continue; } if (item.name === '__consent__') { - if (this.on) await api.mcpResult(secret, item.id, { allowed: true }); + if (this.on && !asksEachTime(item)) await api.mcpResult(secret, item.id, { allowed: true }); else this.deps.consent.arrive(item, (result) => api.mcpResult(secret, item.id, result)); continue; } diff --git a/frontend/src/dock-adapter.ts b/frontend/src/dock-adapter.ts index 3368c16..97f0b89 100644 --- a/frontend/src/dock-adapter.ts +++ b/frontend/src/dock-adapter.ts @@ -1,7 +1,7 @@ import type { ConsentChoice, ConsentRequest, DockAdapter, DockChannel, DockOwnChat, DockTerminal, StoredChoice, StoredChoiceState } from './dock/adapter'; import { jsonLegacy } from './dock/state'; import { t } from './i18n'; -import { api, ApiError, socketTo, type BridgeItem, type TerminalInfo } from './io/api'; +import { api, ApiError, asksEachTime, consentOffers, socketTo, type BridgeItem, type TerminalInfo } from './io/api'; import { keyHeaders } from './io/window-key'; import { DockChat } from './ui/dock-chat'; import { isMac } from './ui/dom'; @@ -28,10 +28,9 @@ export const outsideAgents = { if (isBlocked) { void reply({ allowed: false }).catch(() => undefined); return; } if (open.has(item.id)) return; const a = item.arguments; - const offers = (Array.isArray(a.answers) ? a.answers : ['deny', 'always']).filter((x): x is ConsentChoice => x === 'deny' || x === 'once' || x === 'always'); const request: ConsentRequest = { id: item.id, agent: typeof a.client === 'string' ? a.client : '', what: typeof a.what === 'string' && a.what ? a.what : 'draw in and edit your documents', - offers, always: 'all', escape: 'deny', notes: ['Each change is one undoable step.'], + offers: consentOffers(item), always: 'all', escape: 'deny', notes: [asksEachTime(item) ? 'Writing files asks each time, even when outside agents are allowed.' : 'Each change is one undoable step.'], ...(typeof a.expiresAt === 'number' ? { expires: a.expiresAt } : {}), }; open.set(item.id, { request, reply }); diff --git a/frontend/src/io/api.ts b/frontend/src/io/api.ts index cbed8e0..0a67f14 100644 --- a/frontend/src/io/api.ts +++ b/frontend/src/io/api.ts @@ -12,6 +12,12 @@ export interface SimilarFont { id: string; family: string; style: string; score: export interface FontOutlines { key: string; upm: number; whole: boolean; glyphs: Record>; chars?: Record } export interface LlmStatus { configured: boolean; baseUrl: string; model: string; hasKey: boolean; store: 'system' | 'file'; vision?: boolean } export interface BridgeItem { id: string; name: string; arguments: Record; inapp?: boolean; once?: boolean } +export const asksEachTime = (item: BridgeItem): boolean => item.name === '__consent__' && item.arguments?.each === true; +export function consentOffers(item: BridgeItem): Array<'deny' | 'once' | 'always'> { + const listed = Array.isArray(item.arguments?.answers) ? (item.arguments.answers as unknown[]) : ['deny', 'always']; + const each = asksEachTime(item); + return listed.filter((x): x is 'deny' | 'once' | 'always' => x === 'deny' || x === 'once' || (x === 'always' && !each)); +} const BRIDGE_HEADER = 'X-Formpath-Bridge'; export class ApiError extends Error { diff --git a/frontend/tests/agent-consent.test.ts b/frontend/tests/agent-consent.test.ts new file mode 100644 index 0000000..546f664 --- /dev/null +++ b/frontend/tests/agent-consent.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; +import bridge from '../src/automation/agent-bridge.ts?raw'; +import { asksEachTime, consentOffers, type BridgeItem } from '../src/io/api'; + +const question = (args: Record): BridgeItem => ({ id: '7', name: '__consent__', arguments: args }); + +describe('a question about writing a file is answered each time', () => { + it('knows a question the engine asks each time', () => { + expect(asksEachTime(question({ each: true, answers: ['deny', 'once'] }))).toBe(true); + expect(asksEachTime(question({ answers: ['deny', 'once', 'always'] }))).toBe(false); + expect(asksEachTime({ id: '8', name: 'select', arguments: { each: true } })).toBe(false); + }); + + it('never offers a standing yes for it, even when the engine lists one', () => { + expect(consentOffers(question({ each: true, answers: ['deny', 'once', 'always'] }))).toEqual(['deny', 'once']); + expect(consentOffers(question({ answers: ['deny', 'once', 'always'] }))).toEqual(['deny', 'once', 'always']); + expect(consentOffers(question({}))).toEqual(['deny', 'always']); + }); + + it('the window does not answer it from the Allowed setting', () => { + expect(bridge).toContain("if (this.on && !asksEachTime(item)) await api.mcpResult(secret, item.id, { allowed: true });"); + }); +});