From 6895e78f5a6cd2ac8f69e211af9e38807eb4cc17 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 14:43:08 -0500 Subject: [PATCH 1/2] fix(export): give each export with no path a new name An export with no path went to the Exports folder under the deck title, so exporting the same deck again replaced the earlier file. Each such export now takes the next free name (Title.pptx, Title (2).pptx, ...), claimed with a hard link or an exclusive create so concurrent exports never share a name, and the answer carries the served url of the new file. The deck export route and the export_deck agent tool follow the same rule. A path the person chose is still replaced whole. --- .../formdeck-harness/references/tools.md | 2 +- .../sub-skills/review-handoff/SUB-SKILL.md | 2 +- backend/HASHOUT_LOG.md | 8 ++ backend/app/core/files.py | 46 ++++++++ backend/app/routers/decks.py | 11 +- backend/app/routers/exports.py | 35 +++--- backend/app/routers/mcp.py | 39 ++++--- backend/tests/test_export_writes.py | 110 ++++++++++++++++++ docs/MANUAL.md | 2 +- frontend/src/io/api.ts | 2 +- 10 files changed, 207 insertions(+), 50 deletions(-) diff --git a/.claude/skills/formdeck-harness/references/tools.md b/.claude/skills/formdeck-harness/references/tools.md index dfccb78..9999f08 100644 --- a/.claude/skills/formdeck-harness/references/tools.md +++ b/.claude/skills/formdeck-harness/references/tools.md @@ -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 diff --git a/.claude/skills/formdeck-harness/sub-skills/review-handoff/SUB-SKILL.md b/.claude/skills/formdeck-harness/sub-skills/review-handoff/SUB-SKILL.md index c911e79..f6c5ec0 100644 --- a/.claude/skills/formdeck-harness/sub-skills/review-handoff/SUB-SKILL.md +++ b/.claude/skills/formdeck-harness/sub-skills/review-handoff/SUB-SKILL.md @@ -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 diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 4107a25..6c2345d 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -909,3 +909,11 @@ 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/` 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. diff --git a/backend/app/core/files.py b/backend/app/core/files.py index 9b26f11..8b642b0 100644 --- a/backend/app/core/files.py +++ b/backend/app/core/files.py @@ -25,3 +25,49 @@ 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 + os.replace(part, path) + return True + + +def write_new(folder: Path, name: str, data: bytes) -> Path: + folder = Path(folder) + 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 diff --git a/backend/app/routers/decks.py b/backend/app/routers/decks.py index 167704e..6b0dddb 100644 --- a/backend/app/routers/decks.py +++ b/backend/app/routers/decks.py @@ -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 @@ -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: diff --git a/backend/app/routers/exports.py b/backend/app/routers/exports.py index a643b6d..6087aee 100644 --- a/backend/app/routers/exports.py +++ b/backend/app/routers/exports.py @@ -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() @@ -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() @@ -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}") @@ -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") @@ -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") @@ -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) diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index 94313c1..6d74644 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -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"}, @@ -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() @@ -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.") @@ -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.") diff --git a/backend/tests/test_export_writes.py b/backend/tests/test_export_writes.py index 933cb83..287c1d3 100644 --- a/backend/tests/test_export_writes.py +++ b/backend/tests/test_export_writes.py @@ -1,4 +1,5 @@ import os +from pathlib import Path import pytest @@ -67,3 +68,112 @@ def test_a_save_over_a_linked_file_writes_the_file_it_links_to(client, deck_from assert r.status_code == 200 assert link.is_symlink() assert real.read_bytes()[:2] == b"PK" + + +def _exports(): + from app.core import config + + return config.exports_dir() + + +def test_an_outline_export_with_no_path_keeps_the_earlier_export(client, deck_from_script): + deck = deck_from_script("# Keep Both\n\n## One\n- a") + first = client.post(f"/api/decks/{deck}/outline", json={"format": "txt"}).json() + Path(first["path"]).write_text("the earlier export") + second = client.post(f"/api/decks/{deck}/outline", json={"format": "txt"}).json() + assert second["path"] != first["path"] + assert Path(first["path"]).read_text() == "the earlier export" + assert Path(second["path"]).parent == _exports() + assert second["url"] == f"/api/exports/{second['name']}" + served = client.get(second["url"]) + assert served.status_code == 200 + assert served.content == Path(second["path"]).read_bytes() + + +def test_a_deck_export_with_no_path_gets_a_new_name_and_a_served_url(client, deck_from_script): + deck = deck_from_script("# Twice Over\n\n## One\n- a") + first = client.post(f"/api/decks/{deck}/export", json={"format": "pptx"}).json() + Path(first["path"]).write_bytes(b"earlier") + second = client.post(f"/api/decks/{deck}/export", json={"format": "pptx"}).json() + assert Path(first["path"]).read_bytes() == b"earlier" + assert Path(second["path"]).name == "Twice Over (2).pptx" + assert second["url"] == "/api/exports/Twice Over (2).pptx" + assert client.get(second["url"]).content[:2] == b"PK" + + +def test_a_deck_export_to_a_chosen_path_has_no_served_url(client, deck_from_script, tmp_path): + deck = deck_from_script("# Chosen\n\n## One\n- a") + r = client.post(f"/api/decks/{deck}/export", json={"format": "pptx", "path": str(tmp_path / "chosen.pptx")}).json() + assert r["path"] == str(tmp_path / "chosen.pptx") + assert r["url"] == "" + + +def test_a_file_export_with_no_path_keeps_the_earlier_export(client, deck_from_script): + deck = deck_from_script("# Files\n\n## One\n- a") + names = [] + for body in (b"one", b"two", b"three"): + r = client.post(f"/api/decks/{deck}/export-file", data={"name": "clip.mp4"}, files={"file": ("clip.mp4", body)}).json() + names.append(r["name"]) + assert names == ["clip.mp4", "clip (2).mp4", "clip (3).mp4"] + assert [(_exports() / n).read_bytes() for n in names] == [b"one", b"two", b"three"] + + +def test_an_agent_export_with_no_path_keeps_the_earlier_export(client, deck_from_script): + from conftest import call_tool + + deck = deck_from_script("# Agent Copies\n\n## One\n- a") + for fmt in ("pptx", "txt"): + first = call_tool(client, "export_deck", {"deck": deck, "format": fmt})["structuredContent"] + Path(first["path"]).write_bytes(b"earlier") + second = call_tool(client, "export_deck", {"deck": deck, "format": fmt})["structuredContent"] + assert Path(first["path"]).read_bytes() == b"earlier" + assert second["path"] != first["path"] + assert Path(second["path"]).parent == _exports() + assert second["url"] == f"/api/exports/{Path(second['path']).name}" + + +def test_an_agent_export_to_a_chosen_path_has_no_served_url(client, deck_from_script, tmp_path): + from conftest import call_tool + + deck = deck_from_script("# Chosen\n\n## One\n- a") + out = call_tool(client, "export_deck", {"deck": deck, "format": "pptx", "path": str(tmp_path / "mine.pptx")})["structuredContent"] + assert out["path"] == str(tmp_path / "mine.pptx") + assert "url" not in out + + +def test_a_new_export_takes_the_next_free_name_and_leaves_nothing_else(tmp_path): + from app.core import files + + (tmp_path / "deck.pptx").write_bytes(b"a") + (tmp_path / "deck (2).pptx").write_bytes(b"b") + made = files.write_new(tmp_path, "deck.pptx", b"c") + assert made == tmp_path / "deck (3).pptx" + assert sorted(p.name for p in tmp_path.iterdir()) == ["deck (2).pptx", "deck (3).pptx", "deck.pptx"] + assert [(tmp_path / n).read_bytes() for n in ("deck.pptx", "deck (2).pptx", "deck (3).pptx")] == [b"a", b"b", b"c"] + + +def test_a_new_export_on_a_disk_without_hard_links_still_keeps_the_earlier_file(tmp_path, monkeypatch): + from app.core import files + + def no_links(src, dst, **kw): + raise OSError(1, "Operation not permitted") + + monkeypatch.setattr(os, "link", no_links) + (tmp_path / "deck.pptx").write_bytes(b"a") + made = files.write_new(tmp_path, "deck.pptx", b"b") + assert made == tmp_path / "deck (2).pptx" + assert (tmp_path / "deck.pptx").read_bytes() == b"a" + assert made.read_bytes() == b"b" + assert sorted(p.name for p in tmp_path.iterdir()) == ["deck (2).pptx", "deck.pptx"] + + +def test_a_failed_new_export_leaves_no_file_behind(tmp_path, monkeypatch): + from app.core import files + + def full(fd): + raise OSError(28, "No space left on device") + + monkeypatch.setattr(os, "fsync", full) + with pytest.raises(OSError): + files.write_new(tmp_path, "deck.pptx", b"x") + assert list(tmp_path.iterdir()) == [] diff --git a/docs/MANUAL.md b/docs/MANUAL.md index f5aa486..48a551c 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -475,7 +475,7 @@ Exporting a deck as PDF and printing are unchanged (see Import, export and print - Video (MP4 where the browser can record it, otherwise WebM; 720p or 1080p) and Animated GIF (480, 720 or 960 px wide): seconds per slide for slides without a timing, recorded timings and narration, animations as build steps and transitions as fades. A video records in real time, so keep the window open; Cancel stops it. Hidden slides are skipped. - Web page (File > Export > Publish as Web Page): one .html file with every slide (or hidden slides too) that plays in any browser, offline or from any web host, with arrow keys, clicks, full screen and optional auto-advance and looping; slide text is included for screen readers. Copy Embed Code gives an iframe to paste into a page that sits next to the file. Nothing is uploaded. - Outline as Text (.txt) or Rich Text (.rtf): each slide's title with its bullets indented by level, optionally with the speaker notes and hidden slides; the .rtf opens in Word's outline view. - In the desktop app exports go to a path you choose (default the Exports folder); the browser downloads them. + In the desktop app exports go to a path you choose (default the Exports folder); the browser downloads them. An export to the Exports folder never replaces an earlier one: when the name is taken, the new file gets a number after the title, such as `Pitch (2).pptx`. Exporting to a file you chose yourself replaces that file. - **Print** (Mod+P): Full page slides, Notes pages, Outline, or Handouts with 2, 3 (with lines for notes), 4, 6 or 9 slides per page; A4 or Letter paper; colour or grayscale; include hidden slides; frame slides. Choose Save as PDF in the print window for a quick PDF; File > Export > PDF gives searchable text. ## Agents diff --git a/frontend/src/io/api.ts b/frontend/src/io/api.ts index 1d342e1..9252caf 100644 --- a/frontend/src/io/api.ts +++ b/frontend/src/io/api.ts @@ -64,7 +64,7 @@ export const api = { template: (id: string, w = 960, h = 540) => get(`/api/templates/${encodeURIComponent(id)}?w=${w}&h=${h}`), applyTemplate: (deckId: string, template: string, client: string) => post<{ rev: number }>(`/api/decks/${deckId}/apply-template`, { template, client }), build: (body: { markdown?: string; spec?: unknown; template?: string; intake?: string; title?: string; size?: string }) => post('/api/build', body), - export: (deckId: string, format: string, path?: string, fontScales?: unknown, embedFonts?: string, clean?: boolean) => post<{ path: string; bytes: number; warnings?: string[] }>(`/api/decks/${deckId}/export`, { format, path, fontScales, embedFonts, clean }), + export: (deckId: string, format: string, path?: string, fontScales?: unknown, embedFonts?: string, clean?: boolean) => post<{ path: string; bytes: number; name: string; url: string; warnings?: string[] }>(`/api/decks/${deckId}/export`, { format, path, fontScales, embedFonts, clean }), save: (deckId: string, body: { path?: string; format?: string; fontScales?: unknown } = {}) => post<{ saved: string; bytes?: number }>(`/api/decks/${deckId}/save`, body), saveTemplate: (deckId: string, name: string) => post<{ template: string }>(`/api/decks/${deckId}/save-template`, { name }), versions: (deckId: string) => get<{ versions: Array<{ n: number; name: string; at: string; slides: number }> }>(`/api/decks/${deckId}/versions`), From c087fe476453e9ebfe1bb70b5203d8c55b015964 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 15:07:45 -0500 Subject: [PATCH 2/2] fix(export): keep new export names servable and leave no empty claim A deck title with a leading dash or dot, or a run of dots, gave an Exports file name that /api/exports refuses, so the url in the answer did not answer. write_new now tidies the name before claiming it, so every route that writes a new export hands out a url that is served. On a disk without hard links, a failed move over the empty claim now removes the claim, so a failed write leaves no file behind. --- backend/HASHOUT_LOG.md | 6 ++++++ backend/app/core/files.py | 18 ++++++++++++++++-- backend/tests/test_export_writes.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 6c2345d..91ffa0e 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -917,3 +917,9 @@ An export with no path went to the Exports folder under the deck's title, so a s `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/` 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/` 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. diff --git a/backend/app/core/files.py b/backend/app/core/files.py index 8b642b0..25b4f6f 100644 --- a/backend/app/core/files.py +++ b/backend/app/core/files.py @@ -1,4 +1,5 @@ import os +import re import shutil import tempfile from pathlib import Path @@ -49,12 +50,25 @@ def _claim(part: str, path: Path) -> bool: os.close(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, NEW_FILE_MODE)) except FileExistsError: return False - os.replace(part, path) + 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 = Path(folder) + 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: diff --git a/backend/tests/test_export_writes.py b/backend/tests/test_export_writes.py index 287c1d3..b71525a 100644 --- a/backend/tests/test_export_writes.py +++ b/backend/tests/test_export_writes.py @@ -177,3 +177,31 @@ def full(fd): with pytest.raises(OSError): files.write_new(tmp_path, "deck.pptx", b"x") assert list(tmp_path.iterdir()) == [] + + +def test_a_failed_move_on_a_disk_without_hard_links_leaves_no_empty_file(tmp_path, monkeypatch, failing_replace): + from app.core import files + + def no_links(src, dst, **kw): + raise OSError(1, "Operation not permitted") + + monkeypatch.setattr(os, "link", no_links) + with pytest.raises(OSError): + files.write_new(tmp_path, "deck.pptx", b"x") + assert list(tmp_path.iterdir()) == [] + + +@pytest.mark.parametrize("title", ["-Draft", "...Draft", "Draft..v2", "Draft."]) +def test_an_export_with_no_path_is_served_whatever_the_title(client, deck_from_script, title): + from conftest import call_tool + + deck = deck_from_script(f"# {title}\n\n## One\n- a") + for r in ( + client.post(f"/api/decks/{deck}/export", json={"format": "pptx"}).json(), + client.post(f"/api/decks/{deck}/outline", json={"format": "txt"}).json(), + call_tool(client, "export_deck", {"deck": deck, "format": "txt"})["structuredContent"], + ): + assert Path(r["path"]).parent == _exports() + served = client.get(r["url"]) + assert served.status_code == 200 + assert served.content == Path(r["path"]).read_bytes()