From e2bdac62623b5bbd0b3c1a356d93188939f0e2c3 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 11:46:45 +0000 Subject: [PATCH 1/3] feat(notes): download a note, or all of a namespace's notes, as Markdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A note's ⋯ menu in the tree has Download as Markdown, and the Notes page's ⋯ menu downloads every page of the namespace as a zip of Markdown files in folders that follow the tree, for Obsidian and other notes apps. Each file has front matter (title, date, filing, summary) and links to other notes as [[Title]] wiki links. GET /api/v1/notes/{pid}/markdown and GET /api/v1/notes/export?ns= give agents the same files. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01RrY2byt5BHVeBXJUyfwWpb --- CHANGELOG.md | 3 + docs/api.md | 5 +- docs/notes.md | 15 +++- fastapi_backend/app/api/v1/routes/notebook.py | 49 +++++++++++- fastapi_backend/app/domain/notebook.py | 62 +++++++++++++++ fastapi_backend/tests/api/test_notebook.py | 36 +++++++++ nextjs-frontend/__tests__/notes-find.test.tsx | 14 +++- .../__tests__/notes-today.test.tsx | 3 +- nextjs-frontend/__tests__/notes-tree.test.tsx | 14 +++- nextjs-frontend/app/openapi-client/index.ts | 9 +++ nextjs-frontend/app/openapi-client/sdk.gen.ts | 36 +++++++++ .../app/openapi-client/types.gen.ts | 58 ++++++++++++++ nextjs-frontend/components/notes/download.ts | 31 ++++++++ .../components/notes/notes-home.tsx | 50 ++++++++---- .../components/notes/notes-tree.tsx | 8 ++ nextjs-frontend/openapi.json | 78 +++++++++++++++++++ 16 files changed, 449 insertions(+), 22 deletions(-) create mode 100644 nextjs-frontend/components/notes/download.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ffe4587b..d0d225575 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Download notes as Markdown.** A note's ⋯ menu in the tree downloads it as a Markdown file, and the Notes page's ⋯ + menu downloads all of a namespace's notes as a zip in folders that follow the tree, for Obsidian and other notes apps + ([Downloading as Markdown](docs/notes.md#downloading-as-markdown)). - **Today's note.** Today on the Notes page, or Today's note in Jump to, opens the note for the day, made the first time it's asked for inside a Daily notes note ([Today's note](docs/notes.md#todays-note)). - **Pin notes.** A note's ⋯ menu in the tree has Pin: pinned notes show at the top of the tree and first on the diff --git a/docs/api.md b/docs/api.md index 53d05206b..dc1c1f5be 100644 --- a/docs/api.md +++ b/docs/api.md @@ -692,6 +692,7 @@ GET /api/v1/notes POST /api/v1/notes POST /api/v1/notes/today GET /api/v1/notes/search +GET /api/v1/notes/export GET /api/v1/notes/deleted POST /api/v1/notes/deleted/{pid}/restore DELETE /api/v1/notes/deleted/{pid} @@ -701,6 +702,7 @@ DELETE /api/v1/notes/{pid} POST /api/v1/notes/{pid}/move PUT /api/v1/notes/{pid}/pin DELETE /api/v1/notes/{pid}/pin +GET /api/v1/notes/{pid}/markdown GET /api/v1/notes/{pid}/history GET /api/v1/notes/{pid}/history/{vid} POST /api/v1/notes/{pid}/history/{vid}/restore @@ -717,7 +719,8 @@ matches first, each with the words around the match ([Finding notes](notes.md#fi moves a page to recently deleted for 30 days: `deleted` lists them, `restore` puts one back where it was and `DELETE /notes/deleted/{pid}` deletes one for good ([Deleting](notes.md#deleting-and-putting-back)). `move` puts a free note inside `parent` before `before`. `PUT …/pin` pins a page for you (`pinned` on each page says whether you -did) and `DELETE …/pin` unpins it ([Pinned notes](notes.md#pinned-notes)). `history` lists what the page was before +did) and `DELETE …/pin` unpins it ([Pinned notes](notes.md#pinned-notes)). `markdown` gives a page as a Markdown file and +`export?ns=` every page of a namespace as a zip of them ([Downloading](notes.md#downloading-as-markdown)). `history` lists what the page was before each change, and `restore` puts an earlier version back (what it was becomes a version too). `files` lists the files and images attached to a page; `blobs` uploads (in chunks) and reads them, and `DELETE …/files?key=` removes one. diff --git a/docs/notes.md b/docs/notes.md index 5a73c032a..fa672d27a 100644 --- a/docs/notes.md +++ b/docs/notes.md @@ -128,9 +128,9 @@ Free notes sit in a tree in the left navigation, under the main links. The links long tree has the whole height. A row opens its note, its arrow shows the notes inside it (the tree remembers which are open) and **+** adds a note inside. Each row's **⋯** menu, which always shows on a touch screen, adds a note inside, renames the note in place (Enter saves, Escape leaves it as it was), moves it (**Move to…** finds the note to put it in -by name, Enter picks the first; **Move to the top**), pins it ([below](#pinned-notes)) and deletes it with Undo. -Dragging a note onto another puts it inside, and onto the Notes heading moves it to the top. The pages of recordings -and entities aren't in the tree: they open from those things. +by name, Enter picks the first; **Move to the top**), pins it ([below](#pinned-notes)), downloads it as Markdown and +deletes it with Undo. Dragging a note onto another puts it inside, and onto the Notes heading moves it to the top. The +pages of recordings and entities aren't in the tree: they open from those things. `POST /api/v1/notes/{pid}/move` with `{parent}` moves a note (`null` for the top); `PATCH /api/v1/notes/{pid}` with `{title}` renames it. @@ -151,6 +151,15 @@ read access; up to 50 per namespace. **Unpin** (in the menu, or the button on it `PUT /api/v1/notes/{pid}/pin` pins and `DELETE` unpins; each page in `GET /api/v1/notes` says whether you pinned it (`pinned`). +## Downloading as Markdown + +**Download as Markdown** in a note's ⋯ menu in the tree saves it as a `.md` file, and **Download all as Markdown** +in the Notes page's ⋯ menu saves every page of the namespace as a zip of them, for Obsidian and other notes apps. Each +file starts with front matter (its title, date, where it's filed, its summary, what it's the page of), then its text: +links to other notes become `[[Title]]` wiki links and the rest the names they link to. In the zip, the notes inside a +note sit in a folder named like it, and the pages of recordings, entities and topics under `Pages of things`. +`GET /api/v1/notes/{pid}/markdown` and `GET /api/v1/notes/export?ns=` give the same files to agents. + ## Deleting and putting back **Delete** on a page deletes it at once, with no question first: the notice has **Undo**, which puts it back and opens diff --git a/fastapi_backend/app/api/v1/routes/notebook.py b/fastapi_backend/app/api/v1/routes/notebook.py index 045a9fca2..43218d06c 100644 --- a/fastapi_backend/app/api/v1/routes/notebook.py +++ b/fastapi_backend/app/api/v1/routes/notebook.py @@ -7,11 +7,12 @@ from __future__ import annotations import contextlib +import tempfile from typing import Any from urllib.parse import quote from fastapi import APIRouter, HTTPException, Query, Request -from fastapi.responses import StreamingResponse +from fastapi.responses import Response, StreamingResponse from starlette.concurrency import run_in_threadpool from app.api.deps import Access, Acl, Cfg, CurrentUser, Db, Principal, Writer, domain_errors @@ -170,6 +171,35 @@ def _trashed(acl: Access, db: DB, pid: int, role: str = "viewer") -> dict[str, A return t +def _attachment(name: str) -> str: + ascii_name = name.encode("ascii", "replace").decode().replace('"', "").replace("?", "_") + return f"attachment; filename=\"{ascii_name}\"; filename*=UTF-8''{quote(name)}" + + +@router.get( + "/export", + response_class=StreamingResponse, + responses={200: {"content": {"application/zip": {}}, "description": "a zip of Markdown files"}}, +) +def export_notes(ns: str, user: CurrentUser, acl: Acl, db: Db) -> StreamingResponse: + """Every page of the namespace as Markdown files in a zip, for other notes apps (Obsidian and the like): free notes + in folders that follow the tree, the pages of things under "Pages of things".""" + sid = acl.namespace(ns) + out = tempfile.SpooledTemporaryFile(max_size=32 * 1024 * 1024) + notebook.export(db, sid, out) + out.seek(0) + + def body(): + try: + while part := out.read(256 * 1024): + yield part + finally: + out.close() + + name = f"{notebook.file_name(ns)} notes.zip" + return StreamingResponse(body(), media_type="application/zip", headers={"Content-Disposition": _attachment(name)}) + + @router.get("/deleted") def deleted_pages( user: CurrentUser, @@ -278,6 +308,23 @@ def _version_out(db: DB, v: dict[str, Any], cls: type[NoteVersionItem] = NoteVer return cls(**{**{k: x for k, x in v.items() if k not in ("by", "page", "doc")}, "by": (who or {}).get("email")}) +@router.get( + "/{pid}/markdown", + response_class=Response, + responses={200: {"content": {"text/markdown": {}}, "description": "the page as a Markdown file"}}, +) +def page_markdown(pid: int, user: CurrentUser, acl: Acl, db: Db) -> Response: + """The page as a Markdown file of its own: front matter with its title, date, filing and summary, then its text, + with links to other pages as [[Title]] wiki links.""" + p = _page(acl, db, pid) + titles = {r["id"]: r["title"] for r in notebook.tree(db, p["space"], everything=True)} + return Response( + notebook.markdown(p, titles), + media_type="text/markdown; charset=utf-8", + headers={"Content-Disposition": _attachment(f"{notebook.file_name(p['title'])}.md")}, + ) + + @router.get("/{pid}/history") def page_history(pid: int, user: CurrentUser, acl: Acl, db: Db, limit: int = Query(50, ge=1, le=100)) -> NoteHistory: """What the page was before each change to its title, summary or text, newest first.""" diff --git a/fastapi_backend/app/domain/notebook.py b/fastapi_backend/app/domain/notebook.py index 096398ccf..ba85995e8 100644 --- a/fastapi_backend/app/domain/notebook.py +++ b/fastapi_backend/app/domain/notebook.py @@ -27,8 +27,10 @@ import base64 import datetime as dt import hashlib +import json import os import re +import zipfile from . import activity, store @@ -810,6 +812,66 @@ def labels(db, targets): return out +EXPORT_NAME_MAX = 100 # characters of a file's name, from the page's title +_UNSAFE = re.compile(r'[\\/:*?"<>|\x00-\x1f]+') + + +def file_name(title): + """A page's title as a file name that works everywhere: no slashes or other marks file systems refuse.""" + name = _UNSAFE.sub(" ", str(title or "")).strip(" .") + name = " ".join(name.split())[:EXPORT_NAME_MAX].rstrip(" .") + return name or "Untitled" + + +def markdown(p, titles=None): + """A page as a Markdown file of its own, for other notes apps: YAML front matter (its title, date, where it's + filed, its summary, what it's the page of), then its text. Links to other pages become [[Title]] wiki links (their + title now, from `titles` by id, else as written); links to anything else become its name.""" + titles = titles or {} + + def link(m): + sign, label, kind, key = m.groups() + if kind == "page": + return f"[[{titles.get(int(key), label)}]]" + return label if sign == "@" else f"#{label}" + + head = {"title": p.get("title"), "date": p.get("date"), "place": p.get("place"), "summary": p.get("summary")} + head["page_of"] = p.get("about") + lines = ["---", *(f"{k}: {json.dumps(v, ensure_ascii=False)}" for k, v in head.items() if v), "---", ""] + return "\n".join(lines) + MENTION.sub(link, p.get("body") or "").strip() + "\n" + + +THINGS = {"recording": "Recordings", "entity": "Entities", "topic": "Topics", "collection": "Collections", "speaker": "Speakers"} + + +def export(db, sid, out): + """Every page of the namespace as Markdown files in a zip written to `out`: free notes in folders that follow the + tree (a note's notes in a folder named like it), the pages of things under "Pages of things".""" + rows = db.rows(f"SELECT {FIELDS}, body FROM note_page WHERE space = $s", s=sid) + by_id = {p["id"]: p for p in rows} + titles = {i: p["title"] for i, p in by_id.items()} + + def folder(p, seen=()): + if p.get("about"): + return ["Pages of things", THINGS.get(p["about"].split(":")[0], "Other")] + up = by_id.get(p.get("parent")) if p.get("parent") is not None else None + if not up or up["id"] in seen or len(seen) > DEPTH_MAX: + return [] + return [*folder(up, (*seen, p["id"])), file_name(up["title"])] + + used = set() + with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z: + for p in sorted(rows, key=lambda r: (r.get("position") or 0, r["id"])): + base = "/".join([*folder(p), file_name(p["title"])]) + path, n = f"{base}.md", 1 + while path.casefold() in used: # two pages with one title in one place + n += 1 + path = f"{base} ({n}).md" + used.add(path.casefold()) + z.writestr(path, markdown(p, titles)) + return len(rows) + + SNIPPET = 160 diff --git a/fastapi_backend/tests/api/test_notebook.py b/fastapi_backend/tests/api/test_notebook.py index 8f3d79e31..5593ac7bf 100644 --- a/fastapi_backend/tests/api/test_notebook.py +++ b/fastapi_backend/tests/api/test_notebook.py @@ -591,3 +591,39 @@ def test_daily_notes(client, env, db): assert client.delete(f"/api/v1/notes/{root['id']}", headers=he).status_code == 200 again = client.post("/api/v1/notes/today", headers=he, json={"ns": "pods", "date": "2026-10-17"}).json() assert again["parent"] not in (None, root["id"]) + + +def test_markdown_export(client, env, db): + import io + import zipfile + + he, hv, hx = env["he"], env["hv"], env["hx"] + plans = _new(client, he, title="Plans: Q4", summary="What's next", place="project") + old = _new(client, he, title="Hiring", parent=plans["id"]) + _new(client, he, title="Budget", parent=plans["id"]) + _new(client, he, title="budget", parent=plans["id"]) # the same title twice in one place + ada = _entity(db, "Ada Lovelace", "PERSON") + body = f"Talk to @[Ada](entity:{ada['id']}) about @[Hiring](page:{old['id']})." + client.patch(f"/api/v1/notes/{plans['id']}", headers=he, json={"body": body}) + client.patch(f"/api/v1/notes/{old['id']}", headers=he, json={"title": "Hiring plan"}) + _new(client, he, title="Ada's page", about=f"entity:{ada['id']}") + + r = client.get(f"/api/v1/notes/{plans['id']}/markdown", headers=hv) + assert r.status_code == 200 and r.headers["content-type"].startswith("text/markdown") + assert "Plans Q4.md" not in r.headers["content-disposition"] and "Plans Q4.md" in r.headers["content-disposition"] + assert r.text.startswith('---\ntitle: "Plans: Q4"\n') + assert 'place: "project"' in r.text and 'summary: "What\'s next"' in r.text + assert r.text.endswith("Talk to Ada about [[Hiring plan]].\n") # the page's title now, the entity's name + assert client.get(f"/api/v1/notes/{plans['id']}/markdown", headers=hx).status_code == 404 + + r = client.get("/api/v1/notes/export?ns=pods", headers=hv) + assert r.status_code == 200 and r.headers["content-type"] == "application/zip" + names = sorted(zipfile.ZipFile(io.BytesIO(r.content)).namelist()) + assert names == [ + "Pages of things/Entities/Ada's page.md", + "Plans Q4.md", + "Plans Q4/Budget.md", + "Plans Q4/Hiring plan.md", + "Plans Q4/budget (2).md", + ] + assert client.get("/api/v1/notes/export?ns=pods", headers=hx).status_code == 404 diff --git a/nextjs-frontend/__tests__/notes-find.test.tsx b/nextjs-frontend/__tests__/notes-find.test.tsx index d690a693d..46e17675f 100644 --- a/nextjs-frontend/__tests__/notes-find.test.tsx +++ b/nextjs-frontend/__tests__/notes-find.test.tsx @@ -5,6 +5,7 @@ import "@testing-library/jest-dom"; import { Notes } from "@/app/openapi-client"; import { CommandPalette } from "@/components/app-shell/command-palette"; import { NotesHome } from "@/components/notes/notes-home"; +import { TooltipProvider } from "@/components/ui/tooltip"; jest.mock("@/app/openapi-client", () => ({ Notes: { @@ -19,6 +20,10 @@ jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: const push = jest.fn(); jest.mock("next/navigation", () => ({ usePathname: () => "/notes", useRouter: () => ({ push }) })); jest.mock("@/components/ui/toast", () => ({ useToast: () => jest.fn() })); +const download = jest.fn, [string, string | undefined, string]>(() => Promise.resolve()); +jest.mock("@/components/library/actions", () => ({ + downloadWithToken: (url: string, token: string | undefined, name: string) => download(url, token, name), +})); jest.mock("@/lib/hooks/session", () => ({ useArchive: () => ({ admin: false, @@ -33,7 +38,7 @@ const m = (f: unknown) => f as jest.Mock; const show = (ui: React.ReactNode) => render( - {ui} + {ui} , ); @@ -112,6 +117,13 @@ describe("the Notes page", () => { expect(screen.getByLabelText("Pinned")).toBeInTheDocument(); }); + it("downloads every note as Markdown from its menu", async () => { + show(); + fireEvent.keyDown(await screen.findByRole("button", { name: "More on Notes" }), { key: "Enter" }); + fireEvent.click(await screen.findByRole("menuitem", { name: "Download all as Markdown" })); + await waitFor(() => expect(download).toHaveBeenCalledWith("/api/v1/notes/export?ns=home", "t", "home notes.zip")); + }); + it("says when no note has the words", async () => { m(Notes.searchPages).mockImplementation(() => ok({ total: 0, pages: [] })); show(); diff --git a/nextjs-frontend/__tests__/notes-today.test.tsx b/nextjs-frontend/__tests__/notes-today.test.tsx index 80e6edfe7..d2e0e79c5 100644 --- a/nextjs-frontend/__tests__/notes-today.test.tsx +++ b/nextjs-frontend/__tests__/notes-today.test.tsx @@ -5,6 +5,7 @@ import "@testing-library/jest-dom"; import { Notes } from "@/app/openapi-client"; import { NotesHome } from "@/components/notes/notes-home"; import { TodayNote, localDay } from "@/components/notes/today"; +import { TooltipProvider } from "@/components/ui/tooltip"; jest.mock("@/app/openapi-client", () => ({ Notes: { @@ -35,7 +36,7 @@ const m = (f: unknown) => f as jest.Mock; const show = (ui: React.ReactNode) => render( - {ui} + {ui} , ); diff --git a/nextjs-frontend/__tests__/notes-tree.test.tsx b/nextjs-frontend/__tests__/notes-tree.test.tsx index ae23fab09..1e2495bcc 100644 --- a/nextjs-frontend/__tests__/notes-tree.test.tsx +++ b/nextjs-frontend/__tests__/notes-tree.test.tsx @@ -23,6 +23,10 @@ let pathname = "/notes"; jest.mock("next/navigation", () => ({ usePathname: () => pathname, useRouter: () => ({ push }) })); const toast = jest.fn(); jest.mock("@/components/ui/toast", () => ({ useToast: () => toast })); +const download = jest.fn, [string, string | undefined, string]>(() => Promise.resolve()); +jest.mock("@/components/library/actions", () => ({ + downloadWithToken: (url: string, token: string | undefined, name: string) => download(url, token, name), +})); let editor = true; jest.mock("@/lib/hooks/session", () => ({ useArchive: () => ({ namespaces: [{ name: "home" }], namespace: "home", can: () => editor }), @@ -138,12 +142,12 @@ describe("the notes tree", () => { expect(m(Notes.unpinPage).mock.calls[0][0].path).toEqual({ pid: 4 }); }); - it("lets someone who can only read pin, and nothing else", async () => { + it("lets someone who can only read pin and download, and nothing else", async () => { editor = false; show(); fireEvent.keyDown(await screen.findByRole("button", { name: "More for Trips" }), { key: "Enter" }); const items = await screen.findAllByRole("menuitem"); - expect(items.map((i) => i.textContent)).toEqual(["Pin"]); + expect(items.map((i) => i.textContent)).toEqual(["Pin", "Download as Markdown"]); expect(screen.queryByRole("button", { name: "New note inside Trips" })).not.toBeInTheDocument(); }); @@ -157,4 +161,10 @@ describe("the notes tree", () => { expect(toast.mock.calls[0][0].title).toBe("Couldn’t pin it"); expect(screen.queryByRole("group", { name: "Pinned notes" })).not.toBeInTheDocument(); }); + + it("downloads a note as Markdown", async () => { + show(); + await choose("Trips", "Download as Markdown"); + await waitFor(() => expect(download).toHaveBeenCalledWith("/api/v1/notes/4/markdown", "t", "Trips.md")); + }); }); diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 22f148525..9b3df2c05 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -894,6 +894,11 @@ export type { ExportBatchResultsError, ExportBatchResultsErrors, ExportBatchResultsResponses, + ExportNotesData, + ExportNotesError, + ExportNotesErrors, + ExportNotesResponse, + ExportNotesResponses, ExportRecordingData, ExportRecordingError, ExportRecordingErrors, @@ -2131,6 +2136,10 @@ export type { PageHistoryErrors, PageHistoryResponse, PageHistoryResponses, + PageMarkdownData, + PageMarkdownError, + PageMarkdownErrors, + PageMarkdownResponses, PageVersionData, PageVersionError, PageVersionErrors, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index b67a551f7..2f06d8362 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -425,6 +425,9 @@ import type { ExportBatchResultsData, ExportBatchResultsErrors, ExportBatchResultsResponses, + ExportNotesData, + ExportNotesErrors, + ExportNotesResponses, ExportRecordingData, ExportRecordingErrors, ExportRecordingResponses, @@ -1052,6 +1055,9 @@ import type { PageHistoryData, PageHistoryErrors, PageHistoryResponses, + PageMarkdownData, + PageMarkdownErrors, + PageMarkdownResponses, PageVersionData, PageVersionErrors, PageVersionResponses, @@ -5271,6 +5277,21 @@ export class Notes { }); } + /** + * Export Notes + * + * Every page of the namespace as Markdown files in a zip, for other notes apps (Obsidian and the like): free notes + * in folders that follow the tree, the pages of things under "Pages of things". + */ + public static exportNotes( + options: Options, + ): RequestResult { + return (options.client ?? client).get({ + url: "/api/v1/notes/export", + ...options, + }); + } + /** * Deleted Pages * @@ -5405,6 +5426,21 @@ export class Notes { }); } + /** + * Page Markdown + * + * The page as a Markdown file of its own: front matter with its title, date, filing and summary, then its text, + * with links to other pages as [[Title]] wiki links. + */ + public static pageMarkdown( + options: Options, + ): RequestResult { + return (options.client ?? client).get({ + url: "/api/v1/notes/{pid}/markdown", + ...options, + }); + } + /** * Page History * diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index a9ab644cd..8f3e5fc43 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -27453,6 +27453,36 @@ export type SearchPagesResponses = { export type SearchPagesResponse = SearchPagesResponses[keyof SearchPagesResponses]; +export type ExportNotesData = { + body?: never; + path?: never; + query: { + /** + * Ns + */ + ns: string; + }; + url: "/api/v1/notes/export"; +}; + +export type ExportNotesErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ExportNotesError = ExportNotesErrors[keyof ExportNotesErrors]; + +export type ExportNotesResponses = { + /** + * a zip of Markdown files + */ + 200: Blob | File; +}; + +export type ExportNotesResponse = ExportNotesResponses[keyof ExportNotesResponses]; + export type DeletedPagesData = { body?: never; path?: never; @@ -27737,6 +27767,34 @@ export type HomeSuggestionsResponses = { export type HomeSuggestionsResponse = HomeSuggestionsResponses[keyof HomeSuggestionsResponses]; +export type PageMarkdownData = { + body?: never; + path: { + /** + * Pid + */ + pid: number; + }; + query?: never; + url: "/api/v1/notes/{pid}/markdown"; +}; + +export type PageMarkdownErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type PageMarkdownError = PageMarkdownErrors[keyof PageMarkdownErrors]; + +export type PageMarkdownResponses = { + /** + * the page as a Markdown file + */ + 200: unknown; +}; + export type PageHistoryData = { body?: never; path: { diff --git a/nextjs-frontend/components/notes/download.ts b/nextjs-frontend/components/notes/download.ts new file mode 100644 index 000000000..93c4966ff --- /dev/null +++ b/nextjs-frontend/components/notes/download.ts @@ -0,0 +1,31 @@ +"use client"; + +import { useSession } from "next-auth/react"; +import { useCallback } from "react"; + +import { downloadWithToken } from "@/components/library/actions"; +import { useToast } from "@/components/ui/toast"; +import { ApiError } from "@/lib/api/browser"; + +/** Downloads notes as Markdown, for other notes apps: one note as a .md file, or a namespace's notes as a zip of them + * in folders that follow the tree. */ +export function useNoteDownloads() { + const { data: session } = useSession(); + const token = session?.accessToken; + const toast = useToast(); + const get = useCallback( + (url: string, name: string) => + downloadWithToken(url, token, name).catch((err) => + toast({ + title: "Couldn’t download it", + body: err instanceof ApiError ? err.message : "Please try again.", + tone: "red", + }), + ), + [token, toast], + ); + return { + note: (pid: number, title: string) => get(`/api/v1/notes/${pid}/markdown`, `${title || "Untitled"}.md`), + all: (ns: string) => get(`/api/v1/notes/export?ns=${encodeURIComponent(ns)}`, `${ns} notes.zip`), + }; +} diff --git a/nextjs-frontend/components/notes/notes-home.tsx b/nextjs-frontend/components/notes/notes-home.tsx index bf9dbf3dd..f96496fdd 100644 --- a/nextjs-frontend/components/notes/notes-home.tsx +++ b/nextjs-frontend/components/notes/notes-home.tsx @@ -1,7 +1,7 @@ "use client"; import { keepPreviousData, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query"; -import { CalendarDays, FileText, NotebookPen, Pin, Plus, Search, Sparkles } from "lucide-react"; +import { CalendarDays, Download, Ellipsis, FileText, NotebookPen, Pin, Plus, Search, Sparkles } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useMemo, useState } from "react"; @@ -9,9 +9,11 @@ import { useMemo, useState } from "react"; import { Notes } from "@/app/openapi-client"; import type { NotePageItem } from "@/app/openapi-client/types.gen"; import { PLACES, pageOf } from "@/components/notes/links"; +import { useNoteDownloads } from "@/components/notes/download"; import { RecentlyDeleted } from "@/components/notes/recently-deleted"; -import { Button } from "@/components/ui/button"; +import { Button, IconButton } from "@/components/ui/button"; import { SearchInput } from "@/components/ui/field"; +import { Menu, MenuContent, MenuItem, MenuTrigger } from "@/components/ui/menu"; import { EmptyState, PageHeader, SkeletonRows } from "@/components/ui/states"; import { Segmented } from "@/components/ui/tabs"; import { useToast } from "@/components/ui/toast"; @@ -96,6 +98,25 @@ export function NotesHome() { New note ) : null; + const downloads = useNoteDownloads(); + // Every namespace's notes as Markdown, for other notes apps + const more = + names.length > 0 ? ( + + + + + + + + {names.map((ns) => ( + } onSelect={() => void downloads.all(ns)}> + {names.length > 1 ? `Download ${ns}’s notes as Markdown` : "Download all as Markdown"} + + ))} + + + ) : null; const placeLabel = (v?: string | null) => PLACES.find((p) => p.value === v)?.label; /** "Home lab › Parts": the notes this one is inside, outermost first. */ const path = (r: Row) => { @@ -118,17 +139,20 @@ export function NotesHome() { title="Notes" meta={namespace ?? "All namespaces"} actions={ - editable && ( - <> - - {newNote} - - ) + <> + {editable && ( + <> + + {newNote} + + )} + {more} + } /> {(all.length > 0 || q) && ( diff --git a/nextjs-frontend/components/notes/notes-tree.tsx b/nextjs-frontend/components/notes/notes-tree.tsx index 23dbdc235..ef67d33d9 100644 --- a/nextjs-frontend/components/notes/notes-tree.tsx +++ b/nextjs-frontend/components/notes/notes-tree.tsx @@ -4,6 +4,7 @@ import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/rea import { ArrowUpToLine, ChevronRight, + Download, Ellipsis, FileText, FolderInput, @@ -21,6 +22,7 @@ import { useEffect, useMemo, useState, type DragEvent } from "react"; import { Notes } from "@/app/openapi-client"; import type { NotePageItem as PageItem } from "@/app/openapi-client/types.gen"; import { useDeleteNote } from "@/components/notes/delete"; +import { useNoteDownloads } from "@/components/notes/download"; import { usePin } from "@/components/notes/pin"; import { Dialog } from "@/components/ui/dialog"; import { FindBox } from "@/components/ui/find-box"; @@ -188,6 +190,7 @@ function NamespaceNotes({ }); const deleteNote = useDeleteNote(); const pin = usePin(); + const downloads = useNoteDownloads(); const pathname = usePathname(); const [renaming, setRenaming] = useState(null); const [moving, setMoving] = useState(null); @@ -205,6 +208,7 @@ function NamespaceNotes({ }, startMove: setMoving, pin: (p, on) => void pin(ns, p.id, on), + download: (p) => void downloads.note(p.id, p.title), remove: async (p) => { // deleting the note that's open leaves it for the Notes page if ((await deleteNote(p.id, p.title)) && pathname === `/notes/${p.id}`) router.push("/notes"); @@ -296,6 +300,7 @@ type RowActions = { moveTo: (id: number, parent: number | null) => void; startMove: (page: PageItem) => void; pin: (page: PageItem, on: boolean) => void; + download: (page: PageItem) => void; remove: (page: PageItem) => void; }; @@ -487,6 +492,9 @@ function Node({ : } onSelect={() => actions.pin(page, !page.pinned)}> {page.pinned ? "Unpin" : "Pin"} + } onSelect={() => actions.download(page)}> + Download as Markdown + {canEdit && ( <> diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 8c38e44ed..51bb50bcf 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -10104,6 +10104,45 @@ } } }, + "/api/v1/notes/export": { + "get": { + "tags": [ + "notes" + ], + "summary": "Export Notes", + "description": "Every page of the namespace as Markdown files in a zip, for other notes apps (Obsidian and the like): free notes\nin folders that follow the tree, the pages of things under \"Pages of things\".", + "operationId": "export_notes", + "parameters": [ + { + "name": "ns", + "in": "query", + "required": true, + "schema": { + "type": "string", + "title": "Ns" + } + } + ], + "responses": { + "200": { + "description": "a zip of Markdown files", + "content": { + "application/zip": {} + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/notes/deleted": { "get": { "tags": [ @@ -10535,6 +10574,45 @@ } } }, + "/api/v1/notes/{pid}/markdown": { + "get": { + "tags": [ + "notes" + ], + "summary": "Page Markdown", + "description": "The page as a Markdown file of its own: front matter with its title, date, filing and summary, then its text,\nwith links to other pages as [[Title]] wiki links.", + "operationId": "page_markdown", + "parameters": [ + { + "name": "pid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Pid" + } + } + ], + "responses": { + "200": { + "description": "the page as a Markdown file", + "content": { + "text/markdown": {} + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/notes/{pid}/history": { "get": { "tags": [ From 904f7289dc935584f23a1b5169253bd50a187944 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 14:46:41 +0000 Subject: [PATCH 2/3] test(clicks): entity-merge waits for the imports' jobs, as graph-merge does On a slow runner import-file's pi-episode was still being read (40s in Chromium) when entity-merge ran; its mentions of Lens and Raspberry Pi landed between the merge and its Undo, and graph-merge then found neither in the graph (Clicks and keystrokes per feature on #419). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01RrY2byt5BHVeBXJUyfwWpb --- ci/clicks/journeys.mjs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ci/clicks/journeys.mjs b/ci/clicks/journeys.mjs index cadacf9fd..6cf75183d 100644 --- a/ci/clicks/journeys.mjs +++ b/ci/clicks/journeys.mjs @@ -651,6 +651,11 @@ export const JOURNEYS = [ from: "/", async run(ctx) { const { page, meter } = ctx; + // A slow machine can still be reading import-file's pi-episode here, and its mentions of Lens and Raspberry Pi + // landing between the merge and its Undo leave both out of the graph for graph-merge; so wait for the jobs to + // finish (not counted) + const idle = page.getByRole("button", { name: /^Activity: (Nothing running|\d+ failed)$/ }); + await madeInBackground(ctx, "/", idle, "/", "the imports' jobs finished"); await go(ctx, "Entities"); const main = page.getByRole("main"); await meter.click(main.getByRole("checkbox", { name: "Pick Lens", exact: true }), "tick Lens"); From 97c8ff56cb33da1c05da11d9f90f99bd86bc6448 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sat, 17 Oct 2026 03:15:03 +0000 Subject: [PATCH 3/3] docs(changelog): put the Markdown download entry last under Unreleased Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01RrY2byt5BHVeBXJUyfwWpb --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c91cfe5d5..d5d9e8087 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,6 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased -- **Download notes as Markdown.** A note's ⋯ menu in the tree downloads it as a Markdown file, and the Notes page's ⋯ - menu downloads all of a namespace's notes as a zip in folders that follow the tree, for Obsidian and other notes apps - ([Downloading as Markdown](docs/notes.md#downloading-as-markdown)). - **Punctuation put back in transcripts.** With transcripts cleaned up, Settings → Analysis → Put punctuation back adds full stops, commas and question marks with a local model (kredor/punctuate-all, MIT, 12 languages), to transcripts that have hardly any (imported captions) or to every one, keeping the marks they have. The model and @@ -60,6 +57,9 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version registries or the public web. Files attached to the conversation go in; a file it makes reaches a namespace once the person approves. Off by default; starting the gateway from Settings is in progress ([Code sandbox](docs/assistant.md#code-sandbox)). +- **Download notes as Markdown.** A note's ⋯ menu in the tree downloads it as a Markdown file, and the Notes page's ⋯ + menu downloads all of a namespace's notes as a zip in folders that follow the tree, for Obsidian and other notes apps + ([Downloading as Markdown](docs/notes.md#downloading-as-markdown)). ## 0.13.0 October 16, 2026 {id="0.13.0"}