diff --git a/CHANGELOG.md b/CHANGELOG.md index 79238b230..e51436ee8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Today's note.** Today on the Notes page, or Today's note in Jump to, opens the note for the day, made the first + time it's asked for inside a Daily notes note ([Today's note](docs/notes.md#todays-note)). - **Pin notes.** A note's ⋯ menu in the tree has Pin: pinned notes show at the top of the tree and first on the Notes page, for the person who pinned them only ([Pinned notes](docs/notes.md#pinned-notes)). - **Notes tree menu.** Each note in the tree in the left navigation has a ⋯ menu to add a note inside, rename it in diff --git a/docs/api.md b/docs/api.md index f6b6053e9..cadd175f2 100644 --- a/docs/api.md +++ b/docs/api.md @@ -687,6 +687,7 @@ deleted. ``` GET /api/v1/notes POST /api/v1/notes +POST /api/v1/notes/today GET /api/v1/notes/search GET /api/v1/notes/deleted POST /api/v1/notes/deleted/{pid}/restore @@ -707,7 +708,8 @@ DELETE /api/v1/notes/{pid}/files ``` Note pages ([Notes](notes.md)), apart from the notes on an asset above. `GET /notes?ns=` is a namespace's page tree -(`all=true` adds the pages of things). `search?q=` finds pages by the words in their title, summary or text, title +(`all=true` adds the pages of things). `today` gives the namespace's note for `date`, made the first time it's asked +for ([Today's note](notes.md#todays-note)). `search?q=` finds pages by the words in their title, summary or text, title matches first, each with the words around the match ([Finding notes](notes.md#finding-notes)). `DELETE /notes/{pid}` moves a page to recently deleted for 30 days: `deleted` lists them, `restore` puts one back where it was and `DELETE /notes/deleted/{pid}` deletes one for good ([Deleting](notes.md#deleting-and-putting-back)). `move` puts a diff --git a/docs/notes.md b/docs/notes.md index 64632be63..5a73c032a 100644 --- a/docs/notes.md +++ b/docs/notes.md @@ -135,6 +135,14 @@ and entities aren't in the tree: they open from those things. `POST /api/v1/notes/{pid}/move` with `{parent}` moves a note (`null` for the top); `PATCH /api/v1/notes/{pid}` with `{title}` renames it. +## Today's note + +**Today** on the Notes page (or **Today's note** in Jump to, or the address `/notes/today`) opens the note for the +day in the namespace in view, made the first time it's asked for: titled with the date (like 2026-10-15) and inside a +**Daily notes** note, made too when there's none. It's the day where you are, and one note a day per namespace that +everyone there shares; rename or move it like any note. `POST /api/v1/notes/today` with `{ns, date}` (editors) gives +the same note to agents. + ## Pinned notes **Pin** in a note's ⋯ menu in the tree pins it for you: it shows at the top of the tree, under **Pinned**, and first diff --git a/fastapi_backend/app/api/v1/routes/notebook.py b/fastapi_backend/app/api/v1/routes/notebook.py index 1401a332e..045a9fca2 100644 --- a/fastapi_backend/app/api/v1/routes/notebook.py +++ b/fastapi_backend/app/api/v1/routes/notebook.py @@ -36,6 +36,7 @@ NotePageMove, NotePageUpdate, NoteSearch, + NoteToday, NoteTree, NoteVersion, NoteVersionItem, @@ -116,6 +117,16 @@ def create_page(body: NotePageCreate, user: Writer, acl: Acl, db: Db) -> NotePag return _out(acl, db, notebook.get(db, pid), user) +@router.post("/today") +def today_page(body: NoteToday, user: Writer, acl: Acl, db: Db) -> NotePage: + """The namespace's note for the day (`date`, your today), made the first time it's asked for: titled with the + date, inside the "Daily notes" note. Needs editor access.""" + sid = acl.namespace(body.ns, "editor") + with domain_errors(): + pid = notebook.today(db, sid, user.id, body.date) + return _out(acl, db, notebook.get(db, pid), user) + + @router.get("/targets") def link_targets( ns: str, user: CurrentUser, acl: Acl, db: Db, q: str = "", sign: str = "@", limit: int = Query(20, ge=1, le=50) diff --git a/fastapi_backend/app/domain/notebook.py b/fastapi_backend/app/domain/notebook.py index cb5ab1e93..096398ccf 100644 --- a/fastapi_backend/app/domain/notebook.py +++ b/fastapi_backend/app/domain/notebook.py @@ -413,6 +413,26 @@ def move(db, pid, parent=None, before=None): db.q("UPDATE $r SET parent = $p, position = $pos, updated_at = $t", r=R("note_page", int(pid)), p=parent, pos=position, t=store.now()) +DAILY_ROOT = "Daily notes" + + +def today(db, sid, account, date=None): + """The namespace's note for the day `date` (YYYY-MM-DD, the person's today; default the server's), made the first + time it's asked for: titled with the date, inside the "Daily notes" note, which is made too when there's none. + Its id.""" + day = _date(date) or store.now()[:10] + pid = db.one("SELECT VALUE record::id(id) FROM note_page WHERE space = $s AND daily = $d LIMIT 1", s=sid, d=day) + if pid: + return int(pid) + root = db.one("SELECT VALUE record::id(id) FROM note_page WHERE space = $s AND daily_root = true LIMIT 1", s=sid) + if not root: + root = create(db, sid, account, DAILY_ROOT, summary="A note for each day") + db.q("UPDATE $r SET daily_root = true", r=R("note_page", root)) + pid = create(db, sid, account, day, date=day, parent=root) + db.q("UPDATE $r SET daily = $d", r=R("note_page", pid), d=day) + return pid + + PINS_MAX = 50 # a person's pinned notes, per namespace diff --git a/fastapi_backend/app/schemas/notebook.py b/fastapi_backend/app/schemas/notebook.py index 62e83a504..0b806a575 100644 --- a/fastapi_backend/app/schemas/notebook.py +++ b/fastapi_backend/app/schemas/notebook.py @@ -149,6 +149,11 @@ class NotePageUpdate(RequestModel): view: Literal["page", "edgeless"] | None = Field(None, description="show it as a page or on the edgeless canvas") +class NoteToday(RequestModel): + ns: str = Field(description="the namespace whose daily note it is") + date: str | None = Field(None, description="YYYY-MM-DD, your today (default: the server's)") + + class NotePageMove(RequestModel): parent: int | None = Field(None, description="the page to put it inside; null for the top") before: int | None = Field(None, description="put it before this sibling; null for the end") diff --git a/fastapi_backend/tests/api/test_notebook.py b/fastapi_backend/tests/api/test_notebook.py index 4e7e87a55..8f3d79e31 100644 --- a/fastapi_backend/tests/api/test_notebook.py +++ b/fastapi_backend/tests/api/test_notebook.py @@ -567,3 +567,27 @@ def test_pins(client, env, db): assert client.put(f"/api/v1/notes/{b['id']}/pin", headers=he).status_code == 200 finally: notebook.PINS_MAX = old + + +def test_daily_notes(client, env, db): + he, hv = env["he"], env["hv"] + r = client.post("/api/v1/notes/today", headers=he, json={"ns": "pods", "date": "2026-10-15"}) + assert r.status_code == 200, r.text + day = r.json() + assert (day["title"], day["date"]) == ("2026-10-15", "2026-10-15") + root = client.get(f"/api/v1/notes/{day['parent']}", headers=he).json() + assert root["title"] == "Daily notes" and root["parent"] is None + # the same day again is the same note, even renamed; the next day goes beside it + client.patch(f"/api/v1/notes/{day['id']}", headers=he, json={"title": "Launch day"}) + assert client.post("/api/v1/notes/today", headers=he, json={"ns": "pods", "date": "2026-10-15"}).json()["id"] == day["id"] + nxt = client.post("/api/v1/notes/today", headers=he, json={"ns": "pods", "date": "2026-10-16"}).json() + assert nxt["id"] != day["id"] and nxt["parent"] == root["id"] + # without a date it's the server's today + assert client.post("/api/v1/notes/today", headers=he, json={"ns": "pods"}).json()["date"] == store.now()[:10] + # editors only, and a date that is one + assert client.post("/api/v1/notes/today", headers=hv, json={"ns": "pods"}).status_code == 403 + assert client.post("/api/v1/notes/today", headers=he, json={"ns": "pods", "date": "soon"}).status_code == 400 + # the daily notes' note, when deleted, is made again the next time + assert client.delete(f"/api/v1/notes/{root['id']}", headers=he).status_code == 200 + again = client.post("/api/v1/notes/today", headers=he, json={"ns": "pods", "date": "2026-10-17"}).json() + assert again["parent"] not in (None, root["id"]) diff --git a/fastapi_backend/tests/api/test_sensors.py b/fastapi_backend/tests/api/test_sensors.py index 63e1b120c..9cebe1d2a 100644 --- a/fastapi_backend/tests/api/test_sensors.py +++ b/fastapi_backend/tests/api/test_sensors.py @@ -153,7 +153,8 @@ def busy_once(self): monkeypatch.setattr(socketserver.ThreadingTCPServer, "server_bind", busy_once) listener = syslog.Listener("127.0.0.1", 0, [], lambda *a: None).start() try: - assert len(tries) == 2 and listener.tcp.server_address[1] == listener.port + # at least one more try: the next port UDP picks can be taken on TCP too, on a busy machine + assert len(tries) >= 2 and listener.tcp.server_address[1] == listener.port finally: listener.stop() diff --git a/nextjs-frontend/__tests__/notes-today.test.tsx b/nextjs-frontend/__tests__/notes-today.test.tsx new file mode 100644 index 000000000..80e6edfe7 --- /dev/null +++ b/nextjs-frontend/__tests__/notes-today.test.tsx @@ -0,0 +1,88 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import "@testing-library/jest-dom"; + +import { Notes } from "@/app/openapi-client"; +import { NotesHome } from "@/components/notes/notes-home"; +import { TodayNote, localDay } from "@/components/notes/today"; + +jest.mock("@/app/openapi-client", () => ({ + Notes: { + todayPage: jest.fn(), + listPages: jest.fn(() => + Promise.resolve({ data: { namespace: "home", pages: [] }, response: { ok: true, status: 200 } }), + ), + deletedPages: jest.fn(() => Promise.resolve({ data: [], response: { ok: true, status: 200 } })), + }, +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); +const replace = jest.fn(); +jest.mock("next/navigation", () => ({ useRouter: () => ({ replace, push: jest.fn() }) })); +jest.mock("@/components/ui/toast", () => ({ useToast: () => jest.fn() })); +let roles: Record = { home: "editor", pods: "viewer" }; +let picked: string | null = "home"; +jest.mock("@/lib/hooks/session", () => ({ + useArchive: () => ({ + loaded: true, + namespace: picked, + namespaces: Object.keys(roles).map((name) => ({ name })), + can: (role: string, ns?: string) => (ns ? roles[ns] === "editor" || role === "viewer" : true), + }), +})); + +const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); +const m = (f: unknown) => f as jest.Mock; +const show = (ui: React.ReactNode) => + render( + + {ui} + , + ); + +beforeEach(() => { + jest.clearAllMocks(); + roles = { home: "editor", pods: "viewer" }; + picked = "home"; +}); + +describe("today's note", () => { + it("is today here, not in UTC", () => { + expect(localDay(new Date(2026, 9, 5, 23, 30))).toBe("2026-10-05"); + }); + + it("opens today's note of the namespace in view", async () => { + m(Notes.todayPage).mockImplementation(() => ok({ id: 12, title: "2026-10-15" })); + show(); + await waitFor(() => expect(replace).toHaveBeenCalledWith("/notes/12")); + expect(m(Notes.todayPage).mock.calls[0][0].body).toEqual({ ns: "home", date: localDay() }); + }); + + it("with every namespace in view, uses the first one you can write in", async () => { + picked = null; + roles = { pods: "viewer", home: "editor" }; + m(Notes.todayPage).mockImplementation(() => ok({ id: 3 })); + show(); + await waitFor(() => expect(Notes.todayPage).toHaveBeenCalled()); + expect(m(Notes.todayPage).mock.calls[0][0].body.ns).toBe("home"); + }); + + it("says what went wrong, and tries again", async () => { + m(Notes.todayPage) + .mockImplementationOnce(() => + Promise.resolve({ + error: { detail: "A namespace can have up to 20000 pages." }, + response: { ok: false, status: 400 }, + }), + ) + .mockImplementationOnce(() => ok({ id: 4 })); + show(); + expect(await screen.findByText("Couldn’t open today’s note")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Try again" })); + await waitFor(() => expect(replace).toHaveBeenCalledWith("/notes/4")); + }); + + it("is one click from the Notes page", async () => { + show(); + expect(await screen.findByRole("link", { name: "Today" })).toHaveAttribute("href", "/notes/today"); + }); +}); diff --git a/nextjs-frontend/app/(app)/notes/today/page.tsx b/nextjs-frontend/app/(app)/notes/today/page.tsx new file mode 100644 index 000000000..74637af0b --- /dev/null +++ b/nextjs-frontend/app/(app)/notes/today/page.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from "next"; + +import { TodayNote } from "@/components/notes/today"; + +export const metadata: Metadata = { title: "Today’s note" }; + +/** Today's note: made the first time it's asked for, then opened. A bookmark or ⌘K gets there in one step. */ +export default function Page() { + return ; +} diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 94988bf82..22f148525 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -2073,6 +2073,7 @@ export type { NotePageMove, NotePageUpdate, NoteSearch, + NoteToday, NoteTree, NoteUpdate, NoteVersion, @@ -3023,6 +3024,11 @@ export type { TestTikaResponses, TicketRequest, TikaTestResult, + TodayPageData, + TodayPageError, + TodayPageErrors, + TodayPageResponse, + TodayPageResponses, TokenData, TokenError, TokenErrors, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index fbbac447a..10d61bc1e 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -1456,6 +1456,9 @@ import type { TestTelemetryResponses, TestTikaData, TestTikaResponses, + TodayPageData, + TodayPageErrors, + TodayPageResponses, TokenData, TokenErrors, TokenLimitsData, @@ -5217,6 +5220,25 @@ export class Notes { }); } + /** + * Today Page + * + * The namespace's note for the day (`date`, your today), made the first time it's asked for: titled with the + * date, inside the "Daily notes" note. Needs editor access. + */ + public static todayPage( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/notes/today", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + /** * Link Targets * diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 433a0a3d1..15e10ea0f 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -10724,6 +10724,24 @@ export type NoteSearch = { [key: string]: unknown; }; +/** + * NoteToday + */ +export type NoteToday = { + /** + * Ns + * + * the namespace whose daily note it is + */ + ns: string; + /** + * Date + * + * YYYY-MM-DD, your today (default: the server's) + */ + date?: string | null; +}; + /** * NoteTree */ @@ -27294,6 +27312,31 @@ export type CreatePageResponses = { export type CreatePageResponse = CreatePageResponses[keyof CreatePageResponses]; +export type TodayPageData = { + body: NoteToday; + path?: never; + query?: never; + url: "/api/v1/notes/today"; +}; + +export type TodayPageErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type TodayPageError = TodayPageErrors[keyof TodayPageErrors]; + +export type TodayPageResponses = { + /** + * Successful Response + */ + 200: NotePage; +}; + +export type TodayPageResponse = TodayPageResponses[keyof TodayPageResponses]; + export type LinkTargetsData = { body?: never; path?: never; diff --git a/nextjs-frontend/components/app-shell/command-palette.tsx b/nextjs-frontend/components/app-shell/command-palette.tsx index fcf945272..a45dbc19d 100644 --- a/nextjs-frontend/components/app-shell/command-palette.tsx +++ b/nextjs-frontend/components/app-shell/command-palette.tsx @@ -81,6 +81,12 @@ export function CommandPalette() { href: "/import", icon: , }, + { + group: "Actions", + label: "Today’s note", + href: "/notes/today", + icon: , + }, ] : []), { diff --git a/nextjs-frontend/components/notes/notes-home.tsx b/nextjs-frontend/components/notes/notes-home.tsx index 80b7c778e..bf9dbf3dd 100644 --- a/nextjs-frontend/components/notes/notes-home.tsx +++ b/nextjs-frontend/components/notes/notes-home.tsx @@ -1,7 +1,7 @@ "use client"; import { keepPreviousData, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query"; -import { FileText, NotebookPen, Pin, Plus, Search, Sparkles } from "lucide-react"; +import { CalendarDays, FileText, NotebookPen, Pin, Plus, Search, Sparkles } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useMemo, useState } from "react"; @@ -90,12 +90,12 @@ export function NotesHome() { tone: "red", }), }); - const newNote = - target && can("editor", target) ? ( - - ) : null; + const editable = !!target && can("editor", target); + const newNote = editable ? ( + + ) : null; const placeLabel = (v?: string | null) => PLACES.find((p) => p.value === v)?.label; /** "Home lab › Parts": the notes this one is inside, outermost first. */ const path = (r: Row) => { @@ -114,7 +114,23 @@ export function NotesHome() { const loading = trees.some((t) => t.isPending) || (!!words && search.isPending); return (
- + + + {newNote} + + ) + } + /> {(all.length > 0 || q) && (
String(n).padStart(2, "0"); + return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())}`; +} + +/** /notes/today: opens today's note of the namespace in view (the first one you can write in, with all in view), + * made the first time it's asked for, inside "Daily notes". */ +export function TodayNote() { + const client = useApiClient(); + const router = useRouter(); + const { namespace, namespaces, can, loaded } = useArchive(); + const ns = + namespace && can("editor", namespace) + ? namespace + : (namespaces.map((n) => n.name).find((n) => can("editor", n)) ?? null); + const [err, setErr] = useState(null); + const [tries, setTries] = useState(0); + useEffect(() => { + if (!ns) return; + let gone = false; + data(Notes.todayPage({ client, body: { ns, date: localDay() } })) + .then((p) => !gone && router.replace(`/notes/${p.id}`)) + .catch((e) => !gone && setErr(e instanceof ApiError ? e.message : "Please try again.")); + return () => { + gone = true; + }; + }, [client, ns, router, tries]); + if (loaded && !ns) + return ( + } title="No namespace to write in" className="mt-16"> + Today’s note goes in a namespace you can edit; ask an owner for editor access. + + ); + if (err) + return ( + } + title="Couldn’t open today’s note" + className="mt-16" + actions={ + + } + > + {err} + + ); + return ( +
+

+ Opening today’s note… +

+ +
+ ); +} diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 39018cd96..14e931293 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -9870,6 +9870,48 @@ } } }, + "/api/v1/notes/today": { + "post": { + "tags": [ + "notes" + ], + "summary": "Today Page", + "description": "The namespace's note for the day (`date`, your today), made the first time it's asked for: titled with the\ndate, inside the \"Daily notes\" note. Needs editor access.", + "operationId": "today_page", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NoteToday" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NotePage" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/notes/targets": { "get": { "tags": [ @@ -46546,6 +46588,33 @@ ], "title": "NoteSearch" }, + "NoteToday": { + "properties": { + "ns": { + "type": "string", + "title": "Ns", + "description": "the namespace whose daily note it is" + }, + "date": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Date", + "description": "YYYY-MM-DD, your today (default: the server's)" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "ns" + ], + "title": "NoteToday" + }, "NoteTree": { "properties": { "namespace": {