Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(inbox): stop the list falling behind the unread badge (#8290)
Bohan Jiang885ef12232bf
diff --git a/apps/mobile/data/mutations/inbox.ts b/apps/mobile/data/mutations/inbox.tsindex 759f9d5937..ef0f2c4426 100644--- a/apps/mobile/data/mutations/inbox.ts+++ b/apps/mobile/data/mutations/inbox.ts@@ -30,18 +30,21 @@ 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 {+ refreshInboxList,+ 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.+ * Re-read both inbox caches a write can change: the workspace list and the+ * cross-workspace unread summary that backs the tab badge. The summary lives+ * under its own account-level key, so refreshing the 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.+ * Deliberately the shared entry points rather than local copies: a mutation+ * racing a first load hits exactly the same in-flight hole a WS event does,+ * and a plain invalidate of the list would let it fall behind the badge.* 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.@@ -50,7 +53,8 @@ import { useWorkspaceStore } from "@/data/workspace-store";* 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) {+function refreshInboxAfterWrite(qc: QueryClient, wsId: string | null) {+ if (wsId) void refreshInboxList(qc, wsId);void refreshInboxUnreadSummary(qc);}@@ -75,8 +79,7 @@ export function useMarkInboxRead() {if (ctx?.prev) qc.setQueryData(ctx.key, ctx.prev);},onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -111,8 +114,7 @@ export function useArchiveInbox() {if (ctx?.prev) qc.setQueryData(ctx.key, ctx.prev);},onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -138,8 +140,7 @@ export function useMarkAllInboxRead() {if (ctx?.prev) qc.setQueryData(ctx.key, ctx.prev);},onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -155,8 +156,7 @@ export function useArchiveAllInbox() {return useMutation({mutationFn: () => api.archiveAllInbox(),onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -167,8 +167,7 @@ export function useArchiveAllReadInbox() {return useMutation({mutationFn: () => api.archiveAllReadInbox(),onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -179,8 +178,7 @@ export function useArchiveCompletedInbox() {return useMutation({mutationFn: () => api.archiveCompletedInbox(),onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}diff --git a/apps/mobile/data/realtime/inbox-ws-updaters.test.ts b/apps/mobile/data/realtime/inbox-ws-updaters.test.tsindex 24f1abf062..c45adeb6f4 100644--- a/apps/mobile/data/realtime/inbox-ws-updaters.test.ts+++ b/apps/mobile/data/realtime/inbox-ws-updaters.test.ts@@ -7,6 +7,7 @@ import { inboxKeys } from "@/data/queries/inbox";import {dropInboxItemsByIssue,patchInboxIssueStatus,+ refreshInboxList,refreshInboxUnreadSummary,} from "./inbox-ws-updaters";@@ -121,3 +122,36 @@ describe("patchInboxIssueStatus", () => {expect(invalidate).not.toHaveBeenCalled();});});++describe("refreshInboxList", () => {+ it("cancels the in-flight list request BEFORE invalidating", async () => {+ // Parity with web. Without the cancel, a change during the list's first+ // load is answered by the pre-change request and never re-read — the tab+ // badge (already cancel-first) then counts rows the list does not show+ // (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 refreshInboxList(qc, wsId);++ expect(calls).toEqual(["cancel", "invalidate"]);+ });++ it("targets this workspace's list, never the account-level summary", async () => {+ const qc = new QueryClient();+ const cancel = vi.spyOn(qc, "cancelQueries");++ await refreshInboxList(qc, wsId);++ expect(cancel).toHaveBeenCalledWith({ queryKey: inboxKeys.list(wsId) });+ expect(cancel).not.toHaveBeenCalledWith({+ queryKey: inboxKeys.unreadSummary(),+ });+ });+});diff --git a/apps/mobile/data/realtime/inbox-ws-updaters.ts b/apps/mobile/data/realtime/inbox-ws-updaters.tsindex 08dfa89592..ea77bbac21 100644--- a/apps/mobile/data/realtime/inbox-ws-updaters.ts+++ b/apps/mobile/data/realtime/inbox-ws-updaters.ts@@ -14,7 +14,7 @@** Listing-level only; use-inbox-realtime wires these into the WS layer.*/-import type { QueryClient } from "@tanstack/react-query";+import type { QueryClient, QueryKey } from "@tanstack/react-query";import type { InboxItem, IssueStatus } from "@multica/core/types";import { inboxKeys } from "@/data/queries/inbox";@@ -32,23 +32,45 @@ export function patchInboxIssueStatus(}/**- * 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+ * Re-read a query because the server changed, in a way a request already on+ * the wire cannot answer. Mirrors `refreshInboxQuery` 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).+ * `state.data !== undefined`, and otherwise returns the in-flight promise). A+ * change during a query's FIRST load is therefore answered by the pre-change+ * response, which resolves successfully and clears `isInvalidated`, with+ * nothing scheduled to ask again. Cancelling first makes a refresh behave the+ * same whether or not the query has loaded yet (MUL-6967).+ *+ * Both inbox caches go through this, not only the badge: the tab badge and the+ * list it counts are separate reads, so a hole in either one surfaces as the+ * badge disagreeing with the rows on screen.+ */+async function refreshInboxQuery(qc: QueryClient, queryKey: QueryKey) {+ await qc.cancelQueries({ queryKey });+ await qc.invalidateQueries({ queryKey });+}++/**+ * THE entry point for refreshing the workspace inbox list. Inbox events,+ * mutations and reconnect all go through here. The list's first load is not+ * a one-off: the inbox tab is mounted lazily, so the first visit loads it+ * while notifications keep arriving.+ */+export async function refreshInboxList(qc: QueryClient, wsId: string) {+ await refreshInboxQuery(qc, inboxKeys.list(wsId));+}++/**+ * 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.*/export async function refreshInboxUnreadSummary(qc: QueryClient) {- await qc.cancelQueries({ queryKey: inboxKeys.unreadSummary() });- await qc.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });+ await refreshInboxQuery(qc, inboxKeys.unreadSummary());}// Dropping unread rows changes the tab badge, which reads the server-sidediff --git a/apps/mobile/data/realtime/use-inbox-realtime.ts b/apps/mobile/data/realtime/use-inbox-realtime.tsindex 8f767f49ee..aa18618173 100644--- a/apps/mobile/data/realtime/use-inbox-realtime.ts+++ b/apps/mobile/data/realtime/use-inbox-realtime.ts@@ -25,11 +25,11 @@* no replay buffer in v1).*/import { useQueryClient } from "@tanstack/react-query";-import { inboxKeys } from "@/data/queries/inbox";import { useWSSubscriptions } from "@/lib/use-ws-subscriptions";import {dropInboxItemsByIssue,patchInboxIssueStatus,+ refreshInboxList,refreshInboxUnreadSummary,} from "./inbox-ws-updaters";@@ -39,9 +39,10 @@ export function useInboxRealtime() {useWSSubscriptions((ws, wsId) => {const invalidate = () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });- // Shared entry point: it cancels an in-flight summary request before+ // Shared entry points: each cancels an in-flight request before// invalidating, which a plain invalidate cannot do on a first load.+ // Both caches, because the badge is rendered over the list it counts.+ void refreshInboxList(qc, wsId);void refreshInboxUnreadSummary(qc);};diff --git a/packages/core/inbox/badge-convergence.test.tsx b/packages/core/inbox/badge-convergence.test.tsxnew file mode 100644index 0000000000..0b0a0bd4a4--- /dev/null+++ b/packages/core/inbox/badge-convergence.test.tsx@@ -0,0 +1,243 @@+/** @vitest-environment jsdom */+import { act, cleanup, renderHook } from "@testing-library/react";+import { QueryClientProvider, useQuery } from "@tanstack/react-query";+import type { QueryClient } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, expect, it, vi } from "vitest";+import { setApiInstance } from "../api";+import type { ApiClient } from "../api/client";+import { createQueryClient } from "../query-client";+import type { InboxItem, InboxWorkspaceUnread } from "../types";+import { useMarkInboxRead } from "./mutations";+import {+ deduplicateInboxItems,+ inboxKeys,+ inboxListOptions,+ useInboxUnreadCount,+} from "./queries";+import {+ onInboxInvalidate,+ onInboxNew,+ onInboxSummaryInvalidate,+} from "./ws-updaters";++/**+ * The badge and the list it counts are two independent server reads, rendered+ * side by side. This pins the property that makes that safe (MUL-6967): once+ * everything settles, the badge equals the unread rows the list shows, and+ * both equal the server — whatever order responses and events arrive in.+ *+ * The first release shipped with the list violating it: "2 unread" over a list+ * with nothing unread. A change that landed while the list's FIRST load was in+ * flight was answered by that pre-change request and never re-read. The first+ * load is exercised repeatedly here on purpose, because in the app it is not a+ * one-off — nothing outside the Inbox page observes the list, so on web the+ * cache is collected while the user is elsewhere and every return is a first+ * load again.+ */++vi.mock("../hooks", () => ({ useWorkspaceId: () => "ws-1" }));+afterEach(cleanup);++const WS = "ws-1";+// Deterministic, so the range is a fixed set of interleavings. Seeds 4, 16 and+// 21 fail against the pre-fix code (a list refresh swallowed by the list's+// first load) — the range keeps them so this guard has proven teeth, at a+// fraction of the cost of a wider sweep. The mechanism itself is pinned+// directly in ws-updaters.test.ts; this covers the interleavings around it.+const SEEDS = 25;++// Deterministic PRNG, so a failing interleaving replays exactly by seed.+function mulberry32(seed: number) {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/**+ * A server with the grouping rule of CountUnreadInboxByWorkspace and+ * ListInboxItems. Each response is computed when the request ARRIVES but+ * handed back only when the scheduler releases it — the adversarial case,+ * where a response describing an older state lands after newer writes.+ */+class FakeServer {+ rows: InboxItem[] = [];+ private clock = 0;+ private seq = 0;++ notify(issueId: string): InboxItem {+ // Strictly increasing: each autocommit INSERT gets its own now().+ this.clock += 1;+ const row: InboxItem = {+ id: `n${++this.seq}`,+ workspace_id: WS,+ recipient_type: "member",+ recipient_id: "me",+ actor_type: "agent",+ actor_id: "agent",+ type: "new_comment",+ severity: "info",+ issue_id: issueId,+ title: issueId,+ body: null,+ issue_status: null,+ read: false,+ archived: false,+ created_at: new Date(Date.UTC(2026, 8, 1, 0, 0, this.clock)).toISOString(),+ details: null,+ };+ this.rows.push(row);+ return row;+ }++ markRead(id: string) {+ const row = this.rows.find((r) => r.id === id);+ if (row) row.read = true;+ }++ list(): InboxItem[] {+ return this.rows+ .filter((r) => !r.archived)+ .map((r) => ({ ...r }))+ .sort((a, b) => b.created_at.localeCompare(a.created_at));+ }++ unread(): number {+ return deduplicateInboxItems(this.list()).filter((r) => !r.read).length;+ }++ summary(): InboxWorkspaceUnread[] {+ const count = this.unread();+ return count > 0 ? [{ workspace_id: WS, count }] : [];+ }+}++async function tick() {+ await act(async () => {+ await new Promise((r) => setTimeout(r, 0));+ });+}++function unreadIn(list: InboxItem[] | undefined) {+ return deduplicateInboxItems(list ?? []).filter((r) => r.read !== true);+}++it.each(Array.from({ length: SEEDS }, (_, i) => i + 1))(+ "badge converges on the listed unread rows (seed %i)",+ async (seed) => {+ const rand = mulberry32(seed);+ const server = new FakeServer();+ for (const issue of ["i1", "i2", "i3"]) server.notify(issue);+ server.markRead("n2");++ const pending: Array<() => void> = [];+ const events: Array<(qc: QueryClient) => void> = [];+ const qc = createQueryClient();++ const deferred = <T,>(value: () => T): Promise<T> => {+ const snapshot = value();+ return new Promise<T>((resolve) => {+ pending.push(() => resolve(snapshot));+ });+ };++ setApiInstance({+ listInbox: vi.fn(() => deferred(() => server.list())),+ getInboxUnreadSummary: vi.fn(() => deferred(() => server.summary())),+ markInboxRead: vi.fn((id: string) => {+ // Commit, then publish: the event exists before the response does.+ server.markRead(id);+ events.push((c) => {+ void onInboxInvalidate(c, WS);+ void onInboxSummaryInvalidate(c);+ });+ return deferred(() => server.rows.find((r) => r.id === id)!);+ }),+ } as unknown as ApiClient);++ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ // The sidebar: always mounted, reads only the summary.+ const shell = renderHook(+ () => ({+ badge: useInboxUnreadCount(WS),+ markRead: useMarkInboxRead(),+ }),+ { wrapper },+ );+ // The Inbox page: the list's only observer, so it comes and goes.+ const mountPage = () =>+ renderHook(() => useQuery(inboxListOptions(WS)).data, { wrapper });+ let page: ReturnType<typeof mountPage> | null = mountPage();++ try {+ for (let step = 0; step < 40; step++) {+ const roll = rand();+ if (roll < 0.18) {+ const row = server.notify(`i${1 + Math.floor(rand() * 5)}`);+ events.push((c) => {+ void onInboxNew(c, WS, row);+ void onInboxSummaryInvalidate(c);+ });+ } else if (roll < 0.34 && page) {+ // The user opens an unread row the list is showing.+ const unread = unreadIn(page.result.current);+ if (unread.length > 0) {+ const target = unread[Math.floor(rand() * unread.length)]!;+ act(() => shell.result.current.markRead.mutate(target.id));+ }+ } else if (roll < 0.42) {+ // Leave the Inbox long enough for the list cache to be collected,+ // then come back — the next read is a first load again.+ if (page) {+ page.unmount();+ page = null;+ qc.removeQueries({ queryKey: inboxKeys.list(WS), exact: true });+ } else {+ page = mountPage();+ }+ } else if (roll < 0.75 && pending.length > 0) {+ // Release a random in-flight response — possibly a stale one.+ const [release] = pending.splice(Math.floor(rand() * pending.length), 1);+ await act(async () => release!());+ } else if (events.length > 0) {+ // Deliver the next event, in publish order.+ const event = events.shift()!;+ await act(async () => event(qc));+ }+ await tick();+ }++ // Drain: every event and response is eventually delivered, and the user+ // ends up back on the Inbox page.+ if (!page) page = mountPage();+ for (let guard = 0; guard < 500 && (pending.length || events.length); guard++) {+ const event = events.shift();+ if (event) await act(async () => event(qc));+ while (pending.length) {+ const [release] = pending.splice(Math.floor(rand() * pending.length), 1);+ await act(async () => release!());+ }+ for (let i = 0; i < 4; i++) await tick();+ }+ for (let i = 0; i < 6; i++) await tick();++ const truth = server.unread();+ expect({+ badge: shell.result.current.badge,+ listed: unreadIn(page.result.current).length,+ }).toEqual({ badge: truth, listed: truth });+ } finally {+ for (const release of pending) release();+ page?.unmount();+ shell.unmount();+ qc.clear();+ }+ },+);diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.tsindex 310901716d..0ba3e85ac4 100644--- a/packages/core/inbox/mutations.ts+++ b/packages/core/inbox/mutations.ts@@ -2,12 +2,13 @@ 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 { onInboxInvalidate, onInboxSummaryInvalidate } from "./ws-updaters";import { useWorkspaceId } from "../hooks";import type { InboxItem } from "../types";/**- * Refresh the cross-workspace unread summary after a write.+ * Re-read every inbox cache a write can change: both workspace lists and the+ * cross-workspace unread summary.** The unread badge reads that summary (`useInboxUnreadCount`), and it lives* under its own account-level key which `inboxKeys.all(wsId)` does not reach.@@ -15,10 +16,11 @@ import type { InboxItem } from "../types";* 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.+ * Deliberately the same entry points realtime uses, not local copies: both+ * refreshes have to cancel any in-flight request first, and a mutation racing+ * a first load hits exactly the same hole a WS event does. A plain+ * `invalidateQueries` on the list here would let the list fall behind the+ * badge — the two are rendered side by side (see `refreshInboxQuery`).** Not awaited by `onSettled`: the mutation is finished once the server has* answered, and a background refresh should not hold its lifecycle open.@@ -35,7 +37,8 @@ import type { InboxItem } from "../types";* 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) {+function refreshInboxAfterWrite(qc: QueryClient, wsId: string) {+ void onInboxInvalidate(qc, wsId);void onInboxSummaryInvalidate(qc);}@@ -62,8 +65,7 @@ export function useMarkInboxRead() {if (ctx?.prevArchived) qc.setQueryData(inboxKeys.archived(wsId), ctx.prevArchived);},onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -74,8 +76,7 @@ export function useRetrySourceContextQuickCreate() {return useMutation({mutationFn: (taskId: string) => api.retrySourceContextQuickCreate(taskId),onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -89,7 +90,7 @@ export function useRetrySourceContextQuickCreate() {* two different read states for one notification after a view switch.** The rows flip at once; the badge follows on settle — see- * {@link invalidateUnreadSummary} for why it is not patched locally.+ * {@link refreshInboxAfterWrite} for why it is not patched locally.*/export function useMarkInboxUnread() {const qc = useQueryClient();@@ -111,10 +112,9 @@ export function useMarkInboxUnread() {if (ctx?.prevArchived) qc.setQueryData(inboxKeys.archived(wsId), ctx.prevArchived);},onSettled: () => {- 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.- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -144,8 +144,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);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -188,8 +187,7 @@ export function useUnarchiveInbox() {onSettled: () => {// 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) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -213,8 +211,7 @@ export function useMarkAllInboxRead() {if (ctx?.prev) qc.setQueryData(inboxKeys.list(wsId), ctx.prev);},onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -228,8 +225,7 @@ export function useArchiveAllInbox() {return useMutation({mutationFn: () => api.archiveAllInbox(),onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -240,8 +236,7 @@ export function useArchiveAllReadInbox() {return useMutation({mutationFn: () => api.archiveAllReadInbox(),onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}@@ -252,8 +247,7 @@ export function useArchiveCompletedInbox() {return useMutation({mutationFn: () => api.archiveCompletedInbox(),onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });- invalidateUnreadSummary(qc);+ refreshInboxAfterWrite(qc, wsId);},});}diff --git a/packages/core/inbox/ws-updaters.test.ts b/packages/core/inbox/ws-updaters.test.tsindex ed23269ff3..4360054df2 100644--- a/packages/core/inbox/ws-updaters.test.ts+++ b/packages/core/inbox/ws-updaters.test.ts@@ -1,8 +1,9 @@import { describe, it, expect, vi } from "vitest";-import { QueryClient } from "@tanstack/react-query";+import { QueryClient, QueryObserver } from "@tanstack/react-query";import {onInboxInvalidate,onInboxIssueDeleted,+ onInboxNew,onInboxIssueStatusChanged,onInboxSummaryInvalidate,patchInboxIssueProjection,@@ -96,18 +97,18 @@ describe("onInboxIssueDeleted", () => {});describe("onInboxInvalidate", () => {- it("invalidates the workspace prefix, covering both the main and archived lists", () => {+ it("invalidates the workspace prefix, covering both the main and archived lists", async () => {// Every inbox event can move an item across the two lists, so they are// always refreshed together (MUL-3736).const qc = new QueryClient();const spy = vi.spyOn(qc, "invalidateQueries");- onInboxInvalidate(qc, wsId);+ await onInboxInvalidate(qc, wsId);expect(spy).toHaveBeenCalledWith({ queryKey: inboxKeys.all(wsId) });});- it("does not reach the account-level summary key", () => {+ it("does not reach the account-level summary key", async () => {// The summary is keyed ["inbox", "unread-summary"], NOT under the// workspace prefix — its own updater owns it.const qc = new QueryClient();@@ -116,12 +117,32 @@ describe("onInboxInvalidate", () => {.getQueryCache().find({ queryKey: inboxKeys.unreadSummary() });- onInboxInvalidate(qc, wsId);+ await onInboxInvalidate(qc, wsId);expect(summaryQuery?.state.isInvalidated).toBe(false);});});+describe("onInboxInvalidate ordering", () => {+ it("cancels the in-flight list request BEFORE invalidating", async () => {+ // Same reason as the summary: a change during the list's first load must+ // not be answered by the request already on the wire. See the MUL-6967+ // regression at the bottom of this file for the end-to-end sequence.+ 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 onInboxInvalidate(qc, wsId);++ expect(calls).toEqual(["cancel", "invalidate"]);+ });+});+describe("onInboxSummaryInvalidate", () => {it("invalidates the account-level summary key regardless of active workspace", async () => {const qc = new QueryClient();@@ -239,3 +260,54 @@ describe("patchInboxIssueProjection", () => {).not.toHaveProperty("issue_priority");});});++// MUL-6967 regression: the inbox list must pick up a change that happens while+// its FIRST load is still in flight. Plain invalidation cannot do that —+// TanStack only cancels an in-flight request on invalidation once the query+// holds data, and otherwise answers the refetch with the request already on+// the wire. That pre-change response then clears `isInvalidated`, and with+// `staleTime: Infinity` nothing asks again, so the list stays behind while the+// badge (whose refresh already cancels first) moves on — "2 unread" over a list+// with nothing unread. The first load is not rare: nothing outside the Inbox+// page observes the list, so on web every visit after the cache is collected+// is a first load again.+describe("inbox list refresh during the first load", () => {+ it.each([+ ["new notification", (qc: QueryClient) => onInboxNew(qc, wsId, makeItem("n2", "issue-b"))],+ ["read / archive event", (qc: QueryClient) => onInboxInvalidate(qc, wsId)],+ ])("re-reads the list after a %s arrives mid-load", async (_label, signal) => {+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });+ let releaseFirst!: (rows: InboxItem[]) => void;+ const firstResponse = new Promise<InboxItem[]>((resolve) => {+ releaseFirst = resolve;+ });+ let server: InboxItem[] = [makeItem("n1", "issue-a", { read: true })];+ const queryFn = vi+ .fn<() => Promise<InboxItem[]>>()+ .mockImplementationOnce(() => firstResponse)+ .mockImplementation(async () => server);+ const observer = new QueryObserver(qc, { queryKey: inboxKeys.list(wsId), queryFn });+ const unsubscribe = observer.subscribe(() => {});++ try {+ expect(queryFn).toHaveBeenCalledTimes(1);+ // The server changes while the first read is still on the wire...+ server = [makeItem("n2", "issue-b", { read: false }), ...server];+ await signal(qc);+ // ...and only then does the pre-change response land.+ releaseFirst([makeItem("n1", "issue-a", { read: true })]);++ await vi.waitFor(() =>+ expect(qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId))?.map((i) => i.id)).toEqual([+ "n2",+ "n1",+ ]),+ );+ expect(queryFn.mock.calls.length).toBeGreaterThan(1);+ } finally {+ releaseFirst([]);+ unsubscribe();+ qc.clear();+ }+ });+});diff --git a/packages/core/inbox/ws-updaters.ts b/packages/core/inbox/ws-updaters.tsindex 37ffb09f0b..b01676c2f1 100644--- a/packages/core/inbox/ws-updaters.ts+++ b/packages/core/inbox/ws-updaters.ts@@ -1,20 +1,47 @@-import type { QueryClient } from "@tanstack/react-query";+import type { QueryClient, QueryKey } from "@tanstack/react-query";import { inboxKeys } from "./queries";import type { InboxItem, IssuePriority, IssueStatus } from "../types";-export function onInboxNew(+// Re-read a query because the server changed — in a way that is never answered+// by a request that was already on the wire before the change.+//+// Plain invalidation does not give that guarantee. 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 request already in flight:+//+// if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {+// this.cancel({ silent: true })+// } else if (this.#retryer) {+// return this.#retryer.promise // ← the pre-change request+// }+//+// That branch exists to dedupe concurrent mounts, not to carry freshness. So a+// change that lands during a query's FIRST load is answered by the pre-change+// response, which resolves successfully and clears `isInvalidated`; with+// `staleTime: Infinity` and no refetch on focus, nothing asks again. Cancelling+// first makes a refresh behave the same whether or not the query has loaded.+//+// Every inbox cache is refreshed through here — both lists and the unread+// summary. They are rendered side by side (the badge next to the rows it+// counts), so a hole in either one shows up as the two disagreeing (MUL-6967).+async function refreshInboxQuery(qc: QueryClient, queryKey: QueryKey) {+ await qc.cancelQueries({ queryKey });+ await qc.invalidateQueries({ queryKey });+}++export async function onInboxNew(qc: QueryClient,wsId: string,_item: InboxItem,) {- // Use invalidateQueries instead of setQueryData — triggers a refetch that- // reliably notifies all observers. The inbox list is small so this is cheap.+ // Refetch instead of setQueryData, so every observer is notified.//// Both lists: a new notification on an ARCHIVED issue puts that issue back in// the main inbox, which means it must also leave the archived list. The// server owns that split (ListArchivedInboxItems excludes issues with an// active row), so refetching both is what keeps them mutually exclusive.- qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });+ await onInboxInvalidate(qc, wsId);}export function patchInboxIssueProjection(@@ -90,12 +117,18 @@ export async function onInboxIssueDeleted(await onInboxSummaryInvalidate(qc);}-// Refresh both the main and archived lists. Every inbox event can move an item-// across that boundary (archive, unarchive, or a new notification reviving an-// archived issue), and the split is decided server-side, so the two are always-// invalidated together.-export function onInboxInvalidate(qc: QueryClient, wsId: string) {- qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });+// THE entry point for refreshing the workspace's inbox lists — main and+// archived. Every inbox event can move an item across that boundary (archive,+// unarchive, or a new notification reviving an archived issue), and the split+// is decided server-side, so the two are always refreshed together.+//+// Cancels first, like the summary refresh below, and for the same reason. The+// list's first load is where the hole bites hardest: nothing outside the Inbox+// page observes the list, so on web it is collected once the user has been+// away, and every return is a first load again — with notifications arriving+// while a large, unbounded list is still downloading.+export async function onInboxInvalidate(qc: QueryClient, wsId: string) {+ await refreshInboxQuery(qc, inboxKeys.all(wsId));}// THE entry point for refreshing the cross-workspace unread summary — the@@ -104,27 +137,7 @@ export function onInboxInvalidate(qc: QueryClient, wsId: string) {// 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.-//-// 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).+// scoped list refresh cannot reach. Cancels first; see `refreshInboxQuery`.export async function onInboxSummaryInvalidate(qc: QueryClient) {- await qc.cancelQueries({ queryKey: inboxKeys.unreadSummary() });- await qc.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });+ await refreshInboxQuery(qc, inboxKeys.unreadSummary());}diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 6f7a4a8f1c..3d567673b3 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -45,7 +45,6 @@ import {invalidateUpdatedAtSortedIssueLists,} from "../issues/cache-coordinator";import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted, onInboxSummaryInvalidate } from "../inbox/ws-updaters";-import { inboxKeys } from "../inbox/queries";import {notificationPreferenceOptions,notificationPreferenceKeys,@@ -564,7 +563,7 @@ export async function handleInboxNew(item: InboxItem,): Promise<void> {const sourceWsId = item.workspace_id;- if (sourceWsId) onInboxNew(qc, sourceWsId, item);+ if (sourceWsId) void 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.void onInboxSummaryInvalidate(qc);@@ -643,7 +642,10 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {const wsId = getCurrentWsId();if (wsId) {qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });- qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });+ // Through the inbox's own entry point, not a plain invalidate: a reconnect+ // can land during the list's first load, and a plain invalidate would be+ // answered by the request already on the wire (see refreshInboxQuery).+ void onInboxInvalidate(qc, wsId);qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });qc.invalidateQueries({ queryKey: workspaceKeys.members(wsId) });qc.invalidateQueries({ queryKey: workspaceKeys.squads(wsId) });@@ -752,7 +754,7 @@ export function useRealtimeSync(const refreshMap: Record<string, () => void> = {inbox: () => {const wsId = getCurrentWsId();- if (wsId) onInboxInvalidate(qc, wsId);+ if (wsId) void onInboxInvalidate(qc, wsId);// inbox:read / inbox:archived / inbox:unarchived / batch events arrive// here. They can originate from a workspace other than the active one// (personal events fan out to all the user's connections), so always