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
2 changes: 1 addition & 1 deletion .claude/skills/formdeck-harness/references/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ Returns: `Undo Agent: theme (11 steps) · deck now 8 slides`. Refuses when the n

### export_deck
- deck, format (required): pptx | potx | odp | fdec | pdf | png | gif | txt | rtf
- path: absolute file or existing folder (default the Exports folder in the formdeck data folder)
- path: absolute file or existing folder (default the Exports folder in the formdeck data folder; there an earlier export is never replaced, the new file takes the next free name such as `Title (2).pptx`, and the result carries its served `url`)
- slides: array (pdf, png and gif)
- notes: boolean, txt and rtf include the speaker notes
- width: integer, gif frame width in pixels
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ A deck that passed the visual-qa gate (or a request that only needs export, undo

### Export

`export_deck {deck, format, path}`. Formats: pptx (PowerPoint and Google Slides import), potx (a PowerPoint template), fdec (formdeck's own package with media), pdf (each slide a full-page picture at deck size, with an invisible searchable text layer and one outline entry per slide), png (one slide is a .png, several are a .zip). `path` is an absolute file path or an existing folder; without it the file goes to the formdeck Exports folder. pdf and png are drawn by the window, so they need it open; pptx, potx and fdec do not. `slides` limits pdf and png to named slides; hidden slides are skipped by default. Report the exact path from the result.
`export_deck {deck, format, path}`. Formats: pptx (PowerPoint and Google Slides import), potx (a PowerPoint template), fdec (formdeck's own package with media), pdf (each slide a full-page picture at deck size, with an invisible searchable text layer and one outline entry per slide), png (one slide is a .png, several are a .zip). `path` is an absolute file path or an existing folder; without it the file goes to the formdeck Exports folder under a name no earlier export holds (`Title (2).pptx` and so on). pdf and png are drawn by the window, so they need it open; pptx, potx and fdec do not. `slides` limits pdf and png to named slides; hidden slides are skipped by default. Report the exact path from the result.

### Open an existing file

Expand Down
14 changes: 14 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -909,3 +909,17 @@ Ran: tests/test_windows_start.py, tests/test_agent_manifest.py, tests/test_claud
## 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.

## 152. An export with no path never replaces an earlier export · (core/files.py write_new, new_names; routers/exports.py deliver; routers/decks.py export; routers/mcp.py export_deck; tests/test_export_writes.py)

An export with no path went to the Exports folder under the deck's title, so a second export of the same deck in the same format replaced the first. Now every such write goes through `files.write_new`: the bytes go to a hidden `.part` file in the folder, fsynced, and that file is hard linked to the first free name of `Title.ext`, `Title (2).ext`, `Title (3).ext` and so on. A link fails when the name exists, so two exports at once can never take the same name or replace a file another wrote. Where the disk has no hard links, the name is claimed with an exclusive create and the `.part` file is moved over the empty claim. The `.part` file is always removed, and a failed write leaves nothing behind. A counter rather than a timestamp keeps names short and in order, and matches the folder naming of multi-picture exports in `compose`.

`exports.deliver` holds the choice for every engine route (compose, outline, gif, export-file and the deck export): no path means a new name and a served `/api/exports/<name>` url in the answer; a path the person chose is replaced whole with `write_whole`, as before, and the url is empty. The deck export now answers with `name` and `url` too. The agent tool `export_deck` uses the same rule through `_export_write` and adds `url` to its result only for a file in the Exports folder. pdf and png from an agent are written by the window through compose, so they follow the same rule.

Ran: tests/, 342 passed.

## 153. A new export name is always one the engine serves · (core/files.py plain_name, _claim; tests/test_export_writes.py)

The served url from entry 152 is only worth giving when `/api/exports/<name>` answers for it, and that route takes a name that starts with a letter or digit and holds no `..`. A deck titled `-Draft`, `...Draft`, `Draft..v2` or `Draft.` gave a file the route refused. `write_new` now passes the name through `plain_name` first: runs of dots become one, leading spaces, dots, dashes and brackets and trailing spaces and dots are dropped, and an empty stem becomes `slides`. Every caller of `write_new` gets this, so no export route can hand out a url that does not answer. On a disk without hard links, a failed move over the empty claim now removes the claim, so a failed write leaves nothing behind there too.

Ran: tests/, 347 passed.
60 changes: 60 additions & 0 deletions backend/app/core/files.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import re
import shutil
import tempfile
from pathlib import Path
Expand All @@ -25,3 +26,62 @@ def write_whole(path: Path, data: bytes) -> None:
except OSError:
pass
raise


NEW_NAME_LIMIT = 10000


def new_names(name: str):
stem, suffix = Path(name).stem, Path(name).suffix
yield name
for n in range(2, NEW_NAME_LIMIT):
yield f"{stem} ({n}){suffix}"


def _claim(part: str, path: Path) -> bool:
try:
os.link(part, path)
return True
except FileExistsError:
return False
except OSError:
pass
try:
os.close(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, NEW_FILE_MODE))
except FileExistsError:
return False
try:
os.replace(part, path)
except BaseException:
try:
os.unlink(path)
except OSError:
pass
raise
return True


def plain_name(name: str) -> str:
stem, suffix = Path(name).stem, Path(name).suffix
stem = re.sub(r"\.{2,}", ".", stem).lstrip(" .-()").rstrip(" .") or "slides"
return f"{stem}{suffix}"


def write_new(folder: Path, name: str, data: bytes) -> Path:
folder, name = Path(folder), plain_name(name)
fd, part = tempfile.mkstemp(prefix=f".{name}.", suffix=".part", dir=folder)
try:
with os.fdopen(fd, "wb") as f:
f.write(data)
f.flush()
os.fsync(f.fileno())
os.chmod(part, NEW_FILE_MODE)
for candidate in new_names(name):
if _claim(part, folder / candidate):
return folder / candidate
raise FileExistsError(f"Every name for {name} in {folder} is taken.")
finally:
try:
os.unlink(part)
except OSError:
pass
11 changes: 2 additions & 9 deletions backend/app/routers/decks.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from fastapi.responses import FileResponse, Response

from app.core import config, files, ids
from app.routers.exports import _target
from app.routers.exports import _target, deliver
from app.services import compiler, model, package, templates
from app.services import ops as opsmod
from app.services.media import store as media_store
Expand Down Expand Up @@ -274,14 +274,7 @@ async def export(deck_id: str, body: dict = Body(default={})) -> dict:
if body.get("clean") and fmt in package.FORMATS:
deck = package.clean_copy(deck)
data, name, _ = await asyncio.to_thread(export_bytes, deck, fmt, body.get("fontScales"), body.get("embedFonts"), notes)
path, _ = _target(name, body.get("path"))
if not path.parent.is_dir():
raise HTTPException(400, f"The folder {path.parent} does not exist.")
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}")
return {"path": str(path), "bytes": len(data), "warnings": notes}
return {**await deliver(name, body.get("path"), data), "warnings": notes}


def import_bytes(data: bytes, name: str, as_template: bool = False) -> dict:
Expand Down
35 changes: 16 additions & 19 deletions backend/app/routers/exports.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,13 +292,6 @@ 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 All @@ -316,6 +309,18 @@ def _target(name: str, raw: str | None) -> tuple[Path, bool]:
return config.exports_dir() / name, True


async def deliver(name: str, raw: str | None, data: bytes) -> dict:
path, fresh = _target(name, raw)
try:
if fresh:
path = await asyncio.to_thread(files.write_new, path.parent, path.name, data)
else:
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), "name": path.name, "url": f"/api/exports/{path.name}" if fresh else ""}


@router.post("/decks/{deck_id}/compose")
async def compose(deck_id: str, format: str = Form(...), meta: str = Form("{}"), images: list[UploadFile] = File(default=[]), bares: list[UploadFile] = File(default=[])) -> dict:
fmt = format.lower().strip()
Expand Down Expand Up @@ -368,9 +373,7 @@ def write_folder() -> int:
data, name = await asyncio.to_thread(compose_bytes, deck_id, fmt, info, blobs, aligned)
except Exception as exc:
raise HTTPException(400, f"Could not compose the {fmt}: {exc}")
path, served = _target(name, info.get("path"))
await _write(path, data)
return {"path": str(path), "bytes": len(data), "name": path.name, "url": f"/api/exports/{path.name}" if served else ""}
return await deliver(name, info.get("path"), data)


@router.get("/exports/{name}")
Expand Down Expand Up @@ -554,9 +557,7 @@ async def export_outline(deck_id: str, body: dict = Body(...)) -> dict:
except KeyError:
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 _write(path, data)
return {"path": str(path), "bytes": len(data), "name": path.name, "url": f"/api/exports/{path.name}" if served else ""}
return await deliver(name, body.get("path"), data)


@router.post("/decks/{deck_id}/gif")
Expand All @@ -574,9 +575,7 @@ async def export_gif(deck_id: str, meta: str = Form("{}"), images: list[UploadFi
data = await asyncio.to_thread(gif_bytes, blobs, holds, fades, info.get("loop", True) is not False)
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 _write(path, data)
return {"path": str(path), "bytes": len(data), "name": path.name, "url": f"/api/exports/{path.name}" if served else ""}
return await deliver(f"{_title(deck_id)}.gif", info.get("path"), data)


@router.post("/decks/{deck_id}/export-file")
Expand All @@ -587,6 +586,4 @@ async def export_file(deck_id: str, name: str = Form(...), path: str = Form(""),
data = await file.read()
if not data:
raise HTTPException(400, "empty file")
target, served = _target(clean, path or None)
await _write(target, data)
return {"path": str(target), "bytes": len(data), "name": target.name, "url": f"/api/exports/{target.name}" if served else ""}
return await deliver(clean, path or None, data)
39 changes: 21 additions & 18 deletions backend/app/routers/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None =
_tool("render_slides", "Contact-sheet images of slides, rendered by the formdeck window.", {"deck": _DECK, "slides": _SLIDES, "width": {"type": "integer", "description": "Cell width px (default 320)"}, "cols": _INT},
["deck"], read=True),
_tool("export_deck", "Writes a deck as pptx, potx, fdec (formdeck's own file; fsld is accepted as an older name), odp (OpenDocument for LibreOffice Impress), pdf, png, gif (animated, one frame per slide, slide timings or 3 s each), txt or rtf (the outline: "
"titles and indented bullets, notes with notes=true) to an absolute path (default the Exports folder).",
"titles and indented bullets, notes with notes=true) to an absolute path (default the Exports folder, under a new name such as \"Title (2).pptx\" when the name is taken, with the served url in the result).",
{"deck": _DECK, "format": {"type": "string", "enum": ["pptx", "potx", "fdec", "fsld", "odp", "pdf", "png", "gif", "txt", "rtf"]}, "path": _S, "slides": _SLIDES,
"notes": {"type": "boolean"}, "width": _INT,
"clean": {"type": "boolean", "description": "fdec only: a copy to share, without the path the deck was saved to, agent handoff notes, slide scripts that no longer match their slide, and media no slide, layout or master uses"},
Expand Down Expand Up @@ -1607,6 +1607,22 @@ async def t_render_slides(a: Agent, args: dict) -> dict:
return res if res is not None else _fail("The formdeck window closed before rendering; ask the person to reopen it.")


async def _export_write(raw, name: str, data: bytes) -> tuple[Path, bool]:
if not raw:
return await asyncio.to_thread(files.write_new, config.exports_dir(), name, data), True
p = _abs(raw, must_exist=False)
if p.is_dir():
p = p / name
elif not p.parent.is_dir():
raise ToolError(f"The folder {p.parent} does not exist.")
await asyncio.to_thread(files.write_whole, p, data)
return p, False


def _written(p: Path, data: bytes, served: bool) -> dict:
return {"path": str(p), "bytes": len(data), **({"url": f"/api/exports/{p.name}"} if served else {})}


async def t_export_deck(a: Agent, args: dict) -> dict:
deck = _deck(args.get("deck"))
fmt = str(args.get("format") or "pptx").lower()
Expand All @@ -1617,17 +1633,9 @@ async def t_export_deck(a: Agent, args: dict) -> dict:
notes: list[str] = []
clean = bool(args.get("clean")) and fmt in package.FORMATS
data, name, _ = await asyncio.to_thread(export_bytes, package.clean_copy(deck) if clean else deck, fmt, None, embed, notes)
if args.get("path"):
p = _abs(args["path"], must_exist=False)
if p.is_dir():
p = p / name
elif not p.parent.is_dir():
raise ToolError(f"The folder {p.parent} does not exist.")
else:
p = config.exports_dir() / name
await asyncio.to_thread(files.write_whole, p, data)
p, served = await _export_write(args.get("path"), name, 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)})
return _ok(f"Wrote {p} ({len(data) // 1024:,} KB, {len(deck['slides'])} slides)." + ("".join(f"\n{n}" for n in extra)), _written(p, data, served))
if fmt in ("pdf", "png", "jpeg", "jpg"):
if not bridge.window_connected():
return _fail(f"{fmt} export renders the slides in the formdeck window, and none is open. Ask the person to open formdeck (./formdeck), then retry; pptx and fdec export work without it.")
Expand All @@ -1648,13 +1656,8 @@ async def t_export_deck(a: Agent, args: dict) -> dict:
picked = {**deck, "slides": [deck["slides"][i] for i in _sel(deck, args["slides"])]} if args.get("slides") else deck
data, name = await asyncio.to_thread(exports.outline_bytes, picked, fmt, bool(args.get("notes")), bool(args.get("slides")))
n = len([s for s in picked["slides"] if args.get("slides") or not s.get("hidden")])
p = _abs(args["path"], must_exist=False) if args.get("path") else config.exports_dir() / name
if p.is_dir():
p = p / name
elif not p.parent.is_dir():
raise ToolError(f"The folder {p.parent} does not exist.")
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)})
p, served = await _export_write(args.get("path"), name, data)
return _ok(f"Wrote {p} ({max(1, len(data) // 1024):,} KB, {n} slides).", _written(p, data, served))
raise ToolError("format is pptx, potx, fdec, odp, pdf, png, gif, txt or rtf.")


Expand Down
Loading
Loading