From c9c0ebafc6bdb87a179d4505fd926a504fe95420 Mon Sep 17 00:00:00 2001 From: jabradford Date: Tue, 24 Nov 2026 11:08:39 -0800 Subject: [PATCH 1/7] fix(hub): refresh the Inbox badge across navigation Refs: #354 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../routes/real-workspace-navigation.test.tsx | 138 ++++++++++---- .../hub/routes/workspace/index.tsx | 1 + .../workspace-inbox-count-context/index.ts | 6 +- .../use-notification-inbox/index.test.tsx | 175 +++++++++++++----- .../hooks/use-notification-inbox/index.ts | 121 +++++++----- hub/docs/frontend.md | 4 +- 6 files changed, 319 insertions(+), 126 deletions(-) diff --git a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx index ae9d4409e..d71ea4673 100644 --- a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx +++ b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx @@ -149,9 +149,9 @@ function galleryApi(repository: RepositoryRecord, onRead?: (request: Request) => }) } -function unreadMention(repository: RepositoryRecord, prototypeId: string) { +function unreadMention(repository: RepositoryRecord, prototypeId: string, id = 7) { return { - id: 7, + id, version: 1, actor: { login: "mona", name: "Mona", avatarUrl: null }, kind: "mention", @@ -160,9 +160,9 @@ function unreadMention(repository: RepositoryRecord, prototypeId: string) { read: false, repository: repository.nameWithOwner, prototype: "Landing page", - path: `/repositories/${repository.id}/prototypes/${prototypeId}?comment=7`, - updatePath: "/api/notifications/7", - target: { prototypeId, threadId: 7, commentId: 7 }, + path: `/repositories/${repository.id}/prototypes/${prototypeId}?comment=${id}`, + updatePath: `/api/notifications/${id}`, + target: { prototypeId, threadId: id, commentId: id }, } } @@ -194,7 +194,7 @@ function sidebarDestinations() { } describe("real workspace navigation", () => { - it("keeps the collapsed navigation and Inbox count across main pages", async () => { + it("keeps the collapsed navigation and refreshes the Inbox count across main pages", async () => { const repository = { id: "11111111-1111-4111-8111-111111111111", nameWithOwner: "team/alpha", @@ -209,12 +209,16 @@ describe("real workspace navigation", () => { const galleryPath = `/repositories/${repository.id}` const createPath = `${galleryPath}/new` const inboxPath = `/notifications?repositoryId=${repository.id}` - const galleryCount = 3 - const inboxCount = 1 - const notification = unreadMention(repository, "33333333-3333-4333-8333-333333333333") - const inboxReads: [limit: string | null, unread: string | null][] = [] + const prototypeId = "33333333-3333-4333-8333-333333333333" + const newestMention = unreadMention(repository, prototypeId) + const mentions = [ + newestMention, + ...[6, 5].map((id) => unreadMention(repository, prototypeId, id)), + ] + let unreadCount = mentions.length + const inboxReads: [pathname: string, limit: string | null, unread: string | null][] = [] const galleryReads: (string | null)[] = [] - await renderApplication(galleryPath, [ + const router = await renderApplication(galleryPath, [ ...workspaceApi([otherRepository, repository], { role: "MEMBER", reviewInboxAvailable: true, @@ -230,11 +234,12 @@ describe("real workspace navigation", () => { http.get(`${window.location.origin}/api/notifications/inbox`, ({ request }) => { const query = new URL(request.url).searchParams const limit = query.get("limit") - inboxReads.push([limit, query.get("unread")]) + inboxReads.push([window.location.pathname, limit, query.get("unread")]) + const notifications = mentions.slice(0, Math.min(Number(limit), unreadCount)) return HttpResponse.json({ - notifications: [notification], - nextBefore: limit === "1" ? notification.id : null, - unreadCount: limit === "1" ? galleryCount : inboxCount, + notifications, + nextBefore: notifications.length < unreadCount ? notifications.at(-1)?.id : null, + unreadCount, }) }), ]) @@ -247,12 +252,12 @@ describe("real workspace navigation", () => { return within(mainNavigation()).getByRole("link", { name }) } - function navInboxBadge(count: number) { - return within(navLink(/^Inbox\b/)).queryByText(String(count)) + function findInboxBadge(count: number) { + return within(mainNavigation()).findByRole("link", { name: `Inbox, ${count} unread` }) } - await waitFor(() => expect(navInboxBadge(galleryCount)).toBeVisible()) - expect(inboxReads).toEqual([["1", "true"]]) + expect(await findInboxBadge(3)).toBeVisible() + expect(inboxReads).toEqual([[galleryPath, "1", "true"]]) expect(navLink("Prototypes")).toHaveAttribute("aria-current", "page") fireEvent.click(screen.getByRole("button", { name: "Collapse sidebar" })) const originalNavigation = mainNavigation() @@ -275,20 +280,24 @@ describe("real workspace navigation", () => { expect(window.location.pathname + window.location.search).toBe(path) } + unreadCount = 2 fireEvent.click(navLink("Create")) expect(await screen.findByRole("heading", { name: "What should we create?" })).toBeVisible() expectNavigation("Create", createPath) + expect(await findInboxBadge(2)).toBeVisible() + unreadCount = 1 fireEvent.click(navLink(/^Inbox\b/)) const inbox = await screen.findByRole("region", { name: "Inbox" }) - expect(await within(inbox).findByText(notification.excerpt)).toBeVisible() - await waitFor(() => expect(navInboxBadge(inboxCount)).toBeVisible()) + expect(await within(inbox).findByText(newestMention.excerpt)).toBeVisible() + expect(await findInboxBadge(1)).toBeVisible() expectNavigation("Inbox", inboxPath) + unreadCount = 2 fireEvent.click(navLink("Prototypes")) expect(await screen.findByRole("heading", { name: "Prototypes" })).toBeVisible() expectNavigation("Prototypes", galleryPath) - expect.soft(navInboxBadge(inboxCount), "Inbox count after leaving the list").toBeVisible() + expect(await findInboxBadge(2)).toBeVisible() const searchBox = screen.getByRole("searchbox", { name: "Search prototypes" }) fireEvent.change(searchBox, { target: { value: "landing" } }) @@ -302,12 +311,82 @@ describe("real workspace navigation", () => { expect(screen.getByRole("searchbox", { name: "Search prototypes" })).toHaveValue(""), ) expect(window.location.pathname + window.location.search).toBe(galleryPath) + await act(() => router.navigate(`${galleryPath}#prototypes`)) + expect(window.location.hash).toBe("#prototypes") expect(inboxReads).toEqual([ - ["1", "true"], - ["50", null], + [galleryPath, "1", "true"], + [createPath, "1", "true"], + ["/notifications", "50", null], + [galleryPath, "1", "true"], ]) }, 15_000) + it("keeps the Inbox badge during request failures and refreshes it after leaving Inbox", async () => { + const repository = { + id: "11111111-1111-4111-8111-111111111111", + nameWithOwner: "team/alpha", + defaultBranch: "main", + capabilities: { reviewPrototypes: true, manageSharing: false, browseTemplates: true }, + } + const galleryPath = `/repositories/${repository.id}` + const notification = unreadMention(repository, "33333333-3333-4333-8333-333333333333") + const listFailure = deferResponse() + const countFailure = deferResponse() + const inboxReads: (string | null)[] = [] + let failCount = false + let unreadCount = 1 + await renderApplication(galleryPath, [ + ...workspaceApi([repository], { role: "MEMBER", reviewInboxAvailable: true }), + galleryApi(repository), + json(`/api${galleryPath}/templates`, { repository, templates: [], canCreate: true }), + http.get(`${window.location.origin}/api/notifications/inbox`, async ({ request }) => { + const limit = new URL(request.url).searchParams.get("limit") + inboxReads.push(limit) + if (limit === "50") { + await listFailure.pending + return new HttpResponse(null, { status: 503 }) + } + if (failCount) { + await countFailure.pending + return new HttpResponse(null, { status: 503 }) + } + return HttpResponse.json({ + notifications: unreadCount ? [notification] : [], + nextBefore: null, + unreadCount, + }) + }), + ]) + const badge = { name: "Inbox, 1 unread" } + fireEvent.click(await screen.findByRole("link", badge)) + const inbox = await screen.findByRole("region", { name: "Inbox" }) + await waitFor(() => expect(inboxReads).toEqual(["1", "50"])) + expect(screen.getByRole("link", badge)).toBeVisible() + + listFailure.release() + expect(await within(inbox).findByRole("button", { name: "Retry" })).toBeVisible() + expect(screen.getByRole("link", badge)).toBeVisible() + + failCount = true + fireEvent.click(screen.getByRole("link", { name: "Prototypes" })) + expect(await screen.findByRole("heading", { name: "Prototypes" })).toBeVisible() + await waitFor(() => expect(inboxReads).toEqual(["1", "50", "1"])) + expect(screen.getByRole("link", badge)).toBeVisible() + + await act(() => { + countFailure.release() + return countFailure.pending + }) + expect(screen.getByRole("link", badge)).toBeVisible() + + failCount = false + unreadCount = 0 + fireEvent.click(screen.getByRole("link", { name: "Create" })) + expect(await screen.findByRole("heading", { name: "What should we create?" })).toBeVisible() + expect(await screen.findByRole("link", { name: "Inbox" })).toBeVisible() + expect(inboxReads).toEqual(["1", "50", "1", "1"]) + }) + it("opens Create, Inbox, and Hub settings while repository permissions are pending", async () => { const repository = { id: "11111111-1111-4111-8111-111111111111", @@ -839,13 +918,10 @@ describe("real workspace navigation", () => { http.get(`${window.location.origin}/api${galleryPath}/security-audit`, () => audit("repository"), ), - http.get(`${window.location.origin}/api/notifications/inbox`, ({ request }) => { - const countOnly = new URL(request.url).searchParams.get("limit") === "1" - return HttpResponse.json({ - notifications: [notification], - nextBefore: countOnly ? notification.id : null, - unreadCount: countOnly ? 3 : 1, - }) + json("/api/notifications/inbox", { + notifications: [notification], + nextBefore: null, + unreadCount: 1, }), json("/api/canvas/connections", { connections: [] }), http.get(`${window.location.origin}/api${galleryPath}/analytics`, () => diff --git a/hub/client/application/hub/routes/workspace/index.tsx b/hub/client/application/hub/routes/workspace/index.tsx index 4a1ad48e2..e55314464 100644 --- a/hub/client/application/hub/routes/workspace/index.tsx +++ b/hub/client/application/hub/routes/workspace/index.tsx @@ -202,6 +202,7 @@ function WorkspaceNavigationFrame({ initialUnreadOnly: true, autoLoad: false, autoCount: Boolean(configuration) && section !== "notifications", + countRefreshKey: pathname, synchronize: Boolean(configuration), limit: 10, }) diff --git a/hub/client/application/hub/workspace-inbox-count-context/index.ts b/hub/client/application/hub/workspace-inbox-count-context/index.ts index df527f0ae..9278607c1 100644 --- a/hub/client/application/hub/workspace-inbox-count-context/index.ts +++ b/hub/client/application/hub/workspace-inbox-count-context/index.ts @@ -1,5 +1,5 @@ import { createContext } from "react" -export const WorkspaceInboxCountContext = createContext<((count: number) => void) | undefined>( - undefined, -) +export const WorkspaceInboxCountContext = createContext< + ((count: number | null) => void) | undefined +>(undefined) diff --git a/hub/client/hooks/use-notification-inbox/index.test.tsx b/hub/client/hooks/use-notification-inbox/index.test.tsx index d56194a94..c53471232 100644 --- a/hub/client/hooks/use-notification-inbox/index.test.tsx +++ b/hub/client/hooks/use-notification-inbox/index.test.tsx @@ -23,17 +23,20 @@ const notification: InboxNotification = { const page = { notifications: [notification], nextBefore: null, unreadCount: 12 } function renderClosedBadge() { - return renderHook(() => - useNotificationInbox({ - path: "/api/notifications/inbox", - authenticityToken: "", - initialUnreadCount: 4, - initialUnreadOnly: true, - autoLoad: false, - autoCount: true, - synchronize: true, - limit: 10, - }), + return renderHook( + ({ pathname }) => + useNotificationInbox({ + path: "/api/notifications/inbox", + authenticityToken: "", + initialUnreadCount: 4, + initialUnreadOnly: true, + autoLoad: false, + autoCount: true, + countRefreshKey: pathname, + synchronize: true, + limit: 10, + }), + { initialProps: { pathname: "/repositories/2001" } }, ) } @@ -192,32 +195,58 @@ describe("useNotificationInbox()", () => { expect(result.current.unreadCount).toBe(0) }) - it("loads the latest ten only when the preview opens and keeps the complete unread count", async () => { - const fetch = vi.fn().mockResolvedValue(Response.json(page)) + it("loads the latest ten when the preview opens and ignores an older count that arrives last", async () => { + let finishCount!: (response: Response) => void + const pendingCount = new Promise((resolve) => (finishCount = resolve)) + const fetch = vi + .fn() + .mockReturnValueOnce(pendingCount) + .mockResolvedValueOnce(Response.json(page)) vi.stubGlobal("fetch", fetch) - const { result } = renderHook(() => - useNotificationInbox({ - path: "/notifications/inbox", - authenticityToken: "token", - initialUnreadCount: 12, - autoLoad: false, - limit: 10, - }), - ) - expect(fetch).not.toHaveBeenCalled() - expect(result.current.unreadCount).toBe(12) + const { result } = renderClosedBadge() + expect(fetch).toHaveBeenCalledExactlyOnceWith(badgeUrl, expect.anything()) + act(() => result.current.onOpen()) await waitFor(() => expect(result.current.notifications).toHaveLength(1)) - expect(fetch).toHaveBeenCalledWith( - new URL("http://localhost:3000/notifications/inbox?limit=10"), - { - credentials: "same-origin", - }, + expect(fetch).toHaveBeenLastCalledWith( + new URL("/api/notifications/inbox?limit=10&unread=true", window.location.origin), + expect.anything(), ) expect(result.current.unreadCount).toBe(12) + + await act(async () => { + finishCount(badgeResponse(2)) + await pendingCount + }) + expect(result.current.unreadCount).toBe(12) }) - it("exposes failures, clears inaccessible data, and retries explicitly", async () => { + it("keeps the newer navigation count when an older preview finishes last", async () => { + let finishPreview!: (response: Response) => void + const preview = new Promise((resolve) => (finishPreview = resolve)) + const fetch = vi + .fn() + .mockResolvedValueOnce(badgeResponse(2)) + .mockReturnValueOnce(preview) + .mockResolvedValueOnce(badgeResponse(3)) + vi.stubGlobal("fetch", fetch) + const { result, rerender } = renderClosedBadge() + await waitFor(() => expect(result.current.unreadCount).toBe(2)) + + act(() => result.current.onOpen()) + rerender({ pathname: "/welcome" }) + await waitFor(() => expect(result.current.unreadCount).toBe(3)) + + await act(async () => { + finishPreview(Response.json({ ...page, unreadCount: 2 })) + await preview + }) + expect(result.current.notifications).toEqual([notification]) + expect(result.current.unreadCount).toBe(3) + }) + + it("keeps the last unread count when the preview fails and retries explicitly", async () => { + const onUnreadCountChange = vi.fn() const fetch = vi .fn() .mockResolvedValueOnce(new Response(null, { status: 503 })) @@ -228,11 +257,15 @@ describe("useNotificationInbox()", () => { path: "/notifications/inbox", authenticityToken: "token", initialUnreadCount: 12, + autoLoad: false, + limit: 10, + onUnreadCountChange, }), ) + act(() => result.current.onOpen()) await waitFor(() => expect(result.current.failed).toBe(true)) - expect(result.current.notifications).toHaveLength(0) - expect(result.current.unreadCount).toBe(0) + expect(result.current.unreadCount).toBe(12) + expect(onUnreadCountChange).not.toHaveBeenCalled() act(() => result.current.onRetry()) await waitFor(() => expect(result.current.notifications).toHaveLength(1)) expect(result.current.failed).toBe(false) @@ -572,7 +605,34 @@ describe("useNotificationInbox()", () => { expect(result.current.unreadCount).toBe(1) }) - it("refreshes the closed badge after a separate read when a failed update cleared its count", async () => { + it.each([ + ["clears", 401, 0], + ["keeps", 503, 1], + ] as const)( + "%s the closed badge count when the background request fails with status %s", + async (_outcome, status, count) => { + const failure = Promise.resolve(new Response(null, { status })) + const fetch = vi + .fn() + .mockResolvedValueOnce(Response.json({ ...page, unreadCount: 1 })) + .mockReturnValueOnce(failure) + vi.stubGlobal("fetch", fetch) + const clock = vi.spyOn(performance, "now").mockReturnValue(10) + const { result } = renderClosedBadge() + await waitFor(() => expect(result.current.unreadCount).toBe(1)) + + clock.mockReturnValue(20) + await act(() => { + acknowledgeRead(performance.now()) + return failure + }) + expect(fetch).toHaveBeenCalledTimes(2) + expect(fetch).toHaveBeenLastCalledWith(badgeUrl, expect.anything()) + expect(result.current.unreadCount).toBe(count) + }, + ) + + it("recounts on a separate read after a failed update leaves the badge stale", async () => { const fetch = vi .fn() .mockResolvedValueOnce(badgeResponse(3)) @@ -593,8 +653,7 @@ describe("useNotificationInbox()", () => { await waitFor(() => expect(result.current.notifications).toHaveLength(2)) act(() => result.current.onToggleRead(2)) await waitFor(() => expect(result.current.failed).toBe(true)) - expect(result.current.unreadCount).toBe(0) - expect(result.current.notifications).toHaveLength(0) + expect(result.current.unreadCount).toBe(3) clock.mockReturnValue(20) act(() => acknowledgeRead(performance.now())) @@ -634,32 +693,52 @@ describe("useNotificationInbox()", () => { }) it.each([403, 409, 503])( - "exposes failed read updates with status %s and retries a fresh page", + "reports a failed read with status %s without treating it as saved", async (status) => { + const onReadChange = vi.fn() + const onUnreadCountChange = vi.fn() + const refreshedItem = + status === 409 ? { ...notification, version: 1, read: true } : notification + const refreshedPage = { + ...page, + notifications: + status === 409 ? [refreshedItem] : [{ ...notification, id: 2 }, refreshedItem], + unreadCount: status === 409 ? 0 : 2, + } const fetch = vi .fn() - .mockResolvedValueOnce(Response.json(page)) + .mockResolvedValueOnce(Response.json({ ...page, unreadCount: 1 })) .mockResolvedValueOnce(new Response(null, { status })) - .mockResolvedValueOnce( - Response.json({ - ...page, - notifications: [{ ...notification, version: 1, read: true }], - unreadCount: 0, - }), - ) + .mockResolvedValueOnce(Response.json(refreshedPage)) vi.stubGlobal("fetch", fetch) const { result } = renderHook(() => - useNotificationInbox({ path: "/notifications/inbox", authenticityToken: "token" }), + useNotificationInbox({ + path: "/notifications/inbox", + authenticityToken: "token", + onReadChange, + onUnreadCountChange, + }), ) await waitFor(() => expect(result.current.notifications).toHaveLength(1)) act(() => result.current.onToggleRead(1)) await waitFor(() => expect(result.current.failed).toBe(true)) - expect(result.current.notifications).toHaveLength(0) expect(result.current.loading).toBe(false) + if (status === 403) { + expect(result.current.notifications).toHaveLength(0) + expect(result.current.unreadCount).toBe(0) + } else { + expect(result.current.unreadCount).toBe(1) + expect(onUnreadCountChange).not.toHaveBeenCalledWith(0) + } + expect(onReadChange).not.toHaveBeenCalled() + act(() => result.current.onRetry()) - await waitFor(() => expect(result.current.notifications[0]?.version).toBe(1)) + await waitFor(() => expect(result.current.unreadCount).toBe(refreshedPage.unreadCount)) expect(result.current.failed).toBe(false) - expect(result.current.unreadCount).toBe(0) + expect(result.current.notifications.find((item) => item.id === 1)).toMatchObject({ + version: refreshedItem.version, + read: refreshedItem.read, + }) }, ) }) diff --git a/hub/client/hooks/use-notification-inbox/index.ts b/hub/client/hooks/use-notification-inbox/index.ts index 3b54dee91..e5681dfd6 100644 --- a/hub/client/hooks/use-notification-inbox/index.ts +++ b/hub/client/hooks/use-notification-inbox/index.ts @@ -5,6 +5,15 @@ import { notifyInboxRead, onInboxReadChanged } from "@utils/notification/read-up import type { InboxReadUpdate } from "@utils/notification/read-updates" import type { InboxNotification, NotificationReadUpdate } from "@utils/notification/types" +class InboxAccessDeniedError extends Error {} + +function requireInboxResponse(response: Response) { + if (response.status === 401 || response.status === 403) { + throw new InboxAccessDeniedError("Inbox access denied") + } + if (!response.ok) throw new Error("Inbox request failed") +} + export function useNotificationInbox({ path, authenticityToken, @@ -13,6 +22,7 @@ export function useNotificationInbox({ unreadOnly: controlledUnreadOnly, autoLoad = true, autoCount = false, + countRefreshKey, synchronize = false, limit = 50, onReadChange, @@ -25,10 +35,11 @@ export function useNotificationInbox({ unreadOnly?: boolean autoLoad?: boolean autoCount?: boolean + countRefreshKey?: string synchronize?: boolean limit?: number onReadChange?: (id: number, saved: NotificationReadUpdate) => void - onUnreadCountChange?: (count: number) => void + onUnreadCountChange?: (count: number | null) => void }) { const [localUnreadOnly, setUnreadOnly] = useState(initialUnreadOnly) const unreadOnly = controlledUnreadOnly ?? localUnreadOnly @@ -66,6 +77,45 @@ export function useNotificationInbox({ countReceivedAt.current = null }, [path]) + const clearFailedList = useCallback(() => { + setNotifications([]) + loaded.current = false + setNextBefore(null) + setFailed(true) + setLoading(false) + }, []) + + const receiveUnreadCount = useCallback( + (count: number | null) => { + suppliedCountRevision.current += 1 + pendingCount.current?.abort() + pendingCount.current = null + countReceivedAt.current = count === null ? null : performance.now() + setUnreadCount(count ?? 0) + if (count === null) { + generation.current += 1 + oldest.current = { all: null, unread: null } + clearFailedList() + } + }, + [clearFailedList], + ) + + const failInboxRequest = useCallback( + (error: unknown, countRevision: number) => { + if (countRevision === suppliedCountRevision.current) { + countReceivedAt.current = null + if (error instanceof InboxAccessDeniedError) { + receiveUnreadCount(null) + callbacks.current.onUnreadCountChange?.(null) + return + } + } + clearFailedList() + }, + [clearFailedList, receiveUnreadCount], + ) + const load = useCallback( async (before: number | null = null) => { if (!path) return @@ -84,7 +134,7 @@ export function useNotificationInbox({ credentials: "same-origin", ...(synchronize ? { cache: "no-store" } : {}), }) - if (!response.ok) throw new Error("Inbox is unavailable") + requireInboxResponse(response) return NOTIFICATION_PAGE_SCHEMA.parse(await response.json()) } const reloadPrefix = synchronize && autoLoad @@ -127,24 +177,16 @@ export function useNotificationInbox({ setUnreadCount(page.unreadCount) callbacks.current.onUnreadCountChange?.(page.unreadCount) } - } catch { + } catch (error) { if (requestGeneration !== generation.current) return - setNotifications([]) - loaded.current = false oldest.current = { all: null, unread: null } - if (countRevision === suppliedCountRevision.current) { - countReceivedAt.current = null - setUnreadCount(0) - callbacks.current.onUnreadCountChange?.(0) - } - setNextBefore(null) - setFailed(true) + failInboxRequest(error, countRevision) } finally { if (requestGeneration === generation.current) setLoading(false) } }, - [path, limit, unreadOnly, synchronize, autoLoad], + [path, limit, unreadOnly, synchronize, autoLoad, failInboxRequest], ) useEffect(() => { @@ -166,39 +208,36 @@ export function useNotificationInbox({ url.searchParams.set("unread", "true") void fetch(url, { credentials: "same-origin", cache: "no-store", signal: controller.signal }) .then(async (response) => { - if (!response.ok) throw new Error("Inbox is unavailable") + requireInboxResponse(response) const page = NOTIFICATION_PAGE_SCHEMA.parse(await response.json()) - if (!controller.signal.aborted && requestGeneration === generation.current) { - countReceivedAt.current = performance.now() - setUnreadCount(page.unreadCount) - } + if (controller.signal.aborted || requestGeneration !== generation.current) return + + // An older preview can still supply rows, but it no longer owns the count. + suppliedCountRevision.current += 1 + countReceivedAt.current = performance.now() + setUnreadCount(page.unreadCount) }) - .catch(() => { - if (!controller.signal.aborted && requestGeneration === generation.current) { + .catch((error: unknown) => { + if (controller.signal.aborted || requestGeneration !== generation.current) return + if (error instanceof InboxAccessDeniedError) { + receiveUnreadCount(null) + } else { countReceivedAt.current = null - setUnreadCount(0) + console.warn("Hub could not refresh the Inbox badge.") } }) .finally(() => { if (pendingCount.current === controller) pendingCount.current = null }) - }, [path]) + }, [path, receiveUnreadCount]) useEffect(() => { - if (autoCount && countReceivedAt.current === null) loadCount() + if (autoCount) loadCount() return () => { pendingCount.current?.abort() pendingCount.current = null } - }, [autoCount, loadCount]) - - const receiveUnreadCount = useCallback((count: number) => { - suppliedCountRevision.current += 1 - pendingCount.current?.abort() - pendingCount.current = null - countReceivedAt.current = performance.now() - setUnreadCount(count) - }, []) + }, [autoCount, countRefreshKey, loadCount]) function needsCountRefresh(saved: NotificationReadUpdate, startedAt?: number) { const lastCount = countReceivedAt.current @@ -228,8 +267,9 @@ export function useNotificationInbox({ ), ) if (updateCount) { - if (saved.unreadCount !== undefined) countReceivedAt.current = performance.now() - setUnreadCount((previous) => saved.unreadCount ?? Math.max(0, previous + delta)) + if (saved.unreadCount === undefined) + setUnreadCount((previous) => Math.max(0, previous + delta)) + else receiveUnreadCount(saved.unreadCount) } else { // The visible count omits this save's change. Later saves still need a fresh count. countReceivedAt.current = null @@ -266,6 +306,7 @@ export function useNotificationInbox({ async function toggleRead(notification: InboxNotification) { const requestGeneration = ++generation.current + const countRevision = suppliedCountRevision.current const startedAt = performance.now() setLoading(true) setFailed(false) @@ -279,23 +320,17 @@ export function useNotificationInbox({ notification: { read: !notification.read, version: notification.version }, }), }) - if (!response.ok) throw new Error("Notification could not be updated") + requireInboxResponse(response) if (requestGeneration !== generation.current) return saved = NOTIFICATION_READ_SCHEMA.parse(await response.json()) if (requestGeneration !== generation.current) return if (saved.read !== !notification.read) throw new Error("Notification read state did not change") - } catch { + } catch (error) { if (requestGeneration !== generation.current) return - setNotifications([]) - loaded.current = false - countReceivedAt.current = null - setUnreadCount(0) - setNextBefore(null) - setFailed(true) - setLoading(false) + failInboxRequest(error, countRevision) return } diff --git a/hub/docs/frontend.md b/hub/docs/frontend.md index 4282e6c29..aa2be95c2 100644 --- a/hub/docs/frontend.md +++ b/hub/docs/frontend.md @@ -110,7 +110,9 @@ Pending page navigation shows a thin green pulse moving to the right, with a scr Signed-in page and filter changes refresh the lightweight workspace alongside page data. This keeps the current account and readable repositories in sync when access changes in another tab. GitHub management controls wait for a separate, live lookup for the selected repository. The layout retains that result while the viewer, Hub role, and repository selection stay the same. A failed lookup offers a retry without blocking browsing. An expired session or changed access refreshes the workspace before private navigation returns. These results only control what Hub shows; protected APIs still verify access. -In real mode, one layout keeps the signed-in navigation mounted while the route content changes. It owns the picker, collapse choice, and Inbox badge across Welcome, repository pages, Inbox, Canvas connections, and settings. Route metadata selects the active link. Entering prototype review collapses the sidebar. You can reopen it, and changing Builds or leaving review keeps its current state. A page error stays in the content area, and Inbox rows update the same badge instead of starting another count request. A minimized prototype preview hides navigation without resetting it. +In real mode, one layout keeps the signed-in navigation mounted while the route content changes. It owns the picker, collapse choice, and Inbox badge across Welcome, repository pages, Inbox, Canvas connections, and settings. Route metadata selects the active link. Entering prototype review collapses the sidebar. You can reopen it, and changing Builds or leaving review keeps its current state. A page error stays in the content area. A minimized prototype preview hides navigation without resetting it. + +The sidebar refreshes its Inbox badge in the background when a signed-in page opens. The Inbox page supplies its own count, and changing filters on other pages does not request another count. The badge keeps the last known count while a request runs or fails. Hub clears the count when Inbox access is denied or the viewer changes. Hub settings and audit loaders request their own authorized data. They do not request full workspace data to build navigation. An administrator can still use Hub-wide settings if no repository is readable or if repository navigation fails. For Hub administrators, **Security audit** opens the Hub-wide records. The scope menu also offers the selected repository when Hub verifies repository administrator permission. Repository audit and Analytics still check current repository permissions in their APIs. From 4709c253f54e291324d45d9933bd9ddc15526dc7 Mon Sep 17 00:00:00 2001 From: jabradford Date: Tue, 24 Nov 2026 11:13:09 -0800 Subject: [PATCH 2/7] fix(hub): avoid recounting a supplied Inbox badge Follow up on the Inbox count handoff review in #346. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../use-notification-inbox/index.test.tsx | 86 +++++++++++++++++++ .../hooks/use-notification-inbox/index.ts | 4 +- 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/hub/client/hooks/use-notification-inbox/index.test.tsx b/hub/client/hooks/use-notification-inbox/index.test.tsx index c53471232..fbc4973a2 100644 --- a/hub/client/hooks/use-notification-inbox/index.test.tsx +++ b/hub/client/hooks/use-notification-inbox/index.test.tsx @@ -245,6 +245,92 @@ describe("useNotificationInbox()", () => { expect(result.current.unreadCount).toBe(3) }) + it.each([200, 401])( + "keeps the supplied count when an earlier background request returns %s", + async (status) => { + let finishCount!: (response: Response) => void + const pendingCount = new Promise((resolve) => (finishCount = resolve)) + const fetch = vi.fn().mockReturnValueOnce(pendingCount) + vi.stubGlobal("fetch", fetch) + const { result } = renderClosedBadge() + expect(fetch).toHaveBeenCalledExactlyOnceWith(badgeUrl, expect.anything()) + + act(() => result.current.onUnreadCountChange(7)) + await act(async () => { + finishCount(status === 200 ? badgeResponse(2) : new Response(null, { status })) + await pendingCount + }) + + expect(result.current.unreadCount).toBe(7) + }, + ) + + it.each([200, 403])( + "clears cached rows on fresh open and keeps the supplied count when the preview returns %s", + async (status) => { + let finishPreview!: (response: Response) => void + const pendingPreview = new Promise((resolve) => (finishPreview = resolve)) + const fetch = vi + .fn() + .mockResolvedValueOnce(Response.json(page)) + .mockReturnValueOnce(pendingPreview) + vi.stubGlobal("fetch", fetch) + const { result } = renderHook(() => + useNotificationInbox({ + path: "/api/notifications/inbox", + authenticityToken: "", + autoLoad: false, + synchronize: true, + }), + ) + act(() => result.current.onOpen()) + await waitFor(() => expect(result.current.notifications).toEqual([notification])) + + act(() => result.current.onOpen(true)) + expect(result.current.notifications).toEqual([]) + expect(result.current.loading).toBe(true) + expect(result.current.unreadCount).toBe(12) + act(() => result.current.onUnreadCountChange(7)) + + const fresh = { ...notification, id: 2 } + await act(async () => { + finishPreview( + status === 200 + ? Response.json({ ...page, notifications: [fresh] }) + : new Response(null, { status }), + ) + await pendingPreview + }) + + expect(result.current.notifications).toEqual(status === 200 ? [fresh] : []) + expect(result.current.failed).toBe(status === 403) + expect(result.current.unreadCount).toBe(7) + }, + ) + + it("uses the supplied count when automatic counting resumes without navigation", async () => { + const fetch = vi.fn(() => Promise.resolve(badgeResponse(2))) + vi.stubGlobal("fetch", fetch) + const { result, rerender } = renderHook( + ({ autoCount }) => + useNotificationInbox({ + path: "/api/notifications/inbox", + authenticityToken: "", + autoLoad: false, + autoCount, + }), + { initialProps: { autoCount: true } }, + ) + await waitFor(() => expect(result.current.unreadCount).toBe(2)) + + rerender({ autoCount: false }) + act(() => result.current.onUnreadCountChange(7)) + rerender({ autoCount: true }) + + expect(result.current.unreadCount).toBe(7) + expect(fetch).toHaveBeenCalledOnce() + }) + it("keeps the last unread count when the preview fails and retries explicitly", async () => { const onUnreadCountChange = vi.fn() const fetch = vi diff --git a/hub/client/hooks/use-notification-inbox/index.ts b/hub/client/hooks/use-notification-inbox/index.ts index e5681dfd6..d17f0466a 100644 --- a/hub/client/hooks/use-notification-inbox/index.ts +++ b/hub/client/hooks/use-notification-inbox/index.ts @@ -232,7 +232,9 @@ export function useNotificationInbox({ }, [path, receiveUnreadCount]) useEffect(() => { - if (autoCount) loadCount() + if (autoCount && (countRefreshKey !== undefined || countReceivedAt.current === null)) { + loadCount() + } return () => { pendingCount.current?.abort() pendingCount.current = null From cff76bdb2c959bc1c14f79ae1f57ead608a04769 Mon Sep 17 00:00:00 2001 From: jabradford Date: Tue, 24 Nov 2026 15:37:23 -0800 Subject: [PATCH 3/7] fix(hub): show a database-backed Inbox dot Use unread presence from the lightweight workspace response instead of recounting on page changes. Keep the last snapshot for the same viewer and leave Inbox list and mutation authorization unchanged. Refs: #354 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- hub/client/application/hub/contracts/index.ts | 1 + .../routes/real-workspace-navigation.test.tsx | 201 ++++++------ .../hub/routes/workspace/index.tsx | 110 +++---- .../hub/screens/real-inbox-screen/index.tsx | 4 - .../view-models/workspace-navigation/index.ts | 8 +- .../workspace-inbox-count-context/index.ts | 5 - hub/client/features/workspace-nav/inbox.tsx | 29 +- hub/client/features/workspace-nav/stories.tsx | 11 + .../use-notification-inbox/index.test.tsx | 278 ++--------------- .../hooks/use-notification-inbox/index.ts | 57 +--- hub/docs/frontend.md | 4 +- hub/docs/review-collaboration.md | 4 +- .../migration.sql | 2 + hub/schema/review-notification.prisma | 1 + .../create-review-inbox/index.ts | 17 +- .../review-comments/has-unread-inbox/index.ts | 44 +++ .../routes/api/workspace/get/index.db.test.ts | 285 ++++++++++++++++++ hub/server/routes/api/workspace/get/index.ts | 28 +- 18 files changed, 594 insertions(+), 495 deletions(-) delete mode 100644 hub/client/application/hub/workspace-inbox-count-context/index.ts create mode 100644 hub/schema/migrations/20261220150000_inbox_unread_lookup/migration.sql create mode 100644 hub/server/repositories/review-comments/has-unread-inbox/index.ts create mode 100644 hub/server/routes/api/workspace/get/index.db.test.ts diff --git a/hub/client/application/hub/contracts/index.ts b/hub/client/application/hub/contracts/index.ts index 4fa22bfff..6bb04a797 100644 --- a/hub/client/application/hub/contracts/index.ts +++ b/hub/client/application/hub/contracts/index.ts @@ -104,6 +104,7 @@ export const workspaceResponseSchema = z.object({ repositories: z.array(repositorySchema), repositoryPermissionsAvailable: z.literal(true).optional(), reviewInboxAvailable: z.boolean().optional(), + inboxHasUnread: z.boolean().optional(), publicSharingSettingsAvailable: z.boolean().optional(), capabilities: workspaceCapabilitiesSchema.optional(), welcomeHidden: z.boolean().optional(), diff --git a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx index d71ea4673..518ca1d7c 100644 --- a/hub/client/application/hub/routes/real-workspace-navigation.test.tsx +++ b/hub/client/application/hub/routes/real-workspace-navigation.test.tsx @@ -194,7 +194,7 @@ function sidebarDestinations() { } describe("real workspace navigation", () => { - it("keeps the collapsed navigation and refreshes the Inbox count across main pages", async () => { + it("updates the collapsed sidebar's Inbox dot from navigation without extra Inbox reads", async () => { const repository = { id: "11111111-1111-4111-8111-111111111111", nameWithOwner: "team/alpha", @@ -210,18 +210,21 @@ describe("real workspace navigation", () => { const createPath = `${galleryPath}/new` const inboxPath = `/notifications?repositoryId=${repository.id}` const prototypeId = "33333333-3333-4333-8333-333333333333" - const newestMention = unreadMention(repository, prototypeId) - const mentions = [ - newestMention, - ...[6, 5].map((id) => unreadMention(repository, prototypeId, id)), - ] - let unreadCount = mentions.length - const inboxReads: [pathname: string, limit: string | null, unread: string | null][] = [] + const mention = unreadMention(repository, prototypeId) + let inboxHasUnread = false + const inboxReads: (string | null)[] = [] const galleryReads: (string | null)[] = [] const router = await renderApplication(galleryPath, [ ...workspaceApi([otherRepository, repository], { role: "MEMBER", reviewInboxAvailable: true, + respondToWorkspace(request, workspace) { + return HttpResponse.json( + new URL(request.url).searchParams.get("view") === "navigation" + ? { ...workspace, inboxHasUnread } + : workspace, + ) + }, }), galleryApi(repository, (request) => galleryReads.push(new URL(request.url).searchParams.get("q")), @@ -232,14 +235,12 @@ describe("real workspace navigation", () => { canCreate: true, }), http.get(`${window.location.origin}/api/notifications/inbox`, ({ request }) => { - const query = new URL(request.url).searchParams - const limit = query.get("limit") - inboxReads.push([window.location.pathname, limit, query.get("unread")]) - const notifications = mentions.slice(0, Math.min(Number(limit), unreadCount)) + const limit = new URL(request.url).searchParams.get("limit") + inboxReads.push(limit) return HttpResponse.json({ - notifications, - nextBefore: notifications.length < unreadCount ? notifications.at(-1)?.id : null, - unreadCount, + notifications: limit === "50" ? [mention] : [], + nextBefore: null, + unreadCount: limit === "50" ? 1 : 0, }) }), ]) @@ -252,12 +253,7 @@ describe("real workspace navigation", () => { return within(mainNavigation()).getByRole("link", { name }) } - function findInboxBadge(count: number) { - return within(mainNavigation()).findByRole("link", { name: `Inbox, ${count} unread` }) - } - - expect(await findInboxBadge(3)).toBeVisible() - expect(inboxReads).toEqual([[galleryPath, "1", "true"]]) + expect(navLink("Inbox")).toBeVisible() expect(navLink("Prototypes")).toHaveAttribute("aria-current", "page") fireEvent.click(screen.getByRole("button", { name: "Collapse sidebar" })) const originalNavigation = mainNavigation() @@ -280,31 +276,37 @@ describe("real workspace navigation", () => { expect(window.location.pathname + window.location.search).toBe(path) } - unreadCount = 2 + inboxHasUnread = true fireEvent.click(navLink("Create")) expect(await screen.findByRole("heading", { name: "What should we create?" })).toBeVisible() expectNavigation("Create", createPath) - expect(await findInboxBadge(2)).toBeVisible() + expect(inboxReads).toEqual([]) + const unreadLink = navLink("Inbox, unread notifications") + expect(unreadLink).toBeVisible() + expect(unreadLink).not.toHaveTextContent(/\d/) - unreadCount = 1 - fireEvent.click(navLink(/^Inbox\b/)) + inboxHasUnread = false + fireEvent.click(unreadLink) const inbox = await screen.findByRole("region", { name: "Inbox" }) - expect(await within(inbox).findByText(newestMention.excerpt)).toBeVisible() - expect(await findInboxBadge(1)).toBeVisible() + expect(await within(inbox).findByText(mention.excerpt)).toBeVisible() + expect(within(inbox).getByLabelText(/^1 unread\b/)).toBeVisible() + expect(navLink("Inbox")).toBeVisible() expectNavigation("Inbox", inboxPath) - unreadCount = 2 + inboxHasUnread = true fireEvent.click(navLink("Prototypes")) expect(await screen.findByRole("heading", { name: "Prototypes" })).toBeVisible() expectNavigation("Prototypes", galleryPath) - expect(await findInboxBadge(2)).toBeVisible() + expect(navLink("Inbox, unread notifications")).toBeVisible() + inboxHasUnread = false const searchBox = screen.getByRole("searchbox", { name: "Search prototypes" }) fireEvent.change(searchBox, { target: { value: "landing" } }) fireEvent.keyDown(searchBox, { key: "Enter" }) expect(await screen.findByRole("heading", { name: "No prototypes found" })).toBeVisible() expect(window.location.search).toBe("?q=landing") expect(galleryReads).toContain("landing") + expect(navLink("Inbox")).toBeVisible() act(() => window.history.back()) await waitFor(() => @@ -313,15 +315,10 @@ describe("real workspace navigation", () => { expect(window.location.pathname + window.location.search).toBe(galleryPath) await act(() => router.navigate(`${galleryPath}#prototypes`)) expect(window.location.hash).toBe("#prototypes") - expect(inboxReads).toEqual([ - [galleryPath, "1", "true"], - [createPath, "1", "true"], - ["/notifications", "50", null], - [galleryPath, "1", "true"], - ]) + expect(inboxReads).toEqual(["50"]) }, 15_000) - it("keeps the Inbox badge during request failures and refreshes it after leaving Inbox", async () => { + it("keeps the same viewer's Inbox dot when the preview, list, or navigation cannot refresh it", async () => { const repository = { id: "11111111-1111-4111-8111-111111111111", nameWithOwner: "team/alpha", @@ -329,63 +326,75 @@ describe("real workspace navigation", () => { capabilities: { reviewPrototypes: true, manageSharing: false, browseTemplates: true }, } const galleryPath = `/repositories/${repository.id}` - const notification = unreadMention(repository, "33333333-3333-4333-8333-333333333333") - const listFailure = deferResponse() - const countFailure = deferResponse() const inboxReads: (string | null)[] = [] - let failCount = false - let unreadCount = 1 - await renderApplication(galleryPath, [ - ...workspaceApi([repository], { role: "MEMBER", reviewInboxAvailable: true }), + let navigation: "unread" | "missing" | "unavailable" | "role-changed" = "unread" + let previewAvailable = false + const router = await renderApplication(galleryPath, [ + ...workspaceApi([repository], { + reviewInboxAvailable: true, + respondToWorkspace(request, workspace) { + if (new URL(request.url).searchParams.get("view") !== "navigation") { + return HttpResponse.json(workspace) + } + if (navigation === "unavailable") return new HttpResponse(null, { status: 503 }) + if (navigation === "unread") { + return HttpResponse.json({ ...workspace, inboxHasUnread: true }) + } + if (navigation === "role-changed") { + return HttpResponse.json({ + ...workspace, + capabilities: { ...workspace.capabilities, administerHub: false }, + }) + } + return HttpResponse.json(workspace) + }, + }), galleryApi(repository), - json(`/api${galleryPath}/templates`, { repository, templates: [], canCreate: true }), - http.get(`${window.location.origin}/api/notifications/inbox`, async ({ request }) => { + json("/api/administrators", { administrators: [], nextCursor: null }), + http.get(`${window.location.origin}/api/notifications/inbox`, ({ request }) => { const limit = new URL(request.url).searchParams.get("limit") inboxReads.push(limit) - if (limit === "50") { - await listFailure.pending - return new HttpResponse(null, { status: 503 }) - } - if (failCount) { - await countFailure.pending - return new HttpResponse(null, { status: 503 }) + if (limit === "10" && previewAvailable) { + return HttpResponse.json({ notifications: [], nextBefore: null, unreadCount: 0 }) } - return HttpResponse.json({ - notifications: unreadCount ? [notification] : [], - nextBefore: null, - unreadCount, - }) + return new HttpResponse(null, { status: 503 }) }), ]) - const badge = { name: "Inbox, 1 unread" } - fireEvent.click(await screen.findByRole("link", badge)) - const inbox = await screen.findByRole("region", { name: "Inbox" }) - await waitFor(() => expect(inboxReads).toEqual(["1", "50"])) - expect(screen.getByRole("link", badge)).toBeVisible() - - listFailure.release() + const dot = { name: "Inbox, unread notifications" } + const inboxLink = screen.getByRole("link", dot) + fireEvent.focus(inboxLink) + const preview = await screen.findByRole("region", { name: "Inbox" }) + const retryPreview = await within(preview).findByRole("button", { name: "Retry" }) + expect(screen.getByRole("link", dot)).toBeVisible() + + previewAvailable = true + fireEvent.click(retryPreview) + expect(await within(preview).findByText(/^No unread activity\./)).toBeVisible() + expect(screen.getByRole("link", dot)).toBeVisible() + + fireEvent.blur(inboxLink) + await act(() => router.navigate(inboxLink.pathname + inboxLink.search)) + const inbox = screen.getByRole("region", { name: "Inbox" }) expect(await within(inbox).findByRole("button", { name: "Retry" })).toBeVisible() - expect(screen.getByRole("link", badge)).toBeVisible() + expect(screen.getByRole("link", dot)).toBeVisible() - failCount = true - fireEvent.click(screen.getByRole("link", { name: "Prototypes" })) - expect(await screen.findByRole("heading", { name: "Prototypes" })).toBeVisible() - await waitFor(() => expect(inboxReads).toEqual(["1", "50", "1"])) - expect(screen.getByRole("link", badge)).toBeVisible() + navigation = "missing" + await act(() => router.navigate(galleryPath)) + expect(screen.getByRole("heading", { name: "Prototypes" })).toBeVisible() + expect(screen.getByRole("link", dot)).toBeVisible() - await act(() => { - countFailure.release() - return countFailure.pending - }) - expect(screen.getByRole("link", badge)).toBeVisible() + navigation = "unavailable" + await act(() => router.navigate(`/settings/administrators?repositoryId=${repository.id}`)) + expect(screen.getByRole("heading", { name: "Hub administrators" })).toBeVisible() + expect(screen.getByRole("button", { name: "Repository navigation unavailable" })).toBeDisabled() + expect(screen.getByRole("link", dot)).toBeVisible() + expect(inboxReads).toEqual(["10", "10", "50"]) - failCount = false - unreadCount = 0 - fireEvent.click(screen.getByRole("link", { name: "Create" })) - expect(await screen.findByRole("heading", { name: "What should we create?" })).toBeVisible() - expect(await screen.findByRole("link", { name: "Inbox" })).toBeVisible() - expect(inboxReads).toEqual(["1", "50", "1", "1"]) - }) + navigation = "role-changed" + await act(() => router.navigate(galleryPath)) + expect(screen.queryByRole("link", { name: "Hub administrators" })).not.toBeInTheDocument() + expect(screen.getByRole("link", dot)).toBeVisible() + }, 15_000) it("opens Create, Inbox, and Hub settings while repository permissions are pending", async () => { const repository = { @@ -840,7 +849,11 @@ describe("real workspace navigation", () => { async respondToWorkspace(request, workspace) { const query = new URL(request.url).searchParams if (query.get("view") === "navigation") { - return HttpResponse.json({ ...workspace, repositoryPermissionsAvailable: true }) + return HttpResponse.json({ + ...workspace, + repositoryPermissionsAvailable: true, + inboxHasUnread: true, + }) } if (query.get("repositoryId") !== selected.id) return HttpResponse.json(workspace) selectedPermissionReads() @@ -948,7 +961,7 @@ describe("real workspace navigation", () => { collapsed: screen.queryByRole("button", { name: "Expand sidebar", expanded: false }) !== null, selectedRepository: screen.queryByRole("button", { name: pickerName }) !== null, - unreadCount: screen.queryByRole("link", { name: "Inbox, 1 unread" }) !== null, + inboxDot: screen.queryByRole("link", { name: "Inbox, unread notifications" }) !== null, }, `Retained navigation on ${destination}`, ) @@ -956,7 +969,7 @@ describe("real workspace navigation", () => { sameNavigation: [true], collapsed: true, selectedRepository: true, - unreadCount: true, + inboxDot: true, }) } @@ -976,9 +989,6 @@ describe("real workspace navigation", () => { fireEvent.click(link) expect(await screen.findByRole("heading", { name: heading })).toBeVisible() - if (pathname === "/notifications") { - expect(await screen.findByRole("link", { name: "Inbox, 1 unread" })).toBeVisible() - } expect(router.state.location.pathname + router.state.location.search).toBe( target.pathname + target.search, ) @@ -1063,7 +1073,7 @@ describe("real workspace navigation", () => { }, ) - it("resets the collapsed nav and private Inbox badge on navigation after an account change", async () => { + it("resets the collapsed navigation and Inbox dot when a new viewer has no snapshot", async () => { const repository = { id: "11111111-1111-4111-8111-111111111111", nameWithOwner: "team/alpha", @@ -1086,21 +1096,14 @@ describe("real workspace navigation", () => { login: "mona", }, } - : workspace, + : { ...workspace, inboxHasUnread: true }, ) }, }), galleryApi(repository), json(`/api${galleryPath}/templates`, { repository, templates: [], canCreate: true }), - http.get(`${window.location.origin}/api/notifications/inbox`, () => - HttpResponse.json({ - notifications: [], - nextBefore: null, - unreadCount: changedViewer ? 0 : 5, - }), - ), ]) - await screen.findByRole("link", { name: "Inbox, 5 unread" }) + expect(screen.getByRole("link", { name: "Inbox, unread notifications" })).toBeVisible() fireEvent.click(screen.getByRole("button", { name: "Collapse sidebar" })) changedViewer = true @@ -1109,7 +1112,7 @@ describe("real workspace navigation", () => { expect(await screen.findByRole("heading", { name: "What should we create?" })).toBeVisible() expect(screen.getByRole("button", { name: "Account menu for @mona" })).toBeVisible() expect(screen.getByRole("button", { name: "Collapse sidebar" })).toBeVisible() - expect(screen.queryByRole("link", { name: "Inbox, 5 unread" })).not.toBeInTheDocument() + expect(screen.getByRole("link", { name: "Inbox" })).toBeVisible() }) it("keeps the Canvas connections return destination on a signed-out deep link", async () => { diff --git a/hub/client/application/hub/routes/workspace/index.tsx b/hub/client/application/hub/routes/workspace/index.tsx index e55314464..2c6d816b6 100644 --- a/hub/client/application/hub/routes/workspace/index.tsx +++ b/hub/client/application/hub/routes/workspace/index.tsx @@ -25,9 +25,7 @@ import { RouteFeedback } from "@application/hub/route-feedback" import { useWorkspaceRepositoryPermissions } from "@application/hub/use-workspace-repository-permissions" import { hubWorkspace } from "@application/hub/view-models/hub-workspace" import { WorkspaceCompletionContext } from "@application/hub/workspace-completion-context" -import { WorkspaceInboxCountContext } from "@application/hub/workspace-inbox-count-context" import { HubWorkspace } from "@features/hub-workspace" -import { useNotificationInbox } from "@hooks/use-notification-inbox" import type { Route } from "./+types/index" import type { WorkspaceRouteHandle } from "./types" @@ -132,18 +130,42 @@ export default function Workspace({ loaderData }: Pick } const { workspace } = loaderData - const viewerKey = `${workspace.viewer.id}:${workspace.viewer.provider ?? ""}:${workspace.capabilities?.administerHub ?? false}` - if (isMockMode()) return + const viewerKey = `${workspace.viewer.id}:${workspace.viewer.provider ?? ""}` + if (isMockMode()) { + return ( + + ) + } return } -function SignedInWorkspace({ - data, - handle, -}: { +type WorkspaceFrameProps = { data: WorkspaceData handle?: WorkspaceRouteHandle -}) { + inboxHasUnread?: boolean +} + +function SignedInWorkspace({ data, handle }: WorkspaceFrameProps) { + const { inboxHasUnread } = data.workspace + const [lastUnread, setLastUnread] = useState(inboxHasUnread) + if (inboxHasUnread !== undefined && inboxHasUnread !== lastUnread) { + setLastUnread(inboxHasUnread) + } + + return ( + + ) +} + +function WorkspaceSession({ data, handle, inboxHasUnread }: WorkspaceFrameProps) { const { key } = useLocation() const navigationPending = useNavigation().state !== "idle" const revalidator = useRevalidator() @@ -172,18 +194,12 @@ function SignedInWorkspace({ } }} > - + ) } -function WorkspaceNavigationFrame({ - data, - handle, -}: { - data: WorkspaceData - handle?: WorkspaceRouteHandle -}) { +function WorkspaceNavigationFrame({ data, handle, inboxHasUnread }: WorkspaceFrameProps) { const { pathname, search } = useLocation() const parameters = new URLSearchParams(search) const repositoryId = readWorkspaceRepositoryId({ pathname, searchParams: parameters }) @@ -194,18 +210,6 @@ function WorkspaceNavigationFrame({ ) const section = handle?.workspaceSection const navigation = hubWorkspace(workspace, parameters, section) - const configuration = checkingWorkspace ? undefined : navigation.notificationInbox - const inbox = useNotificationInbox({ - path: configuration?.path, - authenticityToken: navigation.authenticityToken, - initialUnreadCount: navigation.notificationsUnreadCount, - initialUnreadOnly: true, - autoLoad: false, - autoCount: Boolean(configuration) && section !== "notifications", - countRefreshKey: pathname, - synchronize: Boolean(configuration), - limit: 10, - }) if (checkingWorkspace) { return ( @@ -217,31 +221,27 @@ function WorkspaceNavigationFrame({ ) } return ( - - inbox.onOpen(true) } - : undefined, - inboxPreviewScope: pathname, - }} - > - {data.repositoryNavigationError && !handle?.independentOfRepositoryNavigation ? ( - - ) : ( - - )} - - + + {data.repositoryNavigationError && !handle?.independentOfRepositoryNavigation ? ( + + ) : ( + + )} + ) } diff --git a/hub/client/application/hub/screens/real-inbox-screen/index.tsx b/hub/client/application/hub/screens/real-inbox-screen/index.tsx index 4e521eb58..b7ae1f041 100644 --- a/hub/client/application/hub/screens/real-inbox-screen/index.tsx +++ b/hub/client/application/hub/screens/real-inbox-screen/index.tsx @@ -1,22 +1,18 @@ -import { useContext } from "react" import { useSearchParams } from "react-router" import type { WorkspaceResponse } from "@application/hub/contracts/types" import { hubWorkspace } from "@application/hub/view-models/hub-workspace" -import { WorkspaceInboxCountContext } from "@application/hub/workspace-inbox-count-context" import { useNotificationInbox } from "@hooks/use-notification-inbox" import { NotificationsPage } from "@pages/notifications-page" import { notificationInboxConfiguration } from "@utils/notification/inbox-configuration" export function RealInboxScreen({ workspace }: { workspace: WorkspaceResponse }) { const [search, setSearch] = useSearchParams() - const onUnreadCountChange = useContext(WorkspaceInboxCountContext) const inbox = useNotificationInbox({ path: notificationInboxConfiguration.path, authenticityToken: "", unreadOnly: search.get("unread") === "true", synchronize: true, - onUnreadCountChange, }) return ( 0, - notificationsUnreadCount: unreadCount, - notificationsUnreadLabel: `${real ? "Inbox" : "Notifications"}, ${unreadCount} unread`, + notificationsUnread: real ? workspace.inboxHasUnread : unreadCount > 0, + notificationsUnreadCount: real ? undefined : unreadCount, + notificationsUnreadLabel: real + ? "Inbox, unread notifications" + : `Notifications, ${unreadCount} unread`, administrationLinks: admin ? real ? [ diff --git a/hub/client/application/hub/workspace-inbox-count-context/index.ts b/hub/client/application/hub/workspace-inbox-count-context/index.ts deleted file mode 100644 index 9278607c1..000000000 --- a/hub/client/application/hub/workspace-inbox-count-context/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { createContext } from "react" - -export const WorkspaceInboxCountContext = createContext< - ((count: number | null) => void) | undefined ->(undefined) diff --git a/hub/client/features/workspace-nav/inbox.tsx b/hub/client/features/workspace-nav/inbox.tsx index 9320b8bc8..eb169717d 100644 --- a/hub/client/features/workspace-nav/inbox.tsx +++ b/hub/client/features/workspace-nav/inbox.tsx @@ -32,13 +32,15 @@ export function WorkspaceInbox({ initialUnreadCount: data.notificationsUnreadCount, initialUnreadOnly: true, autoLoad: false, - autoCount: data.selectedSection !== "notifications", synchronize: Boolean(configuration), limit: 10, }) const liveInbox = data.liveInbox ?? (configuration ? { ...managed, copy: configuration.copy } : undefined) - const count = liveInbox?.unreadCount ?? data.notificationsUnreadCount + const count = + data.notificationsUnreadCount === undefined + ? undefined + : (liveInbox?.unreadCount ?? data.notificationsUnreadCount) const { open, triggerRef, panelRef, enter, leave, close } = useHoverPreview( Boolean(inboxPreview || liveInbox), ) @@ -57,10 +59,19 @@ export function WorkspaceInbox({ setPosition({ left, top, width, maxHeight: Math.min(592, window.innerHeight - top - 12) }) } enter() - if (!open) liveInbox?.onOpen() + if (!open) liveInbox?.onOpen(Boolean(configuration)) } if (!data.notificationsPath || !data.notificationsLabel) return null + const label = data.notificationsLabel + const unreadLabel = + liveInbox && count !== undefined + ? count + ? `${label}, ${count} unread` + : undefined + : data.notificationsUnread + ? data.notificationsUnreadLabel + : undefined return (
  • { diff --git a/hub/client/features/workspace-nav/stories.tsx b/hub/client/features/workspace-nav/stories.tsx index aa7a08532..ebb8b1206 100644 --- a/hub/client/features/workspace-nav/stories.tsx +++ b/hub/client/features/workspace-nav/stories.tsx @@ -103,3 +103,14 @@ export const ReadOnly: Story = { }, }, } + +export const UnreadInbox: Story = { + args: { + data: { + ...administrator, + notificationsLabel: "Inbox", + notificationsUnreadCount: undefined, + notificationsUnreadLabel: "Inbox, unread notifications", + }, + }, +} diff --git a/hub/client/hooks/use-notification-inbox/index.test.tsx b/hub/client/hooks/use-notification-inbox/index.test.tsx index fbc4973a2..ac8ffc84b 100644 --- a/hub/client/hooks/use-notification-inbox/index.test.tsx +++ b/hub/client/hooks/use-notification-inbox/index.test.tsx @@ -22,38 +22,6 @@ const notification: InboxNotification = { } const page = { notifications: [notification], nextBefore: null, unreadCount: 12 } -function renderClosedBadge() { - return renderHook( - ({ pathname }) => - useNotificationInbox({ - path: "/api/notifications/inbox", - authenticityToken: "", - initialUnreadCount: 4, - initialUnreadOnly: true, - autoLoad: false, - autoCount: true, - countRefreshKey: pathname, - synchronize: true, - limit: 10, - }), - { initialProps: { pathname: "/repositories/2001" } }, - ) -} - -function badgeResponse(unreadCount: number) { - return Response.json({ - notifications: [{ ...notification, id: 2 }], - unreadCount, - nextBefore: unreadCount > 1 ? 2 : null, - }) -} - -function acknowledgeRead(startedAt: number) { - const receipt = { id: 1, startedAt, saved: { version: 1, read: true } } - notifyInboxRead(receipt) -} - -const badgeUrl = new URL("/api/notifications/inbox?limit=1&unread=true", window.location.origin) const unreadInboxUrl = new URL( "/api/notifications/inbox?limit=50&unread=true", window.location.origin, @@ -76,6 +44,7 @@ describe("useNotificationInbox()", () => { limit: 10, }), ) + expect(fetch).not.toHaveBeenCalled() act(() => result.current.onOpen()) await waitFor(() => expect(result.current.notifications).toHaveLength(1)) act(() => result.current.onOpen()) @@ -195,76 +164,6 @@ describe("useNotificationInbox()", () => { expect(result.current.unreadCount).toBe(0) }) - it("loads the latest ten when the preview opens and ignores an older count that arrives last", async () => { - let finishCount!: (response: Response) => void - const pendingCount = new Promise((resolve) => (finishCount = resolve)) - const fetch = vi - .fn() - .mockReturnValueOnce(pendingCount) - .mockResolvedValueOnce(Response.json(page)) - vi.stubGlobal("fetch", fetch) - const { result } = renderClosedBadge() - expect(fetch).toHaveBeenCalledExactlyOnceWith(badgeUrl, expect.anything()) - - act(() => result.current.onOpen()) - await waitFor(() => expect(result.current.notifications).toHaveLength(1)) - expect(fetch).toHaveBeenLastCalledWith( - new URL("/api/notifications/inbox?limit=10&unread=true", window.location.origin), - expect.anything(), - ) - expect(result.current.unreadCount).toBe(12) - - await act(async () => { - finishCount(badgeResponse(2)) - await pendingCount - }) - expect(result.current.unreadCount).toBe(12) - }) - - it("keeps the newer navigation count when an older preview finishes last", async () => { - let finishPreview!: (response: Response) => void - const preview = new Promise((resolve) => (finishPreview = resolve)) - const fetch = vi - .fn() - .mockResolvedValueOnce(badgeResponse(2)) - .mockReturnValueOnce(preview) - .mockResolvedValueOnce(badgeResponse(3)) - vi.stubGlobal("fetch", fetch) - const { result, rerender } = renderClosedBadge() - await waitFor(() => expect(result.current.unreadCount).toBe(2)) - - act(() => result.current.onOpen()) - rerender({ pathname: "/welcome" }) - await waitFor(() => expect(result.current.unreadCount).toBe(3)) - - await act(async () => { - finishPreview(Response.json({ ...page, unreadCount: 2 })) - await preview - }) - expect(result.current.notifications).toEqual([notification]) - expect(result.current.unreadCount).toBe(3) - }) - - it.each([200, 401])( - "keeps the supplied count when an earlier background request returns %s", - async (status) => { - let finishCount!: (response: Response) => void - const pendingCount = new Promise((resolve) => (finishCount = resolve)) - const fetch = vi.fn().mockReturnValueOnce(pendingCount) - vi.stubGlobal("fetch", fetch) - const { result } = renderClosedBadge() - expect(fetch).toHaveBeenCalledExactlyOnceWith(badgeUrl, expect.anything()) - - act(() => result.current.onUnreadCountChange(7)) - await act(async () => { - finishCount(status === 200 ? badgeResponse(2) : new Response(null, { status })) - await pendingCount - }) - - expect(result.current.unreadCount).toBe(7) - }, - ) - it.each([200, 403])( "clears cached rows on fresh open and keeps the supplied count when the preview returns %s", async (status) => { @@ -308,29 +207,6 @@ describe("useNotificationInbox()", () => { }, ) - it("uses the supplied count when automatic counting resumes without navigation", async () => { - const fetch = vi.fn(() => Promise.resolve(badgeResponse(2))) - vi.stubGlobal("fetch", fetch) - const { result, rerender } = renderHook( - ({ autoCount }) => - useNotificationInbox({ - path: "/api/notifications/inbox", - authenticityToken: "", - autoLoad: false, - autoCount, - }), - { initialProps: { autoCount: true } }, - ) - await waitFor(() => expect(result.current.unreadCount).toBe(2)) - - rerender({ autoCount: false }) - act(() => result.current.onUnreadCountChange(7)) - rerender({ autoCount: true }) - - expect(result.current.unreadCount).toBe(7) - expect(fetch).toHaveBeenCalledOnce() - }) - it("keeps the last unread count when the preview fails and retries explicitly", async () => { const onUnreadCountChange = vi.fn() const fetch = vi @@ -607,146 +483,40 @@ describe("useNotificationInbox()", () => { expect(onReadChange).not.toHaveBeenCalled() }) - it("adjusts a closed badge once without refetching when the count settled before the read began", async () => { - const fetch = vi.fn().mockResolvedValueOnce(badgeResponse(2)) - vi.stubGlobal("fetch", fetch) - const clock = vi.spyOn(performance, "now").mockReturnValue(10) - const { result } = renderClosedBadge() - await waitFor(() => expect(result.current.unreadCount).toBe(2)) - - clock.mockReturnValue(20) - act(() => acknowledgeRead(performance.now())) - - expect(result.current.unreadCount).toBe(1) - expect(fetch).toHaveBeenCalledExactlyOnceWith(badgeUrl, expect.anything()) - }) - - it("refreshes a closed badge when a read would reduce its settled count to zero", async () => { + it("refreshes the open Inbox when another surface saves a read after a failed update", async () => { + const other = { ...notification, id: 2, updatePath: "/api/notifications/2" } + const saved = { version: 1, read: true } const fetch = vi .fn() - .mockResolvedValueOnce(Response.json({ ...page, unreadCount: 1 })) - .mockResolvedValueOnce(badgeResponse(2)) - vi.stubGlobal("fetch", fetch) - const clock = vi.spyOn(performance, "now").mockReturnValue(10) - const { result } = renderClosedBadge() - await waitFor(() => expect(result.current.unreadCount).toBe(1)) - - clock.mockReturnValue(20) - act(() => acknowledgeRead(performance.now())) - - await waitFor(() => expect(result.current.unreadCount).toBe(2)) - expect(fetch).toHaveBeenCalledTimes(2) - expect(fetch).toHaveBeenLastCalledWith(badgeUrl, expect.anything()) - }) - - it("refreshes the closed badge after a read and ignores an earlier count that arrives last", async () => { - let finishInitial!: (response: Response) => void - const initial = new Promise((resolve) => (finishInitial = resolve)) - const fetch = vi.fn().mockReturnValueOnce(initial).mockResolvedValueOnce(badgeResponse(1)) - vi.stubGlobal("fetch", fetch) - const clock = vi.spyOn(performance, "now").mockReturnValue(10) - const { result } = renderClosedBadge() - expect(fetch).toHaveBeenCalledOnce() - clock.mockReturnValue(20) - const startedAt = performance.now() - clock.mockReturnValue(30) - act(() => acknowledgeRead(startedAt)) - - await waitFor(() => expect(result.current.unreadCount).toBe(1)) - await act(async () => { - finishInitial(badgeResponse(2)) - await initial - }) - expect(result.current.unreadCount).toBe(1) - expect(fetch).toHaveBeenCalledTimes(2) - expect(fetch).toHaveBeenLastCalledWith(badgeUrl, expect.anything()) - }) - - it("rechecks the closed badge without subtracting from a count that may already include the read", async () => { - let finishInitial!: (response: Response) => void - let finishFresh!: (response: Response) => void - const initial = new Promise((resolve) => (finishInitial = resolve)) - const fresh = new Promise((resolve) => (finishFresh = resolve)) - const fetch = vi.fn().mockReturnValueOnce(initial).mockReturnValueOnce(fresh) - vi.stubGlobal("fetch", fetch) - const clock = vi.spyOn(performance, "now").mockReturnValue(10) - const { result } = renderClosedBadge() - expect(fetch).toHaveBeenCalledOnce() - clock.mockReturnValue(20) - const startedAt = performance.now() - clock.mockReturnValue(30) - finishInitial(badgeResponse(1)) - await waitFor(() => expect(result.current.unreadCount).toBe(1)) - - clock.mockReturnValue(40) - act(() => acknowledgeRead(startedAt)) - expect(result.current.unreadCount).toBe(1) - await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2)) - expect(fetch).toHaveBeenLastCalledWith(badgeUrl, expect.anything()) - - await act(async () => { - finishFresh(badgeResponse(1)) - await fresh - }) - expect(result.current.unreadCount).toBe(1) - }) - - it.each([ - ["clears", 401, 0], - ["keeps", 503, 1], - ] as const)( - "%s the closed badge count when the background request fails with status %s", - async (_outcome, status, count) => { - const failure = Promise.resolve(new Response(null, { status })) - const fetch = vi - .fn() - .mockResolvedValueOnce(Response.json({ ...page, unreadCount: 1 })) - .mockReturnValueOnce(failure) - vi.stubGlobal("fetch", fetch) - const clock = vi.spyOn(performance, "now").mockReturnValue(10) - const { result } = renderClosedBadge() - await waitFor(() => expect(result.current.unreadCount).toBe(1)) - - clock.mockReturnValue(20) - await act(() => { - acknowledgeRead(performance.now()) - return failure - }) - expect(fetch).toHaveBeenCalledTimes(2) - expect(fetch).toHaveBeenLastCalledWith(badgeUrl, expect.anything()) - expect(result.current.unreadCount).toBe(count) - }, - ) - - it("recounts on a separate read after a failed update leaves the badge stale", async () => { - const fetch = vi - .fn() - .mockResolvedValueOnce(badgeResponse(3)) + .mockResolvedValueOnce( + Response.json({ ...page, notifications: [other, notification], unreadCount: 2 }), + ) + .mockResolvedValueOnce(new Response(null, { status: 503 })) .mockResolvedValueOnce( Response.json({ - notifications: [notification, { ...notification, id: 2 }], - nextBefore: null, - unreadCount: 3, + ...page, + notifications: [other, { ...notification, ...saved }], + unreadCount: 1, }), ) - .mockResolvedValueOnce(new Response(null, { status: 503 })) - .mockResolvedValueOnce(badgeResponse(2)) vi.stubGlobal("fetch", fetch) - const clock = vi.spyOn(performance, "now").mockReturnValue(10) - const { result } = renderClosedBadge() - await waitFor(() => expect(result.current.unreadCount).toBe(3)) - act(() => result.current.onOpen()) + const { result } = renderHook(() => + useNotificationInbox({ + path: "/api/notifications/inbox", + authenticityToken: "token", + synchronize: true, + }), + ) await waitFor(() => expect(result.current.notifications).toHaveLength(2)) act(() => result.current.onToggleRead(2)) await waitFor(() => expect(result.current.failed).toBe(true)) - expect(result.current.unreadCount).toBe(3) - clock.mockReturnValue(20) - act(() => acknowledgeRead(performance.now())) - - await waitFor(() => expect(result.current.unreadCount).toBe(2)) - expect(fetch).toHaveBeenCalledTimes(4) - expect(fetch).toHaveBeenLastCalledWith(badgeUrl, expect.anything()) + act(() => notifyInboxRead({ id: 1, startedAt: performance.now(), saved })) + await waitFor(() => + expect(result.current.notifications).toEqual([other, { ...notification, ...saved }]), + ) + expect(result.current.unreadCount).toBe(1) + expect(result.current.failed).toBe(false) }) it("reloads an unread filter when another surface marks an unloaded item unread", async () => { diff --git a/hub/client/hooks/use-notification-inbox/index.ts b/hub/client/hooks/use-notification-inbox/index.ts index d17f0466a..77702f1a5 100644 --- a/hub/client/hooks/use-notification-inbox/index.ts +++ b/hub/client/hooks/use-notification-inbox/index.ts @@ -21,8 +21,6 @@ export function useNotificationInbox({ initialUnreadOnly = false, unreadOnly: controlledUnreadOnly, autoLoad = true, - autoCount = false, - countRefreshKey, synchronize = false, limit = 50, onReadChange, @@ -34,8 +32,6 @@ export function useNotificationInbox({ initialUnreadOnly?: boolean unreadOnly?: boolean autoLoad?: boolean - autoCount?: boolean - countRefreshKey?: string synchronize?: boolean limit?: number onReadChange?: (id: number, saved: NotificationReadUpdate) => void @@ -60,7 +56,6 @@ export function useNotificationInbox({ const [loading, setLoading] = useState(autoLoad && Boolean(path)) const [failed, setFailed] = useState(false) const generation = useRef(0) - const pendingCount = useRef(null) const countReceivedAt = useRef(null) const suppliedCountRevision = useRef(0) const loaded = useRef(false) @@ -88,8 +83,6 @@ export function useNotificationInbox({ const receiveUnreadCount = useCallback( (count: number | null) => { suppliedCountRevision.current += 1 - pendingCount.current?.abort() - pendingCount.current = null countReceivedAt.current = count === null ? null : performance.now() setUnreadCount(count ?? 0) if (count === null) { @@ -197,56 +190,11 @@ export function useNotificationInbox({ } }, [autoLoad, load, path]) - const loadCount = useCallback(() => { - if (!path) return - pendingCount.current?.abort() - const requestGeneration = generation.current - const controller = new AbortController() - pendingCount.current = controller - const url = new URL(path, window.location.origin) - url.searchParams.set("limit", "1") - url.searchParams.set("unread", "true") - void fetch(url, { credentials: "same-origin", cache: "no-store", signal: controller.signal }) - .then(async (response) => { - requireInboxResponse(response) - const page = NOTIFICATION_PAGE_SCHEMA.parse(await response.json()) - if (controller.signal.aborted || requestGeneration !== generation.current) return - - // An older preview can still supply rows, but it no longer owns the count. - suppliedCountRevision.current += 1 - countReceivedAt.current = performance.now() - setUnreadCount(page.unreadCount) - }) - .catch((error: unknown) => { - if (controller.signal.aborted || requestGeneration !== generation.current) return - if (error instanceof InboxAccessDeniedError) { - receiveUnreadCount(null) - } else { - countReceivedAt.current = null - console.warn("Hub could not refresh the Inbox badge.") - } - }) - .finally(() => { - if (pendingCount.current === controller) pendingCount.current = null - }) - }, [path, receiveUnreadCount]) - - useEffect(() => { - if (autoCount && (countRefreshKey !== undefined || countReceivedAt.current === null)) { - loadCount() - } - return () => { - pendingCount.current?.abort() - pendingCount.current = null - } - }, [autoCount, countRefreshKey, loadCount]) - function needsCountRefresh(saved: NotificationReadUpdate, startedAt?: number) { const lastCount = countReceivedAt.current return ( saved.unreadCount === undefined && - (pendingCount.current !== null || - lastCount === null || + (lastCount === null || (startedAt !== undefined && lastCount >= startedAt) || (saved.read && unreadCount <= 1)) ) @@ -291,13 +239,12 @@ export function useNotificationInbox({ const receiveReadUpdate = useEffectEvent(({ id, saved, startedAt }: InboxReadUpdate) => { if (ownReadUpdate.current === saved) return const reloadList = loaded.current || autoLoad || loading - const needsCount = (reloadList || autoCount) && needsCountRefresh(saved, startedAt) + const needsCount = reloadList && needsCountRefresh(saved, startedAt) applyReadUpdate(id, saved, !needsCount) if (reloadList) { void load() } else { generation.current += 1 - if (needsCount) loadCount() } }) diff --git a/hub/docs/frontend.md b/hub/docs/frontend.md index aa2be95c2..e8d73d91e 100644 --- a/hub/docs/frontend.md +++ b/hub/docs/frontend.md @@ -112,7 +112,7 @@ Signed-in page and filter changes refresh the lightweight workspace alongside pa In real mode, one layout keeps the signed-in navigation mounted while the route content changes. It owns the picker, collapse choice, and Inbox badge across Welcome, repository pages, Inbox, Canvas connections, and settings. Route metadata selects the active link. Entering prototype review collapses the sidebar. You can reopen it, and changing Builds or leaving review keeps its current state. A page error stays in the content area. A minimized prototype preview hides navigation without resetting it. -The sidebar refreshes its Inbox badge in the background when a signed-in page opens. The Inbox page supplies its own count, and changing filters on other pages does not request another count. The badge keeps the last known count while a request runs or fails. Hub clears the count when Inbox access is denied or the viewer changes. +The sidebar shows a dot when the viewer has unread Inbox activity. It updates with the workspace as the viewer moves between pages. Hub keeps the last dot state if navigation fails temporarily and discards it when the session ends or the viewer changes. Opening the Inbox or its preview does not supply the dot state. Hub settings and audit loaders request their own authorized data. They do not request full workspace data to build navigation. An administrator can still use Hub-wide settings if no repository is readable or if repository navigation fails. For Hub administrators, **Security audit** opens the Hub-wide records. The scope menu also offers the selected repository when Hub verifies repository administrator permission. Repository audit and Analytics still check current repository permissions in their APIs. @@ -225,7 +225,7 @@ History loads only the requested page and any successful Build pinned by `build` ### Workspace projections -`GET /api/workspace?view=navigation` returns the signed-in viewer, readable repositories, and Hub preferences without checking live GitHub management permissions. `GET /api/workspace` retains the full response and checks management permissions for the selected repository. Both views verify the session and scope repositories to the viewer's access. +`GET /api/workspace?view=navigation` returns the signed-in viewer, readable repositories, Hub preferences, and the [Inbox unread indicator](review-collaboration.md#inbox-and-live-review). It does not check live GitHub repository permissions. `GET /api/workspace` retains the full response and checks management permissions for the selected repository. Both views verify the session and scope repositories to the viewer's access. ### Prototype metadata edits diff --git a/hub/docs/review-collaboration.md b/hub/docs/review-collaboration.md index efbfa6976..bc325c6b7 100644 --- a/hub/docs/review-collaboration.md +++ b/hub/docs/review-collaboration.md @@ -51,7 +51,9 @@ New roots notify the recorded prototype owner. Replies notify the owner and part Inbox lists only the viewer's accessible activity and returns a total unread count independent of pagination. It rechecks repository access before listing, opening, or changing notice state. Inbox changes use a separate version check. Opening an activity loads the current successful Build and focuses the exact message. Hub acknowledges the notice only after that message opens. Missing messages or repositories are not acknowledged. These are in-app notices only; there is no external delivery or Canvas review endpoint. -`GET /api/notifications/inbox` accepts `unread`, `limit`, and `before`. `GET /api/notifications/:notificationId` returns one authorized notice. `PATCH /api/notifications/:notificationId` accepts `{ notification: { read, version } }` and returns the saved read state and version. Single-notice requests verify only the notice's repository. After saving a read change, the browser checks for new activity before clearing the unread count or leaving the Unread view empty. The sidebar also checks the total before clearing a closed Inbox badge based on its previous count. +`GET /api/notifications/inbox` accepts `unread`, `limit`, and `before`. `GET /api/notifications/:notificationId` returns one authorized notice. `PATCH /api/notifications/:notificationId` accepts `{ notification: { read, version } }` and returns the saved read state and version. Single-notice requests verify only the notice's repository. After saving a read change, the browser checks for new activity before clearing the unread count or leaving the Unread view empty. + +The workspace navigation response includes only whether the viewer has eligible unread activity. For GitHub sessions, including Hub administrators, this dot uses stored repository grants. It can lag a GitHub access change until Hub updates those grants. Hub still checks access live when it returns Inbox details or changes notice state. Opening a notice marks that notice as read once its target message is shown, even when another notice already focused the same message. diff --git a/hub/schema/migrations/20261220150000_inbox_unread_lookup/migration.sql b/hub/schema/migrations/20261220150000_inbox_unread_lookup/migration.sql new file mode 100644 index 000000000..6a943ce55 --- /dev/null +++ b/hub/schema/migrations/20261220150000_inbox_unread_lookup/migration.sql @@ -0,0 +1,2 @@ +-- CreateIndex +CREATE INDEX "review_notifications_recipient_key_read_at_idx" ON "review_notifications"("recipient_key", "read_at"); diff --git a/hub/schema/review-notification.prisma b/hub/schema/review-notification.prisma index c5425d4fe..da9f61362 100644 --- a/hub/schema/review-notification.prisma +++ b/hub/schema/review-notification.prisma @@ -28,6 +28,7 @@ model ReviewNotification { updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) @@unique([recipientKey, sourceKey]) + @@index([recipientKey, readAt]) @@index([recipientKey, publicId]) @@index([commentId]) @@index([actorId]) diff --git a/hub/server/domains/review-comments/create-review-inbox/index.ts b/hub/server/domains/review-comments/create-review-inbox/index.ts index 024ef0807..0c06eafaa 100644 --- a/hub/server/domains/review-comments/create-review-inbox/index.ts +++ b/hub/server/domains/review-comments/create-review-inbox/index.ts @@ -1,5 +1,6 @@ import type { Prisma, PrismaClient } from "../../../generated/prisma/client.ts" import type { GitHubReviewDirectory } from "../../../integrations/github/create-review-directory/types.ts" +import { hasUnreadInbox } from "../../../repositories/review-comments/has-unread-inbox/index.ts" import { countUnreadInbox, findInboxActivity, @@ -26,7 +27,7 @@ interface InboxContext { type Db = Pick< PrismaClient, - "$transaction" | "hubSession" | "repository" | "gitHubRepositoryAccessState" + "$queryRaw" | "$transaction" | "hubSession" | "repository" | "gitHubRepositoryAccessState" > export function createReviewInbox( @@ -134,6 +135,20 @@ export function createReviewInbox( return new ReviewCommentError("not_found", "Notification not found.") } return { + async hasUnread(input: InboxContext, repositories: { id: string; localPath: string | null }[]) { + const local = input.viewer.sessionProvider === "local" + const visible = repositories.filter(({ localPath }) => (localPath !== null) === local) + if (visible.length === 0) return false + + return hasUnreadInbox(database, { + keys: await recipientKeys(database, input), + repositoryIds: visible.map(({ id }) => id), + local, + // Hub administrators can browse repository names without a GitHub grant. + githubMembershipId: + input.viewer.sessionProvider === "github" ? input.viewer.membershipId : undefined, + }) + }, list(input: InboxContext & { unread: boolean; limit: number; before?: number }) { return run(input, async (transaction, where) => { const results = await findInboxPage(transaction, where, input) diff --git a/hub/server/repositories/review-comments/has-unread-inbox/index.ts b/hub/server/repositories/review-comments/has-unread-inbox/index.ts new file mode 100644 index 000000000..07d947ba8 --- /dev/null +++ b/hub/server/repositories/review-comments/has-unread-inbox/index.ts @@ -0,0 +1,44 @@ +import { Prisma } from "../../../generated/prisma/client.ts" + +export async function hasUnreadInbox( + database: Pick, + { + keys, + repositoryIds, + local, + githubMembershipId, + }: { keys: string[]; repositoryIds: string[]; local: boolean; githubMembershipId?: string }, +) { + const githubGrant = githubMembershipId + ? Prisma.sql`AND r.github_repository_id IS NOT NULL AND EXISTS ( + SELECT 1 FROM repository_access_grants g + WHERE g.repository_id = r.id AND g.membership_id = ${githubMembershipId}::uuid + )` + : Prisma.empty + + // Compare the prototype's branch to its repository's default in one join, not one OR arm per repository. + const [result] = await database.$queryRaw<[{ unread: boolean }]>` + SELECT EXISTS ( + SELECT 1 FROM review_notifications n + JOIN review_comments c ON c.id = n.comment_id + JOIN review_threads t ON t.id = c.thread_id + JOIN repositories r ON r.id = t.repository_id + JOIN prototypes p ON p.id = t.prototype_id + WHERE n.recipient_key = ANY(${keys}) + AND n.read_at IS NULL + AND c.deleted_at IS NULL + AND r.id = ANY(${repositoryIds}::uuid[]) + AND r.removed_at IS NULL + AND (r.local_path IS NOT NULL) = ${local} + ${githubGrant} + AND p.registered_at IS NOT NULL + AND p.branch_deleted_at IS NULL + AND NOT p.replica + AND p.branch_name NOT IN (r.default_branch, 'replica/install-workflow') + AND EXISTS ( + SELECT 1 FROM builds b WHERE b.prototype_id = p.id AND b.state = 'successful' + ) + ) AS unread + ` + return result.unread +} diff --git a/hub/server/routes/api/workspace/get/index.db.test.ts b/hub/server/routes/api/workspace/get/index.db.test.ts new file mode 100644 index 000000000..3f1eec7db --- /dev/null +++ b/hub/server/routes/api/workspace/get/index.db.test.ts @@ -0,0 +1,285 @@ +import { createHash, generateKeyPairSync, randomUUID } from "node:crypto" +import { once } from "node:events" +import { createServer } from "node:http" +import type { AddressInfo } from "node:net" +import { describe, expect, it, onTestFinished, vi } from "vitest" + +import { createApp } from "../../../../create-app" +import { createReviewDirectory } from "../../../../integrations/github/create-review-directory" +import { prisma } from "../../../../integrations/prisma" +import { createAuthenticationRouteDependencies } from "../../auth/create-authentication-route-dependencies" +import { createProductRouteDependencies } from "../../product/create-product-route-dependencies" + +async function openNavigation(provider: "local" | "github") { + const requestGitHub = vi + .fn() + .mockRejectedValue(new Error("Navigation must not call GitHub.")) + const privateKey = + provider === "github" ? generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey : null + const authentication = await createAuthenticationRouteDependencies( + { + HUB_APPLICATION_ORIGIN: "http://127.0.0.1:5173", + HUB_AUTHENTICATION_ENCRYPTION_KEY: Buffer.alloc(32, 1).toString("base64"), + HUB_BOOTSTRAP_SECRET: "synthetic-bootstrap-secret-at-least-32-characters", + ...(privateKey + ? { + GITHUB_CLIENT_ID: "synthetic-client", + GITHUB_CLIENT_SECRET: "synthetic-secret", + GITHUB_PROVIDER_REVISION: "1", + GITHUB_APP_ID: "123", + GITHUB_APP_INSTALLATION_ID: "456", + GITHUB_APP_PRIVATE_KEY_BASE64: Buffer.from( + privateKey.export({ format: "pem", type: "pkcs8" }), + ).toString("base64"), + GITHUB_WEBHOOK_SECRET: "synthetic-webhook-secret-at-least-20-characters", + } + : { NODE_ENV: "development", HUB_LOCAL_SIGN_IN: "true" }), + }, + requestGitHub, + ) + const subject = provider === "github" ? "501" : "local-viewer" + const user = await prisma.user.create({ + data: { profile: { create: { provider, login: "renamed-viewer" } } }, + }) + const identity = await prisma.externalIdentity.create({ + data: { + userId: user.id, + provider, + issuer: provider === "github" ? "https://github.com" : "http://localhost", + subject, + }, + }) + const membership = await prisma.membership.create({ data: { userId: user.id } }) + await prisma.membershipAssignment.create({ + data: { + membershipId: membership.id, + externalIdentityId: identity.id, + source: "BOOTSTRAP", + role: "ADMINISTRATOR", + }, + }) + const { selectedRevisionId } = await prisma.authenticationProvider.findUniqueOrThrow({ + where: { key: provider }, + }) + const { revision } = await prisma.sessionRevocationState.findUniqueOrThrow({ + where: { key: "global" }, + }) + const token = randomUUID() + const session = await prisma.hubSession.create({ + data: { + membershipId: membership.id, + externalIdentityId: identity.id, + providerRevisionId: selectedRevisionId, + digest: createHash("sha256").update(token).digest("hex"), + revocationRevision: revision, + expiresAt: new Date("2099-01-01T00:00:00Z"), + }, + }) + const getRepositoryPermission = vi.fn().mockResolvedValue("none") + const server = createServer( + createApp({ + authentication, + product: createProductRouteDependencies({ + scopeGitHubMembers: provider === "github", + getRepositoryPermission, + githubReviewDirectory: privateKey + ? createReviewDirectory( + { appId: "123", installationId: "456", privateKey }, + requestGitHub, + ) + : undefined, + }), + }), + ) + server.listen(0, "127.0.0.1") + await once(server, "listening") + onTestFinished( + () => + new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())) + }), + ) + const { port } = server.address() as AddressInfo + function navigate() { + return fetch(`http://127.0.0.1:${port}/api/workspace?view=navigation`, { + headers: { cookie: `hub_session=${token}` }, + }) + } + async function snapshot() { + const response = await navigate() + expect(response.status).toBe(200) + return (await response.json()) as { + repositories: { id: string }[] + inboxHasUnread?: boolean + reviewInboxAvailable?: boolean + } + } + return { + navigate, + snapshot, + userId: user.id, + membershipId: membership.id, + sessionId: session.id, + githubSubject: subject, + requestGitHub, + getRepositoryPermission, + } +} + +async function saveNotice({ + repositoryId, + actorId, + recipientKey, + branchName = "prototype/welcome", + registeredAt = new Date("2026-10-01T00:00:00Z"), + branchDeletedAt, + replica, + deletedAt, + buildState = "successful", +}: { + repositoryId: string + actorId: string + recipientKey: string + branchName?: string + registeredAt?: Date | null + branchDeletedAt?: Date + replica?: boolean + deletedAt?: Date + buildState?: "successful" | "failed" +}) { + const { id: prototypeId } = await prisma.prototype.create({ + data: { repositoryId, branchName, name: branchName, registeredAt, branchDeletedAt, replica }, + }) + const { id: buildId } = await prisma.build.create({ + data: { prototypeId, number: 1, state: buildState }, + }) + const { id: threadId } = await prisma.reviewThread.create({ + data: { repositoryId, prototypeId, buildId, anchor: { kind: "element" } }, + }) + const { id: commentId } = await prisma.reviewComment.create({ + data: { + threadId, + authorId: actorId, + authorLogin: "author", + body: "Please review.", + createdAt: new Date("2026-10-01T00:00:00Z"), + deletedAt, + }, + }) + return prisma.reviewNotification.create({ + data: { + commentId, + actorId, + actorLogin: "author", + kind: "comment", + recipientKey, + sourceKey: commentId, + }, + }) +} + +describe("workspace navigation Inbox unread state", () => { + it("uses stored GitHub grants even for a Hub administrator and never checks GitHub live", async () => { + const viewer = await openNavigation("github") + const { id: actorId } = await prisma.user.create({ data: {} }) + const { id: repositoryId } = await prisma.repository.create({ + data: { nameWithOwner: "team/design", defaultBranch: "main", githubRepositoryId: 771 }, + }) + const author = await prisma.membership.create({ data: { userId: actorId } }) + await prisma.repositoryAccessGrant.create({ + data: { repositoryId, membershipId: author.id, observedAt: new Date() }, + }) + const mention = await saveNotice({ + repositoryId, + actorId, + recipientKey: `github:${viewer.githubSubject}`, + }) + await saveNotice({ + repositoryId, + actorId, + recipientKey: "github:502", + branchName: "prototype/another-recipient", + }) + + expect(await viewer.snapshot()).toMatchObject({ + repositories: [expect.objectContaining({ id: repositoryId })], + reviewInboxAvailable: true, + inboxHasUnread: false, + }) + const grant = await prisma.repositoryAccessGrant.create({ + data: { repositoryId, membershipId: viewer.membershipId, observedAt: new Date() }, + }) + expect((await viewer.snapshot()).inboxHasUnread).toBe(true) + + await prisma.reviewNotification.update({ + where: { id: mention.id }, + data: { readAt: new Date() }, + }) + expect((await viewer.snapshot()).inboxHasUnread).toBe(false) + await saveNotice({ + repositoryId, + actorId, + recipientKey: `user:${viewer.userId}`, + branchName: "prototype/follow-up", + }) + expect((await viewer.snapshot()).inboxHasUnread).toBe(true) + + await prisma.repositoryAccessGrant.delete({ where: { id: grant.id } }) + expect((await viewer.snapshot()).inboxHasUnread).toBe(false) + expect(viewer.requestGitHub).not.toHaveBeenCalled() + expect(viewer.getRepositoryPermission).not.toHaveBeenCalled() + }) + + it("ignores notices outside the active local viewer's eligible Inbox", async () => { + const viewer = await openNavigation("local") + const { id: actorId } = await prisma.user.create({ data: {} }) + const { id: repositoryId } = await prisma.repository.create({ + data: { nameWithOwner: "team/local", defaultBranch: "trunk", localPath: "/workspace/local" }, + }) + const retiredAt = new Date("2026-10-02T00:00:00Z") + const hosted = await prisma.repository.create({ + data: { nameWithOwner: "team/hosted", defaultBranch: "main", githubRepositoryId: 772 }, + }) + const removed = await prisma.repository.create({ + data: { + nameWithOwner: "team/removed", + defaultBranch: "main", + localPath: "/workspace/removed", + removedAt: retiredAt, + }, + }) + const recipientKey = `user:${viewer.userId}` + for (const excluded of [ + { branchName: "prototype/other-viewer", recipientKey: `user:${actorId}` }, + { branchName: "prototype/deleted-comment", deletedAt: retiredAt }, + { branchName: "prototype/draft", registeredAt: null }, + { branchName: "prototype/retired", branchDeletedAt: retiredAt }, + { branchName: "replica/example", registeredAt: null, replica: true }, + { branchName: "trunk" }, + { branchName: "replica/install-workflow" }, + { branchName: "prototype/failed-build", buildState: "failed" as const }, + { repositoryId: hosted.id }, + { repositoryId: removed.id }, + ]) { + await saveNotice({ repositoryId, actorId, recipientKey, ...excluded }) + } + expect((await viewer.snapshot()).inboxHasUnread).toBe(false) + + const notice = await saveNotice({ repositoryId, actorId, recipientKey }) + expect((await viewer.snapshot()).inboxHasUnread).toBe(true) + await prisma.reviewNotification.update({ + where: { id: notice.id }, + data: { readAt: new Date() }, + }) + expect((await viewer.snapshot()).inboxHasUnread).toBe(false) + + await prisma.reviewNotification.update({ where: { id: notice.id }, data: { readAt: null } }) + await prisma.hubSession.update({ + where: { id: viewer.sessionId }, + data: { endedAt: new Date() }, + }) + const signedOut = await viewer.navigate() + expect(signedOut.status).toBe(401) + expect(await signedOut.json()).not.toHaveProperty("inboxHasUnread") + }) +}) diff --git a/hub/server/routes/api/workspace/get/index.ts b/hub/server/routes/api/workspace/get/index.ts index b92c7467d..a1b7878b5 100644 --- a/hub/server/routes/api/workspace/get/index.ts +++ b/hub/server/routes/api/workspace/get/index.ts @@ -1,6 +1,7 @@ import type { RequestHandler } from "express" import { z } from "zod" +import { hashAuthenticationValue } from "../../../../domains/authentication/hash-authentication-value/index.ts" import { authorizeRepositoryReview } from "../../../../domains/review-comments/authorize-repository-review/index.ts" import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" @@ -21,7 +22,7 @@ export function get( try { const cookie = readCookie(request, hubSessionCookieName) const initial = await readProductSession(cookie, session) - if (!initial) { + if (!initial || !cookie) { response.status(401).json({ error: "Sign in to continue." }) return } @@ -36,6 +37,12 @@ export function get( product.listRepositories(viewer), product.welcome?.isHidden(viewer.userId), ]) + const inboxHasUnread = navigationOnly + ? await product.reviewInbox?.hasUnread( + { viewer, sessionDigest: hashAuthenticationValue(cookie) }, + repositories, + ) + : undefined const requested = selectedRepository.success ? selectedRepository.data.toLowerCase() : null @@ -53,7 +60,14 @@ export function get( permissionUnavailable = true } } - return { repositories, selected, permission, permissionUnavailable, welcomeHidden } + return { + repositories, + selected, + permission, + permissionUnavailable, + welcomeHidden, + inboxHasUnread, + } }, ) if (!read) { @@ -62,7 +76,14 @@ export function get( } const { current, - result: { repositories, selected, permission, permissionUnavailable, welcomeHidden }, + result: { + repositories, + selected, + permission, + permissionUnavailable, + welcomeHidden, + inboxHasUnread, + }, } = read const presentedRepositories = repositories.map(({ localPath, ...repository }) => ({ ...repository, @@ -110,6 +131,7 @@ export function get( ? { repositoryPermissionsAvailable: true } : {}), ...(product.reviewInbox ? { reviewInboxAvailable: true } : {}), + ...(inboxHasUnread !== undefined ? { inboxHasUnread } : {}), ...(manageSharing ? { publicSharingSettingsAvailable: true } : {}), ...(welcomeHidden !== undefined ? { welcomeHidden } : {}), capabilities: { From 4bfd382e691b573a377facbe0c5401c33486a03c Mon Sep 17 00:00:00 2001 From: jabradford Date: Tue, 24 Nov 2026 15:55:38 -0800 Subject: [PATCH 4/7] fix(hub): keep navigation available when the Inbox lookup fails Log unread lookup failures and omit only the unread indicator. The workspace response still returns the repository navigation after verifying the current session. Refs: #354 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- hub/docs/frontend.md | 2 +- hub/server/create-app/index.test.ts | 14 +++++++++++++- hub/server/routes/api/workspace/get/index.ts | 13 ++++++++++--- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/hub/docs/frontend.md b/hub/docs/frontend.md index e8d73d91e..c6bbb21db 100644 --- a/hub/docs/frontend.md +++ b/hub/docs/frontend.md @@ -225,7 +225,7 @@ History loads only the requested page and any successful Build pinned by `build` ### Workspace projections -`GET /api/workspace?view=navigation` returns the signed-in viewer, readable repositories, Hub preferences, and the [Inbox unread indicator](review-collaboration.md#inbox-and-live-review). It does not check live GitHub repository permissions. `GET /api/workspace` retains the full response and checks management permissions for the selected repository. Both views verify the session and scope repositories to the viewer's access. +`GET /api/workspace?view=navigation` returns the signed-in viewer, readable repositories, Hub preferences, and the [Inbox unread indicator](review-collaboration.md#inbox-and-live-review). It does not check live GitHub repository permissions. If the unread lookup fails, Hub omits the indicator rather than blocking navigation. `GET /api/workspace` retains the full response and checks management permissions for the selected repository. Both views verify the session and scope repositories to the viewer's access. ### Prototype metadata edits diff --git a/hub/server/create-app/index.test.ts b/hub/server/create-app/index.test.ts index 99aebf7d4..23c1d68f4 100644 --- a/hub/server/create-app/index.test.ts +++ b/hub/server/create-app/index.test.ts @@ -6,6 +6,7 @@ import type { AddressInfo } from "node:net" import { join } from "node:path" import { describe, expect, it, onTestFinished, vi } from "vitest" +import { Prisma } from "../generated/prisma/client" import { createLogger } from "../integrations/pino/create-logger" import type { AuthenticationRouteDependencies } from "../routes/api/auth/types" import type { ProductRouteDependencies } from "../routes/api/product/types" @@ -158,7 +159,7 @@ describe("createApp()", () => { } }) - it("reads navigation without live permissions and verifies them on a full workspace read", async () => { + it("keeps navigation available on an unread lookup timeout without checking live permissions", async () => { const viewer = { membershipId: randomUUID(), userId: randomUUID(), @@ -179,8 +180,16 @@ describe("createApp()", () => { signOut: { applicationOrigin: "https://hub.example.com", secureCookie: false, end: vi.fn() }, } const getRepositoryPermission = vi.fn().mockResolvedValue("admin") + const hasUnread = vi.fn().mockRejectedValueOnce( + new Prisma.PrismaClientKnownRequestError("Unread query timed out", { + code: "P2010", + clientVersion: "test", + meta: { code: "57014" }, + }), + ) const product: ProductRouteDependencies = { getRepositoryPermission, + reviewInbox: { hasUnread, list: vi.fn(), find: vi.fn(), setRead: vi.fn() }, isRepositoryVisible: vi.fn().mockResolvedValue(true), listRepositories: vi.fn().mockResolvedValue([repository]), findRepositoryIndex: vi.fn(), @@ -210,13 +219,16 @@ describe("createApp()", () => { expect(workspace).toMatchObject({ viewer: { id: viewer.userId }, repositoryPermissionsAvailable: true, + reviewInboxAvailable: true, repositories: [{ id: repository.id, capabilities: { reviewPrototypes: true } }], }) + expect(workspace).not.toHaveProperty("inboxHasUnread") expect(workspace).not.toHaveProperty("repositories.0.capabilities.administerRepository") expect(workspace).not.toHaveProperty("repositories.0.capabilities.managePrototypeListings") const verified = await fetch(`${base}?repositoryId=${repository.id}`, { headers }) expect(verified.status).toBe(200) + expect(hasUnread).toHaveBeenCalledTimes(1) expect(getRepositoryPermission).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ membershipId: viewer.membershipId, sessionProvider: "github" }), repository.id, diff --git a/hub/server/routes/api/workspace/get/index.ts b/hub/server/routes/api/workspace/get/index.ts index a1b7878b5..c7cdd04c1 100644 --- a/hub/server/routes/api/workspace/get/index.ts +++ b/hub/server/routes/api/workspace/get/index.ts @@ -3,6 +3,7 @@ import { z } from "zod" import { hashAuthenticationValue } from "../../../../domains/authentication/hash-authentication-value/index.ts" import { authorizeRepositoryReview } from "../../../../domains/review-comments/authorize-repository-review/index.ts" +import { Prisma } from "../../../../generated/prisma/client.ts" import { hubSessionCookieName } from "../../../../integrations/express/hub-session-cookie-name/index.ts" import { readCookie } from "../../../../integrations/express/read-cookie/index.ts" import { GitHubProviderRequestError } from "../../../../integrations/github/errors.ts" @@ -37,12 +38,18 @@ export function get( product.listRepositories(viewer), product.welcome?.isHidden(viewer.userId), ]) - const inboxHasUnread = navigationOnly - ? await product.reviewInbox?.hasUnread( + let inboxHasUnread: boolean | undefined + if (navigationOnly && product.reviewInbox) { + try { + inboxHasUnread = await product.reviewInbox.hasUnread( { viewer, sessionDigest: hashAuthenticationValue(cookie) }, repositories, ) - : undefined + } catch (error) { + if (!(error instanceof Prisma.PrismaClientKnownRequestError)) throw error + request.log.warn({ code: error.code }, "Inbox unread status unavailable") + } + } const requested = selectedRepository.success ? selectedRepository.data.toLowerCase() : null From 65c5e0e58883528bad575a69ee2c45b62e3360c8 Mon Sep 17 00:00:00 2001 From: jabradford Date: Tue, 24 Nov 2026 16:15:27 -0800 Subject: [PATCH 5/7] fix(hub): retire numeric Inbox sidebar badges Use unread presence for the sidebar in the app and Storybook. Keep exact counts inside the Inbox list and preview. Refs: #354 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../view-models/workspace-navigation/index.ts | 1 - .../repository-navigation-item/index.tsx | 9 ---- .../repository-navigation-item/styles.css | 35 -------------- hub/client/features/workspace-nav/inbox.tsx | 46 ++++++------------- hub/client/features/workspace-nav/stories.tsx | 16 +------ hub/client/features/workspace-nav/types.ts | 11 ++--- .../hooks/use-repository-inbox/index.ts | 33 ------------- hub/client/hooks/use-workspace-inbox/index.ts | 19 -------- .../pages/notifications-page/index.test.tsx | 6 +-- hub/client/pages/notifications-page/index.tsx | 10 +--- .../pages/notifications-page/stories.tsx | 12 ++++- .../storybook/inbox-prototype/index.test.tsx | 39 +++++++--------- .../storybook/inbox-prototype/index.tsx | 2 - hub/client/utils/notification/types.ts | 9 ---- 14 files changed, 50 insertions(+), 198 deletions(-) delete mode 100644 hub/client/hooks/use-repository-inbox/index.ts delete mode 100644 hub/client/hooks/use-workspace-inbox/index.ts diff --git a/hub/client/application/hub/view-models/workspace-navigation/index.ts b/hub/client/application/hub/view-models/workspace-navigation/index.ts index 550d9995d..71d0d3fcf 100644 --- a/hub/client/application/hub/view-models/workspace-navigation/index.ts +++ b/hub/client/application/hub/view-models/workspace-navigation/index.ts @@ -45,7 +45,6 @@ export function workspaceNavigation( ? { ...notificationInboxConfiguration, connected: true } : undefined, notificationsUnread: workspace.inboxHasUnread, - notificationsUnreadLabel: "Inbox, unread notifications", administrationLinks: admin ? [ { diff --git a/hub/client/components/repository-navigation-item/index.tsx b/hub/client/components/repository-navigation-item/index.tsx index 70820c4c3..434b6118a 100644 --- a/hub/client/components/repository-navigation-item/index.tsx +++ b/hub/client/components/repository-navigation-item/index.tsx @@ -6,7 +6,6 @@ type RepositoryNavigationItemProps = { icon: ElementType label: string ariaLabel?: string - count?: number } & ( | { href: string @@ -27,7 +26,6 @@ type RepositoryNavigationItemProps = { /** Renders a sidebar destination or a control with the same row treatment. */ export function RepositoryNavigationItem({ ariaLabel, - count, expanded, external = false, href, @@ -42,11 +40,6 @@ export function RepositoryNavigationItem({ {label} - {count !== undefined && count > 0 ? ( - - ) : null} ) @@ -54,7 +47,6 @@ export function RepositoryNavigationItem({ 0 ? "true" : undefined} data-active={selected ? "true" : undefined} aria-current={selected ? "page" : undefined} aria-label={ariaLabel} @@ -68,7 +60,6 @@ export function RepositoryNavigationItem({