From 275508cf71fd8e5ed71b86819c2cba0020b1e5e8 Mon Sep 17 00:00:00 2001 From: "Mohamed H. Youssef" Date: Wed, 18 Nov 2026 23:40:46 +0300 Subject: [PATCH 1/6] fix(notifications): reading a notification tells the person's other tabs and devices Before, marking a notification read (or "Mark all read") sent no live event, so a second MegooColab tab or device kept its bell count until a reload. Both endpoints now publish notification.read when something actually became read, mirroring service.read_by_acting. MC-46's tab badge needs it so the favicon bell and "(3)" title clear everywhere. Co-Authored-By: Claude Opus 5.5 --- backend/app/notifications/router.py | 10 ++++++-- backend/tests/notifications/test_core.py | 32 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/backend/app/notifications/router.py b/backend/app/notifications/router.py index e2f36777..77ebbedb 100644 --- a/backend/app/notifications/router.py +++ b/backend/app/notifications/router.py @@ -10,6 +10,7 @@ from app.audit import service as audit from app.auth.deps import AuthedUser from app.core.db import DbSession +from app.core.events import Event, publish from app.notifications.models import DEFAULT_PREFS, Kind, Notification, NotificationPref from app.notifications.schemas import NotificationOut, NotificationPrefIO, UnreadCount @@ -48,14 +49,19 @@ async def mark_read(notification_id: uuid.UUID, user: AuthedUser, db: DbSession) raise HTTPException(status.HTTP_404_NOT_FOUND, "notification_not_found") if n.read_at is None: n.read_at = datetime.now(UTC) + # the person's other tabs and devices refresh their count + await publish(db, Event(type="notification.read", user_id=user.id)) await db.commit() return Response(status_code=status.HTTP_204_NO_CONTENT) @router.post("/api/notifications/read-all", status_code=status.HTTP_204_NO_CONTENT) async def mark_all_read(user: AuthedUser, db: DbSession) -> Response: - await db.execute(update(Notification).where(Notification.user_id == user.id, Notification.read_at.is_(None)) - .values(read_at=datetime.now(UTC))) + done = await db.execute(update(Notification).where(Notification.user_id == user.id, + Notification.read_at.is_(None)) + .values(read_at=datetime.now(UTC))) + if done.rowcount: # the person's other tabs and devices refresh their count + await publish(db, Event(type="notification.read", user_id=user.id)) await db.commit() return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/backend/tests/notifications/test_core.py b/backend/tests/notifications/test_core.py index e55ed6e8..4aadc91a 100644 --- a/backend/tests/notifications/test_core.py +++ b/backend/tests/notifications/test_core.py @@ -13,6 +13,7 @@ from app.core.email import OutboxMailer from app.jobs.models import Job from app.notifications import jobs as notify_jobs +from app.notifications import router as notify_router from app.notifications import service from app.notifications.models import Kind, Notification from app.org.models import ORG_SETTINGS_ID, OrgSettings @@ -201,6 +202,37 @@ async def test_list_read_and_unread_count(client_factory, db): assert task +async def test_mark_read_tells_other_tabs(client_factory, db, monkeypatch): + """Reading in one tab tells the person's other tabs and devices, so their bell (and tab badge) follows.""" + _manager, bea, _m, b, _task = await _world(client_factory, db) + async with SessionLocal() as s: + for i in range(2): + s.add(Notification(user_id=bea.id, kind="assigned", title=f"r{i}", body="", link="/x")) + await s.commit() + first, second = [n for n in await _rows(bea.id) if n.title in ("r0", "r1")] + seen = [] + real = notify_router.publish + + async def capture(session, event): + seen.append((event.type, event.user_id)) + await real(session, event) + + monkeypatch.setattr(notify_router, "publish", capture) + other = client_factory() + await login(other, await make_user(db)) + assert (await other.post(f"/api/notifications/{first.id}/read")).status_code == 404 + assert seen == [] # someone else's notification: nothing read, nothing sent + assert (await b.post(f"/api/notifications/{first.id}/read")).status_code == 204 + assert seen == [("notification.read", bea.id)] + assert (await b.post(f"/api/notifications/{first.id}/read")).status_code == 204 + assert len(seen) == 1 # already read: no event + assert (await b.post("/api/notifications/read-all")).status_code == 204 + assert seen == [("notification.read", bea.id)] * 2 # second (and any other unread) became read + assert (await b.post("/api/notifications/read-all")).status_code == 204 + assert len(seen) == 2 # nothing unread: no event + assert second + + async def test_live_event_per_user(client_factory, db, monkeypatch): _manager, bea, _m, _b, task = await _world(client_factory, db) seen = [] From 8d7478c3577d2b2778df6687e22058893d41ef71 Mon Sep 17 00:00:00 2001 From: "Mohamed H. Youssef" Date: Wed, 18 Nov 2026 23:45:08 +0300 Subject: [PATCH 2/6] feat(notifications): the tab title can start with the unread count Co-Authored-By: Claude Opus 5.5 --- frontend/src/lib/__tests__/title.test.tsx | 35 ++++++++++++++++++++++- frontend/src/lib/title.ts | 11 ++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/frontend/src/lib/__tests__/title.test.tsx b/frontend/src/lib/__tests__/title.test.tsx index 676df0a1..80827b0a 100644 --- a/frontend/src/lib/__tests__/title.test.tsx +++ b/frontend/src/lib/__tests__/title.test.tsx @@ -1,7 +1,7 @@ import { cleanup, render } from "@testing-library/react"; import { afterEach, describe, expect, it } from "vitest"; -import { pageTitle, usePageTitle, useRecordTitle } from "@/lib/title"; +import { pageTitle, setTitleCount, usePageTitle, useRecordTitle } from "@/lib/title"; function Page({ parts }: { parts: (string | null | undefined)[] }) { usePageTitle(...parts); @@ -15,6 +15,7 @@ function Record({ parts }: { parts: (string | null | undefined)[] }) { afterEach(() => { cleanup(); + setTitleCount(0); document.title = "MegooColab"; }); @@ -76,3 +77,35 @@ describe("usePageTitle", () => { expect(document.title).toBe("New project · MegooColab"); }); }); + +describe("setTitleCount", () => { + it("puts the unread count before the page's title", () => { + render(); + setTitleCount(3); + expect(document.title).toBe("(3) Projects · MegooColab"); + }); + + it("shows the number up to 99, then 99+", () => { + render(); + setTitleCount(100); + expect(document.title).toBe("(99+) Projects · MegooColab"); + setTitleCount(99); + expect(document.title).toBe("(99) Projects · MegooColab"); + }); + + it("takes the count away at 0", () => { + render(); + setTitleCount(3); + setTitleCount(0); + expect(document.title).toBe("Projects · MegooColab"); + }); + + it("keeps the count as the page changes and goes", () => { + const { rerender, unmount } = render(); + setTitleCount(2); + rerender(); + expect(document.title).toBe("(2) Teams · MegooColab"); + unmount(); + expect(document.title).toBe("(2) MegooColab"); + }); +}); diff --git a/frontend/src/lib/title.ts b/frontend/src/lib/title.ts index 45a32bc1..4711667d 100644 --- a/frontend/src/lib/title.ts +++ b/frontend/src/lib/title.ts @@ -14,13 +14,22 @@ export function pageTitle(...parts: (string | null | undefined)[]): string { // mount in can't decide this alone. const shown = new Map(); let seq = 0; +// unread notifications, shown before the title (TabBadge): "(3) Projects · MegooColab" +let unread = 0; function apply() { let top: { title: string; record: boolean; seq: number } | undefined; for (const entry of shown.values()) { if (!top || Number(entry.record) > Number(top.record) || (entry.record === top.record && entry.seq > top.seq)) top = entry; } - document.title = top?.title ?? APP_NAME; + const count = unread > 99 ? "99+" : String(unread); + document.title = (unread > 0 ? `(${count}) ` : "") + (top?.title ?? APP_NAME); +} + +/** Puts the unread count before the tab's title; 0 takes it away. */ +export function setTitleCount(count: number): void { + unread = count; + apply(); } function useTitle(record: boolean, parts: (string | null | undefined)[]) { From a7d5d868e6f562776c036412cc9766119f68c00d Mon Sep 17 00:00:00 2001 From: "Mohamed H. Youssef" Date: Wed, 18 Nov 2026 23:48:03 +0300 Subject: [PATCH 3/6] feat(notifications): draw a bell badge over the favicon Co-Authored-By: Claude Opus 5.5 --- frontend/src/lib/__tests__/favicon.test.ts | 110 +++++++++++++++++++++ frontend/src/lib/favicon.ts | 97 ++++++++++++++++++ 2 files changed, 207 insertions(+) create mode 100644 frontend/src/lib/__tests__/favicon.test.ts create mode 100644 frontend/src/lib/favicon.ts diff --git a/frontend/src/lib/__tests__/favicon.test.ts b/frontend/src/lib/__tests__/favicon.test.ts new file mode 100644 index 00000000..7f6ba8a1 --- /dev/null +++ b/frontend/src/lib/__tests__/favicon.test.ts @@ -0,0 +1,110 @@ +import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest"; + +type FakeImage = { onload: (() => void) | null; onerror: (() => void) | null; src: string }; + +const BADGE = "data:image/png;base64,BADGE"; +const ORIGINAL = ["/favicon.ico", "/icon.png?abc", "/apple-icon.png?def"]; + +let images: FakeImage[] = []; +let setFaviconBadge: (on: boolean) => void; +let getContext: MockInstance; +let ctx: Record & { arc: ReturnType }; + +const hrefs = () => [...document.head.querySelectorAll("link")].map((l) => l.getAttribute("href")); + +beforeEach(async () => { + vi.resetModules(); + ({ setFaviconBadge } = await import("@/lib/favicon")); + document.head.innerHTML = [ + '', + '', + '', + ].join(""); + images = []; + vi.stubGlobal( + "Image", + class { + onload: (() => void) | null = null; + onerror: (() => void) | null = null; + src = ""; + constructor() { + images.push(this); + } + }, + ); + ctx = { + drawImage: vi.fn(), + beginPath: vi.fn(), + arc: vi.fn(), + fill: vi.fn(), + moveTo: vi.fn(), + lineTo: vi.fn(), + closePath: vi.fn(), + globalCompositeOperation: "", + fillStyle: "", + }; + getContext = vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(ctx as never); + vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue(BADGE); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + document.head.innerHTML = ""; +}); + +describe("setFaviconBadge", () => { + it("loads the PNG icon and points every icon link at the badge", () => { + setFaviconBadge(true); + expect(images).toHaveLength(1); + expect(images[0].src).toBe("/icon.png?abc"); + expect(hrefs()).toEqual(ORIGINAL); + + images[0].onload!(); + expect(hrefs()).toEqual([BADGE, BADGE, "/apple-icon.png?def"]); + expect(ctx.arc).toHaveBeenCalledWith(46, 18, 16, 0, 2 * Math.PI); + }); + + it("off puts the original addresses back", () => { + setFaviconBadge(true); + images[0].onload!(); + setFaviconBadge(false); + expect(hrefs()).toEqual(ORIGINAL); + expect(document.head.querySelector("[data-megoo-href]")).toBeNull(); + }); + + it("a failed load leaves the links alone and throws nothing", () => { + setFaviconBadge(true); + expect(() => images[0].onerror!()).not.toThrow(); + expect(hrefs()).toEqual(ORIGINAL); + + setFaviconBadge(true); + expect(images).toHaveLength(2); + }); + + it("no 2D canvas: the icon stays", () => { + getContext.mockReturnValue(null); + setFaviconBadge(true); + expect(() => images[0].onload!()).not.toThrow(); + expect(hrefs()).toEqual(ORIGINAL); + }); + + it("off before the icon loads: the late drawing is not applied", () => { + setFaviconBadge(true); + setFaviconBadge(false); + images[0].onload!(); + expect(hrefs()).toEqual(ORIGINAL); + }); + + it("draws once for repeated on and off", () => { + setFaviconBadge(true); + images[0].onload!(); + setFaviconBadge(false); + setFaviconBadge(true); + setFaviconBadge(false); + setFaviconBadge(true); + expect(images).toHaveLength(1); + expect(getContext).toHaveBeenCalledTimes(1); + expect(hrefs()).toEqual([BADGE, BADGE, "/apple-icon.png?def"]); + }); +}); diff --git a/frontend/src/lib/favicon.ts b/frontend/src/lib/favicon.ts new file mode 100644 index 00000000..a6d92c0d --- /dev/null +++ b/frontend/src/lib/favicon.ts @@ -0,0 +1,97 @@ +/** + * The favicon's unread mark: a small red bell drawn in the browser over the app's own icon. Every `rel="icon"` + * link points at the drawing while the mark is on and gets its own address back when it goes. The Apple touch icon + * and the manifest's icons are not `rel="icon"` and stay as they are. + */ + +const SIZE = 64; +// the badge: a red circle in the top-right corner, with a gap cut around it so it stands apart on any tab colour +const BADGE = { x: 46, y: 18, r: 16, gap: 3 }; +const RED = "#ef4444"; + +let wanted = false; +let badged: string | null = null; // the drawing, made once per page load +let drawing = false; + +function links(): HTMLLinkElement[] { + return Array.from(document.head.querySelectorAll('link[rel~="icon"]')); +} + +// the link's own address, also while it points at the drawing +const own = (link: HTMLLinkElement) => link.dataset.megooHref ?? link.getAttribute("href"); + +function source(): string | null { + const all = links(); + const png = all.find((l) => l.type === "image/png") ?? all[0]; + return png ? own(png) : null; +} + +function point() { + for (const link of links()) { + if (wanted && badged) { + if (link.dataset.megooHref === undefined) link.dataset.megooHref = link.getAttribute("href") ?? ""; + link.href = badged; + } else if (link.dataset.megooHref !== undefined) { + link.setAttribute("href", link.dataset.megooHref); + delete link.dataset.megooHref; + } + } +} + +function draw(icon: HTMLImageElement): string { + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = SIZE; + const ctx = canvas.getContext("2d"); + if (!ctx) throw new Error("no 2D canvas"); + ctx.drawImage(icon, 0, 0, SIZE, SIZE); + const circle = (x: number, y: number, r: number) => { + ctx.beginPath(); + ctx.arc(x, y, r, 0, 2 * Math.PI); + ctx.fill(); + }; + ctx.globalCompositeOperation = "destination-out"; + circle(BADGE.x, BADGE.y, BADGE.r + BADGE.gap); + ctx.globalCompositeOperation = "source-over"; + ctx.fillStyle = RED; + circle(BADGE.x, BADGE.y, BADGE.r); + // the bell: body, clapper and knob + ctx.fillStyle = "#ffffff"; + ctx.beginPath(); + ctx.moveTo(37, 24); + ctx.lineTo(55, 24); + ctx.lineTo(52, 20); + ctx.lineTo(52, 15); + ctx.arc(46, 15, 6, 0, Math.PI, true); + ctx.lineTo(40, 20); + ctx.closePath(); + ctx.fill(); + circle(46, 26.5, 2.5); + circle(46, 8.5, 1.5); + return canvas.toDataURL("image/png"); +} + +/** Shows or hides the bell badge on the tab's icon. Never throws: if it can't draw, the icon stays as it is. */ +export function setFaviconBadge(on: boolean): void { + wanted = on; + if (!on || badged) { + point(); + return; + } + const src = source(); + if (drawing || !src) return; + drawing = true; + const icon = new Image(); + icon.onload = () => { + drawing = false; + try { + badged = draw(icon); + } catch { + return; + } + point(); // applies only if the badge is still wanted + }; + icon.onerror = () => { + drawing = false; // the next change of the count tries again + }; + icon.src = src; +} From d74dd3246990d05aa715eb6b15849717c426b8c9 Mon Sep 17 00:00:00 2001 From: "Mohamed H. Youssef" Date: Wed, 18 Nov 2026 23:50:52 +0300 Subject: [PATCH 4/6] feat(notifications): the browser tab shows unread notifications TabBadge reads the shared unread count and marks the tab: a bell on the favicon and the count before the title. It re-applies on every page change, since the head's icon links and title may be re-rendered, and clears both when the signed-in layout goes away. Co-Authored-By: Claude Opus 5.5 --- frontend/src/app/(app)/layout.tsx | 2 + .../src/components/notifications/TabBadge.tsx | 27 ++++++++++ .../notifications/__tests__/TabBadge.test.tsx | 52 +++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 frontend/src/components/notifications/TabBadge.tsx create mode 100644 frontend/src/components/notifications/__tests__/TabBadge.test.tsx diff --git a/frontend/src/app/(app)/layout.tsx b/frontend/src/app/(app)/layout.tsx index c7744d80..4e1b8f8c 100644 --- a/frontend/src/app/(app)/layout.tsx +++ b/frontend/src/app/(app)/layout.tsx @@ -3,6 +3,7 @@ import { Suspense, useState } from "react"; import { NavRecorder } from "@/components/nav/NavRecorder"; +import { TabBadge } from "@/components/notifications/TabBadge"; import { DesktopSidebar } from "@/components/shell/DesktopSidebar"; import { Header } from "@/components/shell/Header"; import { Sidebar } from "@/components/shell/Sidebar"; @@ -26,6 +27,7 @@ export default function AppLayout({ children }: { children: React.ReactNode }) { + {menuOpen && (
diff --git a/frontend/src/components/notifications/TabBadge.tsx b/frontend/src/components/notifications/TabBadge.tsx new file mode 100644 index 00000000..d3186be1 --- /dev/null +++ b/frontend/src/components/notifications/TabBadge.tsx @@ -0,0 +1,27 @@ +"use client"; + +import { usePathname } from "next/navigation"; +import { useEffect } from "react"; + +import { setFaviconBadge } from "@/lib/favicon"; +import { useUnreadCount } from "@/lib/notifications"; +import { setTitleCount } from "@/lib/title"; + +/** Marks the browser tab while anything is unread: a bell on the favicon and "(3) " before the title. Renders nothing. */ +export function TabBadge() { + const count = useUnreadCount().data?.count ?? 0; + // a page change may re-render the head's icon links and title: mark them again + const pathname = usePathname(); + useEffect(() => { + setFaviconBadge(count > 0); + setTitleCount(count); + }, [count, pathname]); + useEffect( + () => () => { + setFaviconBadge(false); + setTitleCount(0); + }, + [], + ); + return null; +} diff --git a/frontend/src/components/notifications/__tests__/TabBadge.test.tsx b/frontend/src/components/notifications/__tests__/TabBadge.test.tsx new file mode 100644 index 00000000..f2825b0e --- /dev/null +++ b/frontend/src/components/notifications/__tests__/TabBadge.test.tsx @@ -0,0 +1,52 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, render, waitFor } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { TabBadge } from "@/components/notifications/TabBadge"; +import { setFaviconBadge } from "@/lib/favicon"; +import { setTitleCount } from "@/lib/title"; + +vi.mock("next/navigation", () => ({ usePathname: () => "/projects" })); +vi.mock("@/lib/favicon", () => ({ setFaviconBadge: vi.fn() })); +vi.mock("@/lib/title", async (importOriginal) => ({ ...(await importOriginal()), setTitleCount: vi.fn() })); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +const marked = () => [vi.mocked(setFaviconBadge).mock.lastCall?.[0], vi.mocked(setTitleCount).mock.lastCall?.[0]]; + +describe("TabBadge", () => { + it("marks the tab while anything is unread, and clears it when it goes", async () => { + let count = 0; + vi.stubGlobal( + "fetch", + vi.fn(async (url: string) => + url === "/api/notifications/unread-count" ? new Response(JSON.stringify({ count }), { status: 200 }) : new Response(null, { status: 404 }), + ), + ); + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + const refresh = (n: number) => { + count = n; + return act(() => client.invalidateQueries({ queryKey: ["notifications", "count"] })); + }; + const { unmount } = render( + + + , + ); + await waitFor(() => expect(marked()).toEqual([false, 0])); + + await refresh(2); + await waitFor(() => expect(marked()).toEqual([true, 2])); + + await refresh(0); + await waitFor(() => expect(marked()).toEqual([false, 0])); + + await refresh(5); + await waitFor(() => expect(marked()).toEqual([true, 5])); + unmount(); + expect(marked()).toEqual([false, 0]); + }); +}); From 55f516bdcc8bc9c9dc664475397e0280bfd7021a Mon Sep 17 00:00:00 2001 From: "Mohamed H. Youssef" Date: Wed, 18 Nov 2026 23:55:56 +0300 Subject: [PATCH 5/6] test(notifications): the tab badge and title count, also across tabs The notifications end-to-end test now checks that while Bea has unread notifications her tab title starts with the count and every favicon link points at the badged drawing, also after a client-side page change and in a second tab. Marking everything read in one tab clears the title and icon in the other through the server's notification.read event. The README describes the new section, and docs/install.md tells people what the tab shows. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/install.md | 4 +++- frontend/e2e/notifications.spec.ts | 32 +++++++++++++++++++++++++++--- 3 files changed, 33 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 117e2c1c..c7d1a2c8 100644 --- a/README.md +++ b/README.md @@ -148,7 +148,7 @@ cd frontend && npx playwright test e2e/questions.spec.ts `frontend/e2e/git.spec.ts` covers git integration on the same stack, with the same requirements as the workflow test (the Go toolchain and `git` on the PATH). It starts a fake GitHub Enterprise API on the host (`frontend/e2e/helpers/fakeGit.ts`, on a free port), which the stack reaches as `http://host.docker.internal:` (the compose file maps that name for the backend and worker). An admin adds the connection in Admin → Git with a token and a webhook secret, and **Test** shows the fake login. Project GIT requires a human code review, and its repository is linked to the connection. The fake agent runs GIT-1 to Finish, which reports pull request #1: the task shows "PR open · checks pending" and waits. The fake host then marks it merged, and a signed webhook makes MegooColab look: the task finishes by itself. A forged or unsigned delivery gets 401. GIT-3's pull request #2 is closed without a merge: the workflow escalates `pr_closed`, and **Accept** finishes it. -`frontend/e2e/notifications.spec.ts` covers notifications on the same stack (it also builds the runner and the fake agent). The admin assigns NOT-1 to an invited member, whose bell shows 1, and the notification opens the task. A mention made with the comment picker reaches her; an outsider mentioned by hand gets nothing. The admin's agent submits NOT-2's design, and the owner is told it awaits approval. Turning off in-app assignments silences the next one. A new notification chimes in her open tab, and no longer once she turns the sound off. +`frontend/e2e/notifications.spec.ts` covers notifications on the same stack (it also builds the runner and the fake agent). The admin assigns NOT-1 to an invited member, whose bell shows 1, and the notification opens the task. A mention made with the comment picker reaches her; an outsider mentioned by hand gets nothing. The admin's agent submits NOT-2's design, and the owner is told it awaits approval. Turning off in-app assignments silences the next one. A new notification chimes in her open tab, and no longer once she turns the sound off. While anything is unread, her tab title starts with the count and the favicon carries a bell, also after a page change, and reading everything in one tab clears both in her other tab. Both create their own users, teams and projects (GIT and NOT), so they need a fresh stack. To run them: diff --git a/docs/install.md b/docs/install.md index a7418565..73c91f0e 100644 --- a/docs/install.md +++ b/docs/install.md @@ -222,7 +222,9 @@ to you or your agent, a mention (`@` in a comment), your agent going offline mid questions that need a person. Each person chooses, per kind, in-app, email and push under **avatar → Notifications** (`/settings/notifications`). Email needs SMTP (section 7); its links use `PUBLIC_URL`. While MegooColab is open in a browser, a short chime also plays when a new notification arrives (after the first click in the tab, as browsers -require); each person turns it off for that browser in the **Sound** card on the same page. +require); each person turns it off for that browser in the **Sound** card on the same page. While anything is unread, +the browser tab shows it too: the title starts with the count, such as `(3) Projects · MegooColab`, and the icon +carries a small red bell. ### Push notifications diff --git a/frontend/e2e/notifications.spec.ts b/frontend/e2e/notifications.spec.ts index 2a096ddd..39af81bc 100644 --- a/frontend/e2e/notifications.spec.ts +++ b/frontend/e2e/notifications.spec.ts @@ -12,9 +12,10 @@ import { pickAssignee } from "./helpers/assignee"; /** * End-to-end test of Plan 7's notifications: an assignment and a mention reach the person through the bell (and an * outsider mentioned by hand gets nothing), the agent's owner is told when the workflow waits for a design - * approval, turning a kind off in-app silences it, and a new notification chimes in an open tab until the sound is - * turned off. Needs the Go toolchain and git on the PATH, and a fresh - * stack (see README "Git and notifications end-to-end tests"). Project key NOT. + * approval, turning a kind off in-app silences it, a new notification chimes in an open tab until the sound is + * turned off, and the tab shows unread notifications in its title and favicon, also in a second tab once they are + * read elsewhere. Needs the Go toolchain and git on the PATH, and a fresh stack (see README "Git and notifications + * end-to-end tests"). Project key NOT. */ const BASE = process.env.E2E_BASE_URL ?? "http://localhost:8080"; @@ -243,4 +244,29 @@ test("notifications reach the right people", async ({ browser }) => { await mentionBea("And the title,"); await expect(bell(beaPage)).toHaveText(String(count + 1), { timeout: 15_000 }); expect(await notes()).toEqual([]); + + // 7. while anything is unread, Bea's tab says so: the count before the title and a bell on the favicon, also after + // a page change; reading everything in one tab clears both in her other tab + const icons = (p: Page) => p.locator('link[rel~="icon"]').evaluateAll((ls) => ls.map((l) => l.getAttribute("href") ?? "")); + const badged = async (p: Page) => (await icons(p)).every((h) => h.startsWith("data:image/png")); + const plain = async (p: Page) => (await icons(p)).every((h) => !h.startsWith("data:")); + count = await unread(); + expect(count).toBeGreaterThan(0); // section 6 left its mention unread + await beaPage.goto("/projects"); + await expect(bell(beaPage)).toHaveText(String(count), { timeout: 15_000 }); + await expect(beaPage).toHaveTitle(`(${count}) Projects · MegooColab`); + await expect.poll(() => badged(beaPage)).toBe(true); + await beaPage.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Teams", exact: true }).click(); + await expect(beaPage).toHaveURL(/\/teams$/); + await expect(beaPage).toHaveTitle(new RegExp(`^\\(${count}\\) `)); + await expect.poll(() => badged(beaPage)).toBe(true); + const other = await bea.ctx.newPage(); + await other.goto("/projects"); + await expect(other).toHaveTitle(`(${count}) Projects · MegooColab`, { timeout: 15_000 }); + await expect.poll(() => badged(other)).toBe(true); + await bell(beaPage).click(); + await beaPage.getByRole("button", { name: "Mark all read" }).click(); + await expect(other).toHaveTitle("Projects · MegooColab", { timeout: 15_000 }); // told by the server, no reload + await expect.poll(() => plain(other)).toBe(true); + await expect(beaPage).not.toHaveTitle(/^\(/); }); From 770992e486f7df6aed5ba64c7aed41caade55d5e Mon Sep 17 00:00:00 2001 From: "Mohamed H. Youssef" Date: Wed, 18 Nov 2026 23:57:25 +0300 Subject: [PATCH 6/6] docs: MC-46 design and plan --- docs/superpowers/plans/MC-46-plan.md | 306 +++++++++++++++++++++++++ docs/superpowers/specs/MC-46-design.md | 81 +++++++ 2 files changed, 387 insertions(+) create mode 100644 docs/superpowers/plans/MC-46-plan.md create mode 100644 docs/superpowers/specs/MC-46-design.md diff --git a/docs/superpowers/plans/MC-46-plan.md b/docs/superpowers/plans/MC-46-plan.md new file mode 100644 index 00000000..0fa5520e --- /dev/null +++ b/docs/superpowers/plans/MC-46-plan.md @@ -0,0 +1,306 @@ +# MC-46 plan: unread notifications in the browser tab + +## Goal +While the signed-in person has unread notifications, the MegooColab tab shows a small red bell badge on the favicon and the unread count before the title (`(3) Projects · MegooColab`, `(99+) …` above 99). Reading everything in one tab or device clears the mark in all the others. + +## Architecture +The unread count already lives in one query (`useUnreadCount`, key `["notifications","count"]`, `frontend/src/lib/notifications.ts:43`), and every `notification.*` live event refreshes it (`frontend/src/lib/realtime.ts:52`). A new component, `TabBadge`, reads that count and paints the tab through two small modules: `lib/favicon.ts` (new, canvas-drawn badged icon) and `lib/title.ts` (extended with a count prefix). On the backend, the two mark-as-read endpoints publish the existing `notification.read` event, so other tabs refetch the count. + +## Facts checked in the code +- `frontend/src/lib/title.ts`: `apply()` computes `document.title` from the `shown` map; `pageTitle`, `usePageTitle`, `useRecordTitle` are exported. Tests: `frontend/src/lib/__tests__/title.test.tsx` (its `afterEach` resets `document.title`). +- `frontend/src/app/` has both `favicon.ico` and `icon.png`. Next.js renders a `` for each: the ICO one (`/favicon.ico`) and a PNG one (`type="image/png"`, `/icon.png?…`). `apple-icon.png` renders as `rel="apple-touch-icon"` and is untouched by a `rel~="icon"` selector. Manifest icons (`app/manifest.ts`) are untouched. +- `frontend/src/app/(app)/layout.tsx`: the signed-in branch renders `` first; `TabBadge` goes right after it. +- `NotificationBell` reads `useUnreadCount().data?.count ?? 0` and shows `99+` above 99: same rule for the title. +- Vitest: jsdom, `frontend/vitest.config.mts`, setup `frontend/vitest.setup.ts` (cleanup after each). Query tests stub `fetch` with `vi.stubGlobal` and wrap with a `QueryClient({ defaultOptions: { queries: { retry: false } } })` (see `components/notifications/__tests__/Notifications.test.tsx`). `next/navigation` is mocked with `vi.mock("next/navigation", () => ({ … }))`. +- Backend: `backend/app/notifications/router.py` `mark_read` / `mark_all_read`; `Event` and `publish` come from `app.core.events`. `service.read_by_acting` already publishes `Event(type="notification.read", user_id=…)` when `rowcount` is non-zero. Tests: `backend/tests/notifications/test_core.py` (`_world`, `test_live_event_per_user` monkeypatches `service.publish`; other tests patch a module's imported `publish` the same way). +- E2E: `frontend/e2e/notifications.spec.ts`, one test "notifications reach the right people"; Bea's context is `bea.ctx`, her page `beaPage`, helpers `bell(page)`, `unread()`, `readAll()` (section 6). The sidebar is `nav[aria-label="Main"]` with links "Projects", "Teams", …. +- Checks (AGENTS.md): frontend in `frontend/`: `npx vitest run `, `npx tsc --noEmit`, `npx eslint `, `npm test`; backend in `backend/`: `uv run pytest ` (never two pytest runs at once). Commits: `type(area): sentence`, body explains why, plus the co-author line. No `npm run gen:api` (no API schema change). + +## File map +| File | Change | Responsibility | +|---|---|---| +| `backend/app/notifications/router.py` | modify | `mark_read` / `mark_all_read` publish `notification.read` when something became read | +| `backend/tests/notifications/test_core.py` | modify | `test_mark_read_tells_other_tabs` | +| `frontend/src/lib/title.ts` | modify | module-level unread count, `setTitleCount(count)`, `(N) ` prefix in `apply()` | +| `frontend/src/lib/__tests__/title.test.tsx` | modify | prefix tests | +| `frontend/src/lib/favicon.ts` | create | `setFaviconBadge(on)`: draw the badged icon once, point/restore `rel~="icon"` links | +| `frontend/src/lib/__tests__/favicon.test.ts` | create | favicon tests with stubbed canvas and `Image` | +| `frontend/src/components/notifications/TabBadge.tsx` | create | reads `useUnreadCount`, calls both setters; clears on unmount | +| `frontend/src/components/notifications/__tests__/TabBadge.test.tsx` | create | TabBadge tests | +| `frontend/src/app/(app)/layout.tsx` | modify | render `` in the signed-in branch | +| `frontend/e2e/notifications.spec.ts` | modify | section 7: title prefix, badged icon, survives page change, cleared in a second tab | +| `README.md`, `docs/install.md` | modify | one sentence each | + +## Steps + +### 1. Backend: mark-as-read endpoints publish notification.read +**Test first** — add to `backend/tests/notifications/test_core.py` (after `test_list_read_and_unread_count`), importing `from app.notifications import router as notify_router`: + +```python +async def test_mark_read_tells_other_tabs(client_factory, db, monkeypatch): + """Reading in one tab tells the person's other tabs and devices, so their bell (and tab badge) follows.""" + _manager, bea, _m, b, _task = await _world(client_factory, db) + async with SessionLocal() as s: + for i in range(2): + s.add(Notification(user_id=bea.id, kind="assigned", title=f"r{i}", body="", link="/x")) + await s.commit() + first, second = [n for n in await _rows(bea.id) if n.title in ("r0", "r1")] + seen = [] + real = notify_router.publish + + async def capture(session, event): + seen.append((event.type, event.user_id)) + await real(session, event) + + monkeypatch.setattr(notify_router, "publish", capture) + other = client_factory() + await login(other, await make_user(db)) + assert (await other.post(f"/api/notifications/{first.id}/read")).status_code == 404 + assert seen == [] # someone else's notification: nothing read, nothing sent + assert (await b.post(f"/api/notifications/{first.id}/read")).status_code == 204 + assert seen == [("notification.read", bea.id)] + assert (await b.post(f"/api/notifications/{first.id}/read")).status_code == 204 + assert len(seen) == 1 # already read: no event + assert (await b.post("/api/notifications/read-all")).status_code == 204 + assert seen == [("notification.read", bea.id)] * 2 # second (and any other unread) became read + assert (await b.post("/api/notifications/read-all")).status_code == 204 + assert len(seen) == 2 # nothing unread: no event + assert second +``` +Run `cd backend; uv run pytest tests/notifications/test_core.py -k mark_read_tells -q` → fails with `AttributeError: … has no attribute 'publish'` (router doesn't import it yet). + +**Implement** in `router.py`: add `from app.core.events import Event, publish`. In `mark_read`, inside `if n.read_at is None:` after setting `read_at` and before `commit`: `await publish(db, Event(type="notification.read", user_id=user.id))`. In `mark_all_read`: `done = await db.execute(update(...)...)`; `if done.rowcount: await publish(db, Event(type="notification.read", user_id=user.id))`; then `commit`. Comment: `# the person's other tabs and devices refresh their count` (one line). NOTIFY is transactional, so publishing before commit is correct. + +Run the test again → passes; then `uv run pytest tests/notifications -q` → all pass. +Commit: `fix(notifications): reading a notification tells the person's other tabs and devices` (body: before, a second tab kept its bell count until reload; MC-46's tab badge needs it). + +### 2. Frontend: unread count prefix in the tab title +**Test first** — in `frontend/src/lib/__tests__/title.test.tsx` import `setTitleCount` too, add `setTitleCount(0)` to `afterEach` (before resetting `document.title`), and add `describe("setTitleCount")`: +- "puts the count before the title": render ``, `setTitleCount(3)` → `"(3) Projects · MegooColab"`. +- "caps at 99+": `setTitleCount(100)` → `"(99+) Projects · MegooColab"`; `setTitleCount(99)` → `"(99) …"`. +- "no prefix at 0": `setTitleCount(3)` then `setTitleCount(0)` → `"Projects · MegooColab"`. +- "keeps the prefix when the page changes": with count 2, `rerender()` → `"(2) Teams · MegooColab"`; `unmount()` → `"(2) MegooColab"`. +Run `cd frontend; npx vitest run src/lib/__tests__/title.test.tsx` → fails (`setTitleCount` is not exported). + +**Implement** in `title.ts`: +```ts +// unread notifications, shown before the title (TabBadge): "(3) Projects · MegooColab" +let unread = 0; + +function apply() { + …existing loop… + const count = unread > 99 ? "99+" : String(unread); + document.title = (unread > 0 ? `(${count}) ` : "") + (top?.title ?? APP_NAME); +} + +/** Puts the unread count before the tab's title; 0 takes it away. */ +export function setTitleCount(count: number): void { + unread = count; + apply(); +} +``` +Run the test file → passes. `npx tsc --noEmit`, `npx eslint src/lib/title.ts src/lib/__tests__/title.test.tsx`. +Commit: `feat(notifications): the tab title can start with the unread count`. + +### 3. Frontend: favicon badge module +Create `frontend/src/lib/favicon.ts` with exactly the code in "Appendix A", and `frontend/src/lib/__tests__/favicon.test.ts` per "Appendix B" (write the test first; run `npx vitest run src/lib/__tests__/favicon.test.ts` → fails because the module does not exist; add the module → passes). `npx tsc --noEmit`; `npx eslint src/lib/favicon.ts src/lib/__tests__/favicon.test.ts`. +Commit: `feat(notifications): draw a bell badge over the favicon`. + +### 4. Frontend: TabBadge in the signed-in layout +**Test first** — `frontend/src/components/notifications/__tests__/TabBadge.test.tsx`: +```tsx +vi.mock("next/navigation", () => ({ usePathname: () => "/projects" })); +vi.mock("@/lib/favicon", () => ({ setFaviconBadge: vi.fn() })); +vi.mock("@/lib/title", async (importOriginal) => ({ ...(await importOriginal()), setTitleCount: vi.fn() })); +``` +One test "marks the tab while anything is unread, and clears it when it goes": mutable `count = 0`; stub `fetch` to answer `/api/notifications/unread-count` with `{ count }`; render `` in a `QueryClientProvider` with a client you keep. `await waitFor` → last calls `setFaviconBadge(false)`, `setTitleCount(0)`. Set `count = 2`, `await act(() => client.invalidateQueries({ queryKey: ["notifications", "count"] }))` → last calls `(true)`, `(2)`. Back to 0 → `(false)`, `(0)`. Set 5, invalidate, then `unmount()` → last calls `(false)`, `(0)`. Use `vi.mocked(fn).mock.lastCall`. Run `npx vitest run src/components/notifications/__tests__/TabBadge.test.tsx` → fails (no module). + +**Implement** `TabBadge.tsx`: +```tsx +"use client"; + +import { usePathname } from "next/navigation"; +import { useEffect } from "react"; + +import { setFaviconBadge } from "@/lib/favicon"; +import { useUnreadCount } from "@/lib/notifications"; +import { setTitleCount } from "@/lib/title"; + +/** Marks the browser tab while anything is unread: a bell on the favicon and "(3) " before the title. Renders nothing. */ +export function TabBadge() { + const count = useUnreadCount().data?.count ?? 0; + // a page change may re-render the head's icon links and title: mark them again + const pathname = usePathname(); + useEffect(() => { + setFaviconBadge(count > 0); + setTitleCount(count); + }, [count, pathname]); + useEffect( + () => () => { + setFaviconBadge(false); + setTitleCount(0); + }, + [], + ); + return null; +} +``` +In `frontend/src/app/(app)/layout.tsx` import it and render `` right after the `NavRecorder` `Suspense` block (signed-in branch only). Run the test → passes; `npm test` (whole suite), `npx tsc --noEmit`, `npx eslint` on the three files. +Commit: `feat(notifications): the browser tab shows unread notifications`. + +### 5. E2E and docs +Add section 7 at the end of the test in `frontend/e2e/notifications.spec.ts` (Appendix C). Docs: in `README.md` line 151 append to the paragraph: "While anything is unread, her tab title starts with the count and the favicon carries a bell, also after a page change, and reading everything in one tab clears both in her other tab." In `docs/install.md`, after the chime sentence (ends "…on the same page."): "While anything is unread, the browser tab shows it too: the title starts with the count, such as `(3) Projects · MegooColab`, and the icon carries a small red bell." Run the spec on a fresh `megoo-e2e` stack as AGENTS.md describes (`npx playwright test e2e/notifications.spec.ts --reporter=line`). If the title prefix or the data URL is lost after the client-side page change, fix it in `TabBadge` (it already re-applies on `pathname`), not in the test. `npx eslint e2e/notifications.spec.ts`; `npx tsc --noEmit`. +Commit: `test(notifications): the tab badge and title count, also across tabs`. + +## Appendix A — `frontend/src/lib/favicon.ts` +```ts +/** + * The favicon's unread mark: a small red bell drawn in the browser over the app's own icon. Every `rel="icon"` + * link points at the drawing while the mark is on and gets its own address back when it goes. The Apple touch icon + * and the manifest's icons are not `rel="icon"` and stay as they are. + */ + +const SIZE = 64; +// the badge: a red circle in the top-right corner, with a gap cut around it so it stands apart on any tab colour +const BADGE = { x: 46, y: 18, r: 16, gap: 3 }; +const RED = "#ef4444"; + +let wanted = false; +let badged: string | null = null; // the drawing, made once per page load +let drawing = false; + +function links(): HTMLLinkElement[] { + return Array.from(document.head.querySelectorAll('link[rel~="icon"]')); +} + +// the link's own address, also while it points at the drawing +const own = (link: HTMLLinkElement) => link.dataset.megooHref ?? link.getAttribute("href"); + +function source(): string | null { + const all = links(); + const png = all.find((l) => l.type === "image/png") ?? all[0]; + return png ? own(png) : null; +} + +function point() { + for (const link of links()) { + if (wanted && badged) { + if (link.dataset.megooHref === undefined) link.dataset.megooHref = link.getAttribute("href") ?? ""; + link.href = badged; + } else if (link.dataset.megooHref !== undefined) { + link.setAttribute("href", link.dataset.megooHref); + delete link.dataset.megooHref; + } + } +} + +function draw(icon: HTMLImageElement): string { + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = SIZE; + const ctx = canvas.getContext("2d"); + if (!ctx) throw new Error("no 2D canvas"); + ctx.drawImage(icon, 0, 0, SIZE, SIZE); + const circle = (x: number, y: number, r: number) => { + ctx.beginPath(); + ctx.arc(x, y, r, 0, 2 * Math.PI); + ctx.fill(); + }; + ctx.globalCompositeOperation = "destination-out"; + circle(BADGE.x, BADGE.y, BADGE.r + BADGE.gap); + ctx.globalCompositeOperation = "source-over"; + ctx.fillStyle = RED; + circle(BADGE.x, BADGE.y, BADGE.r); + // the bell: body, clapper and knob + ctx.fillStyle = "#ffffff"; + ctx.beginPath(); + ctx.moveTo(37, 24); + ctx.lineTo(55, 24); + ctx.lineTo(52, 20); + ctx.lineTo(52, 15); + ctx.arc(46, 15, 6, 0, Math.PI, true); + ctx.lineTo(40, 20); + ctx.closePath(); + ctx.fill(); + circle(46, 26.5, 2.5); + circle(46, 8.5, 1.5); + return canvas.toDataURL("image/png"); +} + +/** Shows or hides the bell badge on the tab's icon. Never throws: if it can't draw, the icon stays as it is. */ +export function setFaviconBadge(on: boolean): void { + wanted = on; + if (!on || badged) { + point(); + return; + } + const src = source(); + if (drawing || !src) return; + drawing = true; + const icon = new Image(); + icon.onload = () => { + drawing = false; + try { + badged = draw(icon); + } catch { + return; + } + point(); // applies only if the badge is still wanted + }; + icon.onerror = () => { + drawing = false; // the next change of the count tries again + }; + icon.src = src; +} +``` +(The icon is same-origin, so the canvas is not tainted; `toDataURL` failing is caught all the same.) + +## Appendix B — `frontend/src/lib/__tests__/favicon.test.ts` +Setup: +- `beforeEach`: `vi.resetModules()`; `const mod = await import("@/lib/favicon")` (fresh module state per test); fill `document.head` with ``, ``, ``. +- Stub `Image`: `vi.stubGlobal("Image", class { onload: (() => void) | null = null; onerror: (() => void) | null = null; src = ""; constructor() { images.push(this); } })` with a module-level `images` array reset each test. +- Canvas: `const ctx = { drawImage: vi.fn(), beginPath: vi.fn(), arc: vi.fn(), fill: vi.fn(), moveTo: vi.fn(), lineTo: vi.fn(), closePath: vi.fn(), globalCompositeOperation: "", fillStyle: "" }`; `getContext = vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(ctx as never)`; `vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue("data:image/png;base64,BADGE")`. +- `afterEach`: `vi.restoreAllMocks()`, `vi.unstubAllGlobals()`, `document.head.innerHTML = ""`. +- `const hrefs = () => [...document.head.querySelectorAll("link")].map((l) => l.getAttribute("href"))`. + +Tests: +1. "loads the PNG icon and points every icon link at the badge": `setFaviconBadge(true)`; `images[0].src === "/icon.png?abc"`; links unchanged before load; `images[0].onload!()`; `hrefs()` → `["data:image/png;base64,BADGE", "data:image/png;base64,BADGE", "/apple-icon.png?def"]`; `ctx.fillStyle` set to `#ef4444` at some point (assert `ctx.arc` was called with `46, 18, 16`). +2. "off puts the original addresses back": on → load → off → `hrefs()` → `["/favicon.ico", "/icon.png?abc", "/apple-icon.png?def"]`, and no link keeps `data-megoo-href`. +3. "a failed load leaves the links alone and throws nothing": on → `images[0].onerror!()` → hrefs original; `setFaviconBadge(true)` again creates a second `Image` (retry). +4. "no 2D canvas: the icon stays": `getContext.mockReturnValue(null)`; on → onload → no throw, hrefs original. +5. "off before the icon loads: the late drawing is not applied": on → off → `images[0].onload!()` → hrefs original. +6. "draws once for repeated on and off": on → load → off → on → off → on: `images.length === 1`, `getContext` called once, links point at the badge. + +## Appendix C — e2e section 7 (end of the test in `notifications.spec.ts`) +```ts + // 7. while anything is unread, Bea's tab says so: the count before the title and a bell on the favicon, also after + // a page change; reading everything in one tab clears both in her other tab + const icons = (p: Page) => p.locator('link[rel~="icon"]').evaluateAll((ls) => ls.map((l) => l.getAttribute("href") ?? "")); + const badged = async (p: Page) => (await icons(p)).every((h) => h.startsWith("data:image/png")); + const plain = async (p: Page) => (await icons(p)).every((h) => !h.startsWith("data:")); + count = await unread(); + expect(count).toBeGreaterThan(0); // section 6 left its mention unread + await beaPage.goto("/projects"); + await expect(bell(beaPage)).toHaveText(String(count), { timeout: 15_000 }); + await expect(beaPage).toHaveTitle(`(${count}) Projects · MegooColab`); + await expect.poll(() => badged(beaPage)).toBe(true); + await beaPage.getByRole("navigation", { name: "Main" }).getByRole("link", { name: "Teams", exact: true }).click(); + await expect(beaPage).toHaveURL(/\/teams$/); + await expect(beaPage).toHaveTitle(new RegExp(`^\\(${count}\\) `)); + await expect.poll(() => badged(beaPage)).toBe(true); + const other = await bea.ctx.newPage(); + await other.goto("/projects"); + await expect(other).toHaveTitle(`(${count}) Projects · MegooColab`, { timeout: 15_000 }); + await expect.poll(() => badged(other)).toBe(true); + await bell(beaPage).click(); + await beaPage.getByRole("button", { name: "Mark all read" }).click(); + await expect(other).toHaveTitle("Projects · MegooColab", { timeout: 15_000 }); // told by the server, no reload + await expect.poll(() => plain(other)).toBe(true); + await expect(beaPage).not.toHaveTitle(/^\(/); +``` +(If `count` were above 99 the title would read `(99+)`; Bea has only a few here.) + +## Final verification +- `cd backend; uv run pytest tests/notifications -q` +- `cd frontend; npm test; npx tsc --noEmit; npx eslint src/lib/title.ts src/lib/favicon.ts src/lib/__tests__/title.test.tsx src/lib/__tests__/favicon.test.ts src/components/notifications/TabBadge.tsx src/components/notifications/__tests__/TabBadge.test.tsx 'src/app/(app)/layout.tsx' e2e/notifications.spec.ts` +- On a fresh `megoo-e2e` stack (AGENTS.md "Browser tests"): `cd frontend; npx playwright test e2e/notifications.spec.ts --reporter=line` +- By hand (optional): with unread notifications, the tab shows the red bell and `(N)`; "Mark all read" in one tab clears another. diff --git a/docs/superpowers/specs/MC-46-design.md b/docs/superpowers/specs/MC-46-design.md new file mode 100644 index 00000000..c3ae4925 --- /dev/null +++ b/docs/superpowers/specs/MC-46-design.md @@ -0,0 +1,81 @@ +# MC-46 design: unread notifications in the browser tab + +## Goal + +When the signed-in person has unread notifications, the MegooColab tab shows it: the favicon carries a small red bell badge and the tab title starts with the unread count, for example `(3) Projects · MegooColab`. Someone working in another tab sees at a glance that MegooColab needs them. With nothing unread, the tab looks as it does today. + +The approved look is mockup v2. + +## Decisions + +| Question | Answer | Why | +|---|---|---| +| What does the tab show? | A **small red bell badge** on the favicon **and the count in the tab title** (human's answer). | The badge catches the eye; the title gives the number, which is not readable inside a 16 px icon. Rejected: plain red dot, count drawn inside the icon. | +| When does it show? | **Whenever the unread count is above 0**, also while the tab is in front (human's answer). | It always agrees with the header bell and needs no visibility tracking. Rejected: only while the tab is hidden; only for notifications that arrived while away. | +| How is the badged icon made? | **Drawn in the browser** on a canvas, over the real favicon (human's answer). | No new image files; a new logo is followed automatically. Rejected: a second, ready-made icon file (must be redrawn by hand, and the repository has no image tooling). | +| Other tabs after reading? | **Fixed in this task** (human's answer): the two mark-as-read endpoints send the live event `notification.read`. | Without it, a second tab or device would keep its badge and `(3)` after everything is read. | +| A switch to turn it off? | None. | Not asked for; the mark is silent and small. See "Out of scope". | + +The count in the title uses the bell's rule: the exact number up to 99, then `99+`. + +## Architecture + +The change is mostly frontend. The unread count already exists as one shared query (`useUnreadCount`, key `["notifications", "count"]`) that the header bell uses and that every `notification.*` live event refreshes, also in a background tab. The new code only reads that count and paints the tab. + +**1. `frontend/src/lib/favicon.ts` (new): the favicon mark.** One small module with one purpose: switch the tab's icon between the normal and the badged image. + +- `setFaviconBadge(on: boolean): void` is the whole interface. +- On: it loads the page's own icon (the PNG `link[rel~="icon"]` that Next.js renders from `app/icon.png`), draws it on a 64×64 canvas, clears a thin ring around the badge area so the badge stands apart on any tab colour, draws a red circle (`#ef4444`) in the top-right corner with a white bell inside (geometry as in mockup v2), and turns the canvas into a PNG data URL. The data URL is made once per page load and kept in the module. +- It then points every `link[rel~="icon"]` in `` at the data URL, remembering each link's original `href` in a data attribute. The Apple touch icon and the PWA manifest icons are not `rel="icon"` and stay untouched. +- Off: it puts the remembered `href`s back. +- The image loads asynchronously, so the module keeps the state it was last asked for and applies the drawing only if the badge is still wanted when the image is ready. + +**2. `frontend/src/lib/title.ts` (changed): the count in the title.** The module already owns `document.title` through `apply()`. It gets a module-level unread count and an exported `setTitleCount(count: number)`, which stores the count and calls `apply()`. `apply()` puts `(N) ` or `(99+) ` in front of the title it already computes when the count is above 0. `pageTitle()`, `usePageTitle` and `useRecordTitle` keep their signatures, so the 49 pages that set a title need no change, and a page change keeps the prefix. + +**3. `frontend/src/components/notifications/TabBadge.tsx` (new): the connection.** A component that renders nothing. It reads `useUnreadCount()` and, in an effect, calls `setFaviconBadge(count > 0)` and `setTitleCount(count)`. Its cleanup calls `setFaviconBadge(false)` and `setTitleCount(0)`. + +**4. `frontend/src/app/(app)/layout.tsx` (changed).** Renders `` in the signed-in branch, next to ``. It is therefore mounted only once the user is known (no unread-count request before sign-in is checked), and it unmounts on sign-out, which restores the normal favicon and title on the sign-in pages. + +**5. `backend/app/notifications/router.py` (changed): tell the other tabs.** + +- `mark_read`: when the notification was unread, publish `Event(type="notification.read", user_id=user.id)` before the commit. +- `mark_all_read`: publish the same event when the update changed at least one row. + +`read_by_acting` in `service.py` already sends this event, and `realtime.ts` already turns any `notification.*` event into a refresh of `["notifications"]` (and the dashboard counts). So every open tab and device of that person refreshes its count, and with it the bell, the favicon and the title. The tab that did the reading also refreshes through its own `onSettled`, as today; the second refresh is harmless. + +**6. Docs.** One sentence each in `README.md` (the paragraph on `frontend/e2e/notifications.spec.ts`) and `docs/install.md` (next to the sentence about the chime). + +## Data and interfaces + +- No new model, endpoint, setting or stored value. No API schema change, so `npm run gen:api` is not needed. +- New frontend exports: `setFaviconBadge(on)` in `lib/favicon.ts`, `setTitleCount(count)` in `lib/title.ts`, `TabBadge` in `components/notifications/TabBadge.tsx`. +- The live event `notification.read` (existing type, `user_id` only) is now also sent by `POST /api/notifications/{id}/read` and `POST /api/notifications/read-all`. + +## Error handling and edge cases + +- **Drawing fails** (the icon doesn't load, no 2D canvas, `toDataURL` throws): the favicon stays as it is, nothing is thrown, and the title count still shows. A later change of the count tries again. +- **The count drops to 0 before the icon has loaded**: the late drawing is not applied. +- **Count unknown** (query loading or failed): treated as 0, as the bell does. +- **Client-side navigation**: the icon links belong to the root layout and are the same on every page. The browser test checks that the badge survives a page change; if Next.js turns out to rewrite the links, `TabBadge` re-applies the badge after navigation (the plan settles this with the real framework). +- **Several MegooColab tabs**: each tab paints itself from the same count; no coordination is needed (unlike the chime). +- **Live socket reconnect**: the existing refetch-everything on reconnect brings the count, and so the mark, up to date. +- **Browsers that ignore a favicon changed by the page** (Safari is known for it): the badge may not show there; the title count still does. Nothing breaks. +- **Already-read notification marked read again, or "Mark all read" with nothing unread**: no event is sent. +- **Installed app (PWA)**: a standalone window has no tab; the code runs but changes nothing visible. The app icon is not touched. + +## Testing + +- **Vitest, `lib/__tests__/favicon.test.ts`** (canvas and `Image` stubbed, since jsdom has neither): on → every `rel="icon"` link gets the data URL and the Apple touch icon is untouched; off → the original `href`s are back; a failed image load leaves the links alone and throws nothing; off before the image loads → links unchanged; the drawing happens once for repeated on/off. +- **Vitest, `lib/__tests__/title.test.tsx`** (extended): `(3) ` prefix, `(99+) ` above 99, no prefix at 0, the prefix stays when the page title changes and on the bare `MegooColab` title. +- **Vitest, `components/notifications/__tests__/TabBadge.test.tsx`**: with the count query answering 0, 2 and then 0, the component calls the two setters accordingly; unmounting clears both. +- **Pytest, `backend/tests/notifications/test_core.py`** (extended, in the style of `test_live_event_per_user`): `mark_read` publishes `notification.read` for the owner once, not for an already-read row, not on another person's 404; `read-all` publishes only when something was unread. +- **Playwright, `frontend/e2e/notifications.spec.ts`** (extended): when Bea's bell shows 1, her tab title starts with `(1) ` and the icon link is a `data:image/png` URL, also after a page change; she opens a second tab, uses "Mark all read" in the first, and the second tab's title loses the prefix and its icon link returns to the original (this covers the backend event end to end). +- The usual frontend chain (vitest, `tsc --noEmit`, eslint) and backend `uv run pytest` for the touched areas. No browser test asserts a tab title today, so the prefix breaks none. + +## Out of scope + +- A setting to turn the badge or the count off. +- The count drawn inside the favicon, animation or blinking. +- Showing the mark only while the tab is in the background. +- A badge on the installed app's icon (`navigator.setAppBadge`), the Apple touch icon and the manifest icons. +- Changes to the chime, to push, email or Telegram notifications, and to which notifications are created.