Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6967 perf(inbox): derive the unread badge from the summary endpoint, not the full list (#7924)

Bohan Jiangb36906e6d512
diff --git a/apps/mobile/data/api.ts b/apps/mobile/data/api.ts
index 0be8316239..4cbfa35cdd 100644
--- a/apps/mobile/data/api.ts
+++ b/apps/mobile/data/api.ts
@@ -26,6 +26,7 @@ import type {
CreateProjectRequest,
CreateProjectResourceRequest,
InboxItem,
+ InboxWorkspaceUnread,
Issue,
IssueLabelsResponse,
Label,
@@ -92,6 +93,7 @@ import {
EMPTY_CHAT_SESSION_LIST,
EMPTY_COMMENT,
EMPTY_INBOX_LIST,
+ EMPTY_INBOX_UNREAD_SUMMARY,
EMPTY_ISSUE_FALLBACK,
EMPTY_LIST_LABELS_RESPONSE,
EMPTY_LIST_PROJECT_RESOURCES_RESPONSE,
@@ -107,6 +109,7 @@ import {
EMPTY_USER,
EMPTY_WORKSPACE_LIST,
InboxListSchema,
+ InboxUnreadSummarySchema,
NotificationPreferenceResponseSchema,
ListLabelsResponseSchema,
ListProjectResourcesResponseSchema,
@@ -479,6 +482,25 @@ class ApiClient {
});
}
+ /**
+ * Cross-workspace unread inbox counts, one entry per workspace with unread
+ * items. Backs the inbox tab badge — see lib/unread-counts.ts for why the
+ * badge reads this instead of counting `listInbox()` locally.
+ */
+ async getInboxUnreadSummary(opts?: {
+ signal?: AbortSignal;
+ }): Promise<InboxWorkspaceUnread[]> {
+ const raw = await this.fetch<unknown>("/api/inbox/unread-summary", {
+ signal: opts?.signal,
+ });
+ return parseWithFallback(
+ raw,
+ InboxUnreadSummarySchema,
+ EMPTY_INBOX_UNREAD_SUMMARY,
+ { endpoint: "getInboxUnreadSummary" },
+ );
+ }
+
async markInboxRead(id: string): Promise<InboxItem> {
return this.fetch<InboxItem>(`/api/inbox/${id}/read`, { method: "POST" });
}
diff --git a/apps/mobile/data/inbox-schema.test.ts b/apps/mobile/data/inbox-schema.test.ts
index df2a633fad..bf3086abd6 100644
--- a/apps/mobile/data/inbox-schema.test.ts
+++ b/apps/mobile/data/inbox-schema.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { InboxListSchema } from "./schemas";
+import { InboxListSchema, InboxUnreadSummarySchema } from "./schemas";
/**
* Tests for mobile's CLIENT-SIDE parsing of GET /api/inbox.
@@ -94,3 +94,52 @@ describe("inbox list schema", () => {
expect(parsed.success).toBe(true);
});
});
+
+/**
+ * GET /api/inbox/unread-summary — the source of the inbox tab badge.
+ *
+ * Blast radius differs from the list above: `getInboxUnreadSummary` falls back
+ * to an empty array, which reads as "nothing unread" and simply hides the
+ * badge. A wrong number would be worse than no number, so the schema stays
+ * strict about the shape and lenient only about extra fields.
+ */
+describe("inbox unread summary schema", () => {
+ it("parses the documented server payload", () => {
+ const parsed = InboxUnreadSummarySchema.safeParse([
+ { workspace_id: "ws-1", count: 3 },
+ { workspace_id: "ws-2", count: 1 },
+ ]);
+
+ expect(parsed.success).toBe(true);
+ expect(parsed.success && parsed.data[1]?.count).toBe(1);
+ });
+
+ it("passes through a field this client does not know yet", () => {
+ const parsed = InboxUnreadSummarySchema.safeParse([
+ { workspace_id: "ws-1", count: 3, unread_mentions: 2 },
+ ]);
+
+ expect(parsed.success).toBe(true);
+ expect(parsed.success && parsed.data[0]?.count).toBe(3);
+ });
+
+ it("reads a non-numeric count as zero rather than failing the list", () => {
+ // One malformed row must not blank every other workspace's count.
+ const parsed = InboxUnreadSummarySchema.safeParse([
+ { workspace_id: "ws-1", count: "many" },
+ { workspace_id: "ws-2", count: 5 },
+ ]);
+
+ expect(parsed.success).toBe(true);
+ expect(parsed.success && parsed.data[0]?.count).toBe(0);
+ expect(parsed.success && parsed.data[1]?.count).toBe(5);
+ });
+
+ it("rejects a row with no workspace id", () => {
+ // Without an id the entry can never be matched to a workspace, so it would
+ // silently contribute nothing — fail loudly into the empty fallback.
+ expect(
+ InboxUnreadSummarySchema.safeParse([{ count: 3 }]).success,
+ ).toBe(false);
+ });
+});
diff --git a/apps/mobile/data/mutations/inbox.ts b/apps/mobile/data/mutations/inbox.ts
index ad1765df1d..759f9d5937 100644
--- a/apps/mobile/data/mutations/inbox.ts
+++ b/apps/mobile/data/mutations/inbox.ts
@@ -26,11 +26,34 @@
* Just invalidate on settle. Matches web.
*/
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import type { QueryClient } from "@tanstack/react-query";
import type { InboxItem } from "@multica/core/types";
import { api } from "@/data/api";
import { inboxKeys } from "@/data/queries/inbox";
+import { refreshInboxUnreadSummary } from "@/data/realtime/inbox-ws-updaters";
import { useWorkspaceStore } from "@/data/workspace-store";
+/**
+ * Refresh the cross-workspace unread summary that backs the tab badge after a
+ * write. It lives under its own account-level key, so invalidating the
+ * workspace list does not reach it — every mutation here can change the number
+ * it holds.
+ *
+ * Deliberately the shared entry point rather than a second local copy: a
+ * mutation racing the first summary load hits exactly the same in-flight hole
+ * a WS event does, and `refreshInboxUnreadSummary` is where that is handled.
+ * Not awaited by `onSettled` — the mutation is done once the server answers.
+ *
+ * Rows are optimistic, the badge is not: it follows the server's confirmation.
+ * Mirrors the same decision in packages/core/inbox/mutations.ts, whose comment
+ * carries the reasoning — recomputing the count from the list cache and
+ * writing it back cannot be made correct once the list is paginated, and races
+ * an in-flight summary response that no `cancelQueries` here covers.
+ */
+function invalidateUnreadSummary(qc: QueryClient) {
+ void refreshInboxUnreadSummary(qc);
+}
+
export function useMarkInboxRead() {
const qc = useQueryClient();
const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);
@@ -53,6 +76,7 @@ export function useMarkInboxRead() {
},
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -88,6 +112,7 @@ export function useArchiveInbox() {
},
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -114,6 +139,7 @@ export function useMarkAllInboxRead() {
},
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -121,7 +147,8 @@ export function useMarkAllInboxRead() {
// Batch archive mutations — invalidate-only, matching web. The optimistic
// path isn't worth the complexity: archive-completed depends on the issue
// status of each linked issue (not carried on InboxItem), and predicting
-// that on the client risks divergence with the server's SQL filter.
+// that on the client risks divergence with the server's SQL filter. The badge
+// therefore catches up on settle rather than moving instantly.
export function useArchiveAllInbox() {
const qc = useQueryClient();
const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);
@@ -129,6 +156,7 @@ export function useArchiveAllInbox() {
mutationFn: () => api.archiveAllInbox(),
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -140,6 +168,7 @@ export function useArchiveAllReadInbox() {
mutationFn: () => api.archiveAllReadInbox(),
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -151,6 +180,7 @@ export function useArchiveCompletedInbox() {
mutationFn: () => api.archiveCompletedInbox(),
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
diff --git a/apps/mobile/data/queries/inbox.ts b/apps/mobile/data/queries/inbox.ts
index a5b351f08c..123ded8e36 100644
--- a/apps/mobile/data/queries/inbox.ts
+++ b/apps/mobile/data/queries/inbox.ts
@@ -12,6 +12,10 @@ export const inboxKeys = {
all: (wsId: string | null) => ["inbox", wsId] as const,
list: (wsId: string | null) =>
[...inboxKeys.all(wsId), "list"] as const,
+ // Account-level, not workspace-scoped: one cache entry holding unread
+ // counts for every workspace the user belongs to. Same key shape as web
+ // (packages/core/inbox/queries.ts) so the mental model stays shared.
+ unreadSummary: () => ["inbox", "unread-summary"] as const,
};
export const inboxListOptions = (wsId: string | null) =>
@@ -20,3 +24,16 @@ export const inboxListOptions = (wsId: string | null) =>
queryFn: ({ signal }) => api.listInbox({ signal }),
enabled: !!wsId,
});
+
+/**
+ * Cross-workspace unread inbox summary — the source of the tab badge count.
+ *
+ * Gated on an active workspace because the endpoint resolves through the
+ * workspace-member middleware, same as web's sidebar does.
+ */
+export const inboxUnreadSummaryOptions = (wsId: string | null) =>
+ queryOptions({
+ queryKey: inboxKeys.unreadSummary(),
+ queryFn: ({ signal }) => api.getInboxUnreadSummary({ signal }),
+ enabled: !!wsId,
+ });
diff --git a/apps/mobile/data/realtime/inbox-ws-updaters.test.ts b/apps/mobile/data/realtime/inbox-ws-updaters.test.ts
new file mode 100644
index 0000000000..24f1abf062
--- /dev/null
+++ b/apps/mobile/data/realtime/inbox-ws-updaters.test.ts
@@ -0,0 +1,123 @@
+// @vitest-environment node
+import { QueryClient } from "@tanstack/react-query";
+import type { InboxItem } from "@multica/core/types";
+import { describe, expect, it, vi } from "vitest";
+
+import { inboxKeys } from "@/data/queries/inbox";
+import {
+ dropInboxItemsByIssue,
+ patchInboxIssueStatus,
+ refreshInboxUnreadSummary,
+} from "./inbox-ws-updaters";
+
+// inbox-ws-updaters imports inboxKeys from data/queries/inbox, which
+// transitively imports the native fetch client. Mock it so the Node test never
+// loads RN modules — inboxKeys itself is a pure key factory (same reason
+// chat-ws-updaters.test.ts does this).
+vi.mock("@/data/api", () => ({ api: {} }));
+
+const wsId = "workspace-1";
+
+function item(id: string, issueId: string | null): InboxItem {
+ return {
+ id,
+ workspace_id: wsId,
+ recipient_type: "member",
+ recipient_id: "member-1",
+ actor_type: "agent",
+ actor_id: "agent-1",
+ type: "new_comment",
+ severity: "info",
+ issue_id: issueId,
+ title: "Issue title",
+ body: null,
+ issue_status: null,
+ read: false,
+ archived: false,
+ created_at: "2026-09-01T08:00:00Z",
+ details: null,
+ };
+}
+
+describe("dropInboxItemsByIssue", () => {
+ it("drops every row pointing at the deleted issue", async () => {
+ const qc = new QueryClient();
+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), [
+ item("n1", "issue-a"),
+ item("n2", "issue-b"),
+ ]);
+
+ await dropInboxItemsByIssue(qc, wsId, "issue-a");
+
+ expect(
+ qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId))?.map((i) => i.id),
+ ).toEqual(["n2"]);
+ });
+
+ it("refreshes the unread summary the dropped rows can change", async () => {
+ // Parity with web (packages/core/inbox/ws-updaters.ts). The tab badge
+ // reads the server summary, and `issue:deleted` fires no `inbox:*` event,
+ // so without this the badge stays lit over an emptied inbox (MUL-6967).
+ const qc = new QueryClient();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), [item("n1", "issue-a")]);
+
+ await dropInboxItemsByIssue(qc, wsId, "issue-a");
+
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: inboxKeys.unreadSummary(),
+ });
+ });
+});
+
+describe("refreshInboxUnreadSummary", () => {
+ it("cancels an in-flight summary request BEFORE invalidating", async () => {
+ // Parity with web. TanStack skips its own cancel on a FIRST fetch
+ // (`Query.fetch` guards it on `state.data !== undefined`) and reuses the
+ // request already on the wire, whose success clears `isInvalidated` — so
+ // an invalidate alone can be answered by a pre-change response and never
+ // asked again (MUL-6967).
+ const qc = new QueryClient();
+ const calls: string[] = [];
+ vi.spyOn(qc, "cancelQueries").mockImplementation(async () => {
+ calls.push("cancel");
+ });
+ vi.spyOn(qc, "invalidateQueries").mockImplementation(async () => {
+ calls.push("invalidate");
+ });
+
+ await refreshInboxUnreadSummary(qc);
+
+ expect(calls).toEqual(["cancel", "invalidate"]);
+ });
+
+ it("targets the summary key only, never a workspace inbox list", async () => {
+ const qc = new QueryClient();
+ const cancel = vi.spyOn(qc, "cancelQueries");
+
+ await refreshInboxUnreadSummary(qc);
+
+ expect(cancel).toHaveBeenCalledWith({
+ queryKey: inboxKeys.unreadSummary(),
+ });
+ expect(cancel).not.toHaveBeenCalledWith({ queryKey: inboxKeys.list(wsId) });
+ });
+});
+
+describe("patchInboxIssueStatus", () => {
+ it("updates the row's status without touching the badge", () => {
+ // A status change moves no notification in or out of the unread set, so
+ // it must NOT invalidate the summary — that would refetch on every
+ // issue:updated frame.
+ const qc = new QueryClient();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), [item("n1", "issue-a")]);
+
+ patchInboxIssueStatus(qc, wsId, "issue-a", "done");
+
+ expect(
+ qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId))?.[0]?.issue_status,
+ ).toBe("done");
+ expect(invalidate).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/data/realtime/inbox-ws-updaters.ts b/apps/mobile/data/realtime/inbox-ws-updaters.ts
index 5220872e74..08dfa89592 100644
--- a/apps/mobile/data/realtime/inbox-ws-updaters.ts
+++ b/apps/mobile/data/realtime/inbox-ws-updaters.ts
@@ -31,7 +31,32 @@ export function patchInboxIssueStatus(
);
}
-export function dropInboxItemsByIssue(
+/**
+ * THE entry point for refreshing the cross-workspace unread summary that backs
+ * the tab badge. Mutations, inbox events, issue deletion and reconnect all go
+ * through here. Mirrors `onInboxSummaryInvalidate` in
+ * packages/core/inbox/ws-updaters.ts — including why the cancel comes first.
+ *
+ * TanStack only cancels an in-flight request on invalidation once the query
+ * already holds data (`Query.fetch` guards that branch on
+ * `state.data !== undefined`, and otherwise returns the in-flight promise). An
+ * invalidation racing the FIRST summary load is therefore answered by the
+ * pre-change response, which resolves successfully and clears `isInvalidated`
+ * — leaving the badge on a count the user's own action already invalidated,
+ * with nothing scheduled to ask again. Cancelling first makes a refresh behave
+ * the same whether or not the summary has loaded yet (MUL-6967).
+ */
+export async function refreshInboxUnreadSummary(qc: QueryClient) {
+ await qc.cancelQueries({ queryKey: inboxKeys.unreadSummary() });
+ await qc.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });
+}
+
+// Dropping unread rows changes the tab badge, which reads the server-side
+// unread summary rather than this list. `issue:deleted` fires no `inbox:*`
+// event, so nothing else would refresh it and the badge would stay above an
+// empty inbox — hence the refresh lives here, not at the call site.
+// Web does the same in packages/core/inbox/ws-updaters.ts (MUL-6967).
+export async function dropInboxItemsByIssue(
qc: QueryClient,
wsId: string,
issueId: string,
@@ -39,4 +64,5 @@ export function dropInboxItemsByIssue(
qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), (old) =>
old?.filter((i) => i.issue_id !== issueId),
);
+ await refreshInboxUnreadSummary(qc);
}
diff --git a/apps/mobile/data/realtime/use-inbox-realtime.ts b/apps/mobile/data/realtime/use-inbox-realtime.ts
index e3970c1396..8f767f49ee 100644
--- a/apps/mobile/data/realtime/use-inbox-realtime.ts
+++ b/apps/mobile/data/realtime/use-inbox-realtime.ts
@@ -3,13 +3,15 @@
*
* Two subscription groups:
*
- * 1. `inbox:*` events → invalidate the inbox query. inbox payloads are
- * small and (apart from inbox:new) rare, so refetching is cheaper than
- * maintaining per-event patchers. Multi-device parity: subscribing to
- * inbox:read / inbox:archived means a read/archive on web reaches
- * mobile within the next WS frame (web's use-realtime-sync deliberately
- * DOESN'T subscribe to those, but mobile's stricter freshness wins for
- * multi-device users).
+ * 1. `inbox:*` events → invalidate the inbox list AND the cross-workspace
+ * unread summary that backs the tab badge (the summary lives under its
+ * own account-level key, so the list invalidation does not reach it).
+ * inbox payloads are small and (apart from inbox:new) rare, so refetching
+ * is cheaper than maintaining per-event patchers. Multi-device parity:
+ * subscribing to inbox:read / inbox:archived means a read/archive on web
+ * reaches mobile within the next WS frame (web's use-realtime-sync
+ * deliberately DOESN'T subscribe to those, but mobile's stricter freshness
+ * wins for multi-device users).
*
* 2. `issue:*` events → patch the inbox cache directly via the dedicated
* updaters (inbox-ws-updaters.ts). Required because:
@@ -28,6 +30,7 @@ import { useWSSubscriptions } from "@/lib/use-ws-subscriptions";
import {
dropInboxItemsByIssue,
patchInboxIssueStatus,
+ refreshInboxUnreadSummary,
} from "./inbox-ws-updaters";
export function useInboxRealtime() {
@@ -35,11 +38,15 @@ export function useInboxRealtime() {
useWSSubscriptions(
(ws, wsId) => {
- const invalidate = () =>
+ const invalidate = () => {
qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });
+ // Shared entry point: it cancels an in-flight summary request before
+ // invalidating, which a plain invalidate cannot do on a first load.
+ void refreshInboxUnreadSummary(qc);
+ };
return [
- // Inbox-domain events: refetch the small inbox list.
+ // Inbox-domain events: refetch the inbox list and the badge count.
ws.on("inbox:new", invalidate),
ws.on("inbox:read", invalidate),
// Mobile has no mark-unread affordance yet (web/desktop right-click
@@ -65,7 +72,7 @@ export function useInboxRealtime() {
);
}),
ws.on("issue:deleted", (payload) => {
- dropInboxItemsByIssue(qc, wsId, payload.issue_id);
+ void dropInboxItemsByIssue(qc, wsId, payload.issue_id);
}),
// After a reconnect we don't know what we missed during the
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index 6ba8bf6d2f..74be0341e4 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -20,6 +20,7 @@ import type {
ChatSession,
Comment,
InboxItem,
+ InboxWorkspaceUnread,
IssueLabelsResponse,
Label,
ListLabelsResponse,
@@ -588,6 +589,24 @@ const InboxItemSchema: z.ZodType<InboxItem> = z.object({
export const InboxListSchema = z.array(InboxItemSchema).default([]);
export const EMPTY_INBOX_LIST: InboxItem[] = [];
+// Cross-workspace unread summary (`GET /api/inbox/unread-summary`): one entry
+// per workspace the user belongs to that has unread items, already
+// deduplicated per issue server-side. Backs the inbox tab badge. Mirrors
+// InboxUnreadSummarySchema in packages/core/api/schemas.ts. On malformed JSON
+// the fallback is an empty list, which reads as "nothing unread" — the badge
+// simply hides rather than showing a wrong number.
+const InboxWorkspaceUnreadSchema: z.ZodType<InboxWorkspaceUnread> = z
+ .object({
+ workspace_id: z.string(),
+ count: z.number().catch(0),
+ })
+ .loose();
+
+export const InboxUnreadSummarySchema = z
+ .array(InboxWorkspaceUnreadSchema)
+ .default([]);
+export const EMPTY_INBOX_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];
+
export const MemberWithUserSchema: z.ZodType<MemberWithUser> = z.object({
id: z.string(),
workspace_id: z.string().default(""),
diff --git a/apps/mobile/lib/unread-counts.ts b/apps/mobile/lib/unread-counts.ts
index c739f07577..3058753009 100644
--- a/apps/mobile/lib/unread-counts.ts
+++ b/apps/mobile/lib/unread-counts.ts
@@ -2,13 +2,14 @@
* Unread count hooks for the bottom tab bar badges.
*
* Mirrors the counting logic from:
- * - packages/core/inbox/queries.ts::useInboxUnreadCount (inbox)
+ * - packages/core/inbox/queries.ts::useInboxUnreadCount (inbox — which,
+ * like this one, reads the server-computed cross-workspace summary)
* - packages/core/chat/unread.ts::countUnreadChatMessages (chat — the
* shared pure function IS the definition; web's sidebar calls the same
* one, so the platforms cannot drift apart)
*
- * Both queries (`inboxListOptions`, `chatSessionsOptions`) are already kept
- * fresh by listing-level realtime hooks mounted in
+ * Both queries (`inboxUnreadSummaryOptions`, `chatSessionsOptions`) are
+ * already kept fresh by listing-level realtime hooks mounted in
* `app/(app)/[workspace]/_layout.tsx`, so these hooks only attach a `select`
* to derive a scalar count — re-rendering the tab layout only when the
* number actually changes (TQ compares select output with Object.is).
@@ -18,20 +19,31 @@
*/
import { useQuery } from "@tanstack/react-query";
import { countUnreadChatMessages } from "@multica/core/chat/unread";
-import { inboxListOptions } from "@/data/queries/inbox";
+import { inboxUnreadSummaryOptions } from "@/data/queries/inbox";
import { chatSessionsOptions } from "@/data/queries/chat";
-import { deduplicateInboxItems } from "@/lib/inbox-display";
/**
- * Unread inbox count, aligned with what the inbox list renders: archived
- * items dropped, then deduplicated by issue (one entry per issue), then
- * filtered to unread. Same definition as web's sidebar badge.
+ * Unread inbox count for the tab badge.
+ *
+ * Read from the cross-workspace unread summary, not from the inbox list.
+ * The summary is one small server-computed row per workspace, and the server
+ * applies the same newest-per-issue rule `deduplicateInboxItems`
+ * (lib/inbox-display.ts) applies before render — so the N here still equals
+ * the N web shows and the N the inbox tab lists. Counting the list locally
+ * meant fetching the entire unbounded inbox on app start just to render this
+ * number (MUL-6967).
+ *
+ * The lookup mirrors `unreadCountForWorkspace` in
+ * packages/core/inbox/queries.ts rather than importing it — that module pulls
+ * in core's API client, which mobile does not use (same reason
+ * `deduplicateInboxItems` is mirrored into lib/inbox-display.ts). A workspace
+ * with nothing unread is absent from the response, so a missing entry is zero.
*/
export function useInboxUnreadCount(wsId: string | null | undefined): number {
const { data } = useQuery({
- ...inboxListOptions(wsId ?? null),
- select: (items) =>
- deduplicateInboxItems(items).filter((i) => !i.read).length,
+ ...inboxUnreadSummaryOptions(wsId ?? null),
+ select: (summary) =>
+ wsId ? (summary.find((s) => s.workspace_id === wsId)?.count ?? 0) : 0,
});
return data ?? 0;
}
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 71b57533bc..aaf477b64f 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -2477,6 +2477,12 @@ export class ApiClient {
return this.fetch(`/api/inbox/${id}/unarchive`, { method: "POST" });
}
+ // Raw unread ROW count — not the number any badge shows. The inbox renders
+ // one row per issue, so a single issue with three unread notifications
+ // counts once there and three times here. `getInboxUnreadSummary` is the
+ // deduplicated, per-workspace count the UI is built on (see
+ // `useInboxUnreadCount`); reach for this one only when raw rows are what
+ // you actually mean.
async getUnreadInboxCount(): Promise<{ count: number }> {
return this.fetch("/api/inbox/unread-count");
}
diff --git a/packages/core/inbox/filter-store.ts b/packages/core/inbox/filter-store.ts
index 4e3ed6e77e..0ce31b8cfa 100644
--- a/packages/core/inbox/filter-store.ts
+++ b/packages/core/inbox/filter-store.ts
@@ -189,9 +189,10 @@ export function inboxFiltersForPrioritySupport(
* touched") than the one the row then displays, so selecting Alice would fill
* the list with Bob. What you filter by is what you see.
*
- * `unreadOnly` likewise reads the rendered row's `read`, which is what the
- * unread badge counts (`useInboxUnreadCount`) — so "only unread" and the
- * number next to Inbox can never disagree.
+ * `unreadOnly` likewise reads the rendered row's `read`. The unread badge
+ * (`useInboxUnreadCount`) counts the same thing from the server's summary
+ * endpoint, which applies that newest-per-issue rule in SQL — so "only unread"
+ * and the number next to Inbox still cannot disagree.
*/
export function filterInboxItems(
items: InboxItem[],
diff --git a/packages/core/inbox/mutations.test.tsx b/packages/core/inbox/mutations.test.tsx
index d44e2867dc..493d5fe7d2 100644
--- a/packages/core/inbox/mutations.test.tsx
+++ b/packages/core/inbox/mutations.test.tsx
@@ -2,15 +2,17 @@
* @vitest-environment jsdom
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { renderHook, waitFor } from "@testing-library/react";
+import { act, renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { setApiInstance } from "../api";
import type { ApiClient } from "../api/client";
-import type { InboxItem } from "../types";
-import { useMarkInboxUnread, useUnarchiveInbox } from "./mutations";
-import { inboxKeys } from "./queries";
+import type { InboxItem, InboxWorkspaceUnread } from "../types";
+import { useMarkInboxRead, useMarkInboxUnread, useUnarchiveInbox } from "./mutations";
+import { inboxKeys, useInboxUnreadCount } from "./queries";
+import { onInboxSummaryInvalidate } from "./ws-updaters";
+import { createQueryClient } from "../query-client";
vi.mock("../hooks", () => ({
useWorkspaceId: () => "workspace-1",
@@ -56,6 +58,13 @@ function listCache(qc: QueryClient) {
return qc.getQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID)) ?? [];
}
+function summaryCount(qc: QueryClient) {
+ const summary = qc.getQueryData<InboxWorkspaceUnread[]>(
+ inboxKeys.unreadSummary(),
+ );
+ return summary?.find((e) => e.workspace_id === WORKSPACE_ID)?.count;
+}
+
describe("useMarkInboxUnread", () => {
let queryClient: QueryClient;
let markInboxUnread: ReturnType<typeof vi.fn>;
@@ -210,3 +219,148 @@ describe("useUnarchiveInbox", () => {
expect(archivedCache(queryClient)).toEqual(original);
});
});
+
+/**
+ * The badge reads the server's cross-workspace summary. Rows stay optimistic;
+ * the badge deliberately does NOT, so there is exactly one writer for it
+ * (MUL-6967). These pin the property that replaces the old local recompute:
+ * whatever races, the badge converges on the server's value.
+ */
+describe("unread summary is server-owned", () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ });
+
+ it("does not move the badge from the list patch alone", async () => {
+ // A local recompute would read the patched list and write 0 here. It must
+ // not: the list cache proves only that the list loaded once, never that it
+ // is complete or concurrent with the summary — and once the list is
+ // paginated, one page cannot produce a workspace-wide count.
+ setApiInstance({
+ markInboxRead: vi.fn(async (id: string) => item({ id, read: true })),
+ } as unknown as ApiClient);
+ queryClient.setQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID), [
+ item({ id: "inbox-1", read: false, archived: false }),
+ ]);
+ queryClient.setQueryData<InboxWorkspaceUnread[]>(
+ inboxKeys.unreadSummary(),
+ [{ workspace_id: WORKSPACE_ID, count: 1 }],
+ );
+
+ const { result } = renderHook(() => useMarkInboxRead(), {
+ wrapper: createWrapper(queryClient),
+ });
+ result.current.mutate("inbox-1");
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ // The row flipped immediately...
+ expect(listCache(queryClient)[0]?.read).toBe(true);
+ // ...and the badge was never written locally; only invalidated.
+ expect(summaryCount(queryClient)).toBe(1);
+ expect(
+ queryClient
+ .getQueryCache()
+ .find({ queryKey: inboxKeys.unreadSummary() })?.state.isInvalidated,
+ ).toBe(true);
+ });
+
+ // Ordering is controlled explicitly: the first summary response is held open
+ // until after the write and the event have both landed. An earlier version
+ // of this test waited for the badge to read 1 first, which meant the first
+ // response had ALREADY resolved — it exercised an ordinary sequential update
+ // and could not have caught the bug below.
+ //
+ // Both parameters matter. With the summary already cached, invalidation
+ // cancels the in-flight request on its own. On a FIRST load it does not:
+ // `Query.fetch` only takes the cancel branch when `state.data !== undefined`
+ // and otherwise returns the request already on the wire, which then resolves
+ // successfully and clears `isInvalidated`. With `staleTime: Infinity` and no
+ // refetch on focus, nothing asks again — so only the uncached case regressed.
+ it.each([
+ ["already cached", true],
+ ["first load", false],
+ ])(
+ "converges after a late summary response — %s",
+ async (_label, cached) => {
+ const qc = createQueryClient();
+ qc.setQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID), [
+ item({ id: "inbox-1", read: false, archived: false }),
+ ]);
+ if (cached) {
+ qc.setQueryData<InboxWorkspaceUnread[]>(inboxKeys.unreadSummary(), [
+ { workspace_id: WORKSPACE_ID, count: 1 },
+ ]);
+ await qc.invalidateQueries({
+ queryKey: inboxKeys.unreadSummary(),
+ refetchType: "none",
+ });
+ }
+
+ let releaseFirst!: (rows: InboxWorkspaceUnread[]) => void;
+ const firstResponse = new Promise<InboxWorkspaceUnread[]>((resolve) => {
+ releaseFirst = resolve;
+ });
+ let serverCount = 1;
+ const getInboxUnreadSummary = vi
+ .fn()
+ .mockImplementationOnce(() => firstResponse)
+ .mockImplementation(async () =>
+ serverCount > 0
+ ? [{ workspace_id: WORKSPACE_ID, count: serverCount }]
+ : [],
+ );
+ setApiInstance({
+ getInboxUnreadSummary,
+ markInboxRead: vi.fn(async (id: string) => {
+ serverCount = 0;
+ return item({ id, read: true });
+ }),
+ } as unknown as ApiClient);
+
+ const { result, unmount } = renderHook(
+ () => ({
+ count: useInboxUnreadCount(WORKSPACE_ID),
+ markRead: useMarkInboxRead(),
+ }),
+ { wrapper: createWrapper(qc) },
+ );
+
+ try {
+ // The first summary read is on the wire and still open.
+ await waitFor(() =>
+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1),
+ );
+ expect(qc.getQueryState(inboxKeys.unreadSummary())?.fetchStatus).toBe(
+ "fetching",
+ );
+
+ await act(async () => {
+ await result.current.markRead.mutateAsync("inbox-1");
+ });
+ // A self-event, or an event from another client, can arrive before the
+ // first read answers — it must not be swallowed by that request.
+ await act(async () => {
+ await onInboxSummaryInvalidate(qc);
+ });
+ // Now the pre-change response finally lands.
+ await act(async () => {
+ releaseFirst([{ workspace_id: WORKSPACE_ID, count: 1 }]);
+ await firstResponse;
+ });
+
+ expect(listCache(qc)[0]?.read).toBe(true);
+ await waitFor(() => expect(result.current.count).toBe(0));
+ // Convergence came from a fresh read, not from the stale one.
+ expect(getInboxUnreadSummary.mock.calls.length).toBeGreaterThan(1);
+ } finally {
+ releaseFirst([]);
+ unmount();
+ qc.clear();
+ }
+ },
+ );
+});
diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.ts
index 7e0df827ff..310901716d 100644
--- a/packages/core/inbox/mutations.ts
+++ b/packages/core/inbox/mutations.ts
@@ -1,9 +1,44 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import type { QueryClient } from "@tanstack/react-query";
import { api } from "../api";
import { inboxKeys } from "./queries";
+import { onInboxSummaryInvalidate } from "./ws-updaters";
import { useWorkspaceId } from "../hooks";
import type { InboxItem } from "../types";
+/**
+ * Refresh the cross-workspace unread summary after a write.
+ *
+ * The unread badge reads that summary (`useInboxUnreadCount`), and it lives
+ * under its own account-level key which `inboxKeys.all(wsId)` does not reach.
+ * Every mutation here can change the number it holds, so each one refreshes it
+ * once the server has confirmed, rather than waiting for the WebSocket echo of
+ * its own action.
+ *
+ * Deliberately the same entry point realtime uses, not a second local copy:
+ * refreshing the summary has to cancel any in-flight request first, and a
+ * mutation racing the first summary load hits exactly the same hole a WS event
+ * does. `onInboxSummaryInvalidate` carries the reasoning.
+ *
+ * Not awaited by `onSettled`: the mutation is finished once the server has
+ * answered, and a background refresh should not hold its lifecycle open.
+ *
+ * The rows are patched optimistically but the badge is NOT: it follows the
+ * server's confirmation, which buys a single writer at the cost of the badge
+ * trailing the row. Deriving it locally instead — recomputing the count from
+ * the list cache and writing that back — reads as instant but is unsound: a
+ * list cache proves only that the list was loaded ONCE, never that it is
+ * complete or concurrent with the summary, and the account-level summary
+ * request is not cancelled by the workspace-scoped `cancelQueries` below, so a
+ * response already in flight lands on top of the local value anyway. Under
+ * pagination it would be wrong by construction — one loaded page cannot
+ * produce a global count. If instant feedback is wanted later, it has to be a
+ * per-group delta that handles the race, not a recomputed total.
+ */
+function invalidateUnreadSummary(qc: QueryClient) {
+ void onInboxSummaryInvalidate(qc);
+}
+
export function useMarkInboxRead() {
const qc = useQueryClient();
const wsId = useWorkspaceId();
@@ -28,6 +63,7 @@ export function useMarkInboxRead() {
},
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -39,6 +75,7 @@ export function useRetrySourceContextQuickCreate() {
mutationFn: (taskId: string) => api.retrySourceContextQuickCreate(taskId),
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -51,10 +88,8 @@ export function useRetrySourceContextQuickCreate() {
* can be actioned from either list, and leaving the other one stale would show
* two different read states for one notification after a view switch.
*
- * The unread badge is derived from the main list's cache (`useInboxUnreadCount`
- * dedupes it client-side), so the optimistic patch raises the badge without
- * waiting for the round-trip; `onSettled` re-pulls the cross-workspace summary,
- * which is server-computed and cannot be patched here.
+ * The rows flip at once; the badge follows on settle — see
+ * {@link invalidateUnreadSummary} for why it is not patched locally.
*/
export function useMarkInboxUnread() {
const qc = useQueryClient();
@@ -79,7 +114,7 @@ export function useMarkInboxUnread() {
qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });
// The switcher dot must light again when the workspace goes back to
// having unread items — that count lives on the server.
- qc.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -110,6 +145,7 @@ export function useArchiveInbox() {
onSettled: () => {
// Both lists: the item just moved from the main inbox into the archive.
qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -153,7 +189,7 @@ export function useUnarchiveInbox() {
// Both lists: the item moves from one to the other, and the unread badge
// rises again when it was archived unread.
qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });
- qc.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -178,12 +214,14 @@ export function useMarkAllInboxRead() {
},
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
// The three batch-archive mutations below all move items into the archive, so
-// each invalidates BOTH lists on settle.
+// each invalidates BOTH lists on settle — plus the unread summary, since an
+// archived unread group leaves the badge.
export function useArchiveAllInbox() {
const qc = useQueryClient();
const wsId = useWorkspaceId();
@@ -191,6 +229,7 @@ export function useArchiveAllInbox() {
mutationFn: () => api.archiveAllInbox(),
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -202,6 +241,7 @@ export function useArchiveAllReadInbox() {
mutationFn: () => api.archiveAllReadInbox(),
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
@@ -213,6 +253,7 @@ export function useArchiveCompletedInbox() {
mutationFn: () => api.archiveCompletedInbox(),
onSettled: () => {
qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });
+ invalidateUnreadSummary(qc);
},
});
}
diff --git a/packages/core/inbox/queries.test.ts b/packages/core/inbox/queries.test.ts
index 7b652edbee..8b968211c4 100644
--- a/packages/core/inbox/queries.test.ts
+++ b/packages/core/inbox/queries.test.ts
@@ -5,6 +5,7 @@ import {
deduplicateInboxItems,
hasOtherWorkspaceUnread,
inboxKeys,
+ unreadCountForWorkspace,
unreadWorkspaceIds,
} from "./queries";
@@ -215,3 +216,31 @@ describe("inboxKeys.unreadSummary", () => {
expect(inboxKeys.unreadSummary()).toEqual(["inbox", "unread-summary"]);
});
});
+
+// The inbox nav / tab / dock badges all read this instead of counting the
+// inbox list, so that the count costs no list fetch (MUL-6967).
+describe("unreadCountForWorkspace", () => {
+ const summary: InboxWorkspaceUnread[] = [
+ { workspace_id: "ws-1", count: 3 },
+ { workspace_id: "ws-2", count: 7 },
+ ];
+
+ it("returns the requested workspace's count", () => {
+ expect(unreadCountForWorkspace(summary, "ws-2")).toBe(7);
+ });
+
+ it("reads an absent workspace as zero", () => {
+ // The endpoint omits workspaces with nothing unread rather than sending a
+ // zero row, so "missing" must mean 0 and not "unknown".
+ expect(unreadCountForWorkspace(summary, "ws-3")).toBe(0);
+ });
+
+ it("returns zero without a workspace", () => {
+ expect(unreadCountForWorkspace(summary, null)).toBe(0);
+ expect(unreadCountForWorkspace(summary, undefined)).toBe(0);
+ });
+
+ it("returns zero for an empty summary", () => {
+ expect(unreadCountForWorkspace([], "ws-1")).toBe(0);
+ });
+});
diff --git a/packages/core/inbox/queries.ts b/packages/core/inbox/queries.ts
index e93b7bff37..c4d0fdb080 100644
--- a/packages/core/inbox/queries.ts
+++ b/packages/core/inbox/queries.ts
@@ -68,17 +68,39 @@ export function unreadWorkspaceIds(summary: InboxWorkspaceUnread[]): Set<string>
}
/**
- * Unread inbox count for the given workspace, aligned with what the inbox
- * list UI renders: archived items excluded, then deduplicated by issue so a
- * single issue with three unread notifications counts once.
+ * Unread inbox count for one workspace within the cross-workspace summary.
+ * A workspace with nothing unread is absent from the response entirely, so a
+ * missing entry means zero rather than "not loaded yet".
+ */
+export function unreadCountForWorkspace(
+ summary: InboxWorkspaceUnread[],
+ wsId: string | null | undefined,
+): number {
+ if (!wsId) return 0;
+ return summary.find((s) => s.workspace_id === wsId)?.count ?? 0;
+}
+
+/**
+ * Unread inbox count for the given workspace — the number the sidebar nav
+ * badge and the desktop dock badge render.
+ *
+ * Read from the cross-workspace summary, NOT from the inbox list. The summary
+ * is one small server-computed row per workspace and the sidebar already
+ * fetches it for the workspace-switcher dot, so the badge costs no request of
+ * its own; deriving it from `listInbox()` instead downloaded the entire
+ * unbounded inbox on every app start just to render a number (MUL-6967).
+ *
+ * `GET /api/inbox/unread-count` is deliberately not the source: it counts raw
+ * notification rows, while the inbox renders one row per issue. The summary
+ * endpoint applies the same newest-per-issue rule `deduplicateInboxItems`
+ * applies client-side, so this number matches the list the user sees.
*/
export function useInboxUnreadCount(wsId: string | null | undefined): number {
const { data } = useQuery({
- queryKey: inboxKeys.list(wsId ?? ""),
- queryFn: () => api.listInbox(),
+ ...inboxUnreadSummaryOptions(),
enabled: !!wsId,
- select: (items: InboxItem[]) =>
- deduplicateInboxItems(items).filter((i) => !i.read).length,
+ select: (summary: InboxWorkspaceUnread[]) =>
+ unreadCountForWorkspace(summary, wsId),
});
return data ?? 0;
}
diff --git a/packages/core/inbox/ws-updaters.test.ts b/packages/core/inbox/ws-updaters.test.ts
index 0ac8b6ec29..ed23269ff3 100644
--- a/packages/core/inbox/ws-updaters.test.ts
+++ b/packages/core/inbox/ws-updaters.test.ts
@@ -76,6 +76,23 @@ describe("onInboxIssueDeleted", () => {
expect(() => onInboxIssueDeleted(qc, wsId, "issue-a")).not.toThrow();
expect(qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId))).toBeUndefined();
});
+
+ it("refreshes the unread summary, which the dropped rows can change", async () => {
+ // The badge reads the server summary, not these lists (MUL-6967). Deletion
+ // arrives as an `issue:*` event, so no `inbox:*` handler runs to refresh
+ // it, and the summary query is staleTime: Infinity with no refetch on
+ // focus — without this the badge stays lit over an empty inbox.
+ const qc = new QueryClient();
+ const spy = vi.spyOn(qc, "invalidateQueries");
+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), [
+ makeItem("i1", "issue-a", { read: false }),
+ ]);
+
+ await onInboxIssueDeleted(qc, wsId, "issue-a");
+
+ expect(qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId))).toEqual([]);
+ expect(spy).toHaveBeenCalledWith({ queryKey: inboxKeys.unreadSummary() });
+ });
});
describe("onInboxInvalidate", () => {
@@ -106,21 +123,46 @@ describe("onInboxInvalidate", () => {
});
describe("onInboxSummaryInvalidate", () => {
- it("invalidates the account-level summary key regardless of active workspace", () => {
+ it("invalidates the account-level summary key regardless of active workspace", async () => {
const qc = new QueryClient();
const spy = vi.spyOn(qc, "invalidateQueries");
- onInboxSummaryInvalidate(qc);
+ await onInboxSummaryInvalidate(qc);
expect(spy).toHaveBeenCalledWith({ queryKey: inboxKeys.unreadSummary() });
});
- it("does not disturb a workspace-scoped inbox list cache", () => {
+ it("cancels an in-flight summary request BEFORE invalidating", async () => {
+ // Order is the whole point. TanStack skips its own cancel on a first fetch
+ // (`Query.fetch` guards it on `state.data !== undefined`) and hands back
+ // the request already on the wire, whose success then clears
+ // `isInvalidated` — so invalidating without cancelling first can be
+ // answered by a pre-change response and never asked again (MUL-6967).
+ const qc = new QueryClient();
+ const calls: string[] = [];
+ vi.spyOn(qc, "cancelQueries").mockImplementation(async () => {
+ calls.push("cancel");
+ });
+ vi.spyOn(qc, "invalidateQueries").mockImplementation(async () => {
+ calls.push("invalidate");
+ });
+
+ await onInboxSummaryInvalidate(qc);
+
+ expect(calls).toEqual(["cancel", "invalidate"]);
+ });
+
+ it("cancels only the summary key, never a workspace inbox list", async () => {
+ // A list request in flight for the active workspace must survive: the
+ // cancel is aimed at the account-level summary alone.
const qc = new QueryClient();
+ const cancel = vi.spyOn(qc, "cancelQueries");
qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), [makeItem("i1", "issue-a")]);
- onInboxSummaryInvalidate(qc);
+ await onInboxSummaryInvalidate(qc);
+ expect(cancel).toHaveBeenCalledWith({ queryKey: inboxKeys.unreadSummary() });
+ expect(cancel).not.toHaveBeenCalledWith({ queryKey: inboxKeys.list(wsId) });
// The list cache entry is untouched (different key); only the summary
// query is marked stale.
expect(qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId))?.[0]?.id).toBe("i1");
diff --git a/packages/core/inbox/ws-updaters.ts b/packages/core/inbox/ws-updaters.ts
index 90e4458965..37ffb09f0b 100644
--- a/packages/core/inbox/ws-updaters.ts
+++ b/packages/core/inbox/ws-updaters.ts
@@ -71,7 +71,14 @@ export function onInboxIssueStatusChanged(
// is deleted, all inbox items that referenced it are gone server-side, so drop
// them from the cache too — from the archived list as well, which holds rows
// for the same issues.
-export function onInboxIssueDeleted(
+//
+// Dropping unread rows changes the unread badge, which reads the server-side
+// summary rather than these lists, so the summary is refreshed here too. It
+// has to happen inside this updater and not at the call site: deletion is an
+// `issue:*` event, so no `inbox:*` handler runs to pick it up, and the summary
+// query is `staleTime: Infinity` with no refetch on focus — nothing else would
+// ever correct it, leaving the badge stuck above an empty inbox (MUL-6967).
+export async function onInboxIssueDeleted(
qc: QueryClient,
wsId: string,
issueId: string,
@@ -80,6 +87,7 @@ export function onInboxIssueDeleted(
old?.filter((i) => i.issue_id !== issueId);
qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), drop);
qc.setQueryData<InboxItem[]>(inboxKeys.archived(wsId), drop);
+ await onInboxSummaryInvalidate(qc);
}
// Refresh both the main and archived lists. Every inbox event can move an item
@@ -90,11 +98,33 @@ export function onInboxInvalidate(qc: QueryClient, wsId: string) {
qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });
}
-// Refresh the cross-workspace unread summary (workspace-switcher dot). The
-// summary spans every workspace, so it is invalidated on ANY inbox event
+// THE entry point for refreshing the cross-workspace unread summary — the
+// workspace-switcher dot and the Inbox unread badge. Every writer goes through
+// here: inbox mutations, inbox events, issue deletion, and reconnect. The
+// summary spans every workspace, so it is refreshed on ANY inbox event
// regardless of which workspace the event came from — including read/archive
// events from a workspace other than the active one, which the workspace-
// scoped list invalidation cannot reach.
-export function onInboxSummaryInvalidate(qc: QueryClient) {
- qc.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });
+//
+// Cancelling before invalidating is load-bearing, not defensive. TanStack only
+// cancels an in-flight request on invalidation once the query already holds
+// data — `Query.fetch` guards that branch on `state.data !== undefined` and
+// otherwise hands back the in-flight promise:
+//
+// if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {
+// this.cancel({ silent: true })
+// } else if (this.#retryer) {
+// return this.#retryer.promise // ← the pre-change request
+// }
+//
+// So an invalidation that races the FIRST summary load is answered by the
+// response that was already on the wire, which then resolves successfully and
+// clears `isInvalidated`. With `staleTime: Infinity` and no refetch on focus,
+// nothing would ever ask again: the badge would sit on a count the user's own
+// action had already invalidated, until some unrelated event happened to
+// refresh it. Cancelling first makes a refresh behave identically whether or
+// not the summary has loaded yet (MUL-6967).
+export async function onInboxSummaryInvalidate(qc: QueryClient) {
+ await qc.cancelQueries({ queryKey: inboxKeys.unreadSummary() });
+ await qc.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });
}
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index 4645c95789..512916fea8 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -2,7 +2,7 @@
* @vitest-environment jsdom
*/
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { renderHook } from "@testing-library/react";
+import { renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import type { WSClient } from "../api/ws-client";
@@ -101,7 +101,7 @@ describe("useRealtimeSync — ws instance change", () => {
expect(invalidateSpy).not.toHaveBeenCalled();
});
- it("invalidates exactly once when a new ws instance appears after null gap", () => {
+ it("invalidates exactly once when a new ws instance appears after null gap", async () => {
const ws1 = createMockWs();
const { rerender } = renderHook(
({ ws }) => useRealtimeSync(ws, stores),
@@ -120,8 +120,12 @@ describe("useRealtimeSync — ws instance change", () => {
// (16 workspace-scoped [incl. property definitions] + 6 per-issue
// prefixes + the workspace working-agents projection + 5 per-chat
// prefixes + 1 workspaceKeys.list() + 1 cross-workspace inbox unread
- // summary = 31 calls)
- expect(invalidateSpy).toHaveBeenCalledTimes(31);
+ // summary = 31 calls).
+ //
+ // Awaited rather than counted synchronously: the inbox unread summary
+ // refresh cancels any in-flight request before invalidating (see
+ // onInboxSummaryInvalidate), so that one lands after the synchronous ones.
+ await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(31));
});
it("does not re-invalidate when rerendered with the same ws instance", () => {
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 00d036da94..6f7a4a8f1c 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -567,7 +567,7 @@ export async function handleInboxNew(
if (sourceWsId) onInboxNew(qc, sourceWsId, item);
// A new item in ANY workspace can light the workspace-switcher dot, so
// refresh the cross-workspace summary regardless of the active workspace.
- onInboxSummaryInvalidate(qc);
+ void onInboxSummaryInvalidate(qc);
// Fire a native OS notification only when the app isn't focused. When
// the user is already looking at Multica, the inbox sidebar's unread
// styling is enough — no need to interrupt with a banner. `desktopAPI`
@@ -666,7 +666,7 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {
}
// Cross-workspace, so outside the wsId guard: a reconnect may have missed
// inbox events from any workspace, so re-pull the switcher-dot summary.
- onInboxSummaryInvalidate(qc);
+ void onInboxSummaryInvalidate(qc);
// Per-issue caches are keyed without wsId, so the issueKeys.all(wsId)
// prefix above does not reach them. They rely entirely on WS events for
// freshness (staleTime: Infinity), so events missed while disconnected
@@ -759,7 +759,7 @@ export function useRealtimeSync(
// refresh the cross-workspace summary — its dot must clear when another
// workspace's items are read/archived, and light again when an unread
// item is restored from the archive.
- onInboxSummaryInvalidate(qc);
+ void onInboxSummaryInvalidate(qc);
},
agent: () => {
const wsId = getCurrentWsId();
@@ -1024,7 +1024,7 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) {
onIssueDeleted(qc, wsId, issue_id);
- onInboxIssueDeleted(qc, wsId, issue_id);
+ void onInboxIssueDeleted(qc, wsId, issue_id);
}
});
diff --git a/packages/views/layout/app-sidebar.test.tsx b/packages/views/layout/app-sidebar.test.tsx
index 53da38dcd3..582e37c925 100644
--- a/packages/views/layout/app-sidebar.test.tsx
+++ b/packages/views/layout/app-sidebar.test.tsx
@@ -4,14 +4,13 @@ import { ApiError } from "@multica/core/api";
import { renderWithI18n } from "../test/i18n";
import { AppSidebar } from "./app-sidebar";
-const { appForeground, chatSessions, chatStore, detail, deletePin, inboxItems, navigation, pins, sidebarState, summary, workspaces } = vi.hoisted(() => ({
+const { appForeground, chatSessions, chatStore, detail, deletePin, navigation, pins, sidebarState, summary, workspaces } = vi.hoisted(() => ({
appForeground: { current: true },
sidebarState: { setOpenMobile: vi.fn() },
chatSessions: { current: [] as { id?: string; unread_count?: number }[] },
chatStore: { current: { activeSessionId: null as string | null, isOpen: false } },
detail: { current: { isPending: false, isError: false, data: null as unknown, error: null as unknown } },
deletePin: vi.fn(),
- inboxItems: { current: [] as { id: string; read: boolean }[] },
navigation: { current: { pathname: "/acme/issues" } },
summary: { current: [] as { workspace_id: string; count: number }[] },
workspaces: {
@@ -151,9 +150,11 @@ vi.mock("@multica/core/api", async (importOriginal) => {
};
});
vi.mock("@multica/core/inbox/queries", () => ({
- deduplicateInboxItems: (items: unknown[]) => items,
- inboxKeys: { list: () => ["inbox"], unreadSummary: () => ["inbox", "unread-summary"] },
inboxUnreadSummaryOptions: () => ({ queryKey: ["inbox", "unread-summary"] }),
+ // The nav badge and the switcher dot read the SAME cross-workspace summary,
+ // so the fixture that drives one drives the other.
+ useInboxUnreadCount: (currentWsId: string | null) =>
+ summary.current.find((s) => s.workspace_id === currentWsId)?.count ?? 0,
hasOtherWorkspaceUnread: (
entries: { workspace_id: string; count: number }[],
currentWsId: string | null,
@@ -183,7 +184,6 @@ vi.mock("@tanstack/react-query", async (importOriginal) => ({
if (queryKey[0] === "pins") return { data: pins.current };
if (queryKey[0] === "issue") return detail.current;
if (queryKey[0] === "inbox" && queryKey[1] === "unread-summary") return { data: summary.current };
- if (queryKey[0] === "inbox") return { data: inboxItems.current };
if (queryKey[0] === "workspaces") return { data: workspaces.current };
if (queryKey[0] === "chat" && queryKey[2] === "sessions") return { data: chatSessions.current };
return { data: [] };
@@ -391,7 +391,7 @@ describe("navigation item presentation", () => {
describe("personal nav — Chat", () => {
beforeEach(() => {
chatSessions.current = [];
- inboxItems.current = [];
+ summary.current = [];
navigation.current = { pathname: "/acme/issues" };
chatStore.current = { activeSessionId: null, isOpen: false };
appForeground.current = true;
@@ -405,7 +405,7 @@ describe("personal nav — Chat", () => {
chatNav(container)?.querySelector("number-flow-react") ?? null;
it("keeps persistent Inbox and Chat counters static", () => {
- inboxItems.current = [{ id: "inbox-1", read: false }];
+ summary.current = [{ workspace_id: "ws-1", count: 1 }];
chatSessions.current = [{ id: "chat-1", unread_count: 2 }];
const { container } = render(<AppSidebar />);
const inboxBadge = container
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
index a062f1c3bd..53d18f62e4 100644
--- a/packages/views/layout/app-sidebar.tsx
+++ b/packages/views/layout/app-sidebar.tsx
@@ -67,7 +67,7 @@ import { useCurrentWorkspace, useWorkspacePaths, paths } from "@multica/core/pat
import { workspaceListOptions, myInvitationListOptions, workspaceKeys } from "@multica/core/workspace/queries";
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
-import { inboxKeys, deduplicateInboxItems, inboxUnreadSummaryOptions, hasOtherWorkspaceUnread, unreadWorkspaceIds } from "@multica/core/inbox/queries";
+import { inboxUnreadSummaryOptions, useInboxUnreadCount, hasOtherWorkspaceUnread, unreadWorkspaceIds } from "@multica/core/inbox/queries";
import { chatSessionsOptions } from "@multica/core/chat/queries";
import { countUnreadChatMessages } from "@multica/core/chat/unread";
import { useChatStore } from "@multica/core/chat";
@@ -104,7 +104,6 @@ function isNavActive(pathname: string, href: string): boolean {
const EMPTY_PINS: PinnedItem[] = [];
const EMPTY_WORKSPACES: Awaited<ReturnType<typeof api.listWorkspaces>> = [];
const EMPTY_INVITATIONS: Awaited<ReturnType<typeof api.listMyInvitations>> = [];
-const EMPTY_INBOX: Awaited<ReturnType<typeof api.listInbox>> = [];
const EMPTY_INBOX_SUMMARY: Awaited<ReturnType<typeof api.getInboxUnreadSummary>> = [];
const PINNED_PREVIEW_LIMIT = 5;
@@ -454,15 +453,10 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
}, [pathname, setOpenMobile]);
const wsId = workspace?.id;
- const { data: inboxItems = EMPTY_INBOX } = useQuery({
- queryKey: wsId ? inboxKeys.list(wsId) : ["inbox", "disabled"],
- queryFn: () => api.listInbox(),
- enabled: !!wsId,
- });
- const unreadCount = React.useMemo(
- () => deduplicateInboxItems(inboxItems).filter((i) => !i.read).length,
- [inboxItems],
- );
+ // Nav badge. Reads the cross-workspace unread summary fetched just below
+ // for the switcher dot, so the count costs no request of its own — it used
+ // to download the whole inbox list here just to count it (MUL-6967).
+ const unreadCount = useInboxUnreadCount(wsId);
// Chat tab unread badge: IM-style total of unread *messages* across chat
// threads (countUnreadChatMessages is the shared definition — mobile's tab
// badge derives from the same function, keeping the platforms in agreement).
diff --git a/packages/views/layout/tab-presentation.test.tsx b/packages/views/layout/tab-presentation.test.tsx
index bdbc604b21..41c6f1abec 100644
--- a/packages/views/layout/tab-presentation.test.tsx
+++ b/packages/views/layout/tab-presentation.test.tsx
@@ -170,16 +170,69 @@ describe("useTabPresentation — live from cache", () => {
});
});
- it("archived inbox: selected issue resolves against the archived list", () => {
- // a1 lives only in the archived list; without ?view=archived it must NOT
- // resolve (title stays Inbox), and with it, it resolves to i1's title.
- expect(presentationOf("/acme/inbox?issue=i1").title).toBe("Inbox");
+ it("issue-backed selection resolves by object, in either view", () => {
+ // The selection key IS the group key (`issue_id ?? id`), so an
+ // issue-backed selection names the issue directly and is answered by the
+ // issue cache — no inbox list involved. That holds in both views on
+ // purpose: i1's notification lives only in the ARCHIVED list, yet the main
+ // view still titles the tab by the object the URL names. Treating "not in
+ // the list I loaded" as "does not exist" is what this must not do — the
+ // page itself resolves such a link to the issue rather than dropping it
+ // (see the deep-link fallback in inbox-page).
+ expect(presentationOf("/acme/inbox?issue=i1")).toEqual({
+ visual: { kind: "icon", icon: "Inbox" },
+ title: "MUL-1: Fix login",
+ });
expect(presentationOf("/acme/inbox?view=archived&issue=i1")).toEqual({
visual: { kind: "icon", icon: "Inbox" },
title: "MUL-1: Fix login",
});
});
+ it("issue-backed selection survives a cold inbox list", () => {
+ // Regression (MUL-6967): the badge no longer pre-warms the inbox list at
+ // app start, so a restored tab may have the issue cached but no list. It
+ // must still show the issue, not collapse to the container label.
+ const qc = makeClient();
+ seed(qc);
+ qc.removeQueries({ queryKey: inboxListOptions("ws1").queryKey });
+ qc.removeQueries({ queryKey: archivedInboxListOptions("ws1").queryKey });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+
+ const { result } = renderHook(
+ () => useTabPresentation("/acme/inbox?issue=i9", "MUL-9: Crash"),
+ { wrapper },
+ );
+
+ expect(result.current.title).toBe("MUL-9: Crash");
+ });
+
+ it("falls back to the persisted title while a selection is unresolved", () => {
+ // Nothing cached for this key yet — an issue-less notification whose row
+ // has not loaded. The persisted title is a better first frame than
+ // "Inbox"; without it the tab loses its identity until the page loads.
+ const qc = makeClient();
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ );
+
+ const { result } = renderHook(
+ () => useTabPresentation("/acme/inbox?issue=n7", "Autopilot paused"),
+ { wrapper },
+ );
+
+ expect(result.current.title).toBe("Autopilot paused");
+ });
+
+ it("uses the container label when nothing is selected, persisted title or not", () => {
+ // The fallback is for a PENDING identity only. An Inbox tab with no
+ // selection is fully resolved — it really is just "Inbox", and a stale
+ // persisted title must not override it.
+ expect(presentationOf("/acme/inbox", "MUL-9: Crash").title).toBe("Inbox");
+ });
+
it("archived inbox: selected non-issue resolves against the archived list", () => {
expect(presentationOf("/acme/inbox?view=archived&issue=a2")).toEqual({
visual: { kind: "icon", icon: "Inbox" },
diff --git a/packages/views/layout/tab-presentation.tsx b/packages/views/layout/tab-presentation.tsx
index bc19989358..8f3ad3b595 100644
--- a/packages/views/layout/tab-presentation.tsx
+++ b/packages/views/layout/tab-presentation.tsx
@@ -94,10 +94,20 @@ function useTabEntityData(subject: TabSubject, wsId: string): TabEntityData {
: null;
// One issue query serves both a direct issue tab and an inbox-selected issue.
+ //
+ // An inbox selection resolves straight from `selectedKey`: it IS the key the
+ // inbox groups by (`issue_id ?? id`), so for an issue-backed notification it
+ // already IS the issue id, and the hop through the list row was redundant.
+ // Going direct means a restored tab resolves from the issue cache alone,
+ // instead of silently depending on someone having fetched the whole Inbox
+ // first (MUL-6967). A key that is an issue-less notification's own id simply
+ // matches no issue, and falls through to the item branch below.
const issueId =
subject.kind === "issue"
? subject.id
- : (inboxItem?.issue_id ?? "");
+ : subject.kind === "inbox"
+ ? (subject.selectedKey ?? "")
+ : "";
// An issue tab's URL segment may be a human-readable identifier (`MUL-123`).
// The route seeds that entry when it resolves, but only the UUID-keyed entry
// receives realtime patches — so hop through it, or a tab opened by
@@ -182,37 +192,54 @@ function useTabEntityData(subject: TabSubject, wsId: string): TabEntityData {
}
break;
case "inbox":
- if (inboxItem) {
- if (inboxItem.issue_id && issue) {
- data.inboxSelection = {
- kind: "issue",
- identifier: issue.identifier,
- title: issue.title,
- };
- } else if (!inboxItem.issue_id) {
- data.inboxSelection = {
- kind: "item",
- title: getInboxDisplayTitle(inboxItem),
- };
- }
+ if (issue) {
+ // Issue-backed selection — answered by the issue cache alone.
+ data.inboxSelection = {
+ kind: "issue",
+ identifier: issue.identifier,
+ title: issue.title,
+ };
+ } else if (inboxItem && !inboxItem.issue_id) {
+ // An issue-less notification (autopilot paused, quota exceeded, …)
+ // carries its title only on the inbox row, so this branch is the one
+ // case that still needs the list cache.
+ data.inboxSelection = {
+ kind: "item",
+ title: getInboxDisplayTitle(inboxItem),
+ };
}
break;
}
return data;
}
-/** Localize a title spec, preferring a persisted fallback while pending. */
-function useTabTitle(spec: TabTitleSpec, fallbackTitle?: string): string {
+/**
+ * Localize a title spec, preferring a persisted fallback while pending.
+ *
+ * `pending` is for identities the spec cannot report as pending on its own. A
+ * resource tab that has not loaded resolves to its type label, which
+ * `PENDING_RESOURCE_KEYS` recognizes; a CONTAINER tab with an unresolved
+ * selection resolves to the container's own nav label, which is
+ * indistinguishable from a container with nothing selected — so the caller,
+ * which still has the subject, decides.
+ */
+function useTabTitle(
+ spec: TabTitleSpec,
+ fallbackTitle?: string,
+ pending = false,
+): string {
const { t: layoutT } = useT("layout");
+ const persisted = fallbackTitle?.trim();
switch (spec.kind) {
case "text":
return spec.text;
case "nav":
- return layoutT(($) => $.nav[spec.navKey]);
+ return pending && persisted
+ ? persisted
+ : layoutT(($) => $.nav[spec.navKey]);
case "tab": {
- if (PENDING_RESOURCE_KEYS.has(spec.tabKey)) {
- const clean = fallbackTitle?.trim();
- if (clean) return clean;
+ if (pending || PENDING_RESOURCE_KEYS.has(spec.tabKey)) {
+ if (persisted) return persisted;
}
return layoutT(($) => $.tab[spec.tabKey]);
}
@@ -240,7 +267,12 @@ export function useTabPresentation(
const wsId = ws?.id ?? "";
const data = useTabEntityData(subject, wsId);
const { visual, title: titleSpec } = resolveTabPresentation(subject, data);
- const title = useTabTitle(titleSpec, fallbackTitle);
+ // A selected notification whose identity has not resolved from cache yet is
+ // pending in exactly the sense a not-yet-loaded issue is — keep the tab's
+ // persisted title instead of collapsing it to the bare container label.
+ const selectionPending =
+ subject.kind === "inbox" && !!subject.selectedKey && !data.inboxSelection;
+ const title = useTabTitle(titleSpec, fallbackTitle, selectionPending);
// The actor avatar resolves through workspace directory queries and throws
// if rendered before the workspace exists. Until it does, show a type icon.