Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions agents/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"apply_template",
"set_theme",
"masters",
"export_deck",
"open_file",
"comments",
"handoff",
Expand Down
16 changes: 16 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
27 changes: 27 additions & 0 deletions backend/app/core/files.py
Original file line number Diff line number Diff line change
@@ -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
6 changes: 3 additions & 3 deletions backend/app/routers/decks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}
Expand Down Expand Up @@ -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"):
Expand Down
17 changes: 12 additions & 5 deletions backend/app/routers/exports.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 ""}


Expand Down Expand Up @@ -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 ""}


Expand All @@ -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 ""}


Expand All @@ -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 ""}
2 changes: 1 addition & 1 deletion backend/app/routers/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions backend/app/routers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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"):
Expand Down Expand Up @@ -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.")

Expand Down
5 changes: 3 additions & 2 deletions backend/app/routers/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
4 changes: 2 additions & 2 deletions backend/app/routers/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading
Loading