From fb4fc6e075f4f8a5c15936d6afd9a28097bdae13 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:58:24 -0500 Subject: [PATCH 01/10] fix(mcp): ask before an agent exports a deck to a path it chose export_deck with a path writes a file outside the Exports folder, so it now goes through the same consent check as other changing tools, and is refused when the person has blocked agents. Exports with no path still write into the Exports folder without asking. --- backend/app/routers/mcp.py | 2 ++ backend/tests/test_f2_consent.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index 8e70558..75f06b3 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -278,6 +278,8 @@ def _mutating(name: str, args: dict) -> bool: return (args.get("action") or "list") != "list" if name == "masters": return (args.get("action") or "list") != "list" + if name == "export_deck": + return bool(str(args.get("path") or "").strip()) return False diff --git a/backend/tests/test_f2_consent.py b/backend/tests/test_f2_consent.py index 5b2cf79..89dd9de 100644 --- a/backend/tests/test_f2_consent.py +++ b/backend/tests/test_f2_consent.py @@ -136,3 +136,34 @@ def test_the_window_can_grant_agent_access(client, origin): r = client.post("/api/settings", json={"agentsAllowed": True}, headers={"origin": origin}) assert r.status_code == 200 assert config.read_settings()["agentsAllowed"] is True + + +def test_export_to_a_chosen_path_asks_before_writing(client, window, deck_from_script, tmp_path): + set_agents_allowed(True) + deck = deck_from_script("# Title\n\n## One\n- a") + set_agents_allowed(False) + window.send_json({"t": "ping"}) + while window.receive_json()["t"] != "pong": + pass + target = tmp_path / "kept.txt" + target.write_text("keep me") + thread, out = agent_call(client, ("export_deck", {"deck": deck, "format": "txt", "path": str(target)})) + result = settle(window, thread, out, False) + assert result["isError"] and ASKED in tool_text(result) + assert target.read_text() == "keep me" + + +def test_export_to_a_chosen_path_is_refused_when_agents_are_blocked(client, deck_from_script, tmp_path): + from app.core import config + + set_agents_allowed(True) + deck = deck_from_script("# Title\n\n## One\n- a") + config.write_settings({"agentsBlocked": True}) + try: + target = tmp_path / "kept.txt" + target.write_text("keep me") + result = call_tool(client, "export_deck", {"deck": deck, "format": "txt", "path": str(target)}) + assert result["isError"] and "blocked agents" in tool_text(result) + assert target.read_text() == "keep me" + finally: + config.write_settings({"agentsBlocked": False}) From 4d79a9e776598a817fbaae07d8071499903c4ba0 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 20:59:05 -0500 Subject: [PATCH 02/10] fix(live): treat a share link connection as a guest from the start A shared window was counted as a formdeck window until it sent hello, so agent questions and tool calls could be routed to it. The connection is now a guest as soon as it opens. --- backend/app/routers/live.py | 2 +- backend/tests/test_guest_comments.py | 36 ++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/live.py b/backend/app/routers/live.py index 7d3dd6d..d351ca3 100644 --- a/backend/app/routers/live.py +++ b/backend/app/routers/live.py @@ -37,7 +37,7 @@ async def send(message: dict) -> None: async with lock: await ws.send_text(json.dumps(message, separators=(",", ":"))) - client = Client(ids.short("c", 8), send) + client = Client(ids.short("c", 8), send, "guest" if guest else "window") client.share = guest client.kick = lambda: ws.close(code=4401) STORE.clients[client.id] = client diff --git a/backend/tests/test_guest_comments.py b/backend/tests/test_guest_comments.py index 8f00745..cecdb3d 100644 --- a/backend/tests/test_guest_comments.py +++ b/backend/tests/test_guest_comments.py @@ -28,3 +28,39 @@ def test_a_comment_guest_cannot_wipe_delete_or_rewrite_comments(deck_from_script assert refusal(deck, [{"op": "del", "path": ["comments"], "id": "c1"}]) assert refusal(deck, [{"op": "set", "path": ["comments", {"id": "c1"}, "text"], "value": "changed"}]) assert refusal(deck, [ADD, {"op": "set", "path": ["slides"], "value": []}]) + + +class SilentGuestSocket: + def __init__(self, share): + self.scope = {"fd_share": share} + self.headers = {} + self.query_params = {} + self.seen = None + + async def accept(self): + return None + + async def send_text(self, _text): + return None + + async def receive_text(self): + from fastapi import WebSocketDisconnect + + from app.services import bridge + + self.seen = (bridge.window_connected(), [c.kind for c in bridge.windows()]) + raise WebSocketDisconnect() + + async def close(self, code=1000): + return None + + +def test_a_share_guest_that_never_says_hello_is_not_taken_for_a_window(deck_from_script): + import asyncio + + from app.routers.live import live + + deck = deck_from_script("# One") + ws = SilentGuestSocket({"deck": deck, "role": "view"}) + asyncio.run(live(ws)) + assert ws.seen == (False, []) From 512e069b27bccc7849c627cc61655c29223a383b Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 21:00:10 -0500 Subject: [PATCH 03/10] fix(media): serve library files as plain data, never as a page Library media and unpacked files now carry nosniff and a sandboxed content policy, so a stored file opened directly in a browser cannot run script on the engine's origin. Pictures, video, audio and fonts load as before. --- backend/app/routers/media.py | 5 +++-- backend/tests/test_media_headers.py | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 backend/tests/test_media_headers.py diff --git a/backend/app/routers/media.py b/backend/app/routers/media.py index 476d056..7594325 100644 --- a/backend/app/routers/media.py +++ b/backend/app/routers/media.py @@ -16,6 +16,7 @@ from app.services import pdf_pages router = APIRouter() +MEDIA_HEADERS = {"X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'; img-src 'self' data:; media-src 'self'; style-src 'unsafe-inline'; sandbox"} @router.post("/media/pdf-pages") @@ -83,7 +84,7 @@ def get_media(media_id: str): if path is None: raise HTTPException(404, "no such media") info = mediamod.store().info(media_id) or {} - return FileResponse(path, media_type=info.get("mime"), headers={"Cache-Control": "public, max-age=31536000, immutable"}) + return FileResponse(path, media_type=info.get("mime"), headers={**MEDIA_HEADERS, "Cache-Control": "public, max-age=31536000, immutable"}) @router.get("/media/{media_id}/still") @@ -242,4 +243,4 @@ def unpacked_file(uid: str, name: str) -> FileResponse: target = (root / uid / name).resolve() if not uid.isalnum() or target.parent != (root / uid).resolve() or not target.is_file(): raise HTTPException(404, "no such unpacked file") - return FileResponse(target, filename=name) + return FileResponse(target, filename=name, headers=MEDIA_HEADERS) diff --git a/backend/tests/test_media_headers.py b/backend/tests/test_media_headers.py new file mode 100644 index 0000000..61f7426 --- /dev/null +++ b/backend/tests/test_media_headers.py @@ -0,0 +1,19 @@ +from app.services import media as mediamod + + +def test_library_media_is_served_as_plain_data_with_no_page_rights(client): + meta = mediamod.store().put(b"

hello

", "note.html", "text/html") + r = client.get(f"/api/media/{meta['id']}") + assert r.status_code == 200 + assert r.headers["x-content-type-options"] == "nosniff" + policy = r.headers["content-security-policy"] + assert "sandbox" in policy and "default-src 'none'" in policy + + +def test_library_pictures_still_load(client): + png = b"\x89PNG\r\n\x1a\n" + b"\x00" * 32 + meta = mediamod.store().put(png, "dot.png", "image/png") + r = client.get(f"/api/media/{meta['id']}") + assert r.status_code == 200 + assert r.headers["content-type"] == "image/png" + assert r.content == png From 8e76699ef75c735f81acb7ea98d4a3e6ea917b96 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 21:01:57 -0500 Subject: [PATCH 04/10] fix(agents): list export_deck among the tools that ask first The agent manifest is generated from the consent gate; regenerate it now that export_deck to a chosen path asks the person. --- agents/manifest.json | 1 + 1 file changed, 1 insertion(+) diff --git a/agents/manifest.json b/agents/manifest.json index 0153726..8314741 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -61,6 +61,7 @@ "apply_template", "set_theme", "masters", + "export_deck", "open_file", "comments", "handoff", From 17c2086106dc2c6859d1a0c4146a2b8e6f5cc31b Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 21:03:35 -0500 Subject: [PATCH 05/10] fix(chat): send the Chat prompt to Claude Code on standard input On Windows a Claude Code install that is a .cmd shim is started through the command interpreter, which reads the command line with its own quoting rules and stops at the first line break. The Chat and layout ideas prompt now goes on standard input, and a tab started that way gets its first message typed in after it opens. --- backend/HASHOUT_LOG.md | 6 +++ backend/app/services/claude_code.py | 25 +++++++++--- backend/tests/test_claude_prompt.py | 59 +++++++++++++++++++++++++++++ backend/tests/test_window_key.py | 2 +- 4 files changed, 85 insertions(+), 7 deletions(-) create mode 100644 backend/tests/test_claude_prompt.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 1656072..c4a963b 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -893,3 +893,9 @@ formdeck kept a place for Claude Code (`claude.bin`) inside the sealed agent cho The update path. The seal is an HMAC over `sealed()`; adding three keys to that body would change the digest of every file sealed by 0.43.0 and 0.44.0 and make each read as broken after the update, which takes agent access back to Ask and empties the Claude Code place. So the three keys enter the body only when they hold a value (`LATER`), as `agentsBlocked` enters it only when true; a file with none of them hashes exactly as before. This is the way FormLit (wave 8) and FormPDF (wave 9) took. Proved before the change with real files: the 0.43.0 backend (`git archive` of origin/main; the seal code is the same in 0.44.0) wrote `settings.json` with agents allowed and a Claude Code place under a keyring stand-in kept in a file; this backend read it with the same key as `seal: ok`, the choice and the place kept, the three new places empty; a write of `codexBin` after that read back as `ok` with the choice and the Claude Code place kept. No migration is needed. `test_a_choice_sealed_by_0_43_0_reads_whole_after_the_update` writes a file of 0.43.0's shape with 0.43.0's digest formula and checks the same through later writes; the parametrized test checks each new place through the endpoint: sealed, given to the finder first (found with how `setting`), a value that is not a string stored as empty, and a hand edit caught. Ran: tests/test_seal.py, tests/test_window_key.py, tests/test_dock_engine.py, tests/test_f3_mcp.py, 66 passed. + +## 149. The Chat prompt goes to Claude Code on standard input · (services/claude_code.py chat_argv, stream_chat, tab_argv, open_tab, via_interpreter; tests/test_claude_prompt.py) + +On Windows an npm install of Claude Code is a `claude.cmd` shim, and the shared finder starts a `.cmd` or `.bat` through `cmd.exe /c`. The command interpreter reads its own line with its own quoting rules, which the argument joining of `subprocess` does not follow, and it ends the line at the first line break. A Chat message or the layout ideas request passed as an argument could therefore be cut short or read as more than one argument. `chat_argv` no longer carries the prompt: `claude -p` reads it from standard input, which `stream_chat` writes and closes before reading the events, so the text never passes through any command line on any system. A tab cannot read its first message from standard input, so when the program is started through the interpreter, `tab_argv` leaves the prompt out and `open_tab` types it into the new tab instead, as it already does for a tab that is running. The shared finder (`agent_lookup.py`) is unchanged; it changes only as a whole new version. + +Ran: tests/test_claude_prompt.py, tests/test_window_key.py, 35 passed. diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index af36897..8ce38b7 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -206,17 +206,21 @@ def _wrap(cmd: list[str]) -> list[str]: return agent_lookup.start_argv(cmd) +def via_interpreter(path: str) -> bool: + return agent_lookup.windows() and str(path).lower().endswith((".cmd", ".bat")) + + def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None) -> list[str]: cmd = [path, "--mcp-config", mcp_file, "--allowedTools", "mcp__formdeck_tab", "--append-system-prompt", NOTE] if resume: cmd += ["--resume", resume] - if prompt: + if prompt and not via_interpreter(path): cmd.append(prompt) return _wrap(cmd) -def chat_argv(path: str, mcp_file: str, text: str, session: str | None, model: str = "") -> list[str]: - cmd = [path, "-p", text, "--output-format", "stream-json", "--verbose", "--include-partial-messages", +def chat_argv(path: str, mcp_file: str, session: str | None, model: str = "") -> list[str]: + cmd = [path, "-p", "--output-format", "stream-json", "--verbose", "--include-partial-messages", "--mcp-config", mcp_file, "--allowedTools", "mcp__formdeck_tab", "--append-system-prompt", CHAT_NOTE] if model: cmd += ["--model", model] @@ -254,6 +258,8 @@ def open_tab(prompt: str | None = None, cols: int = 100, rows: int = 30, fresh: revoke(token) raise session.on_close.append(lambda: revoke(token)) + if prompt and via_interpreter(found.path): + terminal.write(session.id, prompt + "\r") return session.describe() @@ -263,8 +269,8 @@ async def stream_chat(text: str, session: str | None, model: str = ""): raise LookupError(said(found)) token, mcp_file = issue() try: - proc = await asyncio.create_subprocess_exec(*chat_argv(found.path, mcp_file, text, session, model), cwd=str(workdir()), env=child_env(found.path), - stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + proc = await asyncio.create_subprocess_exec(*chat_argv(found.path, mcp_file, session, model), cwd=str(workdir()), env=child_env(found.path), + stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, limit=16 * 1024 * 1024) except BaseException: revoke(token) @@ -279,7 +285,14 @@ async def drain() -> None: errs = asyncio.create_task(drain()) try: - assert proc.stdout is not None + assert proc.stdin is not None and proc.stdout is not None + try: + proc.stdin.write(text.encode("utf-8")) + await proc.stdin.drain() + except (BrokenPipeError, ConnectionResetError): + pass + finally: + proc.stdin.close() async for raw in proc.stdout: try: ev = json.loads(raw.decode("utf-8", "replace")) diff --git a/backend/tests/test_claude_prompt.py b/backend/tests/test_claude_prompt.py new file mode 100644 index 0000000..622b1de --- /dev/null +++ b/backend/tests/test_claude_prompt.py @@ -0,0 +1,59 @@ +import asyncio + +from app.services import agent_lookup, claude_code, terminal + +PROMPT = "hello there" + + +def test_the_chat_prompt_is_never_a_command_line_argument(): + token, path = claude_code.issue() + try: + argv = claude_code.chat_argv("/bin/claude", path, None) + assert PROMPT not in " ".join(argv) + assert " -p " in " ".join(argv) + finally: + claude_code.revoke(token) + + +def test_the_chat_prompt_reaches_the_program_on_standard_input(tmp_path, monkeypatch): + program = tmp_path / "claude" + program.write_text('#!/bin/sh\nseen="$(cat)"\nprintf \'{"type":"seen","stdin":"%s","args":"%s"}\\n\' "$seen" "$*"\n') + program.chmod(0o755) + found = agent_lookup.Found(program="claude", title="Claude Code", path=str(program), state="runs") + monkeypatch.setattr(claude_code, "usable", lambda kind: found) + monkeypatch.setattr(claude_code, "workdir", lambda: tmp_path) + + async def collect(): + return [ev async for ev in claude_code.stream_chat(PROMPT, None)] + + events = asyncio.run(collect()) + seen = next(ev for ev in events if ev.get("type") == "seen") + assert seen["stdin"] == PROMPT + assert PROMPT not in seen["args"] + + +def test_a_tab_started_through_the_command_interpreter_types_its_prompt(tmp_path, monkeypatch): + found = agent_lookup.Found(program="claude", title="Claude Code", path="C:\\npm\\claude.cmd", state="runs") + monkeypatch.setattr(claude_code, "usable", lambda kind: found) + monkeypatch.setattr(claude_code, "workdir", lambda: tmp_path) + monkeypatch.setattr(claude_code, "child_env", lambda path=None, extra=None: {}) + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + started, typed = {}, [] + + class Opened: + id = "t9" + on_close: list = [] + + def describe(self): + return {"id": self.id} + + def open_session(cwd, cols, rows, title, argv, env, kind): + started["argv"] = argv + return Opened() + + monkeypatch.setattr(terminal, "open_session", open_session) + monkeypatch.setattr(terminal, "write", lambda sid, data: typed.append((sid, data))) + monkeypatch.setattr(terminal, "SESSIONS", {}) + claude_code.open_tab(PROMPT, fresh=True) + assert PROMPT not in " ".join(started["argv"]) + assert typed == [("t9", PROMPT + "\r")] diff --git a/backend/tests/test_window_key.py b/backend/tests/test_window_key.py index a5605e7..d8b7cd4 100644 --- a/backend/tests/test_window_key.py +++ b/backend/tests/test_window_key.py @@ -162,7 +162,7 @@ def test_the_token_is_in_no_argument_and_no_plain_terminal_environment(): token, path = claude_code.issue() try: - argv = claude_code.tab_argv("/bin/claude", path, "hello") + claude_code.chat_argv("/bin/claude", path, "hello", None) + argv = claude_code.tab_argv("/bin/claude", path, "hello") + claude_code.chat_argv("/bin/claude", path, None) assert token not in " ".join(argv) assert token not in "".join(terminal.base_env().values()) assert token not in "".join(claude_code.child_env().values()) From 1125bc60b012980797a35652a2833b36c3357570 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sat, 28 Nov 2026 21:04:57 -0500 Subject: [PATCH 06/10] fix(export): replace a saved or exported file whole, or not at all Saves and exports wrote straight into the chosen file, so a write that failed partway left it cut short. They now write a temporary file beside it and move it into place, keeping the file's permissions, and a failed outline, GIF or composed export answers with a clear error. --- backend/app/core/files.py | 27 ++++++++++++++ backend/app/routers/decks.py | 6 +-- backend/app/routers/exports.py | 17 ++++++--- backend/app/routers/mcp.py | 6 +-- backend/tests/test_export_writes.py | 57 +++++++++++++++++++++++++++++ 5 files changed, 102 insertions(+), 11 deletions(-) create mode 100644 backend/app/core/files.py create mode 100644 backend/tests/test_export_writes.py diff --git a/backend/app/core/files.py b/backend/app/core/files.py new file mode 100644 index 0000000..3803687 --- /dev/null +++ b/backend/app/core/files.py @@ -0,0 +1,27 @@ +import os +import shutil +import tempfile +from pathlib import Path + +NEW_FILE_MODE = 0o644 + + +def write_whole(path: Path, data: bytes) -> None: + path = Path(path) + fd, part = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".part", dir=path.parent) + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + if path.is_file(): + shutil.copymode(path, part) + else: + os.chmod(part, NEW_FILE_MODE) + os.replace(part, path) + except BaseException: + try: + os.unlink(part) + except OSError: + pass + raise diff --git a/backend/app/routers/decks.py b/backend/app/routers/decks.py index a4fb828..167704e 100644 --- a/backend/app/routers/decks.py +++ b/backend/app/routers/decks.py @@ -11,7 +11,7 @@ from fastapi import APIRouter, Body, HTTPException, Request, UploadFile from fastapi.responses import FileResponse, Response -from app.core import config, ids +from app.core import config, files, ids from app.routers.exports import _target from app.services import compiler, model, package, templates from app.services import ops as opsmod @@ -278,7 +278,7 @@ async def export(deck_id: str, body: dict = Body(default={})) -> dict: if not path.parent.is_dir(): raise HTTPException(400, f"The folder {path.parent} does not exist.") try: - await asyncio.to_thread(path.write_bytes, data) + await asyncio.to_thread(files.write_whole, path, data) except OSError as exc: raise HTTPException(400, f"Could not write {path}: {exc.strerror or exc}") return {"path": str(path), "bytes": len(data), "warnings": notes} @@ -359,7 +359,7 @@ async def save(deck_id: str, body: dict = Body(default={})) -> dict: data, name, _ = await asyncio.to_thread(export_bytes, deck, fmt, body.get("fontScales"), body.get("embedFonts")) path, _ = _target(name, str(path)) try: - await asyncio.to_thread(path.write_bytes, data) + await asyncio.to_thread(files.write_whole, path, data) except OSError as exc: raise HTTPException(400, f"Could not write {path}: {exc.strerror or exc}") if body.get("path"): diff --git a/backend/app/routers/exports.py b/backend/app/routers/exports.py index 58c617b..a643b6d 100644 --- a/backend/app/routers/exports.py +++ b/backend/app/routers/exports.py @@ -10,7 +10,7 @@ from fastapi import APIRouter, Body, File, Form, HTTPException, UploadFile from fastapi.responses import FileResponse -from app.core import config +from app.core import config, files from app.services import pdf_fonts, pdf_tags from app.services.store import STORE @@ -292,6 +292,13 @@ def compose_bytes(deck_id: str, fmt: str, meta: dict, images: list[bytes], bares _KNOWN_EXT = {".fdec", ".fsld", ".pptx", ".potx", ".ppsx", ".pptm", ".odp", ".otp", ".pdf", ".png", ".jpg", ".jpeg", ".zip", ".gif", ".mp4", ".webm"} +async def _write(path: Path, data: bytes) -> None: + try: + await asyncio.to_thread(files.write_whole, path, data) + except OSError as exc: + raise HTTPException(400, f"Could not write {path}: {exc.strerror or exc}") + + def _target(name: str, raw: str | None) -> tuple[Path, bool]: if raw and str(raw).strip(): p = Path(str(raw).strip()).expanduser() @@ -362,7 +369,7 @@ def write_folder() -> int: except Exception as exc: raise HTTPException(400, f"Could not compose the {fmt}: {exc}") path, served = _target(name, info.get("path")) - await asyncio.to_thread(path.write_bytes, data) + await _write(path, data) return {"path": str(path), "bytes": len(data), "name": path.name, "url": f"/api/exports/{path.name}" if served else ""} @@ -548,7 +555,7 @@ async def export_outline(deck_id: str, body: dict = Body(...)) -> dict: raise HTTPException(404, "no such deck") data, name = await asyncio.to_thread(outline_bytes, deck, fmt, bool(body.get("notes")), bool(body.get("hidden"))) path, served = _target(name, body.get("path")) - await asyncio.to_thread(path.write_bytes, data) + await _write(path, data) return {"path": str(path), "bytes": len(data), "name": path.name, "url": f"/api/exports/{path.name}" if served else ""} @@ -568,7 +575,7 @@ async def export_gif(deck_id: str, meta: str = Form("{}"), images: list[UploadFi except Exception as exc: raise HTTPException(400, f"Could not build the GIF: {exc}") path, served = _target(f"{_title(deck_id)}.gif", info.get("path")) - await asyncio.to_thread(path.write_bytes, data) + await _write(path, data) return {"path": str(path), "bytes": len(data), "name": path.name, "url": f"/api/exports/{path.name}" if served else ""} @@ -581,5 +588,5 @@ async def export_file(deck_id: str, name: str = Form(...), path: str = Form(""), if not data: raise HTTPException(400, "empty file") target, served = _target(clean, path or None) - await asyncio.to_thread(target.write_bytes, data) + await _write(target, data) return {"path": str(target), "bytes": len(data), "name": target.name, "url": f"/api/exports/{target.name}" if served else ""} diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index 75f06b3..94313c1 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -8,7 +8,7 @@ from fastapi import APIRouter, Request, Response -from app.core import config +from app.core import config, files from app.routers.live import local_origin from app.services import bridge, claude_code, compiler, model, templates from app.services import equations @@ -1625,7 +1625,7 @@ async def t_export_deck(a: Agent, args: dict) -> dict: raise ToolError(f"The folder {p.parent} does not exist.") else: p = config.exports_dir() / name - await asyncio.to_thread(p.write_bytes, data) + await asyncio.to_thread(files.write_whole, p, data) extra = [n for n in notes if "font" in n] return _ok(f"Wrote {p} ({len(data) // 1024:,} KB, {len(deck['slides'])} slides)." + ("".join(f"\n{n}" for n in extra)), {"path": str(p), "bytes": len(data)}) if fmt in ("pdf", "png", "jpeg", "jpg"): @@ -1653,7 +1653,7 @@ async def t_export_deck(a: Agent, args: dict) -> dict: p = p / name elif not p.parent.is_dir(): raise ToolError(f"The folder {p.parent} does not exist.") - await asyncio.to_thread(p.write_bytes, data) + await asyncio.to_thread(files.write_whole, p, data) return _ok(f"Wrote {p} ({max(1, len(data) // 1024):,} KB, {n} slides).", {"path": str(p), "bytes": len(data)}) raise ToolError("format is pptx, potx, fdec, odp, pdf, png, gif, txt or rtf.") diff --git a/backend/tests/test_export_writes.py b/backend/tests/test_export_writes.py new file mode 100644 index 0000000..49ec6da --- /dev/null +++ b/backend/tests/test_export_writes.py @@ -0,0 +1,57 @@ +import os + +import pytest + + +@pytest.fixture() +def failing_replace(monkeypatch, tmp_path): + real = os.replace + + def refuse(src, dst, **kw): + if str(dst).startswith(str(tmp_path)): + raise OSError(28, "No space left on device") + return real(src, dst, **kw) + + monkeypatch.setattr(os, "replace", refuse) + + +def test_a_failed_save_over_a_file_leaves_the_file_as_it_was(client, deck_from_script, tmp_path, failing_replace): + deck = deck_from_script("# Title\n\n## One\n- a") + target = tmp_path / "pitch.pptx" + target.write_bytes(b"the person's own file") + r = client.post(f"/api/decks/{deck}/export", json={"format": "pptx", "path": str(target)}) + assert r.status_code == 400 + assert target.read_bytes() == b"the person's own file" + assert sorted(p.name for p in tmp_path.iterdir()) == ["pitch.pptx"] + + +def test_a_failed_outline_export_leaves_the_file_as_it_was(client, deck_from_script, tmp_path, failing_replace): + deck = deck_from_script("# Title\n\n## One\n- a") + target = tmp_path / "outline.txt" + target.write_text("keep me") + r = client.post(f"/api/decks/{deck}/outline", json={"format": "txt", "path": str(target)}) + assert r.status_code == 400 + assert target.read_text() == "keep me" + assert sorted(p.name for p in tmp_path.iterdir()) == ["outline.txt"] + + +def test_an_agent_export_that_fails_leaves_the_file_as_it_was(client, deck_from_script, tmp_path, failing_replace): + from conftest import call_tool + + deck = deck_from_script("# Title\n\n## One\n- a") + target = tmp_path / "kept.pptx" + target.write_bytes(b"keep me") + result = call_tool(client, "export_deck", {"deck": deck, "format": "pptx", "path": str(target)}) + assert result.get("isError") + assert target.read_bytes() == b"keep me" + assert sorted(p.name for p in tmp_path.iterdir()) == ["kept.pptx"] + + +def test_a_save_over_a_file_replaces_it_whole(client, deck_from_script, tmp_path): + deck = deck_from_script("# Title\n\n## One\n- a") + target = tmp_path / "pitch.pptx" + target.write_bytes(b"old") + r = client.post(f"/api/decks/{deck}/export", json={"format": "pptx", "path": str(target)}) + assert r.status_code == 200 + assert target.read_bytes()[:2] == b"PK" + assert sorted(p.name for p in tmp_path.iterdir()) == ["pitch.pptx"] From 66ac579813fcf2b1c9a5f41b8d12ca40d88f81b6 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:28:16 -0500 Subject: [PATCH 07/10] fix(agents): run npm shims directly and check words for the command interpreter On Windows a .cmd or .bat agent program was started through cmd.exe /c with its arguments as they were. The shared finder (1.0.2) now follows an npm shim to the exe or node script it starts and runs that directly. Any other .cmd or .bat still goes through the interpreter, and a word with a control character, a percent sign or a double quote, or with one of the interpreter's special characters outside a quoted word, is refused with a clear message. --- backend/HASHOUT_LOG.md | 6 +++ backend/app/routers/terminal.py | 4 +- backend/app/services/agent_lookup.py | 54 +++++++++++++++++-- backend/app/services/chat/engine.py | 2 +- backend/app/services/chat/ideas.py | 2 +- backend/app/services/claude_code.py | 2 +- backend/tests/test_windows_start.py | 77 ++++++++++++++++++++++++++++ setup/agents.py | 2 +- 8 files changed, 138 insertions(+), 11 deletions(-) create mode 100644 backend/tests/test_windows_start.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index c4a963b..1fe7bcf 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -899,3 +899,9 @@ Ran: tests/test_seal.py, tests/test_window_key.py, tests/test_dock_engine.py, te On Windows an npm install of Claude Code is a `claude.cmd` shim, and the shared finder starts a `.cmd` or `.bat` through `cmd.exe /c`. The command interpreter reads its own line with its own quoting rules, which the argument joining of `subprocess` does not follow, and it ends the line at the first line break. A Chat message or the layout ideas request passed as an argument could therefore be cut short or read as more than one argument. `chat_argv` no longer carries the prompt: `claude -p` reads it from standard input, which `stream_chat` writes and closes before reading the events, so the text never passes through any command line on any system. A tab cannot read its first message from standard input, so when the program is started through the interpreter, `tab_argv` leaves the prompt out and `open_tab` types it into the new tab instead, as it already does for a tab that is running. The shared finder (`agent_lookup.py`) is unchanged; it changes only as a whole new version. Ran: tests/test_claude_prompt.py, tests/test_window_key.py, 35 passed. + +## 150. The shared finder follows npm shims and checks what goes to the command interpreter · (services/agent_lookup.py 1.0.2 shim_target, interpreter_words, start_argv, check; setup/agents.py LOOKUP_HASHES; services/claude_code.py via_interpreter; routers/terminal.py; services/chat/engine.py, ideas.py; tests/test_windows_start.py) + +On Windows `start_argv` put `cmd.exe /c` in front of any `.cmd` or `.bat`. The command interpreter reads its line with its own rules: it expands `%` and `!`, treats `& | < > ^ ( )` outside quotes as its own, reads a `\"` from the argument joining of `subprocess` as a quote that opens or closes, and ends the line at a line break. Version 1.0.2 of the shared finder first follows an npm shim (`"%dp0%\...\x" %*`) to what it starts: the `.exe` it names, or `node.exe` beside the shim (else `node` on PATH) and the script, and runs that directly with the same words. Only when the file is not such a shim, or its target is missing, does the interpreter start it, and then `interpreter_words` refuses any word with a control character (line breaks included), a `%` or a `"`, and any word with `& | < > ^ ( ) !` that holds no space or tab, since the joining quotes only words with a space or tab. A refusal is a `ValueError`: `check` records it as broken with the message, the tab routes answer 409, Chat and layout ideas show it as their error. `via_interpreter` is false for a shim that was followed, so its tab takes the first message as an argument again. The hash of 1.0.2 is recorded beside 1.0.0 and 1.0.1; the other engines take the same bytes when they move to 1.0.2. + +Ran: tests/test_windows_start.py, tests/test_agent_manifest.py, tests/test_claude_prompt.py, 31 passed. diff --git a/backend/app/routers/terminal.py b/backend/app/routers/terminal.py index 5fc3ab6..6fcb595 100644 --- a/backend/app/routers/terminal.py +++ b/backend/app/routers/terminal.py @@ -110,7 +110,7 @@ async def claude_open(body: ClaudeBody, request: Request) -> dict: terminal.bind(asyncio.get_running_loop()) try: return claude_code.open_tab(body.prompt, body.cols, body.rows, body.fresh, body.resume) - except LookupError as exc: + except (LookupError, ValueError) as exc: raise HTTPException(status_code=409, detail=str(exc)) from None except OSError as exc: raise HTTPException(status_code=500, detail=f"Claude Code could not start: {exc}") from None @@ -135,7 +135,7 @@ async def agent_open(kind: str, body: AgentBody, request: Request) -> dict: terminal.bind(asyncio.get_running_loop()) try: return agent_programs.open_tab(kind, body.cols, body.rows) - except LookupError as exc: + except (LookupError, ValueError) as exc: raise HTTPException(status_code=409, detail=str(exc)) from None except OSError as exc: raise HTTPException(status_code=500, detail=f"{agent_programs.PROGRAMS[kind]['title']} could not start: {exc}") from None diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index ea34eba..6eaaaaf 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -26,7 +26,7 @@ from dataclasses import dataclass, field from pathlib import Path -VERSION = "1.0.1" +VERSION = "1.0.2" PROGRAMS: dict = { "claude": {"title": "Claude Code", "names": ("claude",), "setting": "claudeBin", "install": "curl -fsSL https://claude.ai/install.sh | bash", "install_windows": "irm https://claude.ai/install.ps1 | iex", @@ -45,6 +45,10 @@ MARK = "__FORM_AGENT_LOOKUP__" HOW = {"setting": "your setting", "override": "the development override", "path": "the engine's PATH", "folder": "a known install folder", "shell": "your shell's PATH"} RETRY_SECONDS = 60.0 +SHIM_TARGET = re.compile(r'"%dp0%\\([^"%\r\n]+)"\s+%\*') +SHIM_SCRIPTS = (".js", ".cjs", ".mjs") +INTERPRETER_ALWAYS = re.compile(r'[\x00-\x1f\x7f%"]') +INTERPRETER_SPECIAL = re.compile(r"[&|<>^()!]") _lock = threading.RLock() _shell: dict = {} @@ -359,13 +363,53 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +def shim_target(path: str | os.PathLike, env: dict | None = None) -> list[str] | None: + """The program an npm .cmd shim starts, as the words to run it directly: the .exe it names, or node and the script. + None when the file is not such a shim or what it names is not there.""" + shim = Path(path) + try: + text = shim.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + said = SHIM_TARGET.search(text) + if not said: + return None + target = shim.parent.joinpath(*[part for part in said.group(1).split("\\") if part]) + if not target.is_file(): + return None + if target.suffix.lower() == ".exe": + return [str(target)] + if target.suffix.lower() not in SHIM_SCRIPTS: + return None + beside = shim.parent / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=(env or os.environ).get("PATH")) + return [node, str(target)] if node else None + + +def interpreter_words(words: list[str]) -> list[str]: + """Words safe to hand to the command interpreter after /c, which reads the line with its own rules: refused when a word + holds a control character, a percent sign or a double quote, or one of its special characters outside a quoted word.""" + for word in words: + if INTERPRETER_ALWAYS.search(word): + raise ValueError("An argument for a program started through the command interpreter holds a line break, a control character, a percent sign or a double quote.") + if INTERPRETER_SPECIAL.search(word) and not (" " in word or "\t" in word): + raise ValueError("An argument for a program started through the command interpreter holds one of & | < > ^ ( ) ! outside quotes.") + return words + + def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]: """How a program is started, the same for a tab, Chat and a check: through the person's login shell on macOS and Linux - (exec, so the process is the program), directly on Windows with the command interpreter in front of a .cmd or .bat.""" + (exec, so the process is the program), directly on Windows. An npm .cmd shim is followed to the program it starts; any + other .cmd or .bat runs with the command interpreter in front, its words checked first.""" words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words + if not words[0].lower().endswith((".cmd", ".bat")): + return words + direct = shim_target(words[0], env) + if direct: + return [*direct, *words[1:]] + return [env.get("COMSPEC") or "cmd.exe", "/c", *interpreter_words(words)] shell = login_shell(env, platform) fish = Path(shell).name == "fish" return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] @@ -414,8 +458,8 @@ def check(found: Found, env: dict | None = None, timeout: float = 15.0, fresh: b kept = ("broken", None, _last_line(out.stderr) or _last_line(out.stdout) or f"it ended with code {out.returncode}", time.monotonic()) except subprocess.TimeoutExpired: kept = ("broken", None, f"it gave no answer to --version in {timeout:g} seconds", time.monotonic()) - except OSError as exc: - kept = ("broken", None, exc.strerror or str(exc), time.monotonic()) + except (OSError, ValueError) as exc: + kept = ("broken", None, getattr(exc, "strerror", None) or str(exc), time.monotonic()) with _lock: _checked[key] = kept found.state, found.version, found.error = kept[0], kept[1], kept[2] diff --git a/backend/app/services/chat/engine.py b/backend/app/services/chat/engine.py index 873b5ee..79bb4dd 100644 --- a/backend/app/services/chat/engine.py +++ b/backend/app/services/chat/engine.py @@ -213,7 +213,7 @@ async def _run_claude(c: cv.Convo, cfg: dict, deck_id: str | None, text: str) -> elif result is None: tail = (exit_info or {}).get("tail") or [] c.add("note", "Claude Code stopped before answering" + (f": {tail[-1]}" if tail else ". Run claude once in a terminal to sign in."), level="error") - except LookupError as exc: + except (LookupError, ValueError) as exc: c.add("note", str(exc), level="error") except asyncio.CancelledError: if streaming is not None: diff --git a/backend/app/services/chat/ideas.py b/backend/app/services/chat/ideas.py index cb9cad5..090f1f1 100644 --- a/backend/app/services/chat/ideas.py +++ b/backend/app/services/chat/ideas.py @@ -146,7 +146,7 @@ async def run() -> None: await asyncio.wait_for(run(), CLAUDE_TIMEOUT) except asyncio.TimeoutError: raise IdeasError(504, "The agent took too long to answer.") - except (LookupError, OSError) as exc: + except (LookupError, OSError, ValueError) as exc: raise IdeasError(502, str(exc)[:300]) if not found or found.get("is_error"): raise IdeasError(502, "Claude Code did not answer.") diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index 8ce38b7..bcb0108 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -207,7 +207,7 @@ def _wrap(cmd: list[str]) -> list[str]: def via_interpreter(path: str) -> bool: - return agent_lookup.windows() and str(path).lower().endswith((".cmd", ".bat")) + return agent_lookup.windows() and str(path).lower().endswith((".cmd", ".bat")) and not agent_lookup.shim_target(path) def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None) -> list[str]: diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py new file mode 100644 index 0000000..36db7cb --- /dev/null +++ b/backend/tests/test_windows_start.py @@ -0,0 +1,77 @@ +import pytest + +from app.services import agent_lookup, claude_code + +ENV = {"COMSPEC": "cmd.exe", "PATH": ""} +NPM_SHIM = '@ECHO off\r\nGOTO start\r\n:start\r\nSETLOCAL\r\nendLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js" %*\r\n' + + +def windows_start(cmd): + return agent_lookup.start_argv(cmd, ENV, "win32") + + +@pytest.mark.parametrize("word", ["line one\nline two", "tab\there\r", "bell\x07", "del\x7f", "100%", "%PATH%", 'say "hi"', 'a"b']) +def test_the_command_interpreter_refuses_words_it_would_read_its_own_way(tmp_path, word): + with pytest.raises(ValueError): + windows_start([str(tmp_path / "claude.cmd"), "-p", word]) + + +@pytest.mark.parametrize("word", ["a&b", "x|y", "", "^", "(x)", "wow!"]) +def test_special_characters_are_refused_outside_a_quoted_word(tmp_path, word): + with pytest.raises(ValueError): + windows_start([str(tmp_path / "claude.bat"), word]) + + +def test_special_characters_inside_a_quoted_word_pass(tmp_path): + words = [str(tmp_path / "claude.cmd"), "--append-system-prompt", "use **bold** & keep (short) notes"] + assert windows_start(words) == ["cmd.exe", "/c", *words] + + +def test_an_npm_shim_runs_its_script_with_the_node_beside_it_without_the_interpreter(tmp_path): + shim = tmp_path / "claude.cmd" + shim.write_text(NPM_SHIM, encoding="utf-8") + script = tmp_path / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("", encoding="utf-8") + node = tmp_path / "node.exe" + node.write_text("", encoding="utf-8") + text = 'two lines\nwith "quotes" & 100%' + assert windows_start([str(shim), "-p", text]) == [str(node), str(script), "-p", text] + assert agent_lookup.shim_target(shim) == [str(node), str(script)] + + +def test_an_npm_shim_for_an_exe_runs_the_exe(tmp_path): + shim = tmp_path / "tool.cmd" + shim.write_text('@ECHO off\r\n"%dp0%\\bin\\tool.exe" %*\r\n', encoding="utf-8") + exe = tmp_path / "bin" / "tool.exe" + exe.parent.mkdir() + exe.write_text("", encoding="utf-8") + assert windows_start([str(shim), "--version"]) == [str(exe), "--version"] + + +def test_a_shim_whose_target_is_missing_falls_back_to_the_checked_interpreter(tmp_path): + shim = tmp_path / "claude.cmd" + shim.write_text(NPM_SHIM, encoding="utf-8") + assert agent_lookup.shim_target(shim) is None + assert windows_start([str(shim), "--version"]) == ["cmd.exe", "/c", str(shim), "--version"] + with pytest.raises(ValueError): + windows_start([str(shim), "-p", "a\nb"]) + + +def test_a_refused_start_reads_as_broken_not_as_a_crash(tmp_path): + found = agent_lookup.Found(program="claude", title="Claude Code", path=str(tmp_path / "a&b" / "claude.cmd"), state="runs") + agent_lookup.check(found, ENV, fresh=True, platform="win32") + assert found.state == "broken" + assert "command interpreter" in found.error + + +def test_a_resolved_shim_takes_its_tab_prompt_as_an_argument(tmp_path, monkeypatch): + shim = tmp_path / "claude.cmd" + shim.write_text(NPM_SHIM, encoding="utf-8") + monkeypatch.setattr(agent_lookup, "windows", lambda platform=None: True) + assert claude_code.via_interpreter(str(shim)) + script = tmp_path / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("", encoding="utf-8") + (tmp_path / "node.exe").write_text("", encoding="utf-8") + assert not claude_code.via_interpreter(str(shim)) diff --git a/setup/agents.py b/setup/agents.py index 915f79a..a904b4a 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -18,7 +18,7 @@ DOCK = {"present": True, "positions": ["right", "bottom"], "tabs": ["chat", "terminal", "claude", "codex", "cursor", "antigravity"]} DOCK_MODULE = ROOT / "frontend" / "src" / "dock" LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "c733042fc385c6f35ecdbee5ac58c81a9c18d439f0bee48deaf7507ae7d923cc"} PORT = int(os.environ.get("FORMDECK_PORT") or os.environ.get("FORMSLD_PORT") or 8197) PY = "python" if os.name == "nt" else "python3" USAGE = """usage: ./formdeck agents install [--dry-run] set up Claude Code, Codex, Cursor and Antigravity here and in the folder you ran it from From 61705489a348bb3f9c0608c8f9703cc6a53d694b Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:42:38 -0500 Subject: [PATCH 08/10] fix(agents): hold the program path to the interpreter's quote rule The command interpreter keeps the quotes of a /c line only when there are exactly two with nothing special between them; otherwise it drops the first and last quote, which shifts every quote in between. The shared finder (1.0.2) now refuses a program path that holds & | < > ^ ( ) ! @, and a quoted program path followed by another quoted word. A name such as claude.cmd. counts as a .cmd, and an npm shim is not followed to a node on PATH that is itself a .cmd or .bat. The recorded hash of 1.0.2 is updated. --- backend/HASHOUT_LOG.md | 4 ++-- backend/app/services/agent_lookup.py | 22 ++++++++++++++--- backend/app/services/claude_code.py | 2 +- backend/tests/test_windows_start.py | 36 ++++++++++++++++++++++++++++ setup/agents.py | 2 +- 5 files changed, 59 insertions(+), 7 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 1fe7bcf..71a7399 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -902,6 +902,6 @@ Ran: tests/test_claude_prompt.py, tests/test_window_key.py, 35 passed. ## 150. The shared finder follows npm shims and checks what goes to the command interpreter · (services/agent_lookup.py 1.0.2 shim_target, interpreter_words, start_argv, check; setup/agents.py LOOKUP_HASHES; services/claude_code.py via_interpreter; routers/terminal.py; services/chat/engine.py, ideas.py; tests/test_windows_start.py) -On Windows `start_argv` put `cmd.exe /c` in front of any `.cmd` or `.bat`. The command interpreter reads its line with its own rules: it expands `%` and `!`, treats `& | < > ^ ( )` outside quotes as its own, reads a `\"` from the argument joining of `subprocess` as a quote that opens or closes, and ends the line at a line break. Version 1.0.2 of the shared finder first follows an npm shim (`"%dp0%\...\x" %*`) to what it starts: the `.exe` it names, or `node.exe` beside the shim (else `node` on PATH) and the script, and runs that directly with the same words. Only when the file is not such a shim, or its target is missing, does the interpreter start it, and then `interpreter_words` refuses any word with a control character (line breaks included), a `%` or a `"`, and any word with `& | < > ^ ( ) !` that holds no space or tab, since the joining quotes only words with a space or tab. A refusal is a `ValueError`: `check` records it as broken with the message, the tab routes answer 409, Chat and layout ideas show it as their error. `via_interpreter` is false for a shim that was followed, so its tab takes the first message as an argument again. The hash of 1.0.2 is recorded beside 1.0.0 and 1.0.1; the other engines take the same bytes when they move to 1.0.2. +On Windows `start_argv` put `cmd.exe /c` in front of any `.cmd` or `.bat`. The command interpreter reads its line with its own rules: it expands `%` and `!`, treats `& | < > ^ ( )` outside quotes as its own, reads a `\"` from the argument joining of `subprocess` as a quote that opens or closes, and ends the line at a line break. Version 1.0.2 of the shared finder first follows an npm shim (`"%dp0%\...\x" %*`) to what it starts: the `.exe` it names, or `node.exe` beside the shim (else `node` on PATH) and the script, and runs that directly with the same words. Only when the file is not such a shim, or its target is missing, does the interpreter start it, and then `interpreter_words` refuses any word with a control character (line breaks included), a `%` or a `"`, and any word with `& | < > ^ ( ) !` that holds no space or tab, since the joining quotes only words with a space or tab. The program's path is held to more: it may not hold `& | < > ^ ( ) ! @` at all, and when it has a space (so it is quoted) no other word may be quoted, because the interpreter keeps the quotes of a `/c` line only when there are exactly two and nothing special between them, and otherwise drops the first and the last quote, which moves every quote in between. A name such as `claude.cmd.` counts as a `.cmd`, as Windows reads it, and a shim is not followed to a `node` on PATH that is itself a `.cmd` or `.bat`. A refusal is a `ValueError`: `check` records it as broken with the message, the tab routes answer 409, Chat and layout ideas show it as their error. `via_interpreter` is false for a shim that was followed, so its tab takes the first message as an argument again. The hash of 1.0.2 is recorded beside 1.0.0 and 1.0.1; the other engines take the same bytes when they move to 1.0.2. -Ran: tests/test_windows_start.py, tests/test_agent_manifest.py, tests/test_claude_prompt.py, 31 passed. +Ran: tests/test_windows_start.py, tests/test_agent_manifest.py, tests/test_claude_prompt.py, 40 passed. diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index 6eaaaaf..646f97d 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -49,6 +49,8 @@ SHIM_SCRIPTS = (".js", ".cjs", ".mjs") INTERPRETER_ALWAYS = re.compile(r'[\x00-\x1f\x7f%"]') INTERPRETER_SPECIAL = re.compile(r"[&|<>^()!]") +INTERPRETER_FIRST = re.compile(r"[&|<>^()!@]") +BATCH_ENDINGS = (".cmd", ".bat") _lock = threading.RLock() _shell: dict = {} @@ -383,17 +385,31 @@ def shim_target(path: str | os.PathLike, env: dict | None = None) -> list[str] | return None beside = shim.parent / "node.exe" node = str(beside) if beside.is_file() else shutil.which("node", path=(env or os.environ).get("PATH")) - return [node, str(target)] if node else None + return [node, str(target)] if node and not batch(node) else None + + +def batch(path: str | os.PathLike) -> bool: + return str(path).lower().rstrip(". ").endswith(BATCH_ENDINGS) + + +def _joined_in_quotes(word: str) -> bool: + return not word or " " in word or "\t" in word def interpreter_words(words: list[str]) -> list[str]: """Words safe to hand to the command interpreter after /c, which reads the line with its own rules: refused when a word - holds a control character, a percent sign or a double quote, or one of its special characters outside a quoted word.""" + holds a control character, a percent sign or a double quote, or one of its special characters outside a quoted word, and + when the program's path holds one of them or, being quoted, comes before another quoted word, since the interpreter then + drops the first and last quote of the line.""" for word in words: if INTERPRETER_ALWAYS.search(word): raise ValueError("An argument for a program started through the command interpreter holds a line break, a control character, a percent sign or a double quote.") if INTERPRETER_SPECIAL.search(word) and not (" " in word or "\t" in word): raise ValueError("An argument for a program started through the command interpreter holds one of & | < > ^ ( ) ! outside quotes.") + if INTERPRETER_FIRST.search(words[0]): + raise ValueError("The path of a program started through the command interpreter holds one of & | < > ^ ( ) ! @.") + if _joined_in_quotes(words[0]) and any(_joined_in_quotes(w) for w in words[1:]): + raise ValueError("A program started through the command interpreter from a path with a space cannot take an argument with a space.") return words @@ -404,7 +420,7 @@ def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - if not words[0].lower().endswith((".cmd", ".bat")): + if not batch(words[0]): return words direct = shim_target(words[0], env) if direct: diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index bcb0108..0e8e977 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -207,7 +207,7 @@ def _wrap(cmd: list[str]) -> list[str]: def via_interpreter(path: str) -> bool: - return agent_lookup.windows() and str(path).lower().endswith((".cmd", ".bat")) and not agent_lookup.shim_target(path) + return agent_lookup.windows() and agent_lookup.batch(path) and not agent_lookup.shim_target(path) def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None) -> list[str]: diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py index 36db7cb..bcb5379 100644 --- a/backend/tests/test_windows_start.py +++ b/backend/tests/test_windows_start.py @@ -75,3 +75,39 @@ def test_a_resolved_shim_takes_its_tab_prompt_as_an_argument(tmp_path, monkeypat script.write_text("", encoding="utf-8") (tmp_path / "node.exe").write_text("", encoding="utf-8") assert not claude_code.via_interpreter(str(shim)) + + +def test_a_program_path_with_a_space_takes_no_argument_with_a_space(tmp_path): + program = str(tmp_path / "my tools" / "claude.cmd") + assert windows_start([program, "--version"]) == ["cmd.exe", "/c", program, "--version"] + with pytest.raises(ValueError): + windows_start([program, "--append-system-prompt", "keep (short) & plain"]) + with pytest.raises(ValueError): + windows_start([program, ""]) + + +@pytest.mark.parametrize("folder", ["a&b c", "tools (old)", "x@y z", "wow!"]) +def test_a_program_path_with_an_interpreter_character_is_refused(tmp_path, folder): + with pytest.raises(ValueError): + windows_start([str(tmp_path / folder / "claude.cmd"), "--version"]) + + +@pytest.mark.parametrize("name", ["claude.cmd.", "claude.BAT", "claude.cmd. ."]) +def test_a_batch_name_in_any_spelling_goes_through_the_checks(tmp_path, name): + with pytest.raises(ValueError): + windows_start([str(tmp_path / name), "-p", "a\nb"]) + + +def test_a_shim_is_not_followed_to_a_node_that_is_itself_a_batch_file(tmp_path, monkeypatch): + shim = tmp_path / "claude.cmd" + shim.write_text(NPM_SHIM, encoding="utf-8") + script = tmp_path / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("", encoding="utf-8") + node = tmp_path / "bin" / "node.CMD" + monkeypatch.setattr(agent_lookup.shutil, "which", lambda name, path=None: str(node)) + assert agent_lookup.shim_target(shim, ENV) is None + with pytest.raises(ValueError): + windows_start([str(shim), "-p", "a\nb"]) + monkeypatch.setattr(agent_lookup.shutil, "which", lambda name, path=None: str(tmp_path / "bin" / "node.exe")) + assert agent_lookup.shim_target(shim, ENV) == [str(tmp_path / "bin" / "node.exe"), str(script)] diff --git a/setup/agents.py b/setup/agents.py index a904b4a..e3e89c0 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -18,7 +18,7 @@ DOCK = {"present": True, "positions": ["right", "bottom"], "tabs": ["chat", "terminal", "claude", "codex", "cursor", "antigravity"]} DOCK_MODULE = ROOT / "frontend" / "src" / "dock" LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "c733042fc385c6f35ecdbee5ac58c81a9c18d439f0bee48deaf7507ae7d923cc"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "9e0fd5504c4fadd586baec3fcc6b453db916cbfeacf9ef4c8f3c61f74b2a6b83"} PORT = int(os.environ.get("FORMDECK_PORT") or os.environ.get("FORMSLD_PORT") or 8197) PY = "python" if os.name == "nt" else "python3" USAGE = """usage: ./formdeck agents install [--dry-run] set up Claude Code, Codex, Cursor and Antigravity here and in the folder you ran it from From 87e0be54a615c3b6812f49f308ebbcea5b9636fb Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:42:38 -0500 Subject: [PATCH 09/10] fix(export): keep a linked save target linked Saving over a file that is a symbolic link replaced the link with a plain file. The whole-file write now follows the link and replaces the file it points to, as the direct write did before. --- backend/app/core/files.py | 2 +- backend/tests/test_export_writes.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/backend/app/core/files.py b/backend/app/core/files.py index 3803687..9b26f11 100644 --- a/backend/app/core/files.py +++ b/backend/app/core/files.py @@ -7,7 +7,7 @@ def write_whole(path: Path, data: bytes) -> None: - path = Path(path) + path = Path(os.path.realpath(path)) if Path(path).is_symlink() else Path(path) fd, part = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".part", dir=path.parent) try: with os.fdopen(fd, "wb") as f: diff --git a/backend/tests/test_export_writes.py b/backend/tests/test_export_writes.py index 49ec6da..933cb83 100644 --- a/backend/tests/test_export_writes.py +++ b/backend/tests/test_export_writes.py @@ -55,3 +55,15 @@ def test_a_save_over_a_file_replaces_it_whole(client, deck_from_script, tmp_path assert r.status_code == 200 assert target.read_bytes()[:2] == b"PK" assert sorted(p.name for p in tmp_path.iterdir()) == ["pitch.pptx"] + + +def test_a_save_over_a_linked_file_writes_the_file_it_links_to(client, deck_from_script, tmp_path): + deck = deck_from_script("# Title\n\n## One\n- a") + real = tmp_path / "real.pptx" + real.write_bytes(b"old") + link = tmp_path / "pitch.pptx" + link.symlink_to(real) + r = client.post(f"/api/decks/{deck}/export", json={"format": "pptx", "path": str(link)}) + assert r.status_code == 200 + assert link.is_symlink() + assert real.read_bytes()[:2] == b"PK" From 8b2cc629ed87dfaa1dcd51776ffcb68407a74bf9 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:34:14 -0500 Subject: [PATCH 10/10] fix(agents): refuse every interpreter special character in any word A .cmd file passes its words on with %*, which the command interpreter reads again, and quotes do not hold against its expansion, so a quoted word is no protection. When the interpreter is still used (a .cmd or .bat that is not an npm shim the finder can follow), any word holding a control character or one of & | < > ^ ( ) ! % " is now refused, with or without a space, and the message points to standard input or a file for long text. An npm shim is still run directly as its exe or node and script. The recorded hash of the shared finder 1.0.2 is updated. --- backend/HASHOUT_LOG.md | 4 ++++ backend/app/services/agent_lookup.py | 24 ++++++++++------------ backend/tests/test_windows_start.py | 30 ++++++++++++++++++++++------ setup/agents.py | 2 +- 4 files changed, 40 insertions(+), 20 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 71a7399..4107a25 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -905,3 +905,7 @@ Ran: tests/test_claude_prompt.py, tests/test_window_key.py, 35 passed. On Windows `start_argv` put `cmd.exe /c` in front of any `.cmd` or `.bat`. The command interpreter reads its line with its own rules: it expands `%` and `!`, treats `& | < > ^ ( )` outside quotes as its own, reads a `\"` from the argument joining of `subprocess` as a quote that opens or closes, and ends the line at a line break. Version 1.0.2 of the shared finder first follows an npm shim (`"%dp0%\...\x" %*`) to what it starts: the `.exe` it names, or `node.exe` beside the shim (else `node` on PATH) and the script, and runs that directly with the same words. Only when the file is not such a shim, or its target is missing, does the interpreter start it, and then `interpreter_words` refuses any word with a control character (line breaks included), a `%` or a `"`, and any word with `& | < > ^ ( ) !` that holds no space or tab, since the joining quotes only words with a space or tab. The program's path is held to more: it may not hold `& | < > ^ ( ) ! @` at all, and when it has a space (so it is quoted) no other word may be quoted, because the interpreter keeps the quotes of a `/c` line only when there are exactly two and nothing special between them, and otherwise drops the first and the last quote, which moves every quote in between. A name such as `claude.cmd.` counts as a `.cmd`, as Windows reads it, and a shim is not followed to a `node` on PATH that is itself a `.cmd` or `.bat`. A refusal is a `ValueError`: `check` records it as broken with the message, the tab routes answer 409, Chat and layout ideas show it as their error. `via_interpreter` is false for a shim that was followed, so its tab takes the first message as an argument again. The hash of 1.0.2 is recorded beside 1.0.0 and 1.0.1; the other engines take the same bytes when they move to 1.0.2. Ran: tests/test_windows_start.py, tests/test_agent_manifest.py, tests/test_claude_prompt.py, 40 passed. + +## 151. The command interpreter takes no special character in any word · (services/agent_lookup.py 1.0.2 interpreter_words; setup/agents.py LOOKUP_HASHES; tests/test_windows_start.py) + +Entry 150 let a word with `& | < > ^ ( ) !` through when it held a space or tab, on the reading that the argument joining of `subprocess` quotes it. A `.cmd` file passes its words on with `%*`, which the interpreter reads again, and quotes do not hold against `%` and `!` expansion at all, so the quote is no protection. `interpreter_words` now refuses any word that holds a control character or one of `& | < > ^ ( ) ! % "`, with a space or without, the program's path included; the path is still refused for an `@`, and a quoted path still takes no other quoted word. The message tells the caller to pass long or free text through standard input or a file when the program reads it there, as Chat already does (entry 149). The preferred path is unchanged: an npm shim is followed to its `.exe` or to node and the script, started directly with an argument list and no interpreter. The formdeck notes passed as `--append-system-prompt` hold none of the refused characters. 1.0.2 is not yet on main, so its recorded hash is replaced rather than a new version added. diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index 646f97d..0963ade 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -47,9 +47,9 @@ RETRY_SECONDS = 60.0 SHIM_TARGET = re.compile(r'"%dp0%\\([^"%\r\n]+)"\s+%\*') SHIM_SCRIPTS = (".js", ".cjs", ".mjs") -INTERPRETER_ALWAYS = re.compile(r'[\x00-\x1f\x7f%"]') -INTERPRETER_SPECIAL = re.compile(r"[&|<>^()!]") -INTERPRETER_FIRST = re.compile(r"[&|<>^()!@]") +INTERPRETER_REFUSED = re.compile(r'[\x00-\x1f\x7f&|<>^()!%"]') +INTERPRETER_FIRST = re.compile(r"[@]") +INTERPRETER_HINT = "Pass long or free text through standard input or a file when the program can read it there." BATCH_ENDINGS = (".cmd", ".bat") _lock = threading.RLock() @@ -397,19 +397,17 @@ def _joined_in_quotes(word: str) -> bool: def interpreter_words(words: list[str]) -> list[str]: - """Words safe to hand to the command interpreter after /c, which reads the line with its own rules: refused when a word - holds a control character, a percent sign or a double quote, or one of its special characters outside a quoted word, and - when the program's path holds one of them or, being quoted, comes before another quoted word, since the interpreter then - drops the first and last quote of the line.""" + """Words safe to hand to the command interpreter after /c. The interpreter and a .cmd file's %* read the line again with + their own rules, and quotes do not protect a word from them, so any word that holds a control character or one of + & | < > ^ ( ) ! % " is refused, quoted or not. The program's path may not hold @ either, and when it is quoted (it has a + space) no other word may be quoted, since the interpreter then drops the first and last quote of the line.""" for word in words: - if INTERPRETER_ALWAYS.search(word): - raise ValueError("An argument for a program started through the command interpreter holds a line break, a control character, a percent sign or a double quote.") - if INTERPRETER_SPECIAL.search(word) and not (" " in word or "\t" in word): - raise ValueError("An argument for a program started through the command interpreter holds one of & | < > ^ ( ) ! outside quotes.") + if INTERPRETER_REFUSED.search(word): + raise ValueError("An argument for a program started through the command interpreter holds a control character or one of & | < > ^ ( ) ! % \". " + INTERPRETER_HINT) if INTERPRETER_FIRST.search(words[0]): - raise ValueError("The path of a program started through the command interpreter holds one of & | < > ^ ( ) ! @.") + raise ValueError("The path of a program started through the command interpreter holds an @.") if _joined_in_quotes(words[0]) and any(_joined_in_quotes(w) for w in words[1:]): - raise ValueError("A program started through the command interpreter from a path with a space cannot take an argument with a space.") + raise ValueError("A program started through the command interpreter from a path with a space cannot take an argument with a space. " + INTERPRETER_HINT) return words diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py index bcb5379..a9e0c24 100644 --- a/backend/tests/test_windows_start.py +++ b/backend/tests/test_windows_start.py @@ -16,17 +16,35 @@ def test_the_command_interpreter_refuses_words_it_would_read_its_own_way(tmp_pat windows_start([str(tmp_path / "claude.cmd"), "-p", word]) -@pytest.mark.parametrize("word", ["a&b", "x|y", "", "^", "(x)", "wow!"]) -def test_special_characters_are_refused_outside_a_quoted_word(tmp_path, word): - with pytest.raises(ValueError): +@pytest.mark.parametrize("word", ["a&b", "x|y", "", "^", "(x)", "wow!", "a & b", "keep (short) notes", "x | y", "wow !", 'say "hi" now', "100 %"]) +def test_special_characters_are_refused_with_or_without_a_space(tmp_path, word): + with pytest.raises(ValueError, match="standard input or a file"): windows_start([str(tmp_path / "claude.bat"), word]) -def test_special_characters_inside_a_quoted_word_pass(tmp_path): - words = [str(tmp_path / "claude.cmd"), "--append-system-prompt", "use **bold** & keep (short) notes"] +def test_a_quoted_word_gets_no_exception_from_the_interpreter_checks(tmp_path): + with pytest.raises(ValueError): + windows_start([str(tmp_path / "claude.cmd"), "--append-system-prompt", "use **bold** & keep (short) notes"]) + + +def test_plain_words_pass_to_the_interpreter_unchanged(tmp_path): + words = [str(tmp_path / "claude.cmd"), "--append-system-prompt", "use **bold**, keep short notes. It's fine: a/b, c=d"] assert windows_start(words) == ["cmd.exe", "/c", *words] +def test_the_comspec_from_the_environment_starts_a_checked_batch_file(tmp_path): + words = [str(tmp_path / "tool.bat"), "--version"] + env = {"COMSPEC": r"C:\Windows\System32\cmd.exe", "PATH": ""} + assert agent_lookup.start_argv(words, env, "win32") == [env["COMSPEC"], "/c", *words] + with pytest.raises(ValueError): + agent_lookup.start_argv([*words, "a^b"], env, "win32") + + +def test_an_exe_is_started_directly_with_any_words(tmp_path): + words = [str(tmp_path / "claude.exe"), "-p", 'two lines\nwith "quotes" & 100% (all) !'] + assert windows_start(words) == words + + def test_an_npm_shim_runs_its_script_with_the_node_beside_it_without_the_interpreter(tmp_path): shim = tmp_path / "claude.cmd" shim.write_text(NPM_SHIM, encoding="utf-8") @@ -86,7 +104,7 @@ def test_a_program_path_with_a_space_takes_no_argument_with_a_space(tmp_path): windows_start([program, ""]) -@pytest.mark.parametrize("folder", ["a&b c", "tools (old)", "x@y z", "wow!"]) +@pytest.mark.parametrize("folder", ["a&b c", "tools (old)", "x@y z", "wow!", "50%", "a^b"]) def test_a_program_path_with_an_interpreter_character_is_refused(tmp_path, folder): with pytest.raises(ValueError): windows_start([str(tmp_path / folder / "claude.cmd"), "--version"]) diff --git a/setup/agents.py b/setup/agents.py index e3e89c0..4dd2008 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -18,7 +18,7 @@ DOCK = {"present": True, "positions": ["right", "bottom"], "tabs": ["chat", "terminal", "claude", "codex", "cursor", "antigravity"]} DOCK_MODULE = ROOT / "frontend" / "src" / "dock" LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "9e0fd5504c4fadd586baec3fcc6b453db916cbfeacf9ef4c8f3c61f74b2a6b83"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "c7867152291d30708e58b98491bedd57e08e425d93d8426984141555949b68dd"} PORT = int(os.environ.get("FORMDECK_PORT") or os.environ.get("FORMSLD_PORT") or 8197) PY = "python" if os.name == "nt" else "python3" USAGE = """usage: ./formdeck agents install [--dry-run] set up Claude Code, Codex, Cursor and Antigravity here and in the folder you ran it from