From 3991847d5754da824541b29502040726ea1415cc Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 4 Oct 2026 10:11:50 +0000 Subject: [PATCH 1/2] feat(notes): the assistant keeps notes and files them in PARA Four chat tools keep notes as the assistant's notebook: it looks there first and writes what it learns, linked with @ and #. Writing needs editor access and takes effect at once. Notes nobody filed are filed in projects, areas, resources or archives by a decision model (or the LLM) once their summary is written; when it isn't sure, its suggestion waits on the note (ai.organise_notes, on by default). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01XZQXJtCvJgbG1Z2H312KcS --- DEVLOG.md | 8 +- docs/notes.md | 21 ++- fastapi_backend/app/domain/ai_tools.py | 155 ++++++++++++++++++ fastapi_backend/app/domain/chat.py | 4 +- fastapi_backend/app/domain/notebook.py | 66 +++++++- fastapi_backend/app/domain/routines.py | 2 +- fastapi_backend/app/domain/store.py | 1 + fastapi_backend/app/schemas/notebook.py | 8 + fastapi_backend/tests/api/test_notebook.py | 63 +++++++ nextjs-frontend/app/openapi-client/index.ts | 1 + .../app/openapi-client/types.gen.ts | 41 +++++ .../components/notes/note-page.tsx | 14 ++ .../components/settings/bodies.tsx | 1 + nextjs-frontend/components/settings/model.ts | 11 ++ nextjs-frontend/openapi.json | 85 ++++++++++ 15 files changed, 470 insertions(+), 11 deletions(-) diff --git a/DEVLOG.md b/DEVLOG.md index 498442c9c..623aa446d 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -163,9 +163,11 @@ Todo: text kept for search and the assistant - [x] AI title and summary refinement (ai.refine_notes, on by default, can be switched off) - [ ] Costs of refinement to the activity ledger (once "Activity history and budgets" lands) -- [ ] Assistant and MCP tools: find, read, write, link and file notes; changes by the assistant are undoable -- [ ] Self-organising: a routine files notes into PARA and links them to entities and topics, proposing what it isn't - sure of +- [x] Assistant tools: find, read, write and update notes (at once, no approval: notes are its notebook) +- [ ] MCP tools to read notes; page history so the assistant's changes can be undone +- [x] Self-organising, first step: notes nobody filed are filed in PARA by a decision model (or the LLM), with a + suggestion when it isn't sure (ai.organise_notes) +- [ ] Self-organising, next: link notes to entities and topics, nest them under their project or area - [ ] # topics move to the SKOS topics once the graph thread splits them from entities - [ ] Attachments on a page, encrypted through the keyring - [ ] Object storage (S3, or an rclone remote served as S3) in the setup wizard, no local storage; a downloadable diff --git a/docs/notes.md b/docs/notes.md index 891408371..81ad659cc 100644 --- a/docs/notes.md +++ b/docs/notes.md @@ -4,9 +4,9 @@ Every resource, entity and topic in Lens has a page of its own, and next to them assistant write. The assistant is the main writer and organiser; people can do everything it can. Status: **built**: pages (free notes in a tree, a page per recording, entity, collection or speaker), @ and # links -with backlinks, the tree in the left navigation, the page view with the BlockSuite editor, and the model keeping -titles and summaries up to date. **Planned**: assistant and MCP tools, a routine that files notes (PARA and the -ontology), attachments on encrypted object storage, pages in the graph, # links to SKOS topics. +with backlinks, the tree in the left navigation, the page view with the BlockSuite editor, the model keeping titles +and summaries up to date, and assistant tools to find, read, write and update notes. **Planned**: MCP tools, page +history, linking notes to entities and topics and nesting them under their project or area on their own, attachments on encrypted object storage, pages in the graph, # links to SKOS topics. ## A page @@ -49,6 +49,21 @@ typed is never sent on each keystroke, empty notes are never sent, and nothing i API and `lens worker` processes run this pass with the routines. Model calls are measured by telemetry; their costs go to the activity ledger once it exists. +## Filing (PARA) + +With **Settings → Assistant → File notes in projects, areas, resources and archives** (`ai.organise_notes`, on by +default), free notes nobody filed are filed once their summary is written. It's a routine decision, so a decision model +takes it when one is set up (Settings → Assistant), else the language model. When it's sure (`decisions.act_above`) the +note is filed (`place_by: assistant`); otherwise its best guess waits on the note as a suggestion to accept with one +click. What a person files is never refiled. + +## The assistant + +The chat assistant keeps notes as its notebook: `find_notes`, `read_note`, `write_note` and `update_note` (Settings → +Assistant lists them). It looks there first, and writes or updates a note when it learns something worth keeping, +filed in PARA and linked with @ and #. Writing needs editor access to the namespace and takes effect at once, with no +approval: notes it writes say so. It never deletes a note. + ## Access Pages belong to a namespace: anyone with a role there reads them, editors write, move and delete them. The pages of diff --git a/fastapi_backend/app/domain/ai_tools.py b/fastapi_backend/app/domain/ai_tools.py index 4917c63e2..161553376 100644 --- a/fastapi_backend/app/domain/ai_tools.py +++ b/fastapi_backend/app/domain/ai_tools.py @@ -18,6 +18,7 @@ graph_ask, graph_model, entity_setup, + notebook, ops_tools, recsets, render, @@ -83,6 +84,58 @@ False, ), ("speaker_stats", "Speakers in a namespace with talk time and recordings.", {"namespace": _S}, ["namespace"], False), + ( + "find_notes", + "Find notes (free notes and the pages of recordings, entities, collections and speakers) in scope by words in " + "their title, summary or text. Each has an id, title, one-line summary, where it's filed (PARA) and what it's " + "the page of.", + {"query": _S, "namespace": _S, "place": _S, "limit": _I}, + [], + False, + ), + ( + "read_note", + "Read a note's Markdown, with its links and the notes linking to it: by note_id, or the page of a thing " + '(about, like "recording:12" or "entity:5").', + {"note_id": _I, "about": _S}, + [], + False, + ), + ( + "write_note", + 'Write a new note, or the page of a thing (about, like "entity:5"; one each). You keep notes as you learn: ' + "a specific title, a one-line summary of what it holds, Markdown text, and where it's filed: project (an " + "outcome with an end), area (a responsibility kept up), resource (a topic of interest) or archive (done). Link " + "with @[label](recording:12), @[label](entity:5), @[label](page:3), and topics with #[label](entity:9) (ids " + "from find_entities, find_notes and list_recordings). Put it inside another note with parent_id.", + { + "namespace": _S, + "title": _S, + "body": _S, + "summary": _S, + "place": {"type": "string", "enum": list(notebook.PLACES)}, + "parent_id": _I, + "about": _S, + }, + ["namespace", "title", "body"], + True, + ), + ( + "update_note", + "Change a note: its title, summary, place, or its text (body replaces it; append adds to the end). Move a free " + "note in the tree with parent_id (0: the top).", + { + "note_id": _I, + "title": _S, + "summary": _S, + "place": {"type": "string", "enum": list(notebook.PLACES)}, + "body": _S, + "append": _S, + "parent_id": _I, + }, + ["note_id"], + True, + ), ( "graph_schema", "What the graph holds (namespaces, collections, recordings, speakers, entities and how they link), with example " @@ -642,6 +695,108 @@ def t_run_template(self, template_id, recording_ids=None, collection_id=None): est = batches.estimate(self.db, self.cfg, ids, steps) return self._approval("run_template", {"template_id": t["id"], "recordings": ids}, f"Run {label} on {len(ids)} recording(s)", est) + # ---- notes (notebook.py): the assistant reads and writes them at once; they're its notebook ---- + def _note(self, note_id, edit=False): + try: + p = notebook.get(self.db, int(note_id)) + except KeyError: + raise ValueError(f"no note {note_id}") from None + if p["space"] not in (self.editable if edit else self.readable): + raise ValueError(f"note {note_id} isn't {'yours to change' if edit else 'available'} in this conversation") + return p + + def _space(self, namespace, edit=False): + names = {v: k for k, v in store.space_names(self.db).items()} + sid = names.get(namespace) + if sid not in (self.editable if edit else self.readable): + raise ValueError(f"no namespace called {namespace} {'you can write in' if edit else 'in scope'}") + return sid + + def t_find_notes(self, query=None, namespace=None, place=None, limit=10): + spaces = [self._space(namespace)] if namespace else sorted(self.readable) + names = store.space_names(self.db) + q = " ".join(str(query or "").split()).casefold() + rows = self.db.rows( + "SELECT record::id(id) AS id, space, title, summary, place, about, updated_at, text FROM note_page WHERE space IN $s", + s=spaces, + ) + hits = [ + r + for r in rows + if (not place or r.get("place") == place) + and (not q or any(q in str(r.get(k) or "").casefold() for k in ("title", "summary", "text"))) + ] + hits.sort(key=lambda r: (q not in str(r["title"]).casefold(), r.get("updated_at") or ""), reverse=False) + out = [ + store.clean( + { + "id": r["id"], + "title": r["title"], + "summary": r.get("summary"), + "place": r.get("place"), + "page_of": r.get("about"), + "namespace": names.get(r["space"]), + } + ) + for r in hits[: min(int(limit or 10), 30)] + ] + return {"total": len(hits), "notes": out}, f"Found {len(hits)} note(s)" + + def t_read_note(self, note_id=None, about=None): + if note_id is None and not about: + raise ValueError("give note_id or about") + if note_id is None: + kind, _, key = str(about).partition(":") + sid = notebook.owner(self.db, kind, int(key)) if key.isdigit() else None + if sid not in self.readable: + raise ValueError(f"{about} isn't available in this conversation") + p = notebook.about(self.db, sid, about) + if not p: + return { + "page_of": about, + "note": None, + "hint": "nobody has written its page yet: write_note with about", + }, f"{about} has no page yet" + else: + p = self._note(note_id) + targets = [f"page:{p['id']}"] + ([p["about"]] if p.get("about") else []) + out = store.clean( + { + "id": p["id"], + "title": p["title"], + "summary": p.get("summary"), + "date": p.get("date"), + "place": p.get("place"), + "page_of": p.get("about"), + "parent_id": p.get("parent"), + "namespace": store.space_names(self.db).get(p["space"]), + "written_by": p.get("author"), + "body": (p.get("body") or "")[:20_000], + "links": notebook.links(self.db, p["id"]), + "linked_from": [b for b in notebook.backlinks(self.db, p["space"], targets) if b["page"] != p["id"]], + } + ) + return out, f"Read the note {p['title']}" + + def t_write_note(self, namespace, title, body, summary=None, place=None, parent_id=None, about=None): + sid = self._space(namespace, edit=True) + pid = notebook.create(self.db, sid, self.user["id"], title, body, summary, None, place, parent_id, about, author="assistant") + return {"note_id": pid, "url": f"/notes/{pid}"}, f"Wrote the note {title}" + + def t_update_note(self, note_id, title=None, summary=None, place=None, body=None, append=None, parent_id=None): + p = self._note(note_id, edit=True) + if append: + body = ((body if body is not None else p.get("body") or "").rstrip() + "\n\n" + append).strip() + kw = {} + if summary is not None: + kw["summary"] = summary + if place is not None: + kw["place"] = place + notebook.update(self.db, p["id"], self.user["id"], title=title, body=body, author="assistant", **kw) + if parent_id is not None: + notebook.move(self.db, p["id"], int(parent_id) or None) + return {"note_id": p["id"], "url": f"/notes/{p['id']}"}, f"Changed the note {title or p['title']}" + def t_entity_setup(self, namespace): names = {v: k for k, v in store.space_names(self.db).items()} sid = names.get(namespace) diff --git a/fastapi_backend/app/domain/chat.py b/fastapi_backend/app/domain/chat.py index 8c6943160..cc68d2ad6 100644 --- a/fastapi_backend/app/domain/chat.py +++ b/fastapi_backend/app/domain/chat.py @@ -417,7 +417,9 @@ def request_stop(db, cid): TOOL_SYSTEM = ( SYSTEM + " You can call tools to look things up in the archive. Cite moments with the [n] numbers the tools return, and " - "only those. Tools that run work or change data need the person's approval: say what you proposed and that it's waiting for them." + "only those. Tools that run work or change data need the person's approval: say what you proposed and that it's waiting for them. " + "Notes are your notebook and need no approval: look in them first (find_notes, read_note), and when you learn something " + "worth keeping, write or update a note (write_note, update_note), linking what it's about." ) diff --git a/fastapi_backend/app/domain/notebook.py b/fastapi_backend/app/domain/notebook.py index 1e45fda53..e4ba9b6be 100644 --- a/fastapi_backend/app/domain/notebook.py +++ b/fastapi_backend/app/domain/notebook.py @@ -38,8 +38,8 @@ DEPTH_MAX = 12 MENTION = re.compile(r"([@#])\[([^\]\n]{1,200})\]\(([a-z]+):(\d{1,18})\)") FIELDS = ( - "record::id(id) AS id, space, title, summary, summary_by, date, place, parent, position, about, author, " - "created_by, updated_by, created_at, updated_at" + "record::id(id) AS id, space, title, summary, summary_by, date, place, place_by, place_suggestion, parent, position, " + "about, author, created_by, updated_by, created_at, updated_at" ) @@ -207,6 +207,8 @@ def create(db, sid, account, title, body="", summary=None, date=None, place=None "summary_by": author if summary else None, "date": _date(date) or t[:10], "place": _place(place), + "place_by": author if place else None, + "filed": bool(place), "parent": parent, "position": None if about_thing else _last_position(db, sid, parent), "about": about_thing, @@ -252,8 +254,10 @@ def update(db, pid, account, title=None, body=None, summary=UNSET, date=UNSET, p sets.append("date = $date") args["date"] = _date(date) if place is not UNSET: - sets.append("place = $place") + # whoever files it decides: the assistant doesn't file it again, and its suggestion is done with + sets += ["place = $place", "place_by = $place_by", "place_suggestion = NONE", "filed = true"] args["place"] = _place(place) + args["place_by"] = author if args["place"] else None if title is not None or body is not None: sets.append("refine_pending = true") if body is not None: @@ -478,3 +482,59 @@ def refine_due(db, cfg, log=None): db.q("UPDATE $r SET refine_pending = false, refine_claim = NONE", r=R("note_page", p["id"])) done += 1 return done + + +# ---------- filing notes in PARA (ai.organise_notes) ---------- +PARA = { + "project": "Work toward an outcome with an end: a goal, a deliverable, something with a deadline.", + "area": "A responsibility kept up over time with no end date: health, a team, a home, finances.", + "resource": "A topic or interest kept for reference: research, how-tos, ideas, people, things to know.", + "archive": "Done, cancelled or no longer active: kept only for the record.", +} +FILE_BATCH = 10 + + +def file_due(db, cfg, log=None): + """File free notes nobody has filed yet in PARA, once their summary is written: a routine decision (a decision + model when one is set up, else the language model). Sure enough (decisions.act_above), it's filed; otherwise the + best guess waits on the page as a suggestion. Off with ai.organise_notes.""" + from . import decide + + if not cfg["ai"].get("organise_notes", True) or not decide.engine(cfg): + return 0 + rows = db.rows( + "SELECT record::id(id) AS id, title, summary, text, updated_at FROM note_page " + "WHERE about = NONE AND filed != true AND refine_pending != true LIMIT $n", + n=FILE_BATCH, + ) + done = 0 + for p in rows: + state = {"title": p["title"], "summary": p.get("summary"), "text": (p.get("text") or "")[:4000]} + try: + d = decide.choose(cfg, "Where does this note belong in PARA (projects, areas, resources, archives)?", PARA, state) + except decide.Undecided as e: + if log: + log(f"notes: couldn't file page {p['id']}: {e}") + return done + now = db.one("SELECT updated_at, filed FROM $r", r=R("note_page", p["id"])) + if not now or now.get("filed") or now.get("updated_at") != p.get("updated_at"): + continue # someone filed or changed it meanwhile + if decide.sure(cfg, d): + db.q( + "UPDATE $r SET place = $c, place_by = 'assistant', place_suggestion = NONE, filed = true", + r=R("note_page", p["id"]), + c=d["choice"], + ) + else: + db.q( + "UPDATE $r SET place_suggestion = $s, filed = true", + r=R("note_page", p["id"]), + s={"place": d["choice"], "confidence": round(d["confidence"], 2), "by": d["by"]}, + ) + done += 1 + return done + + +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) diff --git a/fastapi_backend/app/domain/routines.py b/fastapi_backend/app/domain/routines.py index 93bf0e1e3..1cc0b7b9d 100644 --- a/fastapi_backend/app/domain/routines.py +++ b/fastapi_backend/app/domain/routines.py @@ -658,7 +658,7 @@ def loop(): every(lambda: cfg_fn()["sources"]["check_seconds"], sources.poll_due, "watched folders"), every(lambda: CHECK_SECONDS, run_due, "routines"), every(lambda: cfg_fn()["fedora"]["sync_seconds"], fedora.sync_due, "fedora"), - every(lambda: notebook.QUIET_SECONDS / 2, notebook.refine_due, "notes"), + every(lambda: notebook.QUIET_SECONDS / 2, notebook.organise_due, "notes"), ] diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index ec8852113..849a5d6c9 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -247,6 +247,7 @@ def labels(): "tools": True, "extensions": True, # tools, skills, hooks and plugins people add (extensions.py) "refine_notes": True, # the model keeps notes' titles and one-line summaries true to the whole note (notebook.py) + "organise_notes": True, # notes nobody filed are filed in PARA, or a suggestion waits on them (notebook.py) "disabled_tools": [], "max_steps": 6, "max_transcript_reads": 20, diff --git a/fastapi_backend/app/schemas/notebook.py b/fastapi_backend/app/schemas/notebook.py index 48ee5b7d7..f9ad77d08 100644 --- a/fastapi_backend/app/schemas/notebook.py +++ b/fastapi_backend/app/schemas/notebook.py @@ -12,6 +12,12 @@ Sign = Literal["@", "#"] +class PlaceSuggestion(ResponseModel): + place: Place + confidence: float + by: str = Field(description="what decided: jev (a decision model) or llm") + + class NotePageItem(ResponseModel): id: int title: str @@ -19,6 +25,8 @@ class NotePageItem(ResponseModel): summary_by: Literal["person", "assistant"] | None = Field(None, description="who wrote the summary") date: str | None = None place: Place | None = Field(None, description="where it's filed (PARA): project, area, resource or archive") + place_by: Literal["person", "assistant"] | None = Field(None, description="who filed it") + place_suggestion: PlaceSuggestion | None = Field(None, description="where the assistant would file it, when it wasn't sure") parent: int | None = Field(None, description="the page it's inside, in the tree") position: float | None = Field(None, description="its order among its siblings") about: str | None = Field(None, description='what this is the page of, like "recording:12"; null for a free note') diff --git a/fastapi_backend/tests/api/test_notebook.py b/fastapi_backend/tests/api/test_notebook.py index c333e26d9..8e0cf6889 100644 --- a/fastapi_backend/tests/api/test_notebook.py +++ b/fastapi_backend/tests/api/test_notebook.py @@ -203,3 +203,66 @@ def test_refining_titles_and_summaries(client, env, db, cfg, llm): _age(db, p["id"]) notebook.refine_due(db, cfg) assert len(llm.seen) == n + 1 + + +def test_assistant_keeps_notes(client, env, db, cfg): + import json + + from app.domain import ai_tools + + uid = db.one("SELECT record::id(id) AS id FROM account WHERE email = 'ed@x.io'")["id"] + pods, calls = store.ns_id(db, "pods"), store.ns_id(db, "calls") + box = ai_tools.Toolbox(db, cfg, {"id": uid, "email": "ed@x.io"}, {pods}, {pods}, {}, None) + names = [t["function"]["name"] for t in box.specs()] + assert {"find_notes", "read_note", "write_note", "update_note"} <= set(names) + + def call(name, **args): + out, _ = box.call(name, args) + return json.loads(out) + + w = call("write_note", namespace="pods", title="Shipping", body=f"Plan for @[ep1](recording:{env['a']}).", place="project") + assert w["note_id"] + page = notebook.get(db, w["note_id"]) + assert (page["author"], page["place"]) == ("assistant", "project") + assert call("write_note", namespace="calls", title="x", body="y")["error"] # not a namespace it can write in + call("update_note", note_id=w["note_id"], append="Alice sends them.", summary="When the samples ship") + got = call("read_note", note_id=w["note_id"]) + assert got["body"].endswith("Alice sends them.") and got["summary"] == "When the samples ship" + assert got["links"] == [{"sign": "@", "target": f"recording:{env['a']}", "label": "ep1"}] + assert call("read_note", about=f"recording:{env['a']}")["note"] is None + assert [n["id"] for n in call("find_notes", query="alice")["notes"]] == [w["note_id"]] + assert call("find_notes", place="area")["notes"] == [] + # a viewer's assistant reads but doesn't write + view = ai_tools.Toolbox(db, cfg, {"id": uid, "email": "ed@x.io"}, {pods}, set(), {}, None) + vnames = [t["function"]["name"] for t in view.specs()] + assert "read_note" in vnames and "write_note" not in vnames + assert calls not in view.readable + + +def test_filing_in_para(client, env, db, cfg, llm): + he = env["he"] + a = _new(client, he, title="Ship the samples", body="Ship by Friday.") + b = _new(client, he, title="Mine", body="Mine.", place="area") + c = _new(client, he, title="Unsure", body="Hmm.") + for p in (a, b, c): + db.q("UPDATE $r SET refine_pending = false", r=R("note_page", p["id"])) + llm.decision = {"choice": "project", "confidence": 0.95} + db.q("UPDATE $r SET filed = true", r=R("note_page", c["id"])) # c waits for the next pass + assert notebook.file_due(db, cfg) == 1 + got = client.get(f"/api/v1/notes/{a['id']}", headers=he).json() + assert (got["place"], got["place_by"], got["place_suggestion"]) == ("project", "assistant", None) + # what a person filed stays; an unsure answer waits as a suggestion, and filing it takes the suggestion away + assert client.get(f"/api/v1/notes/{b['id']}", headers=he).json()["place"] == "area" + db.q("UPDATE $r SET filed = false", r=R("note_page", c["id"])) + llm.decision = {"choice": "resource", "confidence": 0.4} + assert notebook.file_due(db, cfg) == 1 + got = client.get(f"/api/v1/notes/{c['id']}", headers=he).json() + assert got["place"] is None and got["place_suggestion"]["place"] == "resource" + got = client.patch(f"/api/v1/notes/{c['id']}", headers=he, json={"place": "resource"}).json() + assert (got["place"], got["place_by"], got["place_suggestion"]) == ("resource", "person", None) + # switched off, nothing is decided + d = _new(client, he, title="Later", body="x") + db.q("UPDATE $r SET refine_pending = false", r=R("note_page", d["id"])) + cfg["ai"]["organise_notes"] = False + assert notebook.file_due(db, cfg) == 0 + llm.decision = None diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 865dac694..ede5ce00a 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -1661,6 +1661,7 @@ export type { PlaceRecordingsErrors, PlaceRecordingsResponse, PlaceRecordingsResponses, + PlaceSuggestion, Player, PostNamespaceSparqlData, PostNamespaceSparqlError, diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index b46245980..99c9e4932 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -7263,6 +7263,16 @@ export type NotePage = { * where it's filed (PARA): project, area, resource or archive */ place?: "project" | "area" | "resource" | "archive" | null; + /** + * Place By + * + * who filed it + */ + place_by?: "person" | "assistant" | null; + /** + * where the assistant would file it, when it wasn't sure + */ + place_suggestion?: PlaceSuggestion | null; /** * Parent * @@ -7453,6 +7463,16 @@ export type NotePageItem = { * where it's filed (PARA): project, area, resource or archive */ place?: "project" | "area" | "resource" | "archive" | null; + /** + * Place By + * + * who filed it + */ + place_by?: "person" | "assistant" | null; + /** + * where the assistant would file it, when it wasn't sure + */ + place_suggestion?: PlaceSuggestion | null; /** * Parent * @@ -8738,6 +8758,27 @@ export type PipelineVersionInfo = { [key: string]: unknown; }; +/** + * PlaceSuggestion + */ +export type PlaceSuggestion = { + /** + * Place + */ + place: "project" | "area" | "resource" | "archive"; + /** + * Confidence + */ + confidence: number; + /** + * By + * + * what decided: jev (a decision model) or llm + */ + by: string; + [key: string]: unknown; +}; + /** * Placed */ diff --git a/nextjs-frontend/components/notes/note-page.tsx b/nextjs-frontend/components/notes/note-page.tsx index d05b5d06a..d3bb685c2 100644 --- a/nextjs-frontend/components/notes/note-page.tsx +++ b/nextjs-frontend/components/notes/note-page.tsx @@ -260,6 +260,20 @@ export function NotePage({ id, about }: { id?: number; about?: string }) { ))} + {canEdit && !place && saved?.place_suggestion && ( + + )} {saved?.updated_at && Changed {shortDate(saved.updated_at)}} +
Tools
    diff --git a/nextjs-frontend/components/settings/model.ts b/nextjs-frontend/components/settings/model.ts index 42594d789..eba8798e2 100644 --- a/nextjs-frontend/components/settings/model.ts +++ b/nextjs-frontend/components/settings/model.ts @@ -349,6 +349,10 @@ export const AI_TOOLS: { name: string; label: string; acts: boolean }[] = [ acts: false, }, { name: "speaker_stats", label: "Speakers’ talk time", acts: false }, + { name: "find_notes", label: "Find notes", acts: false }, + { name: "read_note", label: "Read a note", acts: false }, + { name: "write_note", label: "Write notes", acts: false }, + { name: "update_note", label: "Change notes", acts: false }, { name: "run_template", label: "Run a template on recordings", acts: true }, { name: "propose_entity_change", @@ -659,6 +663,13 @@ export const FIELDS: FieldSpec[] = [ hint: "Without tools, answers use search results only.", }, { section: "ai", key: "disabled_tools", label: "Tools", kind: "checks" }, + { + section: "ai", + key: "organise_notes", + label: "File notes in projects, areas, resources and archives", + kind: "switch", + hint: "Notes nobody filed are filed for you; when the assistant isn't sure, its suggestion waits on the note.", + }, { section: "ai", key: "refine_notes", diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index f29424f39..a0a363450 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -33835,6 +33835,33 @@ "title": "Place", "description": "where it's filed (PARA): project, area, resource or archive" }, + "place_by": { + "anyOf": [ + { + "type": "string", + "enum": [ + "person", + "assistant" + ] + }, + { + "type": "null" + } + ], + "title": "Place By", + "description": "who filed it" + }, + "place_suggestion": { + "anyOf": [ + { + "$ref": "#/components/schemas/PlaceSuggestion" + }, + { + "type": "null" + } + ], + "description": "where the assistant would file it, when it wasn't sure" + }, "parent": { "anyOf": [ { @@ -34186,6 +34213,33 @@ "title": "Place", "description": "where it's filed (PARA): project, area, resource or archive" }, + "place_by": { + "anyOf": [ + { + "type": "string", + "enum": [ + "person", + "assistant" + ] + }, + { + "type": "null" + } + ], + "title": "Place By", + "description": "who filed it" + }, + "place_suggestion": { + "anyOf": [ + { + "$ref": "#/components/schemas/PlaceSuggestion" + }, + { + "type": "null" + } + ], + "description": "where the assistant would file it, when it wasn't sure" + }, "parent": { "anyOf": [ { @@ -36453,6 +36507,37 @@ ], "title": "PipelineVersionInfo" }, + "PlaceSuggestion": { + "properties": { + "place": { + "type": "string", + "enum": [ + "project", + "area", + "resource", + "archive" + ], + "title": "Place" + }, + "confidence": { + "type": "number", + "title": "Confidence" + }, + "by": { + "type": "string", + "title": "By", + "description": "what decided: jev (a decision model) or llm" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "place", + "confidence", + "by" + ], + "title": "PlaceSuggestion" + }, "Placed": { "properties": { "ok": { From bb0ee8b76220a7c8db94dfebc2ca5e3e9f3ff38a Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 4 Oct 2026 10:25:27 +0000 Subject: [PATCH 2/2] feat(notes): show notes on the edgeless canvas with drawings and diagrams Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01XZQXJtCvJgbG1Z2H312KcS --- docs/notes.md | 10 ++- fastapi_backend/app/api/v1/routes/notebook.py | 18 ++++- fastapi_backend/app/domain/notebook.py | 42 ++++++++-- fastapi_backend/app/schemas/notebook.py | 6 +- fastapi_backend/tests/api/test_notebook.py | 9 ++- nextjs-frontend/app/openapi-client/sdk.gen.ts | 3 +- .../app/openapi-client/types.gen.ts | 30 ++++++- .../components/notes/block-editor.tsx | 80 ++++++++++++++++--- .../components/notes/note-page.tsx | 45 ++++++++++- nextjs-frontend/openapi.json | 79 +++++++++++++++++- 10 files changed, 289 insertions(+), 33 deletions(-) diff --git a/docs/notes.md b/docs/notes.md index 81ad659cc..996974f44 100644 --- a/docs/notes.md +++ b/docs/notes.md @@ -71,10 +71,12 @@ recordings also need access to the recording. ## Editor -The page view uses AFFiNE's BlockSuite editor, whose documents are Yjs CRDTs, the format OctoBase stores and syncs. -The editor saves its document state in `doc` next to the Markdown; a change to the Markdown alone (the assistant's) -drops `doc`, so the editor rebuilds it from the Markdown. OctoBase is AGPL-3.0, so it would run as a separate service -for live co-editing rather than inside Lens. +The page view uses AFFiNE's BlockSuite editor, whose documents are Yjs CRDTs, the format OctoBase stores and syncs. A +page can be shown as a document or on the edgeless canvas (`view`), with BlockSuite's shapes, connectors, mind maps, +frames and free drawing. The editor saves its document state in `doc` next to the Markdown; the drawings live only +there. A change to the Markdown alone (the assistant's) keeps `doc` and sets `doc_stale`: the editor then replaces its +text with the Markdown and keeps the drawings. OctoBase is AGPL-3.0, so it would run as a separate service for live +co-editing rather than inside Lens. ## Refine later diff --git a/fastapi_backend/app/api/v1/routes/notebook.py b/fastapi_backend/app/api/v1/routes/notebook.py index 114e50476..7d04b4655 100644 --- a/fastapi_backend/app/api/v1/routes/notebook.py +++ b/fastapi_backend/app/api/v1/routes/notebook.py @@ -77,7 +77,18 @@ def create_page(body: NotePageCreate, user: Writer, acl: Acl, db: Db) -> NotePag sid = acl.namespace(body.ns, "editor") with domain_errors(): pid = notebook.create( - db, sid, user.id, body.title, body.body, body.summary, body.date, body.place, body.parent, body.about, doc=body.doc + db, + sid, + user.id, + body.title, + body.body, + body.summary, + body.date, + body.place, + body.parent, + body.about, + doc=body.doc, + view=body.view, ) return _out(acl, db, notebook.get(db, pid), user) @@ -126,10 +137,13 @@ def get_page(pid: int, user: CurrentUser, acl: Acl, db: Db) -> NotePage: @router.patch("/{pid}") def update_page(pid: int, body: NotePageUpdate, user: Writer, acl: Acl, db: Db) -> NotePage: - """Change what's given. A new body without `doc` drops the editor's state, so it's rebuilt from the Markdown.""" + """Change what's given. A new body without `doc` keeps the editor's state (drawings on the canvas live there) but + marks it stale (`doc_stale`), so the editor brings its text in line with the body.""" _page(acl, db, pid, "editor") given = body.model_fields_set kw: dict[str, Any] = {k: getattr(body, k) for k in ("summary", "date", "doc") if k in given} + if body.view is not None: + kw["view"] = body.view if "place" in given: kw["place"] = body.place or None with domain_errors(): diff --git a/fastapi_backend/app/domain/notebook.py b/fastapi_backend/app/domain/notebook.py index e4ba9b6be..fff6457b2 100644 --- a/fastapi_backend/app/domain/notebook.py +++ b/fastapi_backend/app/domain/notebook.py @@ -12,8 +12,9 @@ @ is for resources, people and other pages; # is for topics (entities of type TERM until topics become a SKOS vocabulary of their own). Links are kept as note_link rows, so a page shows its backlinks and the graph sees them. -The editor may also keep its own document state (`doc`, opaque: a BlockSuite/Yjs snapshot) next to the Markdown. A -change to the Markdown alone (the assistant's, say) drops that state so the editor rebuilds it from the Markdown. +The editor may also keep its own document state (`doc`, opaque: a BlockSuite/Yjs snapshot) next to the Markdown, which +holds what Markdown can't, like drawings on the edgeless canvas. A change to the Markdown alone (the assistant's, say) +keeps that state but marks it stale, and the editor brings its text in line with the Markdown. Refine later: pages for partial collection members, page history and undo, attachments, real-time co-editing. """ @@ -28,6 +29,7 @@ R = store.R PLACES = ("project", "area", "resource", "archive") AUTHORS = ("person", "assistant") +VIEWS = ("page", "edgeless") # how the editor shows it: a document, or the endless canvas (drawings, diagrams) KINDS = ("recording", "entity", "collection", "speaker", "page") # what a page can link to ABOUT = ("recording", "entity", "collection", "speaker") # what can have a page of its own TITLE_MAX = 200 @@ -39,7 +41,7 @@ MENTION = re.compile(r"([@#])\[([^\]\n]{1,200})\]\(([a-z]+):(\d{1,18})\)") FIELDS = ( "record::id(id) AS id, space, title, summary, summary_by, date, place, place_by, place_suggestion, parent, position, " - "about, author, created_by, updated_by, created_at, updated_at" + "about, author, view, doc_stale, created_by, updated_by, created_at, updated_at" ) @@ -181,10 +183,26 @@ def _links(db, pid, sid, body): ) -def create(db, sid, account, title, body="", summary=None, date=None, place=None, parent=None, about_thing=None, author="person", doc=None): +def create( + db, + sid, + account, + title, + body="", + summary=None, + date=None, + place=None, + parent=None, + about_thing=None, + author="person", + doc=None, + view=None, +): """A new page; its id. ValueError for bad input, a page that already exists about that thing, or too many.""" if author not in AUTHORS: raise ValueError("A page is written by a person or the assistant.") + if view is not None and view not in VIEWS: + raise ValueError("A page is seen as a page or on the edgeless canvas.") title, body, summary = _title(title), _body(body), _summary(summary) key = None if about_thing: @@ -216,6 +234,7 @@ def create(db, sid, account, title, body="", summary=None, date=None, place=None "body": body, "text": plain(body), "doc": _doc(doc), + "view": view, "author": author, "refine_pending": True, "created_by": account, @@ -239,8 +258,8 @@ def _doc(doc): UNSET = object() -def update(db, pid, account, title=None, body=None, summary=UNSET, date=UNSET, place=UNSET, author="person", doc=UNSET): - """Change what's given. A new body without `doc` drops the editor's state; the summary records who wrote it.""" +def update(db, pid, account, title=None, body=None, summary=UNSET, date=UNSET, place=UNSET, author="person", doc=UNSET, view=UNSET): + """Change what's given. A new body without `doc` marks the editor's state stale; the summary records who wrote it.""" p = get(db, pid) sets, args = ["updated_at = $t", "updated_by = $a"], {"t": store.now(), "a": account} if title is not None: @@ -264,11 +283,18 @@ def update(db, pid, account, title=None, body=None, summary=UNSET, date=UNSET, p sets += ["body = $body", "text = $text"] args["body"] = _body(body) args["text"] = plain(args["body"]) - if doc is UNSET: - doc = None + # a new body without the editor's state (the assistant's): the state is kept, for what Markdown can't hold + # (drawings on the edgeless canvas), and marked stale so the editor brings the text in line with the body + sets.append("doc_stale = $stale") + args["stale"] = doc is UNSET if doc is not UNSET: sets.append("doc = $doc") args["doc"] = _doc(doc) + if view is not UNSET: + if view not in VIEWS: + raise ValueError("A page is seen as a page or on the edgeless canvas.") + sets.append("view = $view") + args["view"] = view db.q(f"UPDATE $r SET {', '.join(sets)}", r=R("note_page", int(pid)), **args) if body is not None: _links(db, int(pid), p["space"], args["body"]) diff --git a/fastapi_backend/app/schemas/notebook.py b/fastapi_backend/app/schemas/notebook.py index f9ad77d08..eca0a22fa 100644 --- a/fastapi_backend/app/schemas/notebook.py +++ b/fastapi_backend/app/schemas/notebook.py @@ -31,6 +31,7 @@ class NotePageItem(ResponseModel): position: float | None = Field(None, description="its order among its siblings") about: str | None = Field(None, description='what this is the page of, like "recording:12"; null for a free note') author: Literal["person", "assistant"] = Field("person", description="who wrote it") + view: Literal["page", "edgeless"] | None = Field(None, description="how the editor shows it (default: page)") created_at: str | None = None updated_at: str | None = None @@ -54,6 +55,7 @@ class NotePage(NotePageItem): namespace: str body: str = Field("", description="Markdown, with mentions written @[label](kind:id) and #[label](entity:id)") doc: str | None = Field(None, description="the editor's own document state, if it kept one") + doc_stale: bool | None = Field(None, description="the body changed without the editor: its text follows the body") created_by: str | None = Field(None, description="its writer's email") links: list[NoteLink] = [] backlinks: list[NoteBacklink] = [] @@ -87,6 +89,7 @@ class NotePageCreate(RequestModel): parent: int | None = Field(None, description="put it inside this page") about: str | None = Field(None, description='make the page of this thing, like "recording:12" or "entity:5"') doc: str | None = None + view: Literal["page", "edgeless"] | None = None class NotePageUpdate(RequestModel): @@ -95,7 +98,8 @@ class NotePageUpdate(RequestModel): summary: str | None = Field(None, max_length=300, description="empty to clear it") date: str | None = None place: Place | Literal[""] | None = Field(None, description='"" to unfile it') - doc: str | None = Field(None, description="the editor's document state; a new body without it drops the old one") + doc: str | None = Field(None, description="the editor's document state; a new body without it marks the old one stale") + view: Literal["page", "edgeless"] | None = Field(None, description="show it as a page or on the edgeless canvas") class NotePageMove(RequestModel): diff --git a/fastapi_backend/tests/api/test_notebook.py b/fastapi_backend/tests/api/test_notebook.py index 8e0cf6889..a2bc0cb8e 100644 --- a/fastapi_backend/tests/api/test_notebook.py +++ b/fastapi_backend/tests/api/test_notebook.py @@ -131,9 +131,12 @@ def test_pages_of_things(client, env, db, cfg): assert client.get("/api/v1/notes?ns=pods", headers=hv).json()["pages"] == [] assert [x["id"] for x in client.get("/api/v1/notes?ns=pods&all=true", headers=hv).json()["pages"]] == [p["id"]] assert client.post(f"/api/v1/notes/{p['id']}/move", headers=he, json={}).status_code == 400 - # a new body without the editor's state drops it - r = client.patch(f"/api/v1/notes/{p['id']}", headers=he, json={"body": "Changed by the assistant"}) - assert r.json()["doc"] is None + # a new body without the editor's state keeps it (drawings live there) but marks it stale; the editor's save clears it + r = client.patch(f"/api/v1/notes/{p['id']}", headers=he, json={"body": "Changed by the assistant", "view": "edgeless"}) + assert (r.json()["doc"], r.json()["doc_stale"], r.json()["view"]) == ("opaque-editor-state", True, "edgeless") + r = client.patch(f"/api/v1/notes/{p['id']}", headers=he, json={"body": "Changed by the assistant", "doc": "state-2"}) + assert (r.json()["doc"], r.json()["doc_stale"]) == ("state-2", False) + assert client.patch(f"/api/v1/notes/{p['id']}", headers=he, json={"view": "canvas"}).status_code == 422 # an entity's page; the entity merged away leaves its page as a free note e1, e2 = _entity(db, "Ada Lovelace", "PERSON")["id"], _entity(db, "A. Lovelace", "PERSON")["id"] ep = _new(client, he, title="Who", about=f"entity:{e2}") diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 70ca30d2c..50bf90916 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -3778,7 +3778,8 @@ export class Notes { /** * Update Page * - * Change what's given. A new body without `doc` drops the editor's state, so it's rebuilt from the Markdown. + * Change what's given. A new body without `doc` keeps the editor's state (drawings on the canvas live there) but + * marks it stale (`doc_stale`), so the editor brings its text in line with the body. */ public static updatePage( options: Options, diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 99c9e4932..b69938c5f 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -7297,6 +7297,12 @@ export type NotePage = { * who wrote it */ author?: "person" | "assistant"; + /** + * View + * + * how the editor shows it (default: page) + */ + view?: "page" | "edgeless" | null; /** * Created At */ @@ -7321,6 +7327,12 @@ export type NotePage = { * the editor's own document state, if it kept one */ doc?: string | null; + /** + * Doc Stale + * + * the body changed without the editor: its text follows the body + */ + doc_stale?: boolean | null; /** * Created By * @@ -7390,6 +7402,10 @@ export type NotePageCreate = { * Doc */ doc?: string | null; + /** + * View + */ + view?: "page" | "edgeless" | null; }; /** @@ -7497,6 +7513,12 @@ export type NotePageItem = { * who wrote it */ author?: "person" | "assistant"; + /** + * View + * + * how the editor shows it (default: page) + */ + view?: "page" | "edgeless" | null; /** * Created At */ @@ -7557,9 +7579,15 @@ export type NotePageUpdate = { /** * Doc * - * the editor's document state; a new body without it drops the old one + * the editor's document state; a new body without it marks the old one stale */ doc?: string | null; + /** + * View + * + * show it as a page or on the edgeless canvas + */ + view?: "page" | "edgeless" | null; }; /** diff --git a/nextjs-frontend/components/notes/block-editor.tsx b/nextjs-frontend/components/notes/block-editor.tsx index db313d93f..b68f0c6aa 100644 --- a/nextjs-frontend/components/notes/block-editor.tsx +++ b/nextjs-frontend/components/notes/block-editor.tsx @@ -15,6 +15,10 @@ type Props = { /** The editor's own state (a Yjs update, base64) from the last save, when there is one. */ doc: string | null; readOnly?: boolean; + /** "page" (a document) or "edgeless" (the endless canvas: shapes, connectors, mind maps, drawing). */ + view?: "page" | "edgeless"; + /** The Markdown changed without the editor (the assistant wrote it): bring the text in line, keep the drawings. */ + stale?: boolean; onChange: (change: EditorChange) => void; /** What @ (resources, people, pages) and # (topics) offer for what was typed after them. */ search: (sign: "@" | "#", query: string) => Promise; @@ -42,12 +46,26 @@ function fromBase64(text: string): Uint8Array { /** AFFiNE's BlockSuite editor on one page. Its documents are Yjs CRDTs (what OctoBase stores and syncs). It keeps the * Markdown and its own state in step: @ and # open a menu of what to link, written as @[label](kind:id) in the * Markdown. Loaded in the browser only. */ -export default function BlockEditor({ markdown, doc, readOnly, onChange, search, onOpenLink, className }: Props) { +export default function BlockEditor({ + markdown, + doc, + readOnly, + view = "page", + stale, + onChange, + search, + onOpenLink, + className, +}: Props) { const host = useRef(null); const latest = useRef({ onChange, search, onOpenLink }); latest.current = { onChange, search, onOpenLink }; // The page is read once per mount: the parent remounts the editor (key) for another page. - const initial = useRef({ markdown, doc, readOnly }); + const initial = useRef({ markdown, doc, readOnly, view, stale }); + const editorRef = useRef<{ mode: string } | null>(null); + useEffect(() => { + if (editorRef.current && editorRef.current.mode !== view) editorRef.current.mode = view; + }, [view]); useEffect(() => { let disposed = false; @@ -67,7 +85,7 @@ export default function BlockEditor({ markdown, doc, readOnly, onChange, search, presetEffects.effects(); } if (disposed || !host.current) return; - const { markdown, doc: state, readOnly } = initial.current; + const { markdown, doc: state, readOnly, view, stale } = initial.current; const schema = new store.Schema().register(blocks.AffineSchemas); const collection = new store.DocCollection({ schema }); collection.meta.initialize(); @@ -95,6 +113,23 @@ export default function BlockEditor({ markdown, doc, readOnly, onChange, search, const page = collection.getDoc(id, { readonly: Boolean(readOnly) }); if (!page || disposed || !host.current) return; page.load(); + if (state && stale && !readOnly) { + // The text follows the Markdown; the canvas's shapes and drawings (outside the notes) stay as they were. + const notes = page.getBlocksByFlavour("affine:note").map((b) => b.model); + for (const note of notes) for (const child of [...note.children]) page.deleteBlock(child); + const target = notes[0]?.id; + if (target && markdown.trim()) { + const job = new store.Job({ collection }); + const slice = await new blocks.MarkdownAdapter(job).toSliceSnapshot({ + file: markdown, + assets: job.assetsManager, + workspaceId: collection.id, + pageId: page.id, + }); + for (const b of slice?.content.flatMap((x) => x.children) ?? []) await job.snapshotToBlock(b, page, target); + } + if (disposed || !host.current) return; + } const linkedWidget = { triggerKeys: ["@", "#"], @@ -140,9 +175,12 @@ export default function BlockEditor({ markdown, doc, readOnly, onChange, search, }; const editor = new presets.AffineEditorContainer(); - editor.pageSpecs = [...blocks.PageEditorBlockSpecs, std.ConfigExtension("affine:page", { linkedWidget })]; + const config = std.ConfigExtension("affine:page", { linkedWidget }); + editor.pageSpecs = [...blocks.PageEditorBlockSpecs, config]; + editor.edgelessSpecs = [...blocks.EdgelessEditorBlockSpecs, config]; editor.doc = page; - editor.mode = "page"; + editor.mode = view; + editorRef.current = editor; host.current.replaceChildren(editor); // Links to things in Lens open in the app, not as web addresses. Other links open only as web or mail addresses: @@ -174,20 +212,35 @@ export default function BlockEditor({ markdown, doc, readOnly, onChange, search, doc: toBase64(Y.encodeStateAsUpdate(page.spaceDoc)), }); }; - const changed = page.slots.blockUpdated.on(() => { + // Any change to the document: text, and the canvas's shapes and drawings, which aren't blocks. + // Opening a page changes its document too (the editor sets itself up): only what someone does is saved. + let touched = false; + const touch = () => { + touched = true; + }; + host.current.addEventListener("keydown", touch, true); + host.current.addEventListener("pointerdown", touch, true); + host.current.addEventListener("paste", touch, true); + host.current.addEventListener("drop", touch, true); + const onUpdate = () => { + if (!touched) return; clearTimeout(timer); timer = setTimeout(() => { timer = undefined; void save(); }, 600); - }); + }; + page.spaceDoc.on("update", onUpdate); const el = host.current; + if (state && stale && !readOnly) void save(); // the brought-in-line text, so the page isn't stale any more cleanup = () => { + editorRef.current = null; if (timer) void save(true); // what was typed in the last moment before leaving the page clearTimeout(timer); - changed.dispose(); + page.spaceDoc.off("update", onUpdate); el.removeEventListener("click", onClick, true); el.removeEventListener("auxclick", onClick, true); + for (const t of ["keydown", "pointerdown", "paste", "drop"]) el.removeEventListener(t, touch, true); el.replaceChildren(); collection.dispose(); }; @@ -199,5 +252,14 @@ export default function BlockEditor({ markdown, doc, readOnly, onChange, search, }, []); // The page's title is Lens's own field above the editor, so the editor's title line is hidden. - return
    ; + return ( +
    + ); } diff --git a/nextjs-frontend/components/notes/note-page.tsx b/nextjs-frontend/components/notes/note-page.tsx index d3bb685c2..5ab238082 100644 --- a/nextjs-frontend/components/notes/note-page.tsx +++ b/nextjs-frontend/components/notes/note-page.tsx @@ -1,7 +1,7 @@ "use client"; import { useQuery, useQueryClient } from "@tanstack/react-query"; -import { ArrowUpRight, FileText, Link2, Sparkles, Trash2 } from "lucide-react"; +import { ArrowUpRight, FileText, Link2, Shapes, Sparkles, Trash2 } from "lucide-react"; import dynamic from "next/dynamic"; import Link from "next/link"; import { useRouter } from "next/navigation"; @@ -23,7 +23,16 @@ const BlockEditor = dynamic(() => import("@/components/notes/block-editor"), { loading: () => , }); -type Changes = { title?: string; summary?: string; date?: string; place?: string; body?: string; doc?: string }; +type View = "page" | "edgeless"; +type Changes = { + title?: string; + summary?: string; + date?: string; + place?: string; + body?: string; + doc?: string; + view?: View; +}; /** A note: a free note (`id`), or the page of a thing (`about`, like "entity:5"), which is a draft until someone writes * on it. Everything saves as you type. */ @@ -48,6 +57,7 @@ export function NotePage({ id, about }: { id?: number; about?: string }) { const [summary, setSummary] = useState(""); const [date, setDate] = useState(""); const [place, setPlace] = useState(""); + const [view, setView] = useState("page"); const loadedFor = useRef(null); useEffect(() => { if (!page) return; @@ -58,6 +68,7 @@ export function NotePage({ id, about }: { id?: number; about?: string }) { setSummary(saved?.summary ?? ""); setDate(saved?.date ?? ""); setPlace(saved?.place ?? ""); + setView((saved?.view as View | null) ?? "page"); }, [page, saved]); // Saving: changes gather for a moment, then go in one request. A thing's draft becomes its page on the first one. @@ -91,6 +102,7 @@ export function NotePage({ id, about }: { id?: number; about?: string }) { summary: c.summary || null, date: c.date || null, place: (c.place || null) as Page["place"], + view: c.view ?? null, }, }), ); @@ -101,6 +113,7 @@ export function NotePage({ id, about }: { id?: number; about?: string }) { if (c.summary !== undefined) body.summary = c.summary; if (c.date !== undefined && c.date) body.date = c.date; if (c.place !== undefined) body.place = c.place; + if (c.view !== undefined) body.view = c.view; if (c.body !== undefined) { body.body = c.body; body.doc = c.doc ?? null; @@ -275,12 +288,40 @@ export function NotePage({ id, about }: { id?: number; about?: string }) { )} {saved?.updated_at && Changed {shortDate(saved.updated_at)}} + +
    + {( + [ + ["page", "Page", FileText], + ["edgeless", "Canvas", Shapes], + ] as const + ).map(([v, label, Icon]) => ( + + ))} +
    change({ body: c.markdown, doc: c.doc })} search={search} onOpenLink={openLink} diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index a0a363450..8052121d7 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -7226,7 +7226,7 @@ "notes" ], "summary": "Update Page", - "description": "Change what's given. A new body without `doc` drops the editor's state, so it's rebuilt from the Markdown.", + "description": "Change what's given. A new body without `doc` keeps the editor's state (drawings on the canvas live there) but\nmarks it stale (`doc_stale`), so the editor brings its text in line with the body.", "operationId": "update_page", "parameters": [ { @@ -33908,6 +33908,22 @@ "description": "who wrote it", "default": "person" }, + "view": { + "anyOf": [ + { + "type": "string", + "enum": [ + "page", + "edgeless" + ] + }, + { + "type": "null" + } + ], + "title": "View", + "description": "how the editor shows it (default: page)" + }, "created_at": { "anyOf": [ { @@ -33952,6 +33968,18 @@ "title": "Doc", "description": "the editor's own document state, if it kept one" }, + "doc_stale": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Doc Stale", + "description": "the body changed without the editor: its text follows the body" + }, "created_by": { "anyOf": [ { @@ -34089,6 +34117,21 @@ } ], "title": "Doc" + }, + "view": { + "anyOf": [ + { + "type": "string", + "enum": [ + "page", + "edgeless" + ] + }, + { + "type": "null" + } + ], + "title": "View" } }, "additionalProperties": false, @@ -34286,6 +34329,22 @@ "description": "who wrote it", "default": "person" }, + "view": { + "anyOf": [ + { + "type": "string", + "enum": [ + "page", + "edgeless" + ] + }, + { + "type": "null" + } + ], + "title": "View", + "description": "how the editor shows it (default: page)" + }, "created_at": { "anyOf": [ { @@ -34431,7 +34490,23 @@ } ], "title": "Doc", - "description": "the editor's document state; a new body without it drops the old one" + "description": "the editor's document state; a new body without it marks the old one stale" + }, + "view": { + "anyOf": [ + { + "type": "string", + "enum": [ + "page", + "edgeless" + ] + }, + { + "type": "null" + } + ], + "title": "View", + "description": "show it as a page or on the edgeless canvas" } }, "additionalProperties": false,