Skip to content

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

Go

MUL-9635 fix(inbox): retry busy inbox reads and show a load error instead of an empty Inbox (#10959)

Multica Eve32fc2ad9a412
diff --git a/apps/mobile/data/query-client.ts b/apps/mobile/data/query-client.ts
index b46ac9784c..262075c7f4 100644
--- a/apps/mobile/data/query-client.ts
+++ b/apps/mobile/data/query-client.ts
@@ -32,8 +32,9 @@ export const queryClient = new QueryClient({
},
});
-// Match web/desktop: keep the previous inbox result on overload and let the
-// next event or refresh fetch again, without changing other queries' retries.
+// Keep the previous inbox result on overload and let the next event or
+// refresh fetch again, without changing other queries' retries. The inbox
+// screen shows a load error with a retry when nothing has loaded yet.
queryClient.setQueryDefaults(["inbox"], {
retry: (failureCount, error) =>
(error as { status?: number } | null)?.status !== 503 && failureCount < 1,
diff --git a/docs/inbox-read-protection.md b/docs/inbox-read-protection.md
index c16f9f71d9..0d66fc02e4 100644
--- a/docs/inbox-read-protection.md
+++ b/docs/inbox-read-protection.md
@@ -29,11 +29,15 @@ bounded to execution concurrency plus twenty per process.
Capacity exhaustion, connection acquisition deadlines and database statement
timeouts return `503` with `Retry-After: 1`. Other database errors remain `500`.
-Web, desktop and mobile forward cancellation and skip automatic inbox retries
-on 503. They retain cached data on a failed refresh; a subsequent inbox event
-or explicit refresh can fetch again. Existing archive queries already disable
-retries. Older clients may still retry, but
-server execution and waiting remain bounded.
+Web, desktop and mobile forward cancellation and retain cached data on a
+failed refresh. Web and desktop retry a live inbox read that fails with 503
+(or 408, 429, 502, 504, or a network error) up to three times, waiting at least
+`Retry-After` and backing off exponentially from one second with up to 25%
+jitter (`packages/core/inbox/retry.ts`), so one read sends at most four
+requests. When every attempt fails before anything loaded, the Inbox shows a
+load error with a retry button instead of an empty list. Mobile skips
+automatic retries on 503 and shows its load error. Archive queries disable
+retries. Server execution and waiting remain bounded whatever the client does.
## Configuration and monitoring
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index c2d0639a90..674402b39b 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -681,16 +681,31 @@ export class ApiError extends Error {
// error fields like `code` so callers can branch on machine-readable
// identifiers instead of pattern-matching the human-readable message.
readonly body?: unknown;
+ // How long the server asked the client to wait before trying again, from a
+ // `Retry-After` header (seconds or an HTTP date). Absent when not sent.
+ readonly retryAfterMs?: number;
- constructor(message: string, status: number, statusText: string, body?: unknown) {
+ constructor(message: string, status: number, statusText: string, body?: unknown, retryAfterMs?: number) {
super(message);
this.name = "ApiError";
this.status = status;
this.statusText = statusText;
this.body = body;
+ if (retryAfterMs !== undefined) this.retryAfterMs = retryAfterMs;
}
}
+/** A `Retry-After` value in milliseconds, or undefined when absent or unreadable. */
+export function parseRetryAfter(value: string | null, now = Date.now()): number | undefined {
+ if (!value) return undefined;
+ const trimmed = value.trim();
+ if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1000;
+ // An HTTP date names its weekday and month; anything else is unreadable.
+ if (!/[a-z]/i.test(trimmed)) return undefined;
+ const at = Date.parse(trimmed);
+ return Number.isNaN(at) ? undefined : Math.max(0, at - now);
+}
+
function assertAgentConversationStartersWriteSupported(data: {
conversation_starters?: unknown;
}): void {
@@ -1263,7 +1278,7 @@ export class ApiClient {
const logLevel = res.status === 404 ? "warn" : "error";
this.logger[logLevel](`← ${res.status} ${path}`, { rid, duration: `${Date.now() - start}ms`, error: message });
observer?.onEnd({ requestId: rid, status: res.status, error: message });
- throw new ApiError(message, res.status, res.statusText, body);
+ throw new ApiError(message, res.status, res.statusText, body, parseRetryAfter(res.headers.get("Retry-After")));
}
this.logger.info(`← ${res.status} ${path}`, { rid, duration: `${Date.now() - start}ms` });
diff --git a/packages/core/inbox/index.ts b/packages/core/inbox/index.ts
index bffe60d4c3..07f9e5ab00 100644
--- a/packages/core/inbox/index.ts
+++ b/packages/core/inbox/index.ts
@@ -2,3 +2,4 @@ export * from "./queries";
export * from "./mutations";
export * from "./ws-updaters";
export * from "./snooze";
+export * from "./retry";
diff --git a/packages/core/inbox/overload.test.ts b/packages/core/inbox/overload.test.ts
index 6b9f75ad3a..bfb224adef 100644
--- a/packages/core/inbox/overload.test.ts
+++ b/packages/core/inbox/overload.test.ts
@@ -4,6 +4,7 @@ import { QueryClient } from "@tanstack/react-query";
import { ApiClient, ApiError, setApiInstance } from "../api";
import { createQueryClient } from "../query-client";
import { inboxKeys, inboxUnreadSummaryOptions } from "./queries";
+import { INBOX_TRANSIENT_RETRIES } from "./retry";
afterEach(() => vi.unstubAllGlobals());
@@ -18,10 +19,12 @@ it.each(["listInbox", "listSnoozedInbox", "getInboxUnreadSummary"] as const)(
},
);
-it("keeps cached counts on 503 without retrying, then refreshes on the next request", async () => {
+it("retries a busy summary after Retry-After, keeping cached counts until it answers", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
const summary = [{ workspace_id: "ws-1", count: 3 }];
+ const busy = () => Response.json({ error: "busy" }, { status: 503, headers: { "Retry-After": "2" } });
const fetch = vi.fn()
- .mockResolvedValueOnce(Response.json({ error: "busy" }, { status: 503, headers: { "Retry-After": "1" } }))
+ .mockResolvedValueOnce(busy())
.mockResolvedValueOnce(Response.json([{ workspace_id: "ws-1", count: 4 }]));
vi.stubGlobal("fetch", fetch);
setApiInstance(new ApiClient("https://api.example.test"));
@@ -29,12 +32,38 @@ it("keeps cached counts on 503 without retrying, then refreshes on the next requ
qc.setQueryData(inboxKeys.unreadSummary(), summary);
const options = { ...inboxUnreadSummaryOptions(), staleTime: 0 };
try {
- await expect(qc.fetchQuery(options)).rejects.toBeInstanceOf(ApiError);
+ const result = qc.fetchQuery(options);
+ await vi.advanceTimersByTimeAsync(1999);
+ // Not before the server said to come back.
expect(fetch).toHaveBeenCalledTimes(1);
expect(qc.getQueryData(inboxKeys.unreadSummary())).toEqual(summary);
- await expect(qc.fetchQuery(options)).resolves.toEqual([{ workspace_id: "ws-1", count: 4 }]);
+ await vi.advanceTimersByTimeAsync(1000);
+ await expect(result).resolves.toEqual([{ workspace_id: "ws-1", count: 4 }]);
expect(fetch).toHaveBeenCalledTimes(2);
- } finally { qc.clear(); }
+ } finally {
+ qc.clear();
+ vi.useRealTimers();
+ }
+});
+
+it("gives up on a server that stays busy after three retries, keeping cached counts", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ const summary = [{ workspace_id: "ws-1", count: 3 }];
+ const fetch = vi.fn(async () => Response.json({ error: "busy" }, { status: 503, headers: { "Retry-After": "1" } }));
+ vi.stubGlobal("fetch", fetch);
+ setApiInstance(new ApiClient("https://api.example.test"));
+ const qc = createQueryClient();
+ qc.setQueryData(inboxKeys.unreadSummary(), summary);
+ try {
+ const result = qc.fetchQuery({ ...inboxUnreadSummaryOptions(), staleTime: 0 }).catch((error: unknown) => error);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(await result).toBeInstanceOf(ApiError);
+ expect(fetch).toHaveBeenCalledTimes(1 + INBOX_TRANSIENT_RETRIES);
+ expect(qc.getQueryData(inboxKeys.unreadSummary())).toEqual(summary);
+ } finally {
+ qc.clear();
+ vi.useRealTimers();
+ }
});
it("Query cancellation aborts the superseded summary HTTP request", async () => {
@@ -56,13 +85,13 @@ it("Query cancellation aborts the superseded summary HTTP request", async () =>
});
it("does not depend on an API error class to recognize overload", async () => {
- const busy = Object.assign(new Error("busy"), { status: 503 });
- const getInboxUnreadSummary = vi.fn().mockRejectedValue(busy);
+ const busy = Object.assign(new Error("busy"), { status: 503, retryAfterMs: 0 });
+ const getInboxUnreadSummary = vi.fn().mockRejectedValueOnce(busy).mockResolvedValue([]);
setApiInstance({ getInboxUnreadSummary } as unknown as ApiClient);
const qc = createQueryClient();
try {
- await expect(qc.fetchQuery(inboxUnreadSummaryOptions())).rejects.toBe(busy);
- expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);
+ await expect(qc.fetchQuery({ ...inboxUnreadSummaryOptions(), retryDelay: 0 })).resolves.toEqual([]);
+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(2);
} finally { qc.clear(); }
});
diff --git a/packages/core/inbox/retry.test.ts b/packages/core/inbox/retry.test.ts
new file mode 100644
index 0000000000..9c423b35b6
--- /dev/null
+++ b/packages/core/inbox/retry.test.ts
@@ -0,0 +1,77 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { ApiError, parseRetryAfter } from "../api/client";
+import { INBOX_TRANSIENT_RETRIES, inboxQueryRetry, inboxQueryRetryDelay, isTransientInboxError } from "./retry";
+
+const status = (code: number, retryAfterMs?: number) => new ApiError("failed", code, "", undefined, retryAfterMs);
+
+describe("isTransientInboxError", () => {
+ it.each([408, 429, 502, 503, 504])("treats %i as worth another try", (code) => {
+ expect(isTransientInboxError(status(code))).toBe(true);
+ });
+
+ it.each([400, 401, 403, 404, 500])("treats %i as an answer", (code) => {
+ expect(isTransientInboxError(status(code))).toBe(false);
+ });
+
+ it("treats a request that never got an answer as transient, and other errors as not", () => {
+ expect(isTransientInboxError(new TypeError("Failed to fetch"))).toBe(true);
+ expect(isTransientInboxError(new DOMException("Aborted", "AbortError"))).toBe(false);
+ expect(isTransientInboxError(new Error("parse"))).toBe(false);
+ expect(isTransientInboxError(null)).toBe(false);
+ });
+});
+
+describe("inboxQueryRetry", () => {
+ it("retries a transient failure a bounded number of times", () => {
+ const tries = Array.from({ length: 6 }, (_, n) => inboxQueryRetry(n, status(503)));
+ expect(tries.filter(Boolean)).toHaveLength(INBOX_TRANSIENT_RETRIES);
+ expect(tries.slice(0, INBOX_TRANSIENT_RETRIES).every(Boolean)).toBe(true);
+ });
+
+ it("retries any other failure once, as every other query does", () => {
+ expect(inboxQueryRetry(0, status(500))).toBe(true);
+ expect(inboxQueryRetry(1, status(500))).toBe(false);
+ });
+});
+
+describe("inboxQueryRetryDelay", () => {
+ const none = () => 0;
+ const most = () => 1;
+
+ it("backs off exponentially from one second, capped", () => {
+ expect([0, 1, 2, 3, 4, 10].map((n) => inboxQueryRetryDelay(n, status(503), none))).toEqual([
+ 1000, 2000, 4000, 8000, 8000, 8000,
+ ]);
+ });
+
+ it("never comes back before Retry-After", () => {
+ expect(inboxQueryRetryDelay(0, status(503, 5000), none)).toBe(5000);
+ expect(inboxQueryRetryDelay(0, status(503, 60_000), none)).toBe(60_000);
+ // A shorter Retry-After does not cut the backoff.
+ expect(inboxQueryRetryDelay(2, status(503, 1000), none)).toBe(4000);
+ });
+
+ it("spreads clients by up to a quarter of the delay", () => {
+ expect(inboxQueryRetryDelay(0, status(503, 1000), most)).toBe(1250);
+ expect(inboxQueryRetryDelay(1, status(503), most)).toBe(2500);
+ });
+});
+
+describe("parseRetryAfter", () => {
+ const now = Date.parse("2026-11-19T00:00:00Z");
+
+ it("reads seconds and HTTP dates", () => {
+ expect(parseRetryAfter("1", now)).toBe(1000);
+ expect(parseRetryAfter(" 0 ", now)).toBe(0);
+ expect(parseRetryAfter("Thu, 19 Nov 2026 00:00:03 GMT", now)).toBe(3000);
+ expect(parseRetryAfter("Wed, 18 Nov 2026 23:59:00 GMT", now)).toBe(0);
+ });
+
+ it("ignores a missing or unreadable header", () => {
+ expect(parseRetryAfter(null, now)).toBeUndefined();
+ expect(parseRetryAfter("", now)).toBeUndefined();
+ expect(parseRetryAfter("soon", now)).toBeUndefined();
+ expect(parseRetryAfter("-1", now)).toBeUndefined();
+ });
+});
diff --git a/packages/core/inbox/retry.ts b/packages/core/inbox/retry.ts
new file mode 100644
index 0000000000..4e6b941b9f
--- /dev/null
+++ b/packages/core/inbox/retry.ts
@@ -0,0 +1,57 @@
+/**
+ * Retry policy for inbox reads (MUL-9635).
+ *
+ * The server bounds inbox reads and answers `503` with `Retry-After` when it
+ * is busy (docs/inbox-read-protection.md). One busy answer must not leave the
+ * Inbox looking empty until the next refresh, so a transient failure is tried
+ * again a few times — never sooner than the server asked, backing off and
+ * spreading clients apart so a busy server is not hit in lockstep. Any other
+ * failure keeps the app-wide single retry.
+ */
+
+/** Statuses that say "try again shortly", not "this request is wrong". */
+const TRANSIENT_STATUSES = new Set([408, 429, 502, 503, 504]);
+
+/** Retries after a transient failure, so at most four requests per read. */
+export const INBOX_TRANSIENT_RETRIES = 3;
+/** Retries after any other failure: the app-wide default. */
+const OTHER_RETRIES = 1;
+
+const BASE_DELAY_MS = 1000;
+const MAX_BACKOFF_MS = 8000;
+const JITTER = 0.25;
+
+function errorStatus(error: unknown): number | undefined {
+ const status = (error as { status?: unknown } | null)?.status;
+ return typeof status === "number" ? status : undefined;
+}
+
+/**
+ * Whether a failed inbox read is worth trying again shortly: the server said
+ * it is busy or unreachable, or the request never got an answer. Read off the
+ * error's shape, not its class, so mocked or differently built clients count.
+ */
+export function isTransientInboxError(error: unknown): boolean {
+ const status = errorStatus(error);
+ if (status !== undefined) return TRANSIENT_STATUSES.has(status);
+ // `fetch` rejects with a TypeError when the request could not be sent.
+ return error instanceof TypeError;
+}
+
+/** TanStack `retry`: `failureCount` is how many attempts have already been retried. */
+export function inboxQueryRetry(failureCount: number, error: unknown): boolean {
+ return failureCount < (isTransientInboxError(error) ? INBOX_TRANSIENT_RETRIES : OTHER_RETRIES);
+}
+
+/**
+ * TanStack `retryDelay`: exponential backoff from one second, never earlier
+ * than the server's `Retry-After`, plus up to a quarter more so clients that
+ * failed together do not come back together.
+ */
+export function inboxQueryRetryDelay(failureCount: number, error: unknown, random: () => number = Math.random): number {
+ const backoff = Math.min(BASE_DELAY_MS * 2 ** failureCount, MAX_BACKOFF_MS);
+ const retryAfter = (error as { retryAfterMs?: unknown } | null)?.retryAfterMs;
+ const floor = typeof retryAfter === "number" && retryAfter > 0 ? retryAfter : 0;
+ const delay = Math.max(backoff, floor);
+ return Math.round(delay * (1 + JITTER * random()));
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index 36bf4a5180..1a150ddee1 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -71,6 +71,7 @@
"./inbox": "./inbox/index.ts",
"./inbox/group": "./inbox/group.ts",
"./inbox/queries": "./inbox/queries.ts",
+ "./inbox/retry": "./inbox/retry.ts",
"./inbox/mutations": "./inbox/mutations.ts",
"./inbox/filter-store": "./inbox/filter-store.ts",
"./inbox/selection-store": "./inbox/selection-store.ts",
diff --git a/packages/core/query-client.ts b/packages/core/query-client.ts
index 7c515fd3f2..a1e718b595 100644
--- a/packages/core/query-client.ts
+++ b/packages/core/query-client.ts
@@ -1,4 +1,5 @@
import { QueryClient } from "@tanstack/react-query";
+import { inboxQueryRetry, inboxQueryRetryDelay } from "./inbox/retry";
import { setWorkspaceSlugLookup } from "./paths/workspace-slugs";
import { workspaceKeys } from "./workspace/queries";
import type { Workspace } from "./types";
@@ -19,11 +20,12 @@ export function createQueryClient(): QueryClient {
},
});
// Keep the policy on the app client so custom clients and explicit query
- // overrides retain their retry settings. Status checks also work across
- // mocked API modules and different client error classes.
+ // overrides retain their retry settings. A busy server (503 + Retry-After)
+ // is tried again a few times with backoff instead of leaving the Inbox
+ // looking empty (MUL-9635); see ./inbox/retry.
client.setQueryDefaults(["inbox"], {
- retry: (failureCount, error) =>
- (error as { status?: number } | null)?.status !== 503 && failureCount < 1,
+ retry: inboxQueryRetry,
+ retryDelay: (failureCount, error) => inboxQueryRetryDelay(failureCount, error),
});
return client;
}
diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsx
index 1600207010..bd504b76eb 100644
--- a/packages/views/inbox/components/inbox-page.test.tsx
+++ b/packages/views/inbox/components/inbox-page.test.tsx
@@ -1,4 +1,4 @@
-import { act, fireEvent, render, screen } from "@testing-library/react";
+import { act, fireEvent, render, screen, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { toast } from "sonner";
import type { AgentTask, InboxItem } from "@multica/core/types";
@@ -24,6 +24,9 @@ const listData: { active: InboxItem[]; archived: InboxItem[]; lookup?: InboxItem
const NO_SNOOZED: never[] = [];
const queryCalls: Array<{ queryKey: readonly unknown[]; enabled?: boolean }> = [];
const lookupState = { isLoading: false, isError: false, refetch: vi.fn() };
+// The active list as a read that failed before anything loaded, and is
+// possibly being tried again.
+const activeFailure = { failed: false, retrying: false, refetch: vi.fn() };
const queryClient = vi.hoisted(() => ({ setQueryData: vi.fn() }));
vi.mock("@tanstack/react-query", () => ({
queryOptions: (options: unknown) => options,
@@ -39,6 +42,11 @@ vi.mock("@tanstack/react-query", () => ({
isError: false,
refetch: vi.fn(),
...(options.queryKey.includes("lookup") ? lookupState : {}),
+ ...(options.queryKey.at(-1) === "list" && activeFailure.failed
+ ? activeFailure.retrying
+ ? { data: undefined, isError: false, isLoading: true, isFetching: true, errorUpdateCount: 1, refetch: activeFailure.refetch }
+ : { data: undefined, isError: true, isFetching: false, errorUpdateCount: 1, refetch: activeFailure.refetch }
+ : {}),
}); },
useInfiniteQuery: (options: { queryKey: readonly unknown[]; enabled?: boolean }) => {
queryCalls.push(options);
@@ -266,6 +274,9 @@ function reset() {
lookupState.isLoading = false;
lookupState.isError = false;
lookupState.refetch.mockClear();
+ activeFailure.failed = false;
+ activeFailure.retrying = false;
+ activeFailure.refetch.mockClear();
queryCalls.length = 0;
searchParams = new URLSearchParams();
replace.mockClear();
@@ -443,6 +454,40 @@ describe("InboxPage", () => {
expect(screen.queryByTestId("issue-detail")).toBeNull();
});
+ // A list that never loaded is not an empty Inbox (MUL-9635).
+ it.each([
+ ["a phone", PHONE],
+ ["desktop", DESKTOP],
+ ])("on %s, offers another try when the Inbox could not load, not an empty Inbox", (_device, width) => {
+ reset();
+ layout.width = width;
+ activeFailure.failed = true;
+
+ render(<InboxPage />);
+
+ const alert = screen.getByRole("alert");
+ expect(screen.queryByTestId("list")).toBeNull();
+ fireEvent.click(within(alert).getByRole("button"));
+ expect(activeFailure.refetch).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ ["a phone", PHONE],
+ ["desktop", DESKTOP],
+ ])("on %s, keeps the load error while it is tried again", (_device, width) => {
+ reset();
+ layout.width = width;
+ activeFailure.failed = true;
+ activeFailure.retrying = true;
+ searchParams = new URLSearchParams("issue=issue-1");
+
+ render(<InboxPage />);
+
+ expect(within(screen.getByRole("alert")).getByRole("button")).toBeDisabled();
+ // Still unknown, so the open notification is not sent to its issue page.
+ expect(replace).not.toHaveBeenCalled();
+ });
+
// The live Inbox lives in the Work panel; the archive has nowhere else to list.
it("lists the archive in its own column on desktop", () => {
reset();
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 7a6a2ad33c..ff3ff76504 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -7,6 +7,7 @@ import {
useDeferredValue,
useMemo,
useRef,
+ type ReactNode,
} from "react";
import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";
import { useWorkspaceId } from "@multica/core/hooks";
@@ -119,7 +120,7 @@ import {
} from "./inbox-display";
import { AutopilotQuotaNotice } from "./autopilot-quota-notice";
import { InboxKeptActions, useKeptInboxRowText } from "./inbox-kept-actions";
-import { useFilteredInboxRows } from "./use-filtered-inbox-rows";
+import { inboxListLoad, useFilteredInboxRows } from "./use-filtered-inbox-rows";
import { useKeptOpenInboxRow } from "./use-kept-open-inbox-row";
import { useArchiveInboxBatchWithUndo, useArchiveInboxWithUndo, useRestoreInbox } from "./use-leave-inbox-row";
import { useInboxSnooze } from "./use-inbox-snooze";
@@ -173,6 +174,9 @@ export function InboxPage() {
...inboxListOptions(wsId), enabled: !isArchivedView,
});
const { data: rawItems = [], isLoading: loading } = inboxQuery;
+ // The live list never loaded (a refresh that fails keeps the loaded one).
+ // An empty list is not an empty Inbox then.
+ const liveFailed = !isArchivedView && inboxListLoad(inboxQuery) === "failed";
const items = useMemo(() => deduplicateInboxItems(rawItems), [rawItems]);
// The filters read every notification of an issue, not just its newest.
const activeRows = useMemo(() => rawItems.filter((item) => !item.archived), [rawItems]);
@@ -300,7 +304,7 @@ export function InboxPage() {
// Inbox zero: the bleeding m rises once, at the moment the last notification
// leaves; opening an already-empty inbox shows it at rest. Archived and
// filtered views are not inbox zero, so they never arm it.
- const inboxZeroCount = isArchivedView || hasActiveFilters ? -1 : visibleItems.length;
+ const inboxZeroCount = isArchivedView || hasActiveFilters || liveFailed ? -1 : visibleItems.length;
const [prevInboxZeroCount, setPrevInboxZeroCount] = useState(inboxZeroCount);
const [inboxZeroRises, setInboxZeroRises] = useState(false);
if (inboxZeroCount !== prevInboxZeroCount) {
@@ -376,8 +380,9 @@ export function InboxPage() {
// A targeted lookup must not hide pages that have already loaded. Its
// pending/error states only block resolution of the off-page selection.
- const viewLoading = isArchivedView ? archivedLoading : loading;
- const viewError = isArchivedView ? archivedError : inboxQuery.isError && !inboxQuery.data;
+ // A list that failed and is being tried again keeps its error, not a skeleton.
+ const viewLoading = isArchivedView ? archivedLoading : loading && !liveFailed;
+ const viewError = isArchivedView ? archivedError : liveFailed;
const needsLookup = isArchivedView && !!selectedKey && !selectedOnPage;
const lookupLoading = needsLookup && (lookup.isLoading || presence.isLoading);
const lookupError = needsLookup && (lookup.isError || presence.isError) && !selected;
@@ -829,16 +834,28 @@ export function InboxPage() {
</PanelHeader>
);
+ const liveLoadFailed = (
+ <LoadFailed
+ icon={<Inbox className="mb-3 h-8 w-8 text-faint-foreground" />}
+ message={t(($) => $.errors.load_failed)}
+ retryLabel={t(($) => $.list.retry)}
+ retrying={inboxQuery.isFetching}
+ onRetry={() => void inboxQuery.refetch()}
+ />
+ );
+
const list = isArchivedView && archivedError ? (
<div className="flex-1 min-h-0 overflow-y-auto">
- <div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
- <Archive className="mb-3 h-8 w-8 text-faint-foreground" />
- <p className="text-body">{t(($) => $.errors.archived_load_failed)}</p>
- <Button variant="outline" size="sm" className="mt-3" onClick={() => void archiveQuery.refetch()}>
- {t(($) => $.list.retry)}
- </Button>
- </div>
+ <LoadFailed
+ icon={<Archive className="mb-3 h-8 w-8 text-faint-foreground" />}
+ message={t(($) => $.errors.archived_load_failed)}
+ retryLabel={t(($) => $.list.retry)}
+ retrying={archiveQuery.isFetching}
+ onRetry={() => void archiveQuery.refetch()}
+ />
</div>
+ ) : liveFailed ? (
+ <div className="flex-1 min-h-0 overflow-y-auto">{liveLoadFailed}</div>
) : (
<InboxContextMenuProvider
view={view}
@@ -1216,6 +1233,9 @@ export function InboxPage() {
</h1>
</PageHeader>
)}
+ {liveFailed ? (
+ <div className="flex min-h-0 flex-1 flex-col justify-center">{liveLoadFailed}</div>
+ ) : (
<div className="relative flex min-h-0 flex-1 flex-col items-center justify-center overflow-hidden text-muted-foreground">
{inboxZeroCount === 0 ? (
<MulticaBleedMark
@@ -1234,6 +1254,7 @@ export function InboxPage() {
: t(($) => $.detail.empty)}
</p>
</div>
+ )}
</>
);
@@ -1284,3 +1305,28 @@ export function InboxPage() {
</div>
);
}
+
+/** A list that could not load, with another try; never an empty list. */
+function LoadFailed({
+ icon,
+ message,
+ retryLabel,
+ retrying,
+ onRetry,
+}: {
+ icon: ReactNode;
+ message: string;
+ retryLabel: string;
+ retrying: boolean;
+ onRetry: () => void;
+}) {
+ return (
+ <div role="alert" className="flex flex-col items-center justify-center py-16 text-muted-foreground">
+ {icon}
+ <p className="text-body">{message}</p>
+ <Button variant="outline" size="sm" className="mt-3" disabled={retrying} onClick={onRetry}>
+ {retryLabel}
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/views/inbox/components/use-filtered-inbox-rows.ts b/packages/views/inbox/components/use-filtered-inbox-rows.ts
index 1302999384..a8f2f72193 100644
--- a/packages/views/inbox/components/use-filtered-inbox-rows.ts
+++ b/packages/views/inbox/components/use-filtered-inbox-rows.ts
@@ -20,6 +20,25 @@ import { useKeptOpenInboxRow } from "./use-kept-open-inbox-row";
export const INBOX_SECTION_LIST = "section";
const EMPTY_INBOX: InboxItem[] = [];
+
+/** Where the live Inbox list stands: only a `loaded` list may read as empty. */
+export type InboxListLoad = "loading" | "loaded" | "failed";
+
+/**
+ * A list that has loaded stays `loaded` when a later refresh fails: its rows
+ * stay on screen rather than the Inbox emptying. One that failed stays
+ * `failed` while it is tried again: a new attempt resets the query to pending,
+ * and its retries can take seconds.
+ */
+export function inboxListLoad(query: {
+ data: unknown;
+ isError: boolean;
+ isFetching: boolean;
+ errorUpdateCount: number;
+}): InboxListLoad {
+ if (query.data !== undefined) return "loaded";
+ return query.isError || (query.errorUpdateCount > 0 && query.isFetching) ? "failed" : "loading";
+}
const EMPTY_TASKS: AgentTask[] = [];
/**
@@ -36,7 +55,8 @@ const EMPTY_TASKS: AgentTask[] = [];
* `enabled: false` reads nothing, for a caller that may not need the list.
*/
export function useFilteredInboxRows(wsId: string, openKey: string | null, enabled = true) {
- const { data: raw = EMPTY_INBOX } = useQuery({ ...inboxListOptions(wsId), enabled: enabled && !!wsId });
+ const query = useQuery({ ...inboxListOptions(wsId), enabled: enabled && !!wsId });
+ const raw = query.data ?? EMPTY_INBOX;
const stored = useInboxFilters(wsId);
// Every notification, not one per issue: the notification filters match any
// notification of an issue.
@@ -77,6 +97,14 @@ export function useFilteredInboxRows(wsId: string, openKey: string | null, enabl
return {
rows,
kept,
+ /**
+ * Whether the list has loaded. Only a list that loaded may read as empty:
+ * one still loading or that failed shows no rows without meaning there
+ * are none. A failed refresh of a loaded list keeps it as it was.
+ */
+ load: inboxListLoad(query),
+ retry: () => void query.refetch(),
+ retrying: query.isFetching,
notifications,
filtered: inboxFilterCount(filters) > 0,
priorityFilterSupport,
diff --git a/packages/views/layout/panels/inbox-section.test.tsx b/packages/views/layout/panels/inbox-section.test.tsx
index 3525aa56d3..73c4609dfd 100644
--- a/packages/views/layout/panels/inbox-section.test.tsx
+++ b/packages/views/layout/panels/inbox-section.test.tsx
@@ -1,7 +1,9 @@
import type { ReactNode } from "react";
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ApiError } from "@multica/core/api";
+import { createQueryClient } from "@multica/core/query-client";
import {
DEFAULT_SIDEBAR_INBOX_SETTINGS,
useSidebarTreeStore,
@@ -33,6 +35,11 @@ const state = vi.hoisted(() => ({
unsnooze: vi.fn(() => Promise.resolve()),
}));
+const apiMock = vi.hoisted(() => ({ listInbox: vi.fn() }));
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/api")>()),
+ api: apiMock,
+}));
vi.mock("@multica/core/paths", async (importOriginal) => {
const actual = await importOriginal<typeof import("@multica/core/paths")>();
return { ...actual, useWorkspacePaths: () => actual.paths.workspace("acme") };
@@ -712,3 +719,102 @@ describe("InboxSection with every row shown", () => {
expect(rows()).toHaveLength(30);
});
});
+
+describe("InboxSection while the Inbox loads", () => {
+ // The app's own client, so the inbox retry policy is the one under test.
+ function renderUnloaded() {
+ const client = createQueryClient();
+ client.setQueryData(snoozedInboxOptions("ws-1").queryKey, []);
+ client.setQueryData(agentListOptions("ws-1").queryKey, []);
+ client.setQueryData(agentTaskSnapshotOptions("ws-1").queryKey, []);
+ const nav = adapter("/acme/issues");
+ renderWithI18n(
+ <QueryClientProvider client={client}>
+ <NavigationProvider value={nav}>
+ <Harness activeIssueId={null} pathname={nav.pathname} openKey={null} />
+ </NavigationProvider>
+ </QueryClientProvider>,
+ );
+ return client;
+ }
+ const busy = () => new ApiError("inbox reads are busy", 503, "Service Unavailable", undefined, 1000);
+ const advance = (ms: number) => act(() => vi.advanceTimersByTimeAsync(ms));
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ apiMock.listInbox.mockReset();
+ });
+ afterEach(() => vi.useRealTimers());
+
+ it("shows the notifications once a busy server answers", async () => {
+ apiMock.listInbox
+ .mockRejectedValueOnce(busy())
+ .mockResolvedValue([item({ id: "n1", issue_id: "issue-a", title: "After the wait" })]);
+ renderUnloaded();
+ await advance(0);
+ // Waiting out Retry-After is not an empty Inbox.
+ expect(screen.queryByText("No notifications")).toBeNull();
+ expect(screen.queryByRole("alert")).toBeNull();
+
+ await advance(2000);
+ expect(apiMock.listInbox).toHaveBeenCalledTimes(2);
+ expect(rows().map((row) => row.textContent)).toEqual([expect.stringContaining("After the wait")]);
+ });
+
+ it("says the Inbox could not load, with a retry, when the server stays busy", async () => {
+ apiMock.listInbox.mockRejectedValue(busy());
+ renderUnloaded();
+ await advance(30_000);
+
+ expect(apiMock.listInbox).toHaveBeenCalledTimes(4);
+ expect(screen.getByRole("alert")).toHaveTextContent("Failed to load notifications");
+ expect(screen.queryByText("No notifications")).toBeNull();
+
+ apiMock.listInbox.mockResolvedValue([item({ id: "n1", issue_id: "issue-a", title: "Back again" })]);
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ await advance(0);
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(rows().map((row) => row.textContent)).toEqual([expect.stringContaining("Back again")]);
+ });
+
+ it("keeps saying it could not load while a retry waits on a busy server", async () => {
+ apiMock.listInbox.mockRejectedValue(busy());
+ renderUnloaded();
+ await advance(30_000);
+ expect(apiMock.listInbox).toHaveBeenCalledTimes(4);
+
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ await advance(0);
+ expect(apiMock.listInbox).toHaveBeenCalledTimes(5);
+ expect(screen.getByRole("alert")).toHaveTextContent("Failed to load notifications");
+ expect(screen.getByRole("button", { name: "Retry" })).toBeDisabled();
+
+ await advance(30_000);
+ expect(apiMock.listInbox).toHaveBeenCalledTimes(8);
+ expect(screen.getByRole("button", { name: "Retry" })).toBeEnabled();
+ });
+
+ it("says No notifications when the server answers with none", async () => {
+ apiMock.listInbox.mockResolvedValue([]);
+ renderUnloaded();
+ await advance(0);
+ expect(screen.getByText("No notifications")).toBeInTheDocument();
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+
+ it("keeps the rows it has when a refresh fails", async () => {
+ apiMock.listInbox.mockResolvedValueOnce([item({ id: "n1", issue_id: "issue-a", title: "Still here" })]);
+ const client = renderUnloaded();
+ await advance(0);
+ expect(rows()).toHaveLength(1);
+
+ apiMock.listInbox.mockRejectedValue(busy());
+ await act(async () => {
+ void client.invalidateQueries({ queryKey: ["inbox", "ws-1", "list"] });
+ });
+ await advance(30_000);
+ expect(apiMock.listInbox).toHaveBeenCalledTimes(5);
+ expect(rows().map((row) => row.textContent)).toEqual([expect.stringContaining("Still here")]);
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+});
diff --git a/packages/views/layout/panels/inbox-section.tsx b/packages/views/layout/panels/inbox-section.tsx
index a9f407bc16..f2ec8bf1de 100644
--- a/packages/views/layout/panels/inbox-section.tsx
+++ b/packages/views/layout/panels/inbox-section.tsx
@@ -270,6 +270,20 @@ export function InboxSection({
{displayed.map((item) => renderRow(item))}
</PanelList>
)
+ ) : list.load === "failed" ? (
+ // A list that never loaded is not an empty Inbox: say so and offer
+ // another try rather than "No notifications".
+ <div role="alert" className={cn(PANEL_ROW_CLASS, "pl-[2.375rem] text-caption text-faint-foreground")}>
+ <span className="min-w-0 flex-1 truncate">{tInbox(($) => $.errors.load_failed)}</span>
+ <button
+ type="button"
+ disabled={list.retrying}
+ className="shrink-0 rounded-md px-1 font-medium text-muted-foreground outline-none hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50"
+ onClick={list.retry}
+ >
+ {tInbox(($) => $.list.retry)}
+ </button>
+ </div>
) : list.filtered ? (
<div className={cn(PANEL_ROW_CLASS, "pl-[2.375rem] text-caption text-faint-foreground")}>
<span className="min-w-0 flex-1 truncate">{tInbox(($) => $.filters.empty)}</span>
@@ -281,11 +295,11 @@ export function InboxSection({
{tInbox(($) => $.filters.clear)}
</button>
</div>
- ) : (
+ ) : list.load === "loaded" ? (
<p className={cn(PANEL_ROW_CLASS, "pl-[2.375rem] text-caption text-faint-foreground")}>
{t(($) => $.panels.work.inbox_empty)}
</p>
- )}
+ ) : null}
{all.length > limit && (
<button
type="button"
diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.json
index bd894d93a4..c17bfc4122 100644
--- a/packages/views/locales/en/inbox.json
+++ b/packages/views/locales/en/inbox.json
@@ -156,6 +156,7 @@
"archive_completed_failed": "Failed to archive completed",
"unarchive_failed": "Failed to unarchive",
"archived_load_failed": "Failed to load archived notifications",
+ "load_failed": "Failed to load notifications",
"filters_load_failed": "Could not load filters",
"delete_failed": "Failed to delete notification. Try again.",
"unsubscribe_archive_failed": "Failed to unsubscribe",
diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.json
index 7fadfd34dd..5ae46ae5f7 100644
--- a/packages/views/locales/es/inbox.json
+++ b/packages/views/locales/es/inbox.json
@@ -156,6 +156,7 @@
"archive_completed_failed": "No se ha podido archivar lo completado",
"unarchive_failed": "No se ha podido desarchivar",
"archived_load_failed": "No se han podido cargar las notificaciones archivadas",
+ "load_failed": "No se han podido cargar las notificaciones",
"filters_load_failed": "No se han podido cargar los filtros",
"delete_failed": "No se pudo eliminar la notificación. Inténtalo de nuevo.",
"unsubscribe_archive_failed": "No se pudo dar de baja",
diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.json
index 302dcd831a..b31755db7d 100644
--- a/packages/views/locales/fr/inbox.json
+++ b/packages/views/locales/fr/inbox.json
@@ -156,6 +156,7 @@
"archive_completed_failed": "Échec de l'archivage des éléments terminés",
"unarchive_failed": "Échec du désarchivage",
"archived_load_failed": "Échec du chargement des notifications archivées",
+ "load_failed": "Échec du chargement des notifications",
"filters_load_failed": "Impossible de charger les filtres",
"delete_failed": "Impossible de supprimer la notification. Réessayez.",
"unsubscribe_archive_failed": "Échec du désabonnement",
diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.json
index 6ab39b8de1..5a16e9c34c 100644
--- a/packages/views/locales/ja/inbox.json
+++ b/packages/views/locales/ja/inbox.json
@@ -153,6 +153,7 @@
"archive_completed_failed": "完了した項目をアーカイブできませんでした",
"unarchive_failed": "アーカイブ解除に失敗しました",
"archived_load_failed": "アーカイブ済み通知を読み込めませんでした",
+ "load_failed": "通知を読み込めませんでした",
"filters_load_failed": "フィルターを読み込めませんでした",
"delete_failed": "通知を削除できませんでした。もう一度お試しください。",
"unsubscribe_archive_failed": "購読解除に失敗しました",
diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.json
index bb88537967..5d2f74aa9c 100644
--- a/packages/views/locales/ko/inbox.json
+++ b/packages/views/locales/ko/inbox.json
@@ -153,6 +153,7 @@
"archive_completed_failed": "완료된 항목을 보관하지 못했습니다",
"unarchive_failed": "보관 해제에 실패했습니다",
"archived_load_failed": "보관된 알림을 불러오지 못했습니다",
+ "load_failed": "알림을 불러오지 못했습니다",
"filters_load_failed": "필터를 불러올 수 없습니다",
"delete_failed": "알림을 삭제하지 못했습니다. 다시 시도해 주세요.",
"unsubscribe_archive_failed": "구독 해제에 실패했습니다",
diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.json
index 97ce08ac1c..b9bbf643d7 100644
--- a/packages/views/locales/ru/inbox.json
+++ b/packages/views/locales/ru/inbox.json
@@ -162,6 +162,7 @@
"archive_completed_failed": "Не удалось архивировать завершённые",
"unarchive_failed": "Не удалось восстановить из архива",
"archived_load_failed": "Не удалось загрузить архивные уведомления",
+ "load_failed": "Не удалось загрузить уведомления",
"filters_load_failed": "Не удалось загрузить фильтры",
"delete_failed": "Не удалось удалить уведомление. Попробуйте снова.",
"unsubscribe_archive_failed": "Не удалось отписаться",
diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.json
index b40f3f74de..99e37f9fb5 100644
--- a/packages/views/locales/zh-Hans/inbox.json
+++ b/packages/views/locales/zh-Hans/inbox.json
@@ -153,6 +153,7 @@
"archive_completed_failed": "归档已完成失败",
"unarchive_failed": "取消归档失败",
"archived_load_failed": "无法加载已归档通知",
+ "load_failed": "无法加载通知",
"filters_load_failed": "无法加载筛选项",
"delete_failed": "无法删除通知,请重试。",
"unsubscribe_archive_failed": "取消订阅失败",
diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.json
index 35ba82f801..8678352140 100644
--- a/packages/views/locales/zh-Hant/inbox.json
+++ b/packages/views/locales/zh-Hant/inbox.json
@@ -153,6 +153,7 @@
"archive_completed_failed": "歸檔已完成失敗",
"unarchive_failed": "取消歸檔失敗",
"archived_load_failed": "無法載入已歸檔通知",
+ "load_failed": "無法載入通知",
"filters_load_failed": "無法載入篩選項",
"delete_failed": "無法刪除通知,請重試。",
"unsubscribe_archive_failed": "取消訂閱失敗",