diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cfd7ba5f..759b1222d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Every entity has its own page.** An entity's page is named by its name, as a wiki names pages: + `/wiki//` (spaces as underscores), so Ada Lovelace in `work` is `/wiki/work/Ada_Lovelace`. It shows + what the entity is, the notes people and the assistant keep on it in the BlockSuite editor, every line that says it, + and the assets, people and entities it comes up with. Its name on the Entities page now opens it (the rest of + the row still opens the side panel), as do `@` links in notes, the graph panel and the entity's RDF URI. Any case, a + name it had before a rename, or the name of one merged into it opens it too ([Entity pages](docs/notes.md#entity-pages)). +- **The update notice no longer pushes pages off the screen.** While *Lens vX is out* shows above them, Chat, the + graph and a recording's page are that much shorter, so a phone's question box and a recording's player stay in + sight. + ## 0.11.0 October 15, 2026 {id="0.11.0"} - **Installing an update from the web app works again in a microsandbox.** *Back up and install* stopped at the diff --git a/ci/clicks/journeys.mjs b/ci/clicks/journeys.mjs index 96af52437..cadacf9fd 100644 --- a/ci/clicks/journeys.mjs +++ b/ci/clicks/journeys.mjs @@ -492,17 +492,18 @@ export const JOURNEYS = [ ns: "", module: "Entities", feature: "Find an entity and see where it was mentioned", + note: "Its name opens its own page, /wiki//Raspberry_Pi, with its notes and every line that says it.", from: "/", async run(ctx) { const { page, meter } = ctx; - const entity = page.getByRole("main").getByRole("button", { name: "Raspberry Pi", exact: true }); + const entity = page.getByRole("main").getByRole("link", { name: "Raspberry Pi", exact: true }); await madeInBackground(ctx, "/entities", entity, "/", "the entity the imports' analysis makes"); await go(ctx, "Entities"); await meter.type(page.getByRole("searchbox", { name: "Find entities" }), "rasp", "part of its name"); // the list filters as you type: the other entity leaves it await page.getByRole("main").getByRole("table").getByText("Lens", { exact: true }).waitFor({ state: "hidden" }); await meter.click(entity, "Raspberry Pi"); - await page.waitForURL(/entity=\d+/); + await page.waitForURL(/\/wiki\/[^/]+\/Raspberry_Pi$/); await page.getByText(/Raspberry Pi can run Lens/).first().waitFor(); }, }, diff --git a/docs/api.md b/docs/api.md index 1294308a0..c24e81a66 100644 --- a/docs/api.md +++ b/docs/api.md @@ -991,6 +991,7 @@ POST /api/v1/entities/merge POST /api/v1/entities/merges/{mid}/undo POST /api/v1/entities/not-same GET /api/v1/entities/{eid} +GET /api/v1/wiki/{ns}/{address} GET /api/v1/entities/{eid}/mentions GET /api/v1/entities/{eid}/connections POST /api/v1/entities/{eid}/rename @@ -1002,6 +1003,11 @@ GET /api/v1/graph/explore GET /api/v1/graph/path ``` +An entity's `page` is its page in the web app, by name: `/wiki//`. +`GET /wiki/{ns}/{address}` says which entity an address names: by its name in any case and spacing (underscores for +spaces), or a name it had before a rename or a merge. It answers `{kind, id, namespace, title, path, canonical}`; +`canonical` is false when the address is another way of writing `path` ([Notes](notes.md#entity-pages)). + ## metadata ``` diff --git a/docs/mcp.md b/docs/mcp.md index 88356f66c..f41017f99 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -52,7 +52,7 @@ front of the web app also needs `TRUST_PROXY_HEADERS=true` ([Authentication](aut | `fetch` | an asset's whole text at once, as `[m:ss] Speaker: …` lines | | `cite` | a citation for a moment (a line or a second, and a few lines from there): the words, who said or wrote them, the asset and date, the time, the link, and all of it as Markdown | | `list_entities` | people, organisations, products, places, events, works and terms mentioned, by name, type, namespace or asset | -| `get_entity` | one entity: its names, how often and when it is mentioned, what it is mentioned with, who mentions it most, and the lines that mention it | +| `get_entity` | one entity: its names, its page's link, how often and when it is mentioned, what it is mentioned with, who mentions it most, and the lines that mention it | | `explore_graph` | the knowledge graph around an entity (`e12`) or a person (`s3`), one or two steps out | | `find_path` | the shortest chain of links between two of them, with lines that show each link | | `sparql` | a read-only SPARQL query (SELECT, ASK, CONSTRUCT or DESCRIBE) over one namespace's linked data ([RDF](rdf.md)): JSON results, or Turtle | diff --git a/docs/notes.md b/docs/notes.md index 7d03fbe69..9c9ecafa7 100644 --- a/docs/notes.md +++ b/docs/notes.md @@ -7,8 +7,10 @@ Status: **built**: pages (free notes in a tree, a page per asset, entity, topic, links with backlinks (# links topics), the tree in the left navigation, the page view with the BlockSuite editor, the model keeping titles and summaries up to date, assistant tools to find, read, write and update notes, and MCP tools to find, read and write them ([MCP](mcp.md)), page history with restore, suggested links to what a note names, the -project or area a note fits under, and images and attachments kept where Settings → Storage says. -**Planned**: nesting notes under their project or area without a click, pages in the graph. +project or area a note fits under, images and attachments kept where Settings → Storage says, and every entity's +own page at a wiki address, `/wiki//` ([Entity pages](#entity-pages)). +**Planned**: nesting notes under their project or area without a click, pages in the graph, wiki addresses for topics, +recordings and the other things that have pages. ## A page @@ -29,6 +31,28 @@ draft with its name and the pages that already link to it. A page follows its as thing is deleted, or an entity is merged into another, its page stays as a free note at the top of the tree, so nothing written on it is lost. +## Entity pages + +Every entity (a person, organisation, product, place, event, work or term) has a page of its own, named by its name +the way a wiki names pages: spaces become underscores and the rest stays as written, so Ada Lovelace in namespace +`work` is at `/wiki/work/Ada_Lovelace`. Nothing is stored for the address: it is the name. The page shows what the +entity is (its type, the other ways it's said and its description), the notes people and the assistant keep on it in +the BlockSuite editor below, every line that says it with a link to that moment, the assets and the people it comes +up with most, the entities it's mentioned together with (each a link to its own page), the same entity in other +namespaces, and similar content. **Edit** opens the panel that changes it, as on the Entities page; renaming it moves +the page to the new name. + +The address is read the way analysis matches names: in any case and spacing (`/wiki/work/ada_lovelace`), and by a name +the entity had before a rename or the name of one merged into it. Those open the page and switch the address to its +own. A name with `/` or `?` in it is escaped in the address (`AC/DC` is `/wiki/work/AC%2FDC`). The entity's name on the +Entities page, in a note's `@` link, in the graph and in the RDF URI `/id/entity/` all lead to its page, and +`/entities/` (and an entity's page's old address, `/notes/about/entity/`) does too. + +`GET /api/v1/entities/{eid}` and the MCP tool `get_entity` give the page's address (`page`, `url`); the assistant's +`find_entities` gives it too. `GET /api/v1/wiki/{ns}/{address}` says which entity an address names (`id`, `path`, and +`canonical: false` when the address is another way of writing it). An address only answers for the namespace's members; +to anyone else it is not there. + ## Links The body links with mention tokens, which the editor and the assistant both write: @@ -126,5 +150,8 @@ co-editing rather than inside Lens. ## Refine later +Wiki addresses for topics, assets, collections and speakers, and a namespace's wiki index page; two entities whose +names differ only by `_` and a space share an address (the one with spaces wins). + Pages for people who see only some collections of a namespace; differences between versions; live co-editing through OctoBase; pages and their links as nodes and relationships in the graph. diff --git a/docs/processing.md b/docs/processing.md index a6d49ca91..a20b8cb22 100644 --- a/docs/processing.md +++ b/docs/processing.md @@ -110,8 +110,10 @@ Nodes are people and named things. Edges are: People, organisations, products, places, events, works and topics are extracted from every asset's text. Dates and numbers are extracted too, but hidden unless asked for. -The **Entities** page in the web app lists a namespace's entities (search, type and collection filters, a Hidden tab) -and opens each in a side panel where editors rename, retype, describe, merge and hide it. +The **Entities** page in the web app lists a namespace's entities (search, type and collection filters, a Hidden tab). +An entity's name opens its own page, `/wiki//`, with its notes, every line that says it and what it +comes up with ([Entity pages](notes.md#entity-pages)); the rest of its row opens a side panel where editors rename, +retype, describe, merge and hide it. - **Merge from the side panel:** **Merge** opens a find box; type a name and press Enter, and the entity picked is merged into the open one at once. Its **Maybe the same** list offers likely doubles (same letters, an acronym, a near @@ -128,8 +130,10 @@ and opens each in a side panel where editors rename, retype, describe, merge and mentions, and hidden entities. - Sorts: most mentioned, most assets, most recent, rising, and name. - Options: grouping by name across namespaces, a twelve-month sparkline, and facets. -- **Entity page:** its details and aliases, paged mentions (each line with the words highlighted, linking to its moment), - a timeline by month or week and namespace, and connections (entities mentioned together, people, assets). +- **Entity page** (`/wiki//` in the web app; `GET /api/v1/wiki/{ns}/{address}` finds it by name): its + details and aliases, its notes, paged mentions (each line with the words highlighted, linking to its moment), and + connections (entities mentioned together, people, assets); the API also gives a timeline by month or week and + namespace. - **Explorer:** - `GET /api/v1/graph/explore?focus=e12` gives the neighbourhood of an entity or person. Depth is one or two hops, and it can be filtered by type, edge kind and strength, within one namespace or all shared ones. diff --git a/docs/rdf.md b/docs/rdf.md index 7613322a8..7a199026f 100644 --- a/docs/rdf.md +++ b/docs/rdf.md @@ -25,7 +25,7 @@ URIs use the address Lens publishes (`iiif.base_url`, or the address a request a Each URI uses content negotiation. An `Accept` of `text/turtle`, `application/ld+json`, `application/n-triples` or `application/rdf+xml`, or `?format=turtle|json-ld|nt|xml`, returns RDF. A browser is sent to the page instead -(303 See Other). +(303 See Other); an entity's page is named by its name, `/wiki//` ([Notes](notes.md#entity-pages)). A public asset's URI is open to everyone, just like its IIIF manifest. Visitors get its metadata and published custom fields. Members also get the entities it mentions (`dcterms:references`), its access and its internal fields. diff --git a/fastapi_backend/app/api/linked_data.py b/fastapi_backend/app/api/linked_data.py index feda4c2c5..700b1cabc 100644 --- a/fastapi_backend/app/api/linked_data.py +++ b/fastapi_backend/app/api/linked_data.py @@ -16,7 +16,7 @@ from app.api.deps import Acl, Cfg, Db, OptionalUser from app.api.iiif import _rec, base_url -from app.domain import rdf +from app.domain import rdf, store, wiki from app.domain.store import R router = APIRouter(include_in_schema=False, tags=["linked-data"]) @@ -75,9 +75,12 @@ def collection(cid: int, request: Request, acl: Acl, db: Db, cfg: Cfg, format: s @router.get("/id/entity/{eid}") def entity(eid: int, request: Request, acl: Acl, db: Db, cfg: Cfg, format: str | None = FORMAT) -> Response: - _member_of(acl, (db.one("SELECT space FROM $r", r=R("entity", eid)) or {}).get("space")) + e = db.one("SELECT space, name FROM $r", r=R("entity", eid)) or {} + _member_of(acl, e.get("space")) base, fmt = base_url(request, cfg), wanted(request, format) - return rdf_response(rdf.entity_graph(db, base, eid), fmt) if fmt else _see(f"{base}/entities/{eid}") + if not fmt: # its page, by name + return _see(base + wiki.path(store.space_names(db).get(e["space"]) or "", e["name"])) + return rdf_response(rdf.entity_graph(db, base, eid), fmt) @router.get("/id/topic/{tid}") diff --git a/fastapi_backend/app/api/mcp_tools.py b/fastapi_backend/app/api/mcp_tools.py index e642a36af..efbc5d77a 100644 --- a/fastapi_backend/app/api/mcp_tools.py +++ b/fastapi_backend/app/api/mcp_tools.py @@ -914,8 +914,8 @@ def _entities( @tool( "get_entity", "Get an entity", - "One entity: its names, how often and when it is mentioned, the entities mentioned together with it, who mentions " - "it most, and the lines that mention it (newest first), each with a url to that moment.", + "One entity: its names, its page's url, how often and when it is mentioned, the entities mentioned together with " + "it, who mentions it most, and the lines that mention it (newest first), each with a url to that moment.", Arg("entity_id", "integer", "the entity (from list_entities, get_recording or the graph)", required=True), Arg("mentions", "integer", "how many mentioning lines", default=10, minimum=0, maximum=100), Arg("mentions_offset", "integer", "skip this many lines (for the next page)", default=0, minimum=0, maximum=10000), @@ -930,6 +930,7 @@ def get_entity(ctx: Context, entity_id: int, mentions: int, mentions_offset: int "type": d.type, "type_label": d.type_label, "namespace": d.namespace, + "url": f"{ctx.web}{d.page}" if d.page else None, "aliases": d.aliases or None, "mentions": d.mentions, "recordings": d.recordings, diff --git a/fastapi_backend/app/api/v1/routes/entities.py b/fastapi_backend/app/api/v1/routes/entities.py index aba8a4958..f226a3812 100644 --- a/fastapi_backend/app/api/v1/routes/entities.py +++ b/fastapi_backend/app/api/v1/routes/entities.py @@ -11,7 +11,7 @@ from fastapi import APIRouter, HTTPException, Request from app.api.deps import Access, Acl, CurrentUser, Db, Writer, domain_errors -from app.domain import auth, entity_map, entity_setup, graph_history, hierarchy, jobs +from app.domain import auth, entity_map, entity_setup, graph_history, hierarchy, jobs, wiki from app.domain import entities as ents from app.domain.store import DB, R from app.schemas.common import Ok @@ -31,6 +31,7 @@ MentionList, MentionMove, MentionMoved, + WikiPage, ) router = APIRouter(tags=["entities"]) @@ -203,6 +204,19 @@ def get_entity(eid: int, user: CurrentUser, acl: Acl, db: Db) -> EntityDetail: return EntityDetail.model_validate(ents.detail(db, eid, set(acl.roles))) +@router.get("/wiki/{ns}/{address:path}") +def find_wiki_page(ns: str, address: str, user: CurrentUser, acl: Acl, db: Db) -> WikiPage: + """The page /wiki//
names: the entity called that (spaces as underscores, any case), or the one a name + it had before a rename or a merge now belongs to. When `canonical` is false, show `path` instead.""" + sid = acl.namespace(ns) + hit = wiki.find(db, sid, address) + if not hit: + raise HTTPException(404, "not found") + eid, canonical = hit + name = db.one("SELECT VALUE name FROM $r", r=R("entity", eid)) + return WikiPage(kind="entity", id=eid, namespace=ns, title=name, path=wiki.path(ns, name), canonical=canonical) + + @router.get("/entities/{eid}/mentions") def list_entity_mentions( eid: int, diff --git a/fastapi_backend/app/domain/ai_tools.py b/fastapi_backend/app/domain/ai_tools.py index 650176a03..b64509fc8 100644 --- a/fastapi_backend/app/domain/ai_tools.py +++ b/fastapi_backend/app/domain/ai_tools.py @@ -35,6 +35,7 @@ topics, untrusted, uploads, + wiki, ) R = store.R @@ -917,6 +918,7 @@ def t_find_entities(self, query=None, type=None, namespace=None, limit=10): # n "name": e["name"], "type": e["type_label"], "namespace": e["namespace"], + "page": wiki.path(e["namespace"], e["name"]), "mentions": e["mentions"], "recordings": e["recordings"], **({"description": e["description"]} if e.get("description") else {}), diff --git a/fastapi_backend/app/domain/entities.py b/fastapi_backend/app/domain/entities.py index d892666bd..9929c1375 100644 --- a/fastapi_backend/app/domain/entities.py +++ b/fastapi_backend/app/domain/entities.py @@ -13,7 +13,7 @@ import re from collections import Counter, defaultdict, deque -from . import analyze, entity_setup, graph_history, notebook, render, store +from . import analyze, entity_setup, graph_history, notebook, render, store, wiki R = store.R TYPES = { @@ -239,6 +239,7 @@ def detail(db, eid, spaces): "defined": bool(e.get("defined")), "builtin": e.get("builtin"), "collection": e.get("collection"), + "page": wiki.path(names.get(e["space"]) or "", e["name"]), } diff --git a/fastapi_backend/app/domain/wiki.py b/fastapi_backend/app/domain/wiki.py new file mode 100644 index 000000000..0ff11b2ba --- /dev/null +++ b/fastapi_backend/app/domain/wiki.py @@ -0,0 +1,53 @@ +"""Wiki addresses: every entity has a page at /wiki//, as wikis name their pages. + +The name is the address: spaces become underscores and the rest stays as written, so `Ada Lovelace` in namespace `work` +is /wiki/work/Ada_Lovelace. Nothing is stored for it. An address is read the way analysis matches names (any case, +any spacing, the same entity key), so /wiki/work/ada_lovelace finds the page too; a name the entity was known by +before a rename or a merge (its aliases) finds the entity it is part of now. Either way the page answers with the +address to show (`canonical` False means the browser should switch to it). +""" + +from __future__ import annotations + +import re +import urllib.parse + +from . import analyze, store + +R = store.R + + +def slug(name: str) -> str: + """Ada Lovelace -> Ada_Lovelace.""" + return re.sub(r"\s+", "_", (name or "").strip()) + + +def _part(s: str) -> str: + """Escaped as the web app's encodeURIComponent escapes it, so a name with / or ? in it stays one part.""" + return urllib.parse.quote(s, safe="!*'()") + + +def path(namespace: str, name: str) -> str: + """The page's address in the web app, like /wiki/work/Ada_Lovelace.""" + return f"/wiki/{_part(namespace)}/{_part(slug(name))}" + + +def find(db, sid: int, address: str) -> tuple[int, bool] | None: + """(entity id, whether `address` is already its own address) for an address in namespace `sid`, or None.""" + address = (address or "").strip().strip("/") + keys = [k for k in dict.fromkeys((analyze.ent_key(address.replace("_", " ")), analyze.ent_key(address))) if k] + eid = None + for key in keys: + row = db.one("SELECT record::id(id) AS id FROM entity WHERE ekey = $k LIMIT 1", k=f"{sid}:{key}") + if row: + eid = row["id"] + break + if eid is None: # a name it had before a rename, or the name of one merged into it + for key in keys: + row = db.one("SELECT entity FROM entity_alias WHERE space = $s AND key = $k LIMIT 1", s=sid, k=key) + if row and db.one("SELECT VALUE id FROM $r", r=R("entity", row["entity"])): + eid = row["entity"] + break + if eid is None: + return None + return eid, slug(db.one("SELECT VALUE name FROM $r", r=R("entity", eid))) == address diff --git a/fastapi_backend/app/schemas/entities.py b/fastapi_backend/app/schemas/entities.py index e21cc686e..54a27396d 100644 --- a/fastapi_backend/app/schemas/entities.py +++ b/fastapi_backend/app/schemas/entities.py @@ -50,6 +50,20 @@ class EntityDetail(ResponseModel): defined: bool = Field(False, description="on the fixed list people defined") builtin: str | None = Field(None, description="unknown or unlabeled: one of the two entities that are always there") collection: int | None = Field(None, description="a defined entity of one collection (and those inside it)") + page: str | None = Field(None, description="its page in the web app, by name: /wiki//") + + +class WikiPage(ResponseModel): + """What a wiki address names, and the address to show for it.""" + + kind: str = Field(description="entity") + id: int + namespace: str + title: str = Field(description="its name") + path: str = Field(description="its own address, like /wiki/work/Ada_Lovelace") + canonical: bool = Field( + description="false: the address asked for is another way to write it (any case, or a name it had before a rename or merge); show `path`" + ) class MentionList(ResponseModel): diff --git a/fastapi_backend/tests/api/test_entities.py b/fastapi_backend/tests/api/test_entities.py index 3fb829ed4..796a7d893 100644 --- a/fastapi_backend/tests/api/test_entities.py +++ b/fastapi_backend/tests/api/test_entities.py @@ -146,3 +146,45 @@ def test_describe_and_filter_by_collection(env, db): assert inside["Dyno Therapeutics"] == 1 # counted over its recordings only (5 in the namespace) assert "Northwind Labs" in inside and "Amazon Web Services" in inside assert c.get("/api/v1/entities", params={"collection": 999999}, headers=vi).status_code == 404 + + +def test_wiki_addresses(env): + """Every entity has a page named by its name, /wiki//; any case, old names and merged names + find it too, and say which address to show.""" + c, h, ed = env.c, env.h["viewer"], env.h["editor"] + dyno = env.eid("Dyno Therapeutics") + assert c.get(f"/api/v1/entities/{dyno}", headers=h).json()["page"] == "/wiki/pods/Dyno_Therapeutics" + + def find(address, ns="pods", headers=h): + return c.get(f"/api/v1/wiki/{ns}/{address}", headers=headers) + + assert find("Dyno_Therapeutics").json() == { + "kind": "entity", + "id": dyno, + "namespace": "pods", + "title": "Dyno Therapeutics", + "path": "/wiki/pods/Dyno_Therapeutics", + "canonical": True, + } + for other in ("dyno_therapeutics", "Dyno%20Therapeutics", "DYNO__therapeutics"): # the same name, written otherwise + got = find(other).json() + assert (got["id"], got["canonical"], got["path"]) == (dyno, False, "/wiki/pods/Dyno_Therapeutics"), other + assert find("Nobody_Here").status_code == 404 + assert find("Dyno_Therapeutics", ns="calls").status_code == 404 # calls isn't readable + assert find("Dyno_Therapeutics", ns="nowhere").status_code == 404 + assert c.get("/api/v1/wiki/pods/Dyno_Therapeutics").status_code == 401 + + # a rename keeps the old address working, pointing to the new one; so does the name of one merged in + assert c.post(f"/api/v1/entities/{dyno}/rename", headers=ed, json={"name": "Dyno Bio"}).status_code == 200 + got = find("Dyno_Therapeutics").json() + assert (got["id"], got["canonical"], got["path"]) == (dyno, False, "/wiki/pods/Dyno_Bio") + keep, other = env.eid("Northwind Labs"), env.eid("North Wind Labs") + assert c.post("/api/v1/entities/merge", headers=ed, json={"keep": keep, "others": [other]}).status_code == 200 + got = find("North_Wind_Labs").json() + assert (got["id"], got["canonical"], got["path"]) == (keep, False, "/wiki/pods/Northwind_Labs") + + # a name with / or ? in it is escaped in the address, and found from it + made = c.post("/api/v1/namespaces/pods/entities", headers=ed, json={"name": "AC/DC?", "type": "ORG"}).json() + assert made["page"] == "/wiki/pods/AC%2FDC%3F" + got = find("AC%2FDC%3F").json() + assert (got["id"], got["canonical"]) == (made["id"], True) diff --git a/fastapi_backend/tests/api/test_entity_matching.py b/fastapi_backend/tests/api/test_entity_matching.py index b1d760a2c..80210c795 100644 --- a/fastapi_backend/tests/api/test_entity_matching.py +++ b/fastapi_backend/tests/api/test_entity_matching.py @@ -101,7 +101,7 @@ def test_assistant_manages_entities(db, cfg, folder, llm): ai_tools.approve(db, cfg, hide, me, {sid}) assert entities.detail(db, globex, {sid})["hidden"] is True found = json.loads(box.call("find_entities", {"query": "Initech"})[0])["entities"][0] - assert found["defined"] is True + assert found["defined"] is True and found["page"] == "/wiki/pods/Initech" box.call("propose_entity_change", {"action": "define", "namespace": "pods", "new_name": "Hooli"}) with pytest.raises(PermissionError): # approved by someone who can't change pods ai_tools.approve(db, cfg, box.approvals[-1]["id"], me, set()) diff --git a/fastapi_backend/tests/api/test_mcp.py b/fastapi_backend/tests/api/test_mcp.py index 1203d3a47..c40704638 100644 --- a/fastapi_backend/tests/api/test_mcp.py +++ b/fastapi_backend/tests/api/test_mcp.py @@ -281,6 +281,7 @@ def test_entities_and_the_graph(client, env, monkeypatch): e = tool(client, h, "get_entity", entity_id=dyno["entity_id"], mentions=2) assert e["name"] == "Dyno Therapeutics" and e["mentions"] == 4 and e["next_mentions_offset"] == 2 + assert e["url"] == "http://localhost:3000/wiki/pods/Dyno_Therapeutics" # its page, by name assert tool_error(client, h, "get_entity", entity_id=dyno["entity_id"], mentions_offset=10001).startswith("mentions_offset") for name in ("list_recordings", "list_entities", "list_topics"): # every page offset has the same cap as search's assert tool_error(client, h, name, offset=10001).startswith("offset"), name diff --git a/fastapi_backend/tests/api/test_rdf.py b/fastapi_backend/tests/api/test_rdf.py index 5a46b37b7..21bff48c7 100644 --- a/fastapi_backend/tests/api/test_rdf.py +++ b/fastapi_backend/tests/api/test_rdf.py @@ -8,7 +8,8 @@ from rdflib import Graph, Literal, URIRef from rdflib.namespace import DCMITYPE, DCTERMS, FOAF, RDF, SKOS -from app.domain import metadata, rdf +from app.domain import metadata, rdf, wiki +from app.domain.store import R from tests.api.test_iiif import BASE, Env from tests.helpers import login @@ -105,7 +106,8 @@ def test_namespace_graph_and_other_uris(env): eid = next(int(str(e).rsplit("/", 1)[1]) for e in g.subjects(RDF.type, SKOS.Concept)) assert c.get(f"/id/entity/{eid}", headers={**h, "Accept": "text/turtle"}).status_code == 200 r = c.get(f"/id/entity/{eid}", headers={**h, "Accept": "text/html"}, follow_redirects=False) - assert r.status_code == 303 and r.headers["location"].endswith(f"/entities/{eid}") + name = env.db.one("SELECT VALUE name FROM $r", r=R("entity", eid)) + assert r.status_code == 303 and r.headers["location"] == f"{BASE}{wiki.path('pods', name)}" # its page, by name spk = next(int(str(p).rsplit("/", 1)[1]) for p in people if "/id/speaker/" in str(p)) assert (URIRef(f"{BASE}/id/speaker/{spk}"), RDF.type, FOAF.Person) in parse( c.get(f"/id/speaker/{spk}", headers=h, params={"format": "ttl"}) diff --git a/nextjs-frontend/__tests__/notes-find.test.tsx b/nextjs-frontend/__tests__/notes-find.test.tsx index 86a380760..7235a5a17 100644 --- a/nextjs-frontend/__tests__/notes-find.test.tsx +++ b/nextjs-frontend/__tests__/notes-find.test.tsx @@ -89,10 +89,10 @@ describe("the Notes page", () => { const hit = await screen.findByRole("link", { name: /Weekly call/ }); expect(hit).toHaveTextContent("Page of entity"); expect(hit).toHaveTextContent("…we talked about capsids…"); - expect(hit).toHaveAttribute("href", "/notes/about/entity/5"); + expect(hit).toHaveAttribute("href", "/entities/5"); expect(m(Notes.searchPages).mock.calls.at(-1)[0].query).toMatchObject({ q: "capsids", ns: "home", place: null }); fireEvent.keyDown(box, { key: "Enter" }); - expect(push).toHaveBeenCalledWith("/notes/about/entity/5"); + expect(push).toHaveBeenCalledWith("/entities/5"); }); it("says when no note has the words", async () => { diff --git a/nextjs-frontend/__tests__/notes-links.test.ts b/nextjs-frontend/__tests__/notes-links.test.ts index 746e6fe0b..eb393a2cb 100644 --- a/nextjs-frontend/__tests__/notes-links.test.ts +++ b/nextjs-frontend/__tests__/notes-links.test.ts @@ -4,7 +4,7 @@ describe("links in notes", () => { it("open the thing in the app", () => { expect(hrefFor("page:3")).toBe("/notes/3"); expect(hrefFor("recording:12")).toBe("/resources/12"); - expect(hrefFor("entity:5", "pods")).toBe("/entities?entity=5&ns=pods"); + expect(hrefFor("entity:5", "pods")).toBe("/entities/5"); // its page, by name, once looked up expect(hrefFor("topic:2", "pods")).toBe("/topics/2"); expect(hrefFor("speaker:7")).toBe("/speakers/7"); expect(hrefFor("collection:4", "pods")).toBe("/library?namespace=pods&collection=4"); @@ -17,7 +17,8 @@ describe("links in notes", () => { }); it("find a thing's page", () => { - expect(pageOf("entity:5")).toBe("/notes/about/entity/5"); + expect(pageOf("recording:5")).toBe("/notes/about/recording/5"); + expect(pageOf("entity:5")).toBe("/entities/5"); }); }); diff --git a/nextjs-frontend/__tests__/wiki-page.test.tsx b/nextjs-frontend/__tests__/wiki-page.test.tsx new file mode 100644 index 000000000..f21a89624 --- /dev/null +++ b/nextjs-frontend/__tests__/wiki-page.test.tsx @@ -0,0 +1,151 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { render, screen, waitFor, within } from "@testing-library/react"; +import "@testing-library/jest-dom"; + +import { Entities } from "@/app/openapi-client"; +import { WikiPage } from "@/components/wiki/entity-page"; +import { addressOf, samePath, titleOf, wikiPath, wikiSlug } from "@/components/wiki/links"; +import { TooltipProvider } from "@/components/ui/tooltip"; + +jest.mock("@/app/openapi-client", () => ({ + Entities: { + findWikiPage: jest.fn(), + getEntity: jest.fn(), + listEntityMentions: jest.fn(), + getEntityConnections: jest.fn(), + }, +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); +jest.mock("@/components/ui/toast", () => ({ useToast: () => jest.fn() })); +jest.mock("@/lib/hooks/session", () => ({ useArchive: () => ({ can: () => true }) })); +// the notes part and "Similar content" are tested on their own; here they only have to be there +jest.mock("@/components/notes/note-page", () => ({ + NotePage: ({ about, embedded }: { about: string; embedded?: boolean }) => ( +
{`${about} ${embedded ? "embedded" : ""}`}
+ ), +})); +jest.mock("@/components/similar/similar-list", () => ({ SimilarSection: () => null })); +const replace = jest.fn(); +jest.mock("next/navigation", () => ({ useRouter: () => ({ replace, push: jest.fn() }) })); + +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) => { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + {ui} + , + ); +}; + +const ADA = { + id: 5, + name: "Ada Lovelace", + key: "ada lovelace", + type: "PERSON", + type_label: "Person", + namespace: "work", + description: "Wrote the first program", + aliases: ["Countess of Lovelace"], + mentions: 3, + recordings: 2, + speakers: 1, + first: "2026-01-02", + last: "2026-03-04", + links: [{ id: 9, name: "Ada Lovelace", namespace: "home" }], + page: "/wiki/work/Ada_Lovelace", +}; + +beforeEach(() => { + jest.clearAllMocks(); + window.history.replaceState(null, "", "/wiki/work/Ada_Lovelace"); + m(Entities.getEntity).mockReturnValue(ok(ADA)); + m(Entities.listEntityMentions).mockReturnValue( + ok({ + total: 1, + items: [ + { + mention: 1, + recording_id: 12, + title: "Weekly call", + t0: 65000, + time: "01:05", + speaker: "Alice", + text: "We read Ada Lovelace's notes.", + highlight: [8, 20], + }, + ], + }), + ); + m(Entities.getEntityConnections).mockReturnValue( + ok({ + entities: [{ id: 6, name: "Charles Babbage", type: "PERSON", together: 2 }], + speakers: [{ id: 3, name: "Alice", mentions: 3 }], + recordings: [{ id: 12, title: "Weekly call", mentions: 2 }], + }), + ); +}); + +describe("wiki addresses", () => { + it("name a page by the entity's name, spaces as underscores", () => { + expect(wikiSlug(" Ada Lovelace ")).toBe("Ada_Lovelace"); + expect(wikiPath("work", "Ada Lovelace")).toBe("/wiki/work/Ada_Lovelace"); + expect(wikiPath("work", "AC/DC?")).toBe("/wiki/work/AC%2FDC%3F"); + expect(addressOf(["AC%2FDC%3F"])).toBe("AC/DC?"); + expect(addressOf(["AC", "DC"])).toBe("AC/DC"); + expect(addressOf(["100%"])).toBe("100%"); // not escaped: kept as it is + expect(titleOf("Ada_Lovelace")).toBe("Ada Lovelace"); + expect(samePath("/wiki/a/McDonald%27s", "/wiki/a/McDonald's")).toBe(true); + expect(samePath("/wiki/a/Ada_Lovelace", "/wiki/a/ada_lovelace")).toBe(false); + }); +}); + +describe("an entity's page", () => { + it("shows what it is, its notes, where it's said and what it comes up with", async () => { + m(Entities.findWikiPage).mockReturnValue( + ok({ kind: "entity", id: 5, namespace: "work", title: "Ada Lovelace", path: ADA.page, canonical: true }), + ); + show(); + expect(await screen.findByRole("heading", { level: 1, name: "Ada Lovelace" })).toBeInTheDocument(); + expect(m(Entities.findWikiPage).mock.calls[0][0].path).toEqual({ ns: "work", address: "Ada_Lovelace" }); + expect(screen.getByText("Wrote the first program")).toBeInTheDocument(); + expect(screen.getByText("Also said as Countess of Lovelace")).toBeInTheDocument(); + expect(screen.getByTestId("notes")).toHaveTextContent("entity:5 embedded"); + + const said = screen.getByRole("region", { name: "Where it’s said" }); + expect(await within(said).findByRole("link", { name: "Weekly call · 01:05 · Alice" })).toHaveAttribute( + "href", + "/resources/12?t=65", + ); + expect(within(said).getByText("Ada Lovelace", { selector: "mark" })).toBeInTheDocument(); + + const side = screen.getByRole("complementary", { name: "About this entity" }); + expect(await within(side).findByRole("link", { name: "Charles Babbage" })).toHaveAttribute( + "href", + "/wiki/work/Charles_Babbage", + ); + expect(within(side).getByRole("link", { name: "Ada Lovelace" })).toHaveAttribute("href", "/wiki/home/Ada_Lovelace"); + expect(within(side).getByRole("link", { name: "Alice" })).toHaveAttribute("href", "/speakers/3"); + expect(screen.getByRole("link", { name: "Graph" })).toHaveAttribute("href", "/graph?focus=e5"); + expect(replace).not.toHaveBeenCalled(); + }); + + it("switches another way of writing its name to its own address", async () => { + window.history.replaceState(null, "", "/wiki/work/ada_lovelace"); + m(Entities.findWikiPage).mockReturnValue( + ok({ kind: "entity", id: 5, namespace: "work", title: "Ada Lovelace", path: ADA.page, canonical: false }), + ); + show(); + await waitFor(() => expect(replace).toHaveBeenCalledWith("/wiki/work/Ada_Lovelace")); + }); + + it("says when nothing is called that", async () => { + m(Entities.findWikiPage).mockReturnValue( + Promise.resolve({ error: { detail: "not found" }, response: { ok: false, status: 404 } }), + ); + show(); + expect(await screen.findByText("No page by that name")).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Entities in work" })).toHaveAttribute("href", "/entities?ns=work"); + }); +}); diff --git a/nextjs-frontend/app/(app)/entities/[id]/page.tsx b/nextjs-frontend/app/(app)/entities/[id]/page.tsx index 570750b03..c02589935 100644 --- a/nextjs-frontend/app/(app)/entities/[id]/page.tsx +++ b/nextjs-frontend/app/(app)/entities/[id]/page.tsx @@ -1,8 +1,13 @@ -import { notFound, redirect } from "next/navigation"; +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; -/** Entities have no page of their own in the design: an entity opens in the graph with its panel. */ +import { ToEntityPage } from "@/components/wiki/to-entity-page"; + +export const metadata: Metadata = { title: "Entity" }; + +/** An entity by id (what links and the RDF URI /id/entity/ use): its own page, by name, under /wiki. */ export default async function EntityPage({ params }: { params: Promise<{ id: string }> }) { const { id } = await params; if (!/^\d+$/.test(id)) notFound(); - redirect(`/graph?focus=e${id}`); + return ; } diff --git a/nextjs-frontend/app/(app)/notes/about/[kind]/[key]/page.tsx b/nextjs-frontend/app/(app)/notes/about/[kind]/[key]/page.tsx index c5530f6c2..0d359e987 100644 --- a/nextjs-frontend/app/(app)/notes/about/[kind]/[key]/page.tsx +++ b/nextjs-frontend/app/(app)/notes/about/[kind]/[key]/page.tsx @@ -1,11 +1,14 @@ import type { Metadata } from "next"; import { NotePage } from "@/components/notes/note-page"; +import { ToEntityPage } from "@/components/wiki/to-entity-page"; export const metadata: Metadata = { title: "Note" }; -/** The page of a recording, entity, collection or speaker: a draft until someone writes on it. */ +/** The page of a recording, collection, topic or speaker: a draft until someone writes on it. An entity's notes are + * on its own page, under /wiki. */ export default async function Page({ params }: { params: Promise<{ kind: string; key: string }> }) { const { kind, key } = await params; + if (kind === "entity" && /^\d+$/.test(key)) return ; return ; } diff --git a/nextjs-frontend/app/(app)/wiki/[ns]/[...address]/page.tsx b/nextjs-frontend/app/(app)/wiki/[ns]/[...address]/page.tsx new file mode 100644 index 000000000..05fcd7f4e --- /dev/null +++ b/nextjs-frontend/app/(app)/wiki/[ns]/[...address]/page.tsx @@ -0,0 +1,17 @@ +import type { Metadata } from "next"; + +import { WikiPage } from "@/components/wiki/entity-page"; +import { addressOf, titleOf } from "@/components/wiki/links"; + +type Params = { params: Promise<{ ns: string; address: string[] }> }; + +export async function generateMetadata({ params }: Params): Promise { + const { address } = await params; + return { title: titleOf(addressOf(address)) }; +} + +/** An entity's page, by name: /wiki// (app/domain/wiki.py). */ +export default async function Page({ params }: Params) { + const { ns, address } = await params; + return ; +} diff --git a/nextjs-frontend/app/(app)/wiki/[ns]/page.tsx b/nextjs-frontend/app/(app)/wiki/[ns]/page.tsx new file mode 100644 index 000000000..ea4625f31 --- /dev/null +++ b/nextjs-frontend/app/(app)/wiki/[ns]/page.tsx @@ -0,0 +1,7 @@ +import { redirect } from "next/navigation"; + +/** A namespace's wiki: its entities, each a link to its page. */ +export default async function Page({ params }: { params: Promise<{ ns: string }> }) { + const { ns } = await params; + redirect(`/entities?ns=${ns}`); +} diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index c5089f60c..bcdc0bbd8 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -942,6 +942,11 @@ export type { FindSimilarErrors, FindSimilarResponse, FindSimilarResponses, + FindWikiPageData, + FindWikiPageError, + FindWikiPageErrors, + FindWikiPageResponse, + FindWikiPageResponses, FinishData, FinishError, FinishErrors, @@ -3305,6 +3310,7 @@ export type { WatchUpdate, WebImportRequest, WebPage, + WikiPage, WorkerComponents, WorkerInfo, Workflow, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 8fe7b4f38..3663d2a31 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -436,6 +436,9 @@ import type { FindSimilarData, FindSimilarErrors, FindSimilarResponses, + FindWikiPageData, + FindWikiPageErrors, + FindWikiPageResponses, FinishData, FinishErrors, FinishResponses, @@ -6501,6 +6504,21 @@ export class Entities { }); } + /** + * Find Wiki Page + * + * The page /wiki//
names: the entity called that (spaces as underscores, any case), or the one a name + * it had before a rename or a merge now belongs to. When `canonical` is false, show `path` instead. + */ + public static findWikiPage( + options: Options, + ): RequestResult { + return (options.client ?? client).get({ + url: "/api/v1/wiki/{ns}/{address}", + ...options, + }); + } + /** * List Entity Mentions * diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index b255196d0..0037b702f 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -4138,6 +4138,12 @@ export type EntityDetail = { * a defined entity of one collection (and those inside it) */ collection?: number | null; + /** + * Page + * + * its page in the web app, by name: /wiki// + */ + page?: string | null; [key: string]: unknown; }; @@ -20261,6 +20267,47 @@ export type WebPage = { [key: string]: unknown; }; +/** + * WikiPage + * + * What a wiki address names, and the address to show for it. + */ +export type WikiPage = { + /** + * Kind + * + * entity + */ + kind: string; + /** + * Id + */ + id: number; + /** + * Namespace + */ + namespace: string; + /** + * Title + * + * its name + */ + title: string; + /** + * Path + * + * its own address, like /wiki/work/Ada_Lovelace + */ + path: string; + /** + * Canonical + * + * false: the address asked for is another way to write it (any case, or a name it had before a rename or merge); show `path` + */ + canonical: boolean; + [key: string]: unknown; +}; + /** * WorkerComponents */ @@ -29449,6 +29496,40 @@ export type UpdateEntityResponses = { export type UpdateEntityResponse = UpdateEntityResponses[keyof UpdateEntityResponses]; +export type FindWikiPageData = { + body?: never; + path: { + /** + * Ns + */ + ns: string; + /** + * Address + */ + address: string; + }; + query?: never; + url: "/api/v1/wiki/{ns}/{address}"; +}; + +export type FindWikiPageErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type FindWikiPageError = FindWikiPageErrors[keyof FindWikiPageErrors]; + +export type FindWikiPageResponses = { + /** + * Successful Response + */ + 200: WikiPage; +}; + +export type FindWikiPageResponse = FindWikiPageResponses[keyof FindWikiPageResponses]; + export type ListEntityMentionsData = { body?: never; path: { diff --git a/nextjs-frontend/components/app-shell/nav-config.ts b/nextjs-frontend/components/app-shell/nav-config.ts index 2e0a3bd5b..48d253bc4 100644 --- a/nextjs-frontend/components/app-shell/nav-config.ts +++ b/nextjs-frontend/components/app-shell/nav-config.ts @@ -92,6 +92,8 @@ export function isActive(pathname: string, href: string): boolean { if (href === "/sensors" && (pathname === "/sources" || pathname.startsWith("/sources/"))) return true; // Members opening /sensors see their Sources page. if (href === "/sources" && pathname === "/sensors") return true; + // An entity's page is under /wiki, by name. + if (href === "/entities" && pathname.startsWith("/wiki/")) return true; // Speakers live in Settings; a speaker's profile keeps its own address. if (href === "/settings" && (pathname === "/speakers" || pathname.startsWith("/speakers/"))) return true; return pathname === href || pathname.startsWith(`${href}/`); diff --git a/nextjs-frontend/components/entities/entities-page.tsx b/nextjs-frontend/components/entities/entities-page.tsx index 19ee85a8b..638e2afa1 100644 --- a/nextjs-frontend/components/entities/entities-page.tsx +++ b/nextjs-frontend/components/entities/entities-page.tsx @@ -2,6 +2,7 @@ import { keepPreviousData, useQuery } from "@tanstack/react-query"; import { ChevronRight, Plus, Shapes } from "lucide-react"; +import Link from "next/link"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { useEffect, useState } from "react"; @@ -29,6 +30,7 @@ import { EmptyState, PageHeader, SkeletonRows } from "@/components/ui/states"; import { Pagination, SortTh, Table, Td, Th, THead, Tr } from "@/components/ui/table"; import { Tabs } from "@/components/ui/tabs"; import { useToast } from "@/components/ui/toast"; +import { wikiPath } from "@/components/wiki/links"; import { ApiError, data, useApiClient } from "@/lib/api/browser"; import { count, plural, shortDate } from "@/lib/format"; import { needRole, useArchive } from "@/lib/hooks/session"; @@ -350,16 +352,14 @@ export function EntitiesPage() { )} - + {e.builtin ? ( always there diff --git a/nextjs-frontend/components/entities/entity-drawer.tsx b/nextjs-frontend/components/entities/entity-drawer.tsx index b822eddfd..cc30c8ec4 100644 --- a/nextjs-frontend/components/entities/entity-drawer.tsx +++ b/nextjs-frontend/components/entities/entity-drawer.tsx @@ -199,7 +199,7 @@ export function EntityDrawer({ d && ( <> + ))} + + ); return ( -
+
- {page.namespace} + {!embedded && {page.namespace}} {aboutHref && ( Open {page.about?.split(":")[0]} @@ -265,6 +298,7 @@ export function NotePage({ id, about }: { id?: number; about?: string }) { )} + {embedded && views} {canEdit && ( {state === "saving" ? "Saving…" : state === "error" ? "Not saved" : saved ? "Saved" : "Draft"} @@ -281,142 +315,130 @@ export function NotePage({ id, about }: { id?: number; about?: string }) { )}
- { - setTitle(e.target.value); - change({ title: e.target.value }); - }} - onKeyDown={(e) => { - // Enter goes on to the page's first line, as in a document - if (e.key !== "Enter" || e.nativeEvent.isComposing) return; - // (the page root is what takes the focus; the caret goes in its first paragraph, not the hidden title line) - const root = document.querySelector(".lens-block-editor affine-page-root"); - const line = root?.querySelector(".inline-editor"); - if (!root || !line) return; - e.preventDefault(); - root.focus(); - window.getSelection()?.collapse(line, 0); - }} - placeholder="Untitled" - className="w-full bg-transparent text-[30px] font-bold leading-tight tracking-[-.015em] text-fg outline-hidden placeholder:text-fg-muted" - /> - { - setSummary(e.target.value); - change({ summary: e.target.value }); - }} - placeholder={canEdit ? "One line on what this note holds (the assistant reads it first)" : ""} - className="w-full bg-transparent text-[15px] text-fg-secondary outline-hidden placeholder:text-fg-muted" - /> -
- - - {canEdit && !place && saved?.place_suggestion && ( - - )} - {canEdit && saved && !saved.about && saved.parent == null && ( - { - setLinking(true); - try { - await flush(); - const out = await data(Notes.movePage({ client, path: { pid: saved.id }, body: { parent: s.page } })); - qc.setQueryData(key, out); - qc.invalidateQueries({ queryKey: ["notes-tree"] }); - } catch (err) { - toast({ - title: "Couldn’t move it", - body: err instanceof ApiError ? err.message : "Please try again.", - tone: "red", - }); - } finally { - setLinking(false); - } + setSummary(e.target.value); + change({ summary: e.target.value }); }} + placeholder={canEdit ? "One line on what this note holds (the assistant reads it first)" : ""} + className="w-full bg-transparent text-[15px] text-fg-secondary outline-hidden placeholder:text-fg-muted" /> - )} - {saved?.updated_at && Changed {shortDate(saved.updated_at)}} - -
- {( - [ - ["page", "Page", FileText], - ["edgeless", "Canvas", Shapes], - ] as const - ).map(([v, label, Icon]) => ( - - ))} -
-
+
+ + + {canEdit && !place && saved?.place_suggestion && ( + + )} + {canEdit && saved && !saved.about && saved.parent == null && ( + { + setLinking(true); + try { + await flush(); + const out = await data( + Notes.movePage({ client, path: { pid: saved.id }, body: { parent: s.page } }), + ); + qc.setQueryData(key, out); + qc.invalidateQueries({ queryKey: ["notes-tree"] }); + } catch (err) { + toast({ + title: "Couldn’t move it", + body: err instanceof ApiError ? err.message : "Please try again.", + tone: "red", + }); + } finally { + setLinking(false); + } + }} + /> + )} + {saved?.updated_at && Changed {shortDate(saved.updated_at)}} + + {views} +
+ + )} + {embedded && canEdit && !(page.body ?? "").trim() && ( +

+ Nothing written on {page.title} yet. Write below: @ links people, things and recordings, # links topics. +

+ )} )} - {saved && } + {saved && !embedded && }
); } @@ -487,7 +509,10 @@ function Backlinks({ items }: { items: { page: number; title: string; about?: st
    {items.map((b) => (
  • - + {b.title}
  • diff --git a/nextjs-frontend/components/wiki/entity-page.tsx b/nextjs-frontend/components/wiki/entity-page.tsx new file mode 100644 index 000000000..5bb5e5925 --- /dev/null +++ b/nextjs-frontend/components/wiki/entity-page.tsx @@ -0,0 +1,304 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { History, Link2, Pencil, Shapes, Waypoints } from "lucide-react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { type ReactNode, useEffect, useState } from "react"; + +import { Entities } from "@/app/openapi-client"; +import { EntityDrawer } from "@/components/entities/entity-drawer"; +import { NotePage } from "@/components/notes/note-page"; +import { recordingHref } from "@/components/search/links"; +import { SimilarSection } from "@/components/similar/similar-list"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { EmptyState, Skeleton } from "@/components/ui/states"; +import { useToast } from "@/components/ui/toast"; +import { samePath, wikiPath } from "@/components/wiki/links"; +import { data, useApiClient } from "@/lib/api/browser"; +import { count, shortDate } from "@/lib/format"; +import { useArchive } from "@/lib/hooks/session"; + +type Mention = { + mention: number; + recording_id: number; + title?: string | null; + t0?: number | null; + time?: string | null; + speaker?: string | null; + text?: string | null; + highlight?: [number, number] | null; +}; +type Connections = { + entities: { id: number; name: string; type: string; together: number }[]; + speakers: { id: number; name: string; mentions: number }[]; + recordings: { id: number; title?: string | null; mentions: number }[]; +}; + +const MORE = 20; + +/** The page an address under /wiki// names, after it is looked up; another way of writing it (any case, an old or + * merged name) switches the address to the page's own. */ +export function WikiPage({ ns, address }: { ns: string; address: string }) { + const client = useApiClient(); + const router = useRouter(); + const found = useQuery({ + queryKey: ["wiki", ns, address], + queryFn: () => data(Entities.findWikiPage({ client, path: { ns, address } })), + retry: false, + placeholderData: (prev) => prev, // the page stays while a new address of it is looked up + }); + useEffect(() => { + if (found.data && !found.data.canonical) router.replace(found.data.path + window.location.hash); + }, [found.data, router]); + + if (found.isError) + return ( + } + title="No page by that name" + actions={ + + } + > + Nothing in {ns} is called that, or you can’t read {ns}. + + ); + if (!found.data) return ; + return ; +} + +function Loading() { + return ( +
    + + + +
    + ); +} + +/** One entity's page: what it is, the notes people and the assistant keep on it (the BlockSuite editor), where it's + * said, the assets, entities and people it comes up with, and what's like it. */ +export function EntityPage({ id }: { id: number }) { + const client = useApiClient(); + const router = useRouter(); + const toast = useToast(); + const { can } = useArchive(); + const [editing, setEditing] = useState(false); + const [limit, setLimit] = useState(10); + const e = useQuery({ + queryKey: ["entity", id], + queryFn: () => data(Entities.getEntity({ client, path: { eid: id } })), + }); + const mentions = useQuery({ + queryKey: ["entity-mentions", id, limit], + queryFn: () => data(Entities.listEntityMentions({ client, path: { eid: id }, query: { limit } })), + placeholderData: (prev) => prev, + }); + const links = useQuery({ + queryKey: ["entity", id, "connections"], + queryFn: () => data(Entities.getEntityConnections({ client, path: { eid: id } })) as Promise, + }); + + // Renamed here (or by anyone): the address follows the name. + const page = e.data?.page; + useEffect(() => { + if (page && !samePath(window.location.pathname, page)) router.replace(page + window.location.hash); + }, [page, router]); + + if (e.isError) + return ( + } title="This entity isn’t here" tone="error"> + It was merged into another, or it’s in a namespace you can’t read. + + ); + const d = e.data; + if (!d) return ; + const ns = d.namespace ?? ""; + const items = (mentions.data?.items ?? []) as unknown as Mention[]; + const total = mentions.data?.total ?? 0; + const con = links.data; + const copy = async () => { + try { + await navigator.clipboard.writeText(window.location.origin + (d.page ?? "")); + toast({ title: "Link copied", tone: "green" }); + } catch { + toast({ title: "Couldn’t copy the link", tone: "red" }); + } + }; + + return ( +
    +
    + +
    +

    {d.name}

    + {d.defined && On the fixed list} + {d.hidden && Hidden} +
    + {d.aliases && d.aliases.length > 0 && ( +

    Also said as {d.aliases.join(", ")}

    + )} + {d.description ? ( +

    {d.description}

    + ) : ( +

    No description yet.

    + )} +
    + + + + +
    +
    + +
    +
    +
    +

    Notes

    + +
    + +
    +

    + Where it’s said{total ? ` (${count(total)})` : ""} +

    + {mentions.isLoading && } + {mentions.data && !items.length && ( +

    No mentions you can read.

    + )} +
      + {items.map((m) => ( +
    • + + {m.title ?? `Asset ${m.recording_id}`} + {m.time ? ` · ${m.time}` : ""} + {m.speaker ? ` · ${m.speaker}` : ""} + + +
    • + ))} +
    + {items.length < total && ( + + )} +
    +
    + + +
    + {editing && setEditing(false)} />} +
    + ); +} + +/** A list in the side column; nothing when it's empty. */ +function Side({ title, children }: { title: string; children?: ReactNode[] }) { + if (!children?.length) return null; + return ( +
    +

    {title}

    +
      {children}
    +
    + ); +} + +/** A transcript line, with the words that name the entity marked. */ +function Line({ text, mark }: { text: string; mark?: [number, number] | null }) { + const cls = "font-serif text-[14px] leading-[1.45] text-fg"; + if (!mark || mark[0] < 0 || mark[1] > text.length) return {text}; + return ( + + {text.slice(0, mark[0])} + {text.slice(mark[0], mark[1])} + {text.slice(mark[1])} + + ); +} diff --git a/nextjs-frontend/components/wiki/links.ts b/nextjs-frontend/components/wiki/links.ts new file mode 100644 index 000000000..ae53ad926 --- /dev/null +++ b/nextjs-frontend/components/wiki/links.ts @@ -0,0 +1,33 @@ +/** Wiki addresses: an entity's page is /wiki//, as the API's `page` says (app/domain/wiki.py). + * Spaces become underscores; any case, and a name it had before a rename or a merge, find it too. */ +export function wikiSlug(name: string): string { + return name.trim().replace(/\s+/g, "_"); +} + +/** The page of the entity called `name` in namespace `ns`: /wiki/work/Ada_Lovelace. */ +export function wikiPath(ns: string, name: string): string { + return `/wiki/${encodeURIComponent(ns)}/${encodeURIComponent(wikiSlug(name))}`; +} + +function unescape(s: string): string { + try { + return decodeURIComponent(s); + } catch { + return s; + } +} + +/** The address a /wiki//… route was opened with, as written: its parts joined (a name may hold a /), unescaped. */ +export function addressOf(parts: string[]): string { + return parts.map(unescape).join("/"); +} + +/** Whether two paths are the same page however they're escaped (/wiki/a/McDonald's and /wiki/a/McDonald%27s). */ +export function samePath(a: string, b: string): boolean { + return unescape(a) === unescape(b); +} + +/** The name an address reads as, for the tab's title while the page loads: Ada_Lovelace -> Ada Lovelace. */ +export function titleOf(address: string): string { + return address.replace(/_+/g, " ").trim(); +} diff --git a/nextjs-frontend/components/wiki/to-entity-page.tsx b/nextjs-frontend/components/wiki/to-entity-page.tsx new file mode 100644 index 000000000..4335d2321 --- /dev/null +++ b/nextjs-frontend/components/wiki/to-entity-page.tsx @@ -0,0 +1,37 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { Shapes } from "lucide-react"; +import { useRouter } from "next/navigation"; +import { useEffect } from "react"; + +import { Entities } from "@/app/openapi-client"; +import { EmptyState, Skeleton } from "@/components/ui/states"; +import { data, useApiClient } from "@/lib/api/browser"; + +/** /entities/5, and the notes address an entity's page had before (/notes/about/entity/5): its page, by name. */ +export function ToEntityPage({ id }: { id: number }) { + const client = useApiClient(); + const router = useRouter(); + const e = useQuery({ + queryKey: ["entity", id], + queryFn: () => data(Entities.getEntity({ client, path: { eid: id } })), + retry: false, + }); + const page = e.data?.page; + useEffect(() => { + if (page) router.replace(page + window.location.hash); + }, [page, router]); + if (e.isError) + return ( + } title="This entity isn’t here" tone="error"> + It was merged into another, or it’s in a namespace you can’t read. + + ); + return ( +
    + + +
    + ); +} diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 63a2a243a..449ef8c45 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -14386,6 +14386,58 @@ } } }, + "/api/v1/wiki/{ns}/{address}": { + "get": { + "tags": [ + "entities" + ], + "summary": "Find Wiki Page", + "description": "The page /wiki//
    names: the entity called that (spaces as underscores, any case), or the one a name\nit had before a rename or a merge now belongs to. When `canonical` is false, show `path` instead.", + "operationId": "find_wiki_page", + "parameters": [ + { + "name": "ns", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Ns" + } + }, + { + "name": "address", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Address" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WikiPage" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/entities/{eid}/mentions": { "get": { "tags": [ @@ -34813,6 +34865,18 @@ ], "title": "Collection", "description": "a defined entity of one collection (and those inside it)" + }, + "page": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Page", + "description": "its page in the web app, by name: /wiki//" } }, "additionalProperties": true, @@ -62567,6 +62631,50 @@ "title": "WebPage", "description": "A web page captured as a document: where it was, and when." }, + "WikiPage": { + "properties": { + "kind": { + "type": "string", + "title": "Kind", + "description": "entity" + }, + "id": { + "type": "integer", + "title": "Id" + }, + "namespace": { + "type": "string", + "title": "Namespace" + }, + "title": { + "type": "string", + "title": "Title", + "description": "its name" + }, + "path": { + "type": "string", + "title": "Path", + "description": "its own address, like /wiki/work/Ada_Lovelace" + }, + "canonical": { + "type": "boolean", + "title": "Canonical", + "description": "false: the address asked for is another way to write it (any case, or a name it had before a rename or merge); show `path`" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "kind", + "id", + "namespace", + "title", + "path", + "canonical" + ], + "title": "WikiPage", + "description": "What a wiki address names, and the address to show for it." + }, "WorkerComponents": { "properties": { "name": {