From cfcfa6423001d354fce9359218a306e417224717 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 11:23:52 +0000 Subject: [PATCH 1/2] feat(notes): delete a note with Undo, and put it back from Recently deleted Deleting a note no longer asks first: it goes to note_trash under its own id for 30 days, with its files and history, and the notice's Undo puts it back where it was, with the notes that were inside it. The Notes page lists recently deleted notes to put back or delete for good; the notes pass empties ones older than 30 days. GET /notes/deleted, POST /notes/deleted/{pid}/restore, DELETE /notes/deleted/{pid}. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01RrY2byt5BHVeBXJUyfwWpb --- CHANGELOG.md | 4 + docs/api.md | 7 +- docs/notes.md | 16 +- fastapi_backend/app/api/v1/routes/notebook.py | 62 +++++- fastapi_backend/app/domain/notebook.py | 122 +++++++++-- fastapi_backend/app/domain/store.py | 3 + fastapi_backend/app/schemas/notebook.py | 9 + fastapi_backend/tests/api/test_notebook.py | 73 ++++++- .../__tests__/notes-delete.test.tsx | 94 +++++++++ nextjs-frontend/__tests__/notes-find.test.tsx | 7 +- nextjs-frontend/app/openapi-client/index.ts | 16 ++ nextjs-frontend/app/openapi-client/sdk.gen.ts | 54 ++++- .../app/openapi-client/types.gen.ts | 129 ++++++++++++ nextjs-frontend/components/notes/delete.ts | 60 ++++++ .../components/notes/note-page.tsx | 17 +- .../components/notes/notes-home.tsx | 2 + .../components/notes/recently-deleted.tsx | 111 ++++++++++ nextjs-frontend/openapi.json | 197 +++++++++++++++++- 18 files changed, 946 insertions(+), 37 deletions(-) create mode 100644 nextjs-frontend/__tests__/notes-delete.test.tsx create mode 100644 nextjs-frontend/components/notes/delete.ts create mode 100644 nextjs-frontend/components/notes/recently-deleted.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 27439f1b3..10c41f829 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Delete a note with Undo.** Deleting a note no longer asks first: the notice has Undo, which puts it back where it + was. Deleted notes wait in Recently deleted, at the bottom of the Notes page, for 30 days with their files and + history, to put back with one click or delete for good; then they go on their own + ([Deleting and putting back](docs/notes.md#deleting-and-putting-back)). - **The Ask button no longer covers buttons.** The floating Ask button at the bottom right used to sit on whatever was there, such as Import on the Import page. Now, when a button or field is under it and scrolling can't move it clear (a row of buttons pinned to the bottom of the screen, or the last button on a page scrolled to its end), the Ask diff --git a/docs/api.md b/docs/api.md index 1ec2dc8e6..ee9ff1933 100644 --- a/docs/api.md +++ b/docs/api.md @@ -629,6 +629,9 @@ deleted. GET /api/v1/notes POST /api/v1/notes GET /api/v1/notes/search +GET /api/v1/notes/deleted +POST /api/v1/notes/deleted/{pid}/restore +DELETE /api/v1/notes/deleted/{pid} GET /api/v1/notes/{pid} PATCH /api/v1/notes/{pid} DELETE /api/v1/notes/{pid} @@ -644,7 +647,9 @@ DELETE /api/v1/notes/{pid}/files Note pages ([Notes](notes.md)), apart from the notes on a recording above. `GET /notes?ns=` is a namespace's page tree (`all=true` adds the pages of things). `search?q=` finds pages by the words in their title, summary or text, title -matches first, each with the words around the match ([Finding notes](notes.md#finding-notes)). `move` puts a free note inside `parent` before `before`, `history` lists what the +matches first, each with the words around the match ([Finding notes](notes.md#finding-notes)). `DELETE /notes/{pid}` +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`, `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 ab894df54..117ddbccc 100644 --- a/docs/notes.md +++ b/docs/notes.md @@ -66,7 +66,8 @@ Images, attachments and other files dropped or pasted into a page are kept where WebDAV), encrypted with the namespace's key before they leave the machine. The editor names each by the SHA-256 of its bytes, so the same file is kept once per page, and the server checks the name matches the bytes. Anyone who reads the page reads its files; editors add them (`PUT /api/v1/notes/{id}/blobs?key=…`, up to `server.max_upload_mb`). Images -and PDFs show in place; anything a browser could run (HTML, SVG) only downloads. Deleting the page deletes its files. +and PDFs show in place; anything a browser could run (HTML, SVG) only downloads. A deleted page keeps its files while it +can be put back; deleting it for good deletes them. The assistant sees a page's files (names, types, sizes) when it reads it. ## Filing (PARA) @@ -97,6 +98,19 @@ refining it, or someone else always starts a new one. **History** on a page list it; pick one to read it, and editors can restore it. Restoring keeps the page as it was too, so it can be undone. `GET /api/v1/notes/{id}/history`, `GET .../history/{version}` and `POST .../history/{version}/restore`. +## 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 +it. The notes inside it move up a level, and links to it show without a name while it's gone. A deleted page waits in +**Recently deleted**, at the bottom of the Notes page, for 30 days with its files and history: **Put back** returns it +where it was, with the notes that were inside it (those nobody moved since), and **Delete now** (clicked twice) deletes +it for good. After 30 days it goes for good on its own, with its files and history. A thing's page comes back as its +page, or as a free note at the top when the thing is gone or has a new page by now. + +`DELETE /api/v1/notes/{pid}` deletes; `GET /api/v1/notes/deleted?ns=` lists recently deleted pages, +`POST /api/v1/notes/deleted/{pid}/restore` puts one back and `DELETE /api/v1/notes/deleted/{pid}` deletes one for good +(editors). The assistant never deletes notes. + ## Finding notes The **Notes** page lists the free notes in view, the latest changed first, each with the notes it sits inside diff --git a/fastapi_backend/app/api/v1/routes/notebook.py b/fastapi_backend/app/api/v1/routes/notebook.py index e63ac981f..4b531a8da 100644 --- a/fastapi_backend/app/api/v1/routes/notebook.py +++ b/fastapi_backend/app/api/v1/routes/notebook.py @@ -22,6 +22,7 @@ from app.domain.store import DB from app.schemas.common import Ok from app.schemas.notebook import ( + NoteDeleted, NoteFile, NoteHistory, NoteHit, @@ -143,6 +144,58 @@ def search_pages( ) +def _trashed(acl: Access, db: DB, pid: int, role: str = "viewer") -> dict[str, Any]: + try: + t = notebook.trashed(db, pid) + except KeyError: + raise HTTPException(404, "not found") from None + acl.need(t["space"], role) + return t + + +@router.get("/deleted") +def deleted_pages( + user: CurrentUser, + acl: Acl, + db: Db, + ns: str | None = Query(None, description="only this namespace (default: every one you can read)"), +) -> list[NoteDeleted]: + """Pages deleted in the last 30 days, the latest first: each can be put back until then.""" + names = store.space_names(db) + spaces = [acl.namespace(ns)] if ns else (list(names) if user.admin else acl.spaces()) + rows = notebook.trash(db, spaces) + who = {a: (db.one("SELECT VALUE email FROM $r", r=store.R("account", a)) or None) for a in {r.get("deleted_by") for r in rows} if a} + return [ + NoteDeleted( + id=r["id"], + title=r.get("title") or "Untitled", + about=r.get("about"), + namespace=names.get(r["space"], ""), + deleted_at=r["deleted_at"], + deleted_by=who.get(r.get("deleted_by")), + ) + for r in rows + ] + + +@router.post("/deleted/{pid}/restore") +def restore_deleted(pid: int, user: Writer, acl: Acl, db: Db) -> NotePage: + """Put a deleted page back where it was, with its links, files and history (Undo after Delete). Editors.""" + _trashed(acl, db, pid, "editor") + with domain_errors(): + p = notebook.undelete(db, pid) + return _out(acl, db, p, user) + + +@router.delete("/deleted/{pid}") +def purge_deleted(pid: int, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> Ok: + """Delete a deleted page for good now, with its files and history, rather than after 30 days. Editors.""" + _trashed(acl, db, pid, "editor") + with _vault(): + notebook.purge(db, pid, cfg) + return Ok() + + @router.get("/about/{kind}/{key}") def page_about(kind: str, key: int, user: CurrentUser, acl: Acl, db: Db) -> NotePage | NotePageDraft: """The page of a recording, entity, topic, collection or speaker: its page, or a draft while nobody has written one.""" @@ -247,11 +300,12 @@ def move_page(pid: int, body: NotePageMove, user: Writer, acl: Acl, db: Db) -> N @router.delete("/{pid}") -def delete_page(pid: int, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> Ok: - """Delete a page; the pages inside it move up a level. Needs editor access.""" +def delete_page(pid: int, user: Writer, acl: Acl, db: Db) -> Ok: + """Delete a page; the pages inside it move up a level. It can be put back from recently deleted for + `TRASH_DAYS` (30) days (`POST /notes/deleted/{pid}/restore`). Needs editor access.""" _page(acl, db, pid, "editor") - with _vault(): - notebook.delete(db, pid, cfg) + with domain_errors(): + notebook.delete(db, pid, user.id) return Ok() diff --git a/fastapi_backend/app/domain/notebook.py b/fastapi_backend/app/domain/notebook.py index fe77afa69..8557c880e 100644 --- a/fastapi_backend/app/domain/notebook.py +++ b/fastapi_backend/app/domain/notebook.py @@ -413,20 +413,113 @@ def move(db, pid, parent=None, before=None): db.q("UPDATE $r SET parent = $p, position = $pos, updated_at = $t", r=R("note_page", int(pid)), p=parent, pos=position, t=store.now()) -def delete(db, pid, cfg=None): - """Delete a page, with its files (given `cfg`, to reach where they are kept); the pages inside it move up to its - parent. Links to it stay as text.""" - p = get(db, pid) - if cfg is not None: - for f in files(db, int(pid)): - delete_file(db, cfg, int(pid), f["key"]) - for child in db.values("SELECT VALUE record::id(id) FROM note_page WHERE parent = $p", p=int(pid)): +TRASH_DAYS = 30 # a deleted page can be put back for this long, then it's gone with its files and history + + +def delete(db, pid, account=None): + """Delete a page: it goes to the namespace's recently deleted (note_trash, under its own id) for TRASH_DAYS, with + its files and history kept, so it can be put back (undelete). The pages inside it move up to its parent. Links to + it stay as text, and show without a name while it's gone.""" + p = db.one("SELECT * OMIT id FROM $r", r=R("note_page", int(pid))) + if not p: + raise KeyError(pid) + children = db.values("SELECT VALUE record::id(id) FROM note_page WHERE parent = $p", p=int(pid)) + for child in children: db.q("UPDATE $r SET parent = $up", r=R("note_page", child), up=p.get("parent")) db.q("DELETE note_link WHERE page = $p", p=int(pid)) - db.q("DELETE note_version WHERE page = $p", p=int(pid)) + db.q( + "UPSERT $r CONTENT $d", + r=R("note_trash", int(pid)), + d=store.clean( + { + "space": p["space"], + "title": p.get("title"), + "about": p.get("about"), + "page": p, + "children": children, + "deleted_at": store.now(), + "deleted_by": account, + } + ), + ) db.q("DELETE $r", r=R("note_page", int(pid))) +TRASH_FIELDS = "record::id(id) AS id, space, title, about, deleted_at, deleted_by" + + +def trash(db, spaces, limit=100): + """The pages deleted from these namespaces that can still be put back, the latest deleted first.""" + return db.rows( + f"SELECT {TRASH_FIELDS} FROM note_trash WHERE space IN $s ORDER BY deleted_at DESC LIMIT $n", + s=list(spaces), + n=int(limit), + ) + + +def trashed(db, pid): + """A deleted page's trash row (its page under `page`), or KeyError.""" + t = db.one(f"SELECT {TRASH_FIELDS}, page, children FROM $r", r=R("note_trash", int(pid))) + if not t: + raise KeyError(pid) + return t + + +def undelete(db, pid): + """Put a deleted page back where it was, with its links, files and history, and the pages that were inside it + back inside it (those still where they moved to). A thing's page that the thing no longer has (it's gone, moved + away, or has a new page by now) comes back as a free note at the top. Returns the page.""" + t = trashed(db, pid) + p, sid = dict(t["page"]), t["space"] + if p.get("about"): + kind, key = _about(p["about"]) + try: + kept = owner(db, kind, key) == sid and not db.one( + "SELECT VALUE id FROM note_page WHERE about_key = $k LIMIT 1", k=p.get("about_key") + ) + except KeyError: + kept = False + if not kept: + p.update(about=None, about_key=None, parent=None, position=_last_position(db, sid, None)) + parent = p.get("parent") + if parent is not None and not db.one("SELECT VALUE id FROM $r WHERE space = $s", r=R("note_page", int(parent)), s=sid): + p.update(parent=None, position=_last_position(db, sid, None)) + db.q("CREATE $r CONTENT $d", r=R("note_page", int(pid)), d=store.clean(p)) + for child in t.get("children") or []: + c = db.one("SELECT parent, space FROM $r", r=R("note_page", int(child))) + if c and c.get("space") == sid and c.get("parent") == t["page"].get("parent"): # still where it moved up to + db.q("UPDATE $r SET parent = $p", r=R("note_page", int(child)), p=int(pid)) + _links(db, int(pid), sid, p.get("body") or "") + db.q("DELETE $r", r=R("note_trash", int(pid))) + return get(db, pid) + + +def purge(db, pid, cfg=None): + """Delete a page from recently deleted for good: with its files (given `cfg`, to reach where they are kept) and + its history.""" + t = trashed(db, pid) + if cfg is not None: + for f in files(db, int(pid)): + delete_file(db, cfg, int(pid), f["key"], space=t["space"]) + db.q("DELETE note_file WHERE page = $p", p=int(pid)) + db.q("DELETE note_version WHERE page = $p", p=int(pid)) + db.q("DELETE $r", r=R("note_trash", int(pid))) + + +def purge_due(db, cfg, log=None): + """The pages deleted more than TRASH_DAYS ago, gone for good. How many.""" + before = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(days=TRASH_DAYS)).isoformat(timespec="seconds") + gone = 0 + for pid in db.values("SELECT VALUE record::id(id) FROM note_trash WHERE deleted_at < $t LIMIT 50", t=before): + try: + purge(db, pid, cfg) + gone += 1 + except Exception as e: # noqa: BLE001 - one page's files shouldn't stop the rest + if log: + log(f"note {pid}: {type(e).__name__}: {e}") + return gone + + def links(db, pid): """The page's links, in the order its body has them.""" p = get(db, pid) @@ -512,12 +605,13 @@ def _space_of(db, pid): return get(db, pid)["space"] -def delete_file(db, cfg, pid, key): - """Remove a file from a page and from where it's kept.""" +def delete_file(db, cfg, pid, key, space=None): + """Remove a file from a page and from where it's kept (`space`: the page's namespace, for a deleted page).""" from . import blobs row = file_row(db, pid, key) - blobs.delete(db, cfg, row.get("where"), f"notes/{_space_of(db, pid)}/{int(pid)}/{row['id']}") + sid = space if space is not None else _space_of(db, pid) + blobs.delete(db, cfg, row.get("where"), f"notes/{sid}/{int(pid)}/{row['id']}") db.q("DELETE $r", r=R("note_file", row["id"])) @@ -912,5 +1006,5 @@ def file_due(db, cfg, log=None): def organise_due(db, cfg, log=None): - """The notes pass the scheduler runs: titles and summaries first, then filing.""" - return refine_due(db, cfg, log) + file_due(db, cfg, log) + """The notes pass the scheduler runs: titles and summaries first, then filing, then emptying old deletions.""" + return refine_due(db, cfg, log) + file_due(db, cfg, log) + purge_due(db, cfg, log) diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index 669133df4..5a1f28121 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -1416,6 +1416,9 @@ def close(self): # what a page was before each change (notebook.snapshot): its history, to look back at and restore "DEFINE TABLE IF NOT EXISTS note_version SCHEMALESS", "DEFINE INDEX IF NOT EXISTS note_version_page ON note_version FIELDS page", + # deleted pages, under their own id, until they're put back or TRASH_DAYS pass (notebook.delete) + "DEFINE TABLE IF NOT EXISTS note_trash SCHEMALESS", + "DEFINE INDEX IF NOT EXISTS note_trash_space ON note_trash FIELDS space", # the files on a note page (images, attachments), kept where Settings → Storage says (notebook.py, blobs.py) "DEFINE TABLE IF NOT EXISTS note_file SCHEMALESS", "DEFINE INDEX IF NOT EXISTS note_file_page ON note_file FIELDS page, key", diff --git a/fastapi_backend/app/schemas/notebook.py b/fastapi_backend/app/schemas/notebook.py index e62e68eee..a674675d7 100644 --- a/fastapi_backend/app/schemas/notebook.py +++ b/fastapi_backend/app/schemas/notebook.py @@ -111,6 +111,15 @@ class NoteHit(ResponseModel): snippet: str | None = Field(None, description="the words around the match in its text, when the text has it") +class NoteDeleted(ResponseModel): + id: int + title: str + about: str | None = Field(None, description='what it was the page of, like "recording:12"; null for a free note') + namespace: str + deleted_at: str + deleted_by: str | None = Field(None, description="who deleted it (their email)") + + class NoteSearch(ResponseModel): total: int = Field(description="how many pages match; `pages` has the first `limit`") pages: list[NoteHit] diff --git a/fastapi_backend/tests/api/test_notebook.py b/fastapi_backend/tests/api/test_notebook.py index 247ac3ebe..08e9419c1 100644 --- a/fastapi_backend/tests/api/test_notebook.py +++ b/fastapi_backend/tests/api/test_notebook.py @@ -353,8 +353,10 @@ def test_page_history(client, env, db, cfg, llm): notebook.refine_due(db, cfg) h2 = client.get(f"/api/v1/notes/{p['id']}/history", headers=he).json()["versions"] assert h2[0]["author"] == "assistant" and h2[0]["by"] is None and len(h2) == len(h) + 1 - # deleting the page drops its history + # deleting the page keeps its history while it can be put back; deleting it for good drops it client.delete(f"/api/v1/notes/{p['id']}", headers=he) + assert db.rows("SELECT id FROM note_version WHERE page = $p", p=p["id"]) + client.delete(f"/api/v1/notes/deleted/{p['id']}", headers=he) assert not db.rows("SELECT id FROM note_version WHERE page = $p", p=p["id"]) @@ -461,9 +463,76 @@ def test_page_files(client, env, db, cfg, folder): # kept where Settings → Storage says: here, data_dir/objects kept = list((folder / "data" / "objects" / "notes").rglob("*")) assert len([k for k in kept if k.is_file()]) == 2 - # removing one, then the page, removes what was kept + # removing one removes what was kept; deleting the page keeps its files until it's deleted for good assert client.delete(f"/api/v1/notes/{p['id']}/files", params={"key": KS}, headers=he).status_code == 200 assert client.get(url, params={"key": KS}, headers=hv).status_code == 404 assert client.delete(f"/api/v1/notes/{p['id']}", headers=he).status_code == 200 + assert len([k for k in (folder / "data" / "objects" / "notes").rglob("*") if k.is_file()]) == 1 + assert client.post(f"/api/v1/notes/deleted/{p['id']}/restore", headers=he).status_code == 200 + assert client.get(url, params={"key": KP}, headers=hv).content == png # back with the page + assert client.delete(f"/api/v1/notes/{p['id']}", headers=he).status_code == 200 + assert client.delete(f"/api/v1/notes/deleted/{p['id']}", headers=hv).status_code == 403 + assert client.delete(f"/api/v1/notes/deleted/{p['id']}", headers=he).status_code == 200 assert not [k for k in (folder / "data" / "objects" / "notes").rglob("*") if k.is_file()] assert not db.rows("SELECT id FROM note_file") + + +def test_recently_deleted(client, env, db, cfg): + he, hv, hx = env["he"], env["hv"], env["hx"] + plans = _new(client, he, title="Plans", place="project", body="See @[Ideas](page:999).") + hiring = _new(client, he, title="Hiring", parent=plans["id"]) + budget = _new(client, he, title="Budget", parent=plans["id"], body=f"For @[Plans](page:{plans['id']}).") + client.patch(f"/api/v1/notes/{plans['id']}", headers=he, json={"body": "Version two."}) + # deleting moves what's inside up a level, and the page into recently deleted + assert client.delete(f"/api/v1/notes/{plans['id']}", headers=he).status_code == 200 + assert client.get(f"/api/v1/notes/{plans['id']}", headers=hv).status_code == 404 + tree = client.get("/api/v1/notes?ns=pods", headers=hv).json()["pages"] + assert sorted((p["title"], p["parent"]) for p in tree) == [("Budget", None), ("Hiring", None)] + assert client.get("/api/v1/notes/search?q=version", headers=hv).json()["total"] == 0 + gone = client.get("/api/v1/notes/deleted?ns=pods", headers=hv).json() + assert [(d["id"], d["title"], d["namespace"], d["deleted_by"]) for d in gone] == [(plans["id"], "Plans", "pods", "ed@x.io")] + assert client.get("/api/v1/notes/deleted", headers=hx).json() == [] + assert client.get("/api/v1/notes/deleted?ns=pods", headers=hx).status_code == 404 + # a link to it shows without a name while it's gone + links = client.get(f"/api/v1/notes/{budget['id']}", headers=hv).json()["links"] + assert links[0]["target"] == f"page:{plans['id']}" and links[0]["name"] is None + # viewers can't put it back; editors can, where it was, with what was inside it, its links and history + assert client.post(f"/api/v1/notes/deleted/{plans['id']}/restore", headers=hv).status_code == 403 + r = client.post(f"/api/v1/notes/deleted/{plans['id']}/restore", headers=he) + assert r.status_code == 200, r.text + back = r.json() + assert (back["id"], back["title"], back["place"], back["body"]) == (plans["id"], "Plans", "project", "Version two.") + tree = client.get("/api/v1/notes?ns=pods", headers=hv).json()["pages"] + assert sorted((p["title"], p["parent"]) for p in tree) == [("Budget", plans["id"]), ("Hiring", plans["id"]), ("Plans", None)] + assert [b["page"] for b in back["backlinks"]] == [budget["id"]] + assert client.get(f"/api/v1/notes/{plans['id']}/history", headers=hv).json()["versions"] + assert client.get("/api/v1/notes/deleted?ns=pods", headers=hv).json() == [] + assert client.post(f"/api/v1/notes/deleted/{plans['id']}/restore", headers=he).status_code == 404 + # a page that moved out meanwhile stays where it is + assert client.delete(f"/api/v1/notes/{plans['id']}", headers=he).status_code == 200 + client.post(f"/api/v1/notes/{hiring['id']}/move", headers=he, json={"parent": budget["id"]}) + client.post(f"/api/v1/notes/deleted/{plans['id']}/restore", headers=he) + tree = {p["title"]: p["parent"] for p in client.get("/api/v1/notes?ns=pods", headers=hv).json()["pages"]} + assert tree == {"Plans": None, "Budget": plans["id"], "Hiring": budget["id"]} + # a thing's page comes back as its page, unless the thing has a new one by now: then as a free note + a = env["a"] + about = _new(client, he, title="Episode", about=f"recording:{a}", body="First take") + client.delete(f"/api/v1/notes/{about['id']}", headers=he) + assert client.get(f"/api/v1/notes/about/recording/{a}", headers=hv).json()["id"] is None + again = _new(client, he, title="Episode", about=f"recording:{a}", body="Second take") + back = client.post(f"/api/v1/notes/deleted/{about['id']}/restore", headers=he).json() + assert back["about"] is None and back["body"] == "First take" + assert client.get(f"/api/v1/notes/about/recording/{a}", headers=hv).json()["id"] == again["id"] + client.delete(f"/api/v1/notes/{again['id']}", headers=he) + assert client.post(f"/api/v1/notes/deleted/{again['id']}/restore", headers=he).json()["about"] == f"recording:{a}" + + +def test_deleted_pages_go_after_a_while(client, env, db, cfg): + he = env["he"] + old, new = _new(client, he, title="Old"), _new(client, he, title="New") + client.delete(f"/api/v1/notes/{old['id']}", headers=he) + client.delete(f"/api/v1/notes/{new['id']}", headers=he) + db.q("UPDATE $r SET deleted_at = '2000-01-01T00:00:00+00:00'", r=R("note_trash", old["id"])) + assert notebook.purge_due(db, cfg) == 1 + assert [d["title"] for d in client.get("/api/v1/notes/deleted?ns=pods", headers=he).json()] == ["New"] + assert not db.rows("SELECT id FROM note_version WHERE page = $p", p=old["id"]) diff --git a/nextjs-frontend/__tests__/notes-delete.test.tsx b/nextjs-frontend/__tests__/notes-delete.test.tsx new file mode 100644 index 000000000..861b524cb --- /dev/null +++ b/nextjs-frontend/__tests__/notes-delete.test.tsx @@ -0,0 +1,94 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import "@testing-library/jest-dom"; + +import { Notes } from "@/app/openapi-client"; +import { useDeleteNote } from "@/components/notes/delete"; +import { RecentlyDeleted } from "@/components/notes/recently-deleted"; + +jest.mock("@/app/openapi-client", () => ({ + Notes: { deletePage: jest.fn(), restoreDeleted: jest.fn(), deletedPages: jest.fn(), purgeDeleted: jest.fn() }, +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); +const push = jest.fn(); +jest.mock("next/navigation", () => ({ useRouter: () => ({ push }) })); +const toast = jest.fn(); +jest.mock("@/components/ui/toast", () => ({ useToast: () => toast })); +jest.mock("@/lib/hooks/session", () => ({ useArchive: () => ({ can: () => true }) })); + +const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); +const m = (f: unknown) => f as jest.Mock; +const show = (ui: React.ReactNode) => + render( + + {ui} + , + ); + +beforeEach(() => jest.clearAllMocks()); + +function DeleteButton() { + const del = useDeleteNote(); + return ; +} + +describe("deleting a note", () => { + it("deletes at once and the notice's Undo puts it back and opens it", async () => { + m(Notes.deletePage).mockImplementation(() => ok({ ok: true })); + m(Notes.restoreDeleted).mockImplementation(() => ok({ id: 7, title: "Plans" })); + show(); + fireEvent.click(screen.getByRole("button", { name: "Delete" })); + await waitFor(() => expect(toast).toHaveBeenCalled()); + expect(m(Notes.deletePage).mock.calls[0][0].path).toEqual({ pid: 7 }); + const notice = toast.mock.calls[0][0]; + expect(notice.title).toBe("Deleted “Plans”"); + expect(notice.action.label).toBe("Undo"); + notice.action.onClick(); + await waitFor(() => expect(push).toHaveBeenCalledWith("/notes/7")); + expect(m(Notes.restoreDeleted).mock.calls[0][0].path).toEqual({ pid: 7 }); + }); + + it("opens a thing's page where it belongs after Undo", async () => { + m(Notes.deletePage).mockImplementation(() => ok({ ok: true })); + m(Notes.restoreDeleted).mockImplementation(() => ok({ id: 7, title: "Ada", about: "entity:5" })); + show(); + fireEvent.click(screen.getByRole("button", { name: "Delete" })); + await waitFor(() => expect(toast).toHaveBeenCalled()); + toast.mock.calls[0][0].action.onClick(); + await waitFor(() => expect(push).toHaveBeenCalledWith("/notes/about/entity/5")); + }); +}); + +describe("recently deleted", () => { + const gone = [ + { id: 3, title: "Old plans", namespace: "home", deleted_at: new Date().toISOString(), deleted_by: "ed@x.io" }, + ]; + + it("puts a note back with one click", async () => { + m(Notes.deletedPages).mockImplementation(() => ok(gone)); + m(Notes.restoreDeleted).mockImplementation(() => ok({ id: 3, title: "Old plans" })); + show(); + expect(await screen.findByText("Old plans")).toBeInTheDocument(); + expect(screen.getByText(/by ed@x\.io/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Put back" })); + await waitFor(() => expect(push).toHaveBeenCalledWith("/notes/3")); + }); + + it("deletes one for good only on a second click", async () => { + m(Notes.deletedPages).mockImplementation(() => ok(gone)); + m(Notes.purgeDeleted).mockImplementation(() => ok({ ok: true })); + show(); + fireEvent.click(await screen.findByRole("button", { name: "Delete now" })); + expect(Notes.purgeDeleted).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Delete for good" })); + await waitFor(() => expect(Notes.purgeDeleted).toHaveBeenCalled()); + expect(m(Notes.purgeDeleted).mock.calls[0][0].path).toEqual({ pid: 3 }); + }); + + it("shows nothing while nothing was deleted", async () => { + m(Notes.deletedPages).mockImplementation(() => ok([])); + const { container } = show(); + await waitFor(() => expect(Notes.deletedPages).toHaveBeenCalled()); + expect(container).toBeEmptyDOMElement(); + }); +}); diff --git a/nextjs-frontend/__tests__/notes-find.test.tsx b/nextjs-frontend/__tests__/notes-find.test.tsx index 86a380760..6a1aa04e0 100644 --- a/nextjs-frontend/__tests__/notes-find.test.tsx +++ b/nextjs-frontend/__tests__/notes-find.test.tsx @@ -7,7 +7,12 @@ import { CommandPalette } from "@/components/app-shell/command-palette"; import { NotesHome } from "@/components/notes/notes-home"; jest.mock("@/app/openapi-client", () => ({ - Notes: { listPages: jest.fn(), searchPages: jest.fn(), createPage: jest.fn() }, + Notes: { + listPages: jest.fn(), + searchPages: jest.fn(), + createPage: jest.fn(), + deletedPages: jest.fn(() => Promise.resolve({ data: [], response: { ok: true, status: 200 } })), + }, Resources: { listRecordings: jest.fn(() => Promise.resolve({ data: [], response: { ok: true, status: 200 } })) }, })); jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index c5089f60c..afec79cad 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -621,6 +621,11 @@ export type { DeleteCustomNodeErrors, DeleteCustomNodeResponse, DeleteCustomNodeResponses, + DeletedPagesData, + DeletedPagesError, + DeletedPagesErrors, + DeletedPagesResponse, + DeletedPagesResponses, DeleteEntityData, DeleteEntityError, DeleteEntityErrors, @@ -2011,6 +2016,7 @@ export type { Note, NoteBacklink, NoteCreate, + NoteDeleted, NoteFile, NoteHistory, NoteHit, @@ -2212,6 +2218,11 @@ export type { PublicSegment, PublicSpeaker, PublicTranscript, + PurgeDeletedData, + PurgeDeletedError, + PurgeDeletedErrors, + PurgeDeletedResponse, + PurgeDeletedResponses, PushData, Pushed, PushResponse, @@ -2431,6 +2442,11 @@ export type { RestoreBackupErrors, RestoreBackupResponse, RestoreBackupResponses, + RestoreDeletedData, + RestoreDeletedError, + RestoreDeletedErrors, + RestoreDeletedResponse, + RestoreDeletedResponses, RestoreStart, RestoreVersionData, RestoreVersionError, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 4f8b95d2a..97f2e3b5e 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -285,6 +285,9 @@ import type { DeleteCustomNodeData, DeleteCustomNodeErrors, DeleteCustomNodeResponses, + DeletedPagesData, + DeletedPagesErrors, + DeletedPagesResponses, DeleteEntityData, DeleteEntityErrors, DeleteEntityResponses, @@ -1075,6 +1078,9 @@ import type { ProposeGraphChangeData, ProposeGraphChangeErrors, ProposeGraphChangeResponses, + PurgeDeletedData, + PurgeDeletedErrors, + PurgeDeletedResponses, PushData, PushResponses, PushStreamData, @@ -1186,6 +1192,9 @@ import type { RestoreBackupData, RestoreBackupErrors, RestoreBackupResponses, + RestoreDeletedData, + RestoreDeletedErrors, + RestoreDeletedResponses, RestoreVersionData, RestoreVersionErrors, RestoreVersionResponses, @@ -5131,6 +5140,48 @@ export class Notes { }); } + /** + * Deleted Pages + * + * Pages deleted in the last 30 days, the latest first: each can be put back until then. + */ + public static deletedPages( + options?: Options, + ): RequestResult { + return (options?.client ?? client).get({ + url: "/api/v1/notes/deleted", + ...options, + }); + } + + /** + * Restore Deleted + * + * Put a deleted page back where it was, with its links, files and history (Undo after Delete). Editors. + */ + public static restoreDeleted( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/notes/deleted/{pid}/restore", + ...options, + }); + } + + /** + * Purge Deleted + * + * Delete a deleted page for good now, with its files and history, rather than after 30 days. Editors. + */ + public static purgeDeleted( + options: Options, + ): RequestResult { + return (options.client ?? client).delete({ + url: "/api/v1/notes/deleted/{pid}", + ...options, + }); + } + /** * Page About * @@ -5148,7 +5199,8 @@ export class Notes { /** * Delete Page * - * Delete a page; the pages inside it move up a level. Needs editor access. + * Delete a page; the pages inside it move up a level. It can be put back from recently deleted for + * `TRASH_DAYS` (30) days (`POST /notes/deleted/{pid}/restore`). Needs editor access. */ public static deletePage( options: Options, diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index c497f38ab..db460b721 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -9771,6 +9771,41 @@ export type NoteCreate = { shared?: boolean; }; +/** + * NoteDeleted + */ +export type NoteDeleted = { + /** + * Id + */ + id: number; + /** + * Title + */ + title: string; + /** + * About + * + * what it was the page of, like "recording:12"; null for a free note + */ + about?: string | null; + /** + * Namespace + */ + namespace: string; + /** + * Deleted At + */ + deleted_at: string; + /** + * Deleted By + * + * who deleted it (their email) + */ + deleted_by?: string | null; + [key: string]: unknown; +}; + /** * NoteFile */ @@ -26709,6 +26744,100 @@ export type SearchPagesResponses = { export type SearchPagesResponse = SearchPagesResponses[keyof SearchPagesResponses]; +export type DeletedPagesData = { + body?: never; + path?: never; + query?: { + /** + * Ns + * + * only this namespace (default: every one you can read) + */ + ns?: string | null; + }; + url: "/api/v1/notes/deleted"; +}; + +export type DeletedPagesErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type DeletedPagesError = DeletedPagesErrors[keyof DeletedPagesErrors]; + +export type DeletedPagesResponses = { + /** + * Response Notes-Deleted Pages + * + * Successful Response + */ + 200: Array; +}; + +export type DeletedPagesResponse = DeletedPagesResponses[keyof DeletedPagesResponses]; + +export type RestoreDeletedData = { + body?: never; + path: { + /** + * Pid + */ + pid: number; + }; + query?: never; + url: "/api/v1/notes/deleted/{pid}/restore"; +}; + +export type RestoreDeletedErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type RestoreDeletedError = RestoreDeletedErrors[keyof RestoreDeletedErrors]; + +export type RestoreDeletedResponses = { + /** + * Successful Response + */ + 200: NotePage; +}; + +export type RestoreDeletedResponse = RestoreDeletedResponses[keyof RestoreDeletedResponses]; + +export type PurgeDeletedData = { + body?: never; + path: { + /** + * Pid + */ + pid: number; + }; + query?: never; + url: "/api/v1/notes/deleted/{pid}"; +}; + +export type PurgeDeletedErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type PurgeDeletedError = PurgeDeletedErrors[keyof PurgeDeletedErrors]; + +export type PurgeDeletedResponses = { + /** + * Successful Response + */ + 200: Ok; +}; + +export type PurgeDeletedResponse = PurgeDeletedResponses[keyof PurgeDeletedResponses]; + export type PageAboutData = { body?: never; path: { diff --git a/nextjs-frontend/components/notes/delete.ts b/nextjs-frontend/components/notes/delete.ts new file mode 100644 index 000000000..a323ab4ae --- /dev/null +++ b/nextjs-frontend/components/notes/delete.ts @@ -0,0 +1,60 @@ +"use client"; + +import { useQueryClient } from "@tanstack/react-query"; +import { useRouter } from "next/navigation"; +import { useCallback } from "react"; + +import { Notes } from "@/app/openapi-client"; +import { pageOf } from "@/components/notes/links"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; + +/** Deletes a note at once, with Undo on the notice instead of a question first: a deleted note waits in recently + * deleted (on the Notes page) for 30 days, and Undo puts it back where it was and opens it. Resolves true once it's + * deleted. */ +export function useDeleteNote() { + const client = useApiClient(); + const qc = useQueryClient(); + const router = useRouter(); + const toast = useToast(); + const fail = useCallback( + (title: string) => (err: unknown) => + toast({ title, body: err instanceof ApiError ? err.message : "Please try again.", tone: "red" }), + [toast], + ); + const refresh = useCallback(() => { + qc.invalidateQueries({ queryKey: ["notes-tree"] }); + qc.invalidateQueries({ queryKey: ["notes-search"] }); + qc.invalidateQueries({ queryKey: ["notes-deleted"] }); + }, [qc]); + return useCallback( + async (pid: number, title: string): Promise => { + try { + await data(Notes.deletePage({ client, path: { pid } })); + } catch (err) { + fail("Couldn’t delete it")(err); + return false; + } + qc.removeQueries({ queryKey: ["note", pid] }); + refresh(); + toast({ + title: `Deleted “${title}”`, + body: "It’s in Recently deleted on the Notes page for 30 days.", + duration: 8000, + action: { + label: "Undo", + onClick: () => + void data(Notes.restoreDeleted({ client, path: { pid } })) + .then((p) => { + qc.setQueryData(["note", pid], p); + refresh(); + router.push(p.about ? pageOf(p.about) : `/notes/${pid}`); + }) + .catch(fail("Couldn’t put it back")), + }, + }); + return true; + }, + [client, qc, router, toast, fail, refresh], + ); +} diff --git a/nextjs-frontend/components/notes/note-page.tsx b/nextjs-frontend/components/notes/note-page.tsx index 56ac93aeb..133133c4a 100644 --- a/nextjs-frontend/components/notes/note-page.tsx +++ b/nextjs-frontend/components/notes/note-page.tsx @@ -11,6 +11,7 @@ import { Notes } from "@/app/openapi-client"; import type { NotePage as Page, NotePageDraft as PageDraft } from "@/app/openapi-client/types.gen"; import { ActivityPanel } from "@/components/costs/costs"; import type { EditorBlobs, EditorChange, LinkTarget } from "@/components/notes/block-editor"; +import { useDeleteNote } from "@/components/notes/delete"; import { HomeSuggestion } from "@/components/notes/home-suggestions"; import { LinkSuggestions } from "@/components/notes/link-suggestions"; import { NoteHistory } from "@/components/notes/note-history"; @@ -217,20 +218,12 @@ export function NotePage({ id, about }: { id?: number; about?: string }) { [router, page?.namespace], ); + // No question first: the notice has Undo, and the note waits in recently deleted + const deleteNote = useDeleteNote(); const remove = async () => { if (savedId.current == null) return; - if (!window.confirm("Delete this note? The notes inside it move up a level.")) return; - try { - await data(Notes.deletePage({ client, path: { pid: savedId.current } })); - qc.invalidateQueries({ queryKey: ["notes-tree"] }); - router.push("/notes"); - } catch (err) { - toast({ - title: "Couldn’t delete it", - body: err instanceof ApiError ? err.message : "Please try again.", - tone: "red", - }); - } + await flush(); // what was just typed is kept with it, for Undo + if (await deleteNote(savedId.current, title.trim() || page?.title || "Untitled")) router.push("/notes"); }; if (q.isError) diff --git a/nextjs-frontend/components/notes/notes-home.tsx b/nextjs-frontend/components/notes/notes-home.tsx index a80ced6b6..0024a6e69 100644 --- a/nextjs-frontend/components/notes/notes-home.tsx +++ b/nextjs-frontend/components/notes/notes-home.tsx @@ -9,6 +9,7 @@ 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 { RecentlyDeleted } from "@/components/notes/recently-deleted"; import { Button } from "@/components/ui/button"; import { SearchInput } from "@/components/ui/field"; import { EmptyState, PageHeader, SkeletonRows } from "@/components/ui/states"; @@ -213,6 +214,7 @@ export function NotesHome() { )} )} + ); } diff --git a/nextjs-frontend/components/notes/recently-deleted.tsx b/nextjs-frontend/components/notes/recently-deleted.tsx new file mode 100644 index 000000000..2ed7d8a3c --- /dev/null +++ b/nextjs-frontend/components/notes/recently-deleted.tsx @@ -0,0 +1,111 @@ +"use client"; + +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { RotateCcw, Trash2 } from "lucide-react"; +import { useRouter } from "next/navigation"; +import { useState } from "react"; + +import { Notes } from "@/app/openapi-client"; +import { pageOf } from "@/components/notes/links"; +import { Button } from "@/components/ui/button"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; +import { relative } from "@/lib/format"; +import { useArchive } from "@/lib/hooks/session"; + +/** The notes deleted in the last 30 days, under the Notes page's list: each goes back where it was with one click. + * Deleting one for good now takes a second click on the same button (it can't be undone); otherwise they go on their + * own after 30 days. Nothing shows while there are none. */ +export function RecentlyDeleted({ ns }: { ns: string | null }) { + const client = useApiClient(); + const qc = useQueryClient(); + const router = useRouter(); + const toast = useToast(); + const { can } = useArchive(); + const [sure, setSure] = useState(null); // the one whose Delete now was clicked once + const list = useQuery({ + queryKey: ["notes-deleted", ns], + queryFn: () => data(Notes.deletedPages({ client, query: { ns } })), + }); + const fail = (title: string) => (err: unknown) => + toast({ title, body: err instanceof ApiError ? err.message : "Please try again.", tone: "red" }); + const refresh = () => { + qc.invalidateQueries({ queryKey: ["notes-deleted"] }); + qc.invalidateQueries({ queryKey: ["notes-tree"] }); + qc.invalidateQueries({ queryKey: ["notes-search"] }); + }; + const putBack = useMutation({ + mutationFn: (pid: number) => data(Notes.restoreDeleted({ client, path: { pid } })), + onSuccess: (p) => { + refresh(); + router.push(p.about ? pageOf(p.about) : `/notes/${p.id}`); + }, + onError: fail("Couldn’t put it back"), + }); + const purge = useMutation({ + mutationFn: (pid: number) => data(Notes.purgeDeleted({ client, path: { pid } })), + onSuccess: (_, pid) => { + setSure(null); + refresh(); + toast({ title: "Deleted for good", tone: "green" }); + qc.setQueryData(["notes-deleted", ns], (xs: { id: number }[] | undefined) => xs?.filter((x) => x.id !== pid)); + }, + onError: fail("Couldn’t delete it"), + }); + const items = list.data ?? []; + if (!items.length) return null; + return ( +
+ + Recently deleted {items.length} + +
    + {items.map((d) => { + const editor = can("editor", d.namespace); + return ( +
  • + + {d.title} + + {[ + d.about ? `Page of ${d.about.split(":")[0]}` : null, + ns ? null : d.namespace, + `deleted ${relative(d.deleted_at)}`, + d.deleted_by ? `by ${d.deleted_by}` : null, + ] + .filter(Boolean) + .join(" · ")} + + + {editor && ( + <> + + + + )} +
  • + ); + })} +
+

+ Deleted notes go for good after 30 days, with their files and history. +

+
+ ); +} diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 9f5da21a8..6caab63fb 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -9836,6 +9836,148 @@ } } }, + "/api/v1/notes/deleted": { + "get": { + "tags": [ + "notes" + ], + "summary": "Deleted Pages", + "description": "Pages deleted in the last 30 days, the latest first: each can be put back until then.", + "operationId": "deleted_pages", + "parameters": [ + { + "name": "ns", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "only this namespace (default: every one you can read)", + "title": "Ns" + }, + "description": "only this namespace (default: every one you can read)" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/NoteDeleted" + }, + "title": "Response Notes-Deleted Pages" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/notes/deleted/{pid}/restore": { + "post": { + "tags": [ + "notes" + ], + "summary": "Restore Deleted", + "description": "Put a deleted page back where it was, with its links, files and history (Undo after Delete). Editors.", + "operationId": "restore_deleted", + "parameters": [ + { + "name": "pid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Pid" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NotePage" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/notes/deleted/{pid}": { + "delete": { + "tags": [ + "notes" + ], + "summary": "Purge Deleted", + "description": "Delete a deleted page for good now, with its files and history, rather than after 30 days. Editors.", + "operationId": "purge_deleted", + "parameters": [ + { + "name": "pid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Pid" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Ok" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/notes/about/{kind}/{key}": { "get": { "tags": [ @@ -9994,7 +10136,7 @@ "notes" ], "summary": "Delete Page", - "description": "Delete a page; the pages inside it move up a level. Needs editor access.", + "description": "Delete a page; the pages inside it move up a level. It can be put back from recently deleted for\n`TRASH_DAYS` (30) days (`POST /notes/deleted/{pid}/restore`). Needs editor access.", "operationId": "delete_page", "parameters": [ { @@ -44239,6 +44381,59 @@ ], "title": "NoteCreate" }, + "NoteDeleted": { + "properties": { + "id": { + "type": "integer", + "title": "Id" + }, + "title": { + "type": "string", + "title": "Title" + }, + "about": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "About", + "description": "what it was the page of, like \"recording:12\"; null for a free note" + }, + "namespace": { + "type": "string", + "title": "Namespace" + }, + "deleted_at": { + "type": "string", + "title": "Deleted At" + }, + "deleted_by": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Deleted By", + "description": "who deleted it (their email)" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "id", + "title", + "namespace", + "deleted_at" + ], + "title": "NoteDeleted" + }, "NoteFile": { "properties": { "key": { From 79eb1f9c6b9efa89326b8b69a9806a215beb4709 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 13:01:51 +0000 Subject: [PATCH 2/2] test(notes): Undo opens an entity's page at its new address Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01RrY2byt5BHVeBXJUyfwWpb --- nextjs-frontend/__tests__/notes-delete.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nextjs-frontend/__tests__/notes-delete.test.tsx b/nextjs-frontend/__tests__/notes-delete.test.tsx index 861b524cb..8f6165d54 100644 --- a/nextjs-frontend/__tests__/notes-delete.test.tsx +++ b/nextjs-frontend/__tests__/notes-delete.test.tsx @@ -55,7 +55,7 @@ describe("deleting a note", () => { fireEvent.click(screen.getByRole("button", { name: "Delete" })); await waitFor(() => expect(toast).toHaveBeenCalled()); toast.mock.calls[0][0].action.onClick(); - await waitFor(() => expect(push).toHaveBeenCalledWith("/notes/about/entity/5")); + await waitFor(() => expect(push).toHaveBeenCalledWith("/entities/5")); }); });