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", diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 1656072..4107a25 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -893,3 +893,19 @@ 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. + +## 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. 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/core/files.py b/backend/app/core/files.py new file mode 100644 index 0000000..9b26f11 --- /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(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: + 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/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/app/routers/mcp.py b/backend/app/routers/mcp.py index 8e70558..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 @@ -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 @@ -1623,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"): @@ -1651,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/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/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..0963ade 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,12 @@ 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_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() _shell: dict = {} @@ -359,13 +365,65 @@ 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 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. 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_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 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. " + INTERPRETER_HINT) + 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 batch(words[0]): + 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 +472,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 af36897..0e8e977 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 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]: 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_export_writes.py b/backend/tests/test_export_writes.py new file mode 100644 index 0000000..933cb83 --- /dev/null +++ b/backend/tests/test_export_writes.py @@ -0,0 +1,69 @@ +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"] + + +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" 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}) 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, []) 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 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()) diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py new file mode 100644 index 0000000..a9e0c24 --- /dev/null +++ b/backend/tests/test_windows_start.py @@ -0,0 +1,131 @@ +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!", "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_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") + 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)) + + +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!", "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"]) + + +@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 915f79a..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"} +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