From 08c0368bad53cf017cc69f5cfb4d6695faba7aa9 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 12:10:15 +0100 Subject: [PATCH 1/3] feat: refresh visible mailbox health and error reports from current server evidence every minute and on stale tab return --- docs/content/docs/guides/mailboxes.mdx | 2 + .../analytics/accountStatusRecovery.test.tsx | 131 ++++++++++++++++++ .../hooks/app/analytics/useAccountStatus.ts | 5 +- .../hooks/app/analytics/useAccountStatuses.ts | 3 + 4 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 web/src/lib/api/hooks/app/analytics/accountStatusRecovery.test.tsx diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index 73b8b832a..ee3ceb84f 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -642,6 +642,8 @@ The Accounts list groups mailboxes as **Healthy** (sending normally), **Warming* Repeated reports of the same error code count once toward the health score, at their highest unresolved severity, rather than making one problem look like several. The drawer groups identical reports while keeping different error details and sending versus sync failures separate. Connection titles name Gmail, Microsoft Outlook or the mail server. **Reported** shows the stored report time: connection and temporary provider-limit observations refresh it, while other error categories may retain their original report time. It is not proof of an ongoing outage. +While visible, the Accounts list and mailbox drawer refresh their health and error reports every minute as well as on relevant live events. Returning to a tab refreshes stale reports too. These reads show the server's latest recovery evidence; they do not reconnect a mailbox or retry a send. A failed status refresh does not count as recovery. + A later completed sync automatically clears earlier temporary sync errors. A provider-confirmed send clears earlier temporary sending errors, including provider throttling and quota warnings. Recovered reports no longer appear under **Needs attention** or reduce the health score. Older reports that do not identify which operation failed clear once both sending and sync have succeeded after the report; existing reports with that evidence are cleared on upgrade too. A newer failure remains visible, and simply waiting or completing a queued task does not count as recovery. Recoverable connection failures retry automatically while the mailbox is on; a connection warning alone is not a reason to reconnect. A temporary connection, server or throttling failure is not shown at all while the affected sync or sending has still succeeded within the last two hours, because the mailbox is working. It appears only when the failure lasts longer than that. Authentication, credential and policy errors retain their own instructions, and a switched-off mailbox must be switched back on before it can retry. A send safety hold is different from a retryable connection failure. If Warmbly cannot confirm whether the provider accepted a message, sending pauses to avoid retrying a message that might already have been sent. The mailbox is shown as needing attention even without a separate connection warning, and its health details explain the hold. A successful inbox sync does not confirm a send. The hold clears on its own and no customer action is needed. After ten minutes Warmbly sets the uncertain email aside for good: a campaign email waits for confirmation for that one contact while the mailbox sends to everyone else, and a Unibox, placement-test or Warmbly Cloud send simply never runs again. A send that never reached the worker is handed back after 30 minutes so the step can go out fresh. A late confirmed result still updates the email automatically. Only legacy sends without durable execution authorization need provider-confirmed resolution. See [send safety](/development/send-safety/). diff --git a/web/src/lib/api/hooks/app/analytics/accountStatusRecovery.test.tsx b/web/src/lib/api/hooks/app/analytics/accountStatusRecovery.test.tsx new file mode 100644 index 000000000..5b64997aa --- /dev/null +++ b/web/src/lib/api/hooks/app/analytics/accountStatusRecovery.test.tsx @@ -0,0 +1,131 @@ +import type { PropsWithChildren } from "react"; +import { act, cleanup, renderHook } from "@testing-library/react"; +import { focusManager, QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import getAccountStatus from "@/lib/api/client/app/analytics/getAccountStatus"; +import getAccountStatuses from "@/lib/api/client/app/analytics/getAccountStatuses"; +import type AccountStatus from "@/lib/api/models/app/analytics/AccountStatus"; +import useAccountStatus from "./useAccountStatus"; +import useAccountStatuses from "./useAccountStatuses"; + +vi.mock("@/lib/api/client/app/analytics/getAccountStatus", () => ({ default: vi.fn() })); +vi.mock("@/lib/api/client/app/analytics/getAccountStatuses", () => ({ default: vi.fn() })); + +function mailbox(recovered: boolean): AccountStatus { + return { + id: "mailbox", email: "mailbox@example.test", provider: "smtp_imap", status: "active", + last_synced_at: recovered ? new Date() : new Date(Date.now() - 3 * 60 * 60_000), + health: { status: recovered ? "healthy" : "warning", score: recovered ? 100 : 80 }, + errors: recovered ? [] : [{ + id: "failure", error_code: "SERVER_UNREACHABLE", severity: "WARNING", operation: "sync", + title: "Mail server sync connection failed", message: "Automatic retry", created_at: new Date(), + }], + daily_usage: { date: "2026-11-01", campaign_sent: 0, campaign_limit: 10 }, in_campaign: false, + }; +} + +function harness() { + const client = new QueryClient({ defaultOptions: { queries: { + retry: false, gcTime: Infinity, staleTime: 30_000, refetchOnWindowFocus: false, + } } }); + const wrapper = ({ children }: PropsWithChildren) => {children}; + const ids = ["mailbox"]; + const hook = renderHook(({ enabled }) => ({ + drawer: useAccountStatus(enabled ? "mailbox" : ""), list: useAccountStatuses(ids, { enabled }), + }), { wrapper, initialProps: { enabled: true } }); + return { client, ...hook }; +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.clearAllMocks(); + focusManager.setFocused(true); + vi.mocked(getAccountStatus).mockResolvedValue(mailbox(false)); + vi.mocked(getAccountStatuses).mockResolvedValue([mailbox(false)]); +}); + +afterEach(() => { + cleanup(); + focusManager.setFocused(undefined); + vi.useRealTimers(); +}); + +describe("mailbox status freshness without realtime events", () => { + it("replaces a recovered warning and its old success time in both open views", async () => { + const { client, result, unmount } = harness(); + await act(() => vi.advanceTimersByTimeAsync(1)); + expect(result.current.drawer.data?.errors).toHaveLength(1); + expect(result.current.list.data[0]?.errors).toHaveLength(1); + + const recovered = mailbox(true); + vi.mocked(getAccountStatus).mockResolvedValue(recovered); + vi.mocked(getAccountStatuses).mockResolvedValue([recovered]); + await act(() => vi.advanceTimersByTimeAsync(59_000)); + expect(getAccountStatus).toHaveBeenCalledTimes(1); + expect(getAccountStatuses).toHaveBeenCalledTimes(1); + await act(() => vi.advanceTimersByTimeAsync(1_001)); + expect(result.current.drawer.data?.errors).toEqual([]); + expect(result.current.drawer.data?.last_synced_at).toEqual(recovered.last_synced_at); + expect(result.current.list.data[0]?.errors).toEqual([]); + expect(result.current.list.data[0]?.last_synced_at).toEqual(recovered.last_synced_at); + unmount(); client.clear(); + }); + + it("retains a reported failure until the server confirms recovery, and stops after unmount", async () => { + const { client, result, unmount } = harness(); + await act(() => vi.advanceTimersByTimeAsync(60_002)); + expect(getAccountStatus).toHaveBeenCalledTimes(2); + expect(getAccountStatuses).toHaveBeenCalledTimes(2); + expect(result.current.drawer.data?.errors).toHaveLength(1); + expect(result.current.list.data[0]?.errors).toHaveLength(1); + unmount(); + await act(() => vi.advanceTimersByTimeAsync(120_000)); + expect(getAccountStatus).toHaveBeenCalledTimes(2); + expect(getAccountStatuses).toHaveBeenCalledTimes(2); + client.clear(); + }); + + it("pauses periodic reads while hidden and refreshes immediately on return", async () => { + const { client, result, unmount } = harness(); + await act(() => vi.advanceTimersByTimeAsync(1)); + act(() => focusManager.setFocused(false)); + const recovered = mailbox(true); + vi.mocked(getAccountStatus).mockResolvedValue(recovered); + vi.mocked(getAccountStatuses).mockResolvedValue([recovered]); + await act(() => vi.advanceTimersByTimeAsync(60_001)); + expect(getAccountStatus).toHaveBeenCalledTimes(1); + expect(getAccountStatuses).toHaveBeenCalledTimes(1); + act(() => focusManager.setFocused(true)); + await act(() => vi.advanceTimersByTimeAsync(1)); + expect(result.current.drawer.data?.errors).toEqual([]); + expect(result.current.list.data[0]?.errors).toEqual([]); + unmount(); client.clear(); + }); + + it("keeps the last report when a refresh fails instead of assuming recovery", async () => { + const { client, result, unmount } = harness(); + await act(() => vi.advanceTimersByTimeAsync(1)); + vi.mocked(getAccountStatus).mockRejectedValue(new Error("Status unavailable")); + vi.mocked(getAccountStatuses).mockRejectedValue(new Error("Status unavailable")); + await act(() => vi.advanceTimersByTimeAsync(60_001)); + expect(result.current.drawer.isError).toBe(true); + expect(result.current.list.isError).toBe(true); + expect(result.current.drawer.data?.errors).toHaveLength(1); + expect(result.current.list.data[0]?.errors).toHaveLength(1); + expect(result.current.list.observations[0]?.current).toBe(false); + unmount(); client.clear(); + }); + + it("respects disabled status reads during timer and focus changes", async () => { + const { client, rerender, unmount } = harness(); + await act(() => vi.advanceTimersByTimeAsync(1)); + rerender({ enabled: false }); + act(() => focusManager.setFocused(false)); + await act(() => vi.advanceTimersByTimeAsync(60_001)); + act(() => focusManager.setFocused(true)); + await act(() => vi.advanceTimersByTimeAsync(60_001)); + expect(getAccountStatus).toHaveBeenCalledTimes(1); + expect(getAccountStatuses).toHaveBeenCalledTimes(1); + unmount(); client.clear(); + }); +}); diff --git a/web/src/lib/api/hooks/app/analytics/useAccountStatus.ts b/web/src/lib/api/hooks/app/analytics/useAccountStatus.ts index 3a3786299..fa96edbe0 100644 --- a/web/src/lib/api/hooks/app/analytics/useAccountStatus.ts +++ b/web/src/lib/api/hooks/app/analytics/useAccountStatus.ts @@ -6,5 +6,8 @@ export default function useAccountStatus(id: string) { queryKey: ["analytics", "accounts", id], queryFn: () => getAccountStatus(id), enabled: !!id, - }) + // Routine recovery persists without a realtime event. + refetchInterval: 60_000, + refetchOnWindowFocus: true, + }); } diff --git a/web/src/lib/api/hooks/app/analytics/useAccountStatuses.ts b/web/src/lib/api/hooks/app/analytics/useAccountStatuses.ts index bfd442504..fc1279176 100644 --- a/web/src/lib/api/hooks/app/analytics/useAccountStatuses.ts +++ b/web/src/lib/api/hooks/app/analytics/useAccountStatuses.ts @@ -49,6 +49,9 @@ export default function useAccountStatuses(emailIds: string[], options?: { enabl queryKey: ["analytics", "accounts", "list", ids, sourceRevision], queryFn: ({ signal }: { signal: AbortSignal }) => getAccountStatuses(ids, signal), enabled: ids.length > 0 && enabled, + // Routine recovery persists without a realtime event. + refetchInterval: 60_000, + refetchOnWindowFocus: true, })), [chunks, enabled, sourceRevision], ); From ce84486f399b578573147e8ec939a1bee342cfba Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 12:34:12 +0100 Subject: [PATCH 2/3] feat: preserve cached mailbox row measurements with explicit freshness and confirmed recovery during status polling --- docs/content/docs/guides/mailboxes.mdx | 2 +- web/src/app/app/emails/page.test.tsx | 55 ++++++++++++++++++++++++-- web/src/app/app/emails/page.tsx | 50 +++++++++++++---------- 3 files changed, 82 insertions(+), 25 deletions(-) diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index ee3ceb84f..f347ed345 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -642,7 +642,7 @@ The Accounts list groups mailboxes as **Healthy** (sending normally), **Warming* Repeated reports of the same error code count once toward the health score, at their highest unresolved severity, rather than making one problem look like several. The drawer groups identical reports while keeping different error details and sending versus sync failures separate. Connection titles name Gmail, Microsoft Outlook or the mail server. **Reported** shows the stored report time: connection and temporary provider-limit observations refresh it, while other error categories may retain their original report time. It is not proof of an ongoing outage. -While visible, the Accounts list and mailbox drawer refresh their health and error reports every minute as well as on relevant live events. Returning to a tab refreshes stale reports too. These reads show the server's latest recovery evidence; they do not reconnect a mailbox or retry a send. A failed status refresh does not count as recovery. +While visible, the Accounts list and mailbox drawer refresh their health and error reports every minute as well as on relevant live events. Returning to a tab refreshes stale reports too. The list keeps cached row measurements during a refresh or after a failed read, marked **Last observed**. A retained issue stays visible until a fresh successful result confirms recovery. These reads show the server's latest recovery evidence; they do not reconnect a mailbox or retry a send. A failed status refresh does not count as recovery. A later completed sync automatically clears earlier temporary sync errors. A provider-confirmed send clears earlier temporary sending errors, including provider throttling and quota warnings. Recovered reports no longer appear under **Needs attention** or reduce the health score. Older reports that do not identify which operation failed clear once both sending and sync have succeeded after the report; existing reports with that evidence are cleared on upgrade too. A newer failure remains visible, and simply waiting or completing a queued task does not count as recovery. Recoverable connection failures retry automatically while the mailbox is on; a connection warning alone is not a reason to reconnect. A temporary connection, server or throttling failure is not shown at all while the affected sync or sending has still succeeded within the last two hours, because the mailbox is working. It appears only when the failure lasts longer than that. Authentication, credential and policy errors retain their own instructions, and a switched-off mailbox must be switched back on before it can retry. diff --git a/web/src/app/app/emails/page.test.tsx b/web/src/app/app/emails/page.test.tsx index bc5d1b667..29f2cad7e 100644 --- a/web/src/app/app/emails/page.test.tsx +++ b/web/src/app/app/emails/page.test.tsx @@ -33,7 +33,7 @@ vi.mock("@/hooks/usePermission", () => ({ usePermission: () => true })); vi.mock("@/lib/api/hooks/app/emails/useEmails", () => ({ default: ({ tag }: { tag: string }) => ({ emails: statusState.emailsLoading || statusState.emailsError ? [] : tag ? rows.filter((row) => row.tags.includes(tag)) : rows, isLoading: statusState.emailsLoading, isPending: statusState.emailsLoading, isError: statusState.emailsError || statusState.emailsIncomplete, isIncomplete: statusState.emailsIncomplete, refetch: vi.fn() }), })); -vi.mock("@/lib/api/hooks/app/analytics/useAccountStatuses", () => ({ default: () => statusState })); +vi.mock("@/lib/api/hooks/app/analytics/useAccountStatuses", () => ({ default: () => ({ ...statusState, observations: statusState.observations.length ? statusState.observations : statusState.data.map((status) => ({ status, observedAt: 0, current: !statusState.isFetching && !statusState.isError })) }) })); vi.mock("@/lib/api/hooks/app/subscription/useFeatureStatus", () => ({ default: () => ({ data: { can_use_warmup: true } }) })); vi.mock("@/lib/api/hooks/auth/useAuthConfig", () => ({ default: () => ({ data: {}, isLoading: false }) })); vi.mock("@/lib/api/hooks/app/emails/useMailboxGrants", () => ({ useSigninMigration: () => ({ data: { data: [] } }) })); @@ -215,12 +215,59 @@ describe("mailbox status while account and Cloud checks settle", () => { statusState.isFetching = true; await renderPage(); expect(screen.queryByText("Healthy 100")).not.toBeInTheDocument(); + expect(screen.getByText("Last observed: Healthy 100")).toBeInTheDocument(); + expect(screen.getByTitle("0 of 50 campaign emails sent today")).toBeInTheDocument(); statusState.isFetching = false; fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); expect(screen.getAllByText("Unavailable").length).toBeGreaterThan(0); statusState.isError = true; fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); expect(screen.queryByText("Healthy 100")).not.toBeInTheDocument(); + expect(screen.getByText("Last observed: Healthy 100")).toBeInTheDocument(); + expect(screen.getByTitle("0 of 50 campaign emails sent today")).toBeInTheDocument(); + }); + + it.each(["isFetching", "isError"] as const)("retains cached row metrics and marks only unconfirmed chunks stale during %s", async (state) => { + statusState.data = rows.map(measuredStatus); + statusState.data[0].daily_usage = { date: "2026-11-01", campaign_sent: 7, campaign_limit: 50 }; + statusState.observations = statusState.data.map((status) => ({ status, observedAt: Date.now(), current: true })); + await renderPage(); + + statusState[state] = true; + statusState.observations = statusState.observations.map((observation) => ({ ...observation, current: observation.status.id !== rows[0].id })); + fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); + const sara = screen.getByText(rows[0].email).closest("tr"); + const kavya = screen.getByText(rows[1].email).closest("tr"); + expect(sara).not.toBeNull(); + expect(kavya).not.toBeNull(); + expect(within(sara!).getByTitle("7 of 50 campaign emails sent today")).toBeInTheDocument(); + expect(within(sara!).getByText("Last observed: Healthy 100")).toBeInTheDocument(); + expect(within(sara!).queryByText("Checking…")).not.toBeInTheDocument(); + expect(within(kavya!).getByText("Healthy 100")).toBeInTheDocument(); + expect(within(kavya!).queryByText("Last observed: Healthy 100")).not.toBeInTheDocument(); + }); + + it("keeps a retained issue ahead of cached healthy data until a fresh recovery arrives", async () => { + const failed = { ...measuredStatus(rows[0]), health: { status: "error", score: 40 } } satisfies AccountStatus; + statusState.data = [failed]; + statusState.observations = [{ status: failed, observedAt: Date.now(), current: true }]; + await renderPage(); + + const recovered = measuredStatus(rows[0]); + statusState.data = [recovered]; + statusState.isError = true; + statusState.observations = [{ status: recovered, observedAt: Date.now() + 1, current: false }]; + fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); + expect(screen.getAllByText("Last reported issue").length).toBeGreaterThan(0); + expect(screen.getByText("Last observed: Issue 40")).toBeInTheDocument(); + expect(screen.queryByText("Last observed: Healthy 100")).not.toBeInTheDocument(); + expect(screen.getByTitle("0 of 50 campaign emails sent today")).toBeInTheDocument(); + + statusState.isError = false; + statusState.observations = [{ status: recovered, observedAt: Date.now() + 2, current: true }]; + fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); + await waitFor(() => expect(screen.queryAllByText("Last reported issue")).toHaveLength(0)); + expect(screen.getByText("Healthy 100")).toBeInTheDocument(); }); it("does not assume local-only health when the Cloud connection lookup failed", async () => { @@ -230,7 +277,7 @@ describe("mailbox status while account and Cloud checks settle", () => { await renderPage(); expect(screen.queryByText("Healthy 100")).not.toBeInTheDocument(); const sara = screen.getAllByRole("row").find((row) => row.textContent?.includes(rows[0].email)); - expect(within(sara!).getByText("Issue 40")).toBeInTheDocument(); + expect(within(sara!).getByText("Last observed: Issue 40")).toBeInTheDocument(); expect(screen.getAllByText("Unavailable").length).toBeGreaterThan(0); }); @@ -241,10 +288,11 @@ describe("mailbox status while account and Cloud checks settle", () => { await renderPage(); expect(screen.getByText("Issue 40")).toBeInTheDocument(); statusState.isFetching = true; + statusState.observations = statusState.observations.map((observation) => ({ ...observation, current: false })); fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); expect(screen.getAllByText("Last reported issue").length).toBeGreaterThan(0); expect(screen.getByText("Last observed: Issue 40")).toBeInTheDocument(); - expect(screen.queryByTitle("0 of 50 campaign emails sent today")).not.toBeInTheDocument(); + expect(screen.getAllByTitle("0 of 50 campaign emails sent today")).toHaveLength(rows.length); statusState.isFetching = false; statusState.cloudLoading = true; @@ -268,6 +316,7 @@ describe("mailbox status while account and Cloud checks settle", () => { statusState.observations = statusState.data.map((status) => ({ status, observedAt, current: true })); await renderPage(); statusState.isFetching = true; + statusState.observations = statusState.observations.map((observation) => ({ ...observation, current: false })); fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); expect(screen.getAllByText("Last reported issue").length).toBeGreaterThan(0); const clock = vi.spyOn(Date, "now").mockReturnValue(observedAt + 5 * 60_000 + 1); diff --git a/web/src/app/app/emails/page.tsx b/web/src/app/app/emails/page.tsx index ba3ce4bfe..f74627f59 100644 --- a/web/src/app/app/emails/page.tsx +++ b/web/src/app/app/emails/page.tsx @@ -201,14 +201,18 @@ export default function AddressesPage() { // Coerce to an array defensively: a wrong-shape (non-array) response must // never reach a `for…of`, which would throw "{} is not iterable". const accountStatuses = useMemo( - () => (!cloudChecking && !statuses.isError && !statuses.isFetching && Array.isArray(statuses.data) ? statuses.data : []), - [cloudChecking, statuses.data, statuses.isError, statuses.isFetching], + () => (!cloudChecking && Array.isArray(statuses.data) ? statuses.data : []), + [cloudChecking, statuses.data], ); const statusById = useMemo(() => { const m = new Map(); for (const s of accountStatuses) m.set(s.id, s); return m; }, [accountStatuses]); + const currentStatusIds = useMemo( + () => new Set(statuses.observations.filter((observation) => observation.current).map(({ status }) => status.id)), + [statuses.observations], + ); const statusChecking = emailsData.isLoading || cloudChecking || statuses.isLoading || statuses.isFetching; const cloudStandingUnavailable = cloud.connected && (emailsData.emails ?? []).some((box) => { const row = cloud.rowFor(box.id); @@ -248,21 +252,20 @@ export default function AddressesPage() { // Proactively notify the user when a mailbox's health drops. const prevHealth = useRef>(new Map()); useEffect(() => { - if (accountStatuses.length === 0) return; + if (cloudChecking || cloudUnavailable) return; const prev = prevHealth.current; - const next = new Map(); - for (const s of accountStatuses) { + for (const { status: s, current } of statuses.observations) { + if (!current) continue; const cur = s.health?.status ?? "healthy"; - next.set(s.id, cur); const before = prev.get(s.id); // A reputation slowdown is on the row and recovers by itself; a toast reads as the mailbox stopping. if (before && (HEALTH_RANK[cur] ?? 0) > (HEALTH_RANK[before] ?? 0) && !reputationOnlyWarning(s)) { const reason = (!cloudHealthUnavailable(s.warmup_health) && s.warmup_health?.reason) || s.health?.issues?.[0]; toast.error(`${s.email} health dropped to ${cur}${reason ? ` — ${reason}` : ""}`); } + prev.set(s.id, cur); } - prevHealth.current = next; - }, [accountStatuses]); + }, [statuses.observations, cloudChecking, cloudUnavailable]); const removeSelected = () => { if (selected.length === 0 || removing || cloudRemovalPending) return; @@ -628,6 +631,7 @@ export default function AddressesPage() { box={box} tags={p?.user.tags ?? []} status={(cloud.unavailable || cloudStandingUnavailable) && statusById.get(box.id)?.health?.status === "healthy" && !statusById.get(box.id)?.errors?.length ? undefined : statusById.get(box.id)} + statusCurrent={!cloudChecking && !cloud.unavailable && !cloudStandingUnavailable && currentStatusIds.has(box.id)} lastReportedIssue={lastReportedIssues.get(box.id)} statusPending={statusChecking && !statusUnavailable} cloudStatusPending={cloudChecking || cloud.unavailable || cloudStandingUnavailable} @@ -822,6 +826,7 @@ function MailboxRow({ box, tags, status, + statusCurrent, lastReportedIssue, statusPending, cloudStatusPending, @@ -839,6 +844,7 @@ function MailboxRow({ box: Inbox; tags: Tag[]; status?: AccountStatus; + statusCurrent: boolean; lastReportedIssue?: { status: AccountStatus; observedAt: number }; statusPending: boolean; cloudStatusPending: boolean; @@ -902,8 +908,10 @@ function MailboxRow({ // Warmup only runs on a mailbox that is on, whatever its warmup setting says. const warming = active && box.status === "active"; - const historicalIssue = !status && lastReportedIssue && Date.now() - lastReportedIssue.observedAt <= LAST_REPORTED_ISSUE_MS ? lastReportedIssue : undefined; - const tone = healthTone(status ?? historicalIssue?.status); + const historicalIssue = !statusCurrent && lastReportedIssue && Date.now() - lastReportedIssue.observedAt <= LAST_REPORTED_ISSUE_MS ? lastReportedIssue : undefined; + const stale = !!status && !statusCurrent; + const displayedHealth = historicalIssue?.status ?? status; + const tone = healthTone(displayedHealth); const ws = status?.warmup_status; const inCampaign = status?.in_campaign; @@ -1130,7 +1138,7 @@ function MailboxRow({ {/* Too narrow for the metric columns: the same readings, labelled, under the address. */}
- + Warmup {cloudStatusPending ? statusPending ? "Checking…" : "Unavailable" : warmupCell} @@ -1143,8 +1151,8 @@ function MailboxRow({ Health - {historicalIssue && Last observed} - {status?.health?.score ?? historicalIssue?.status.health?.score ?? "—"} + {(historicalIssue || stale) && Last observed} + {displayedHealth?.health?.score ?? "—"}
@@ -1155,7 +1163,7 @@ function MailboxRow({ - + {status?.daily_usage ? ( @@ -1192,10 +1200,10 @@ function MailboxRow({ type="button" onClick={(e) => { e.stopPropagation(); onOpen(box.id, "overview"); }} className={`inline-flex items-center gap-1.5 text-[11px] font-medium max-w-full ${tone.text}`} - title={historicalIssue ? `Last observed ${new Date(historicalIssue.observedAt).toLocaleString()}. Current health unavailable.` : status?.health?.issues?.join("\n") || "View mailbox health"} + title={historicalIssue ? `Last observed ${new Date(historicalIssue.observedAt).toLocaleString()}. Current health unavailable.` : stale ? "Last known measurements. Current status is unconfirmed until a successful refresh." : status?.health?.issues?.join("\n") || "View mailbox health"} > - + e.stopPropagation()}> @@ -1464,8 +1472,8 @@ function MailboxTh({ col, sort, onSort }: { col: MailboxColumn; sort: MailboxSor // What the mailbox is doing right now. Cold sending and warmup run side by // side, so both show when both are on; a problem that stops it wins. // compact spells a problem out, since it is the one reading a phone must not miss. -function MailboxStatusPill({ box, status, historicalIssue, warming, compact = false, pending = false }: { box: Inbox; status?: AccountStatus; historicalIssue?: { status: AccountStatus; observedAt: number }; warming: boolean; compact?: boolean; pending?: boolean }) { - if (!status && historicalIssue && box.status === "active") return Last reported issue; +function MailboxStatusPill({ box, status, stale, historicalIssue, warming, compact = false, pending = false }: { box: Inbox; status?: AccountStatus; stale: boolean; historicalIssue?: { status: AccountStatus; observedAt: number }; warming: boolean; compact?: boolean; pending?: boolean }) { + if (historicalIssue && box.status === "active") return Last reported issue; const critical = status?.errors?.find((e) => e.severity?.toUpperCase() === "CRITICAL"); const error = critical ?? status?.errors?.[0]; const stopped = !!critical || status?.health?.status === "error"; @@ -1510,15 +1518,15 @@ function MailboxStatusPill({ box, status, historicalIssue, warming, compact = fa ].join(", "); const text = sending ? "text-sky-700" : resting ? "text-violet-600" : warming ? "text-orange-600" : "text-slate-400"; return ( - + {sending && } {resting && } {warming && } {!sending && !resting && !warming && } - {label} - {label} + {stale && "Last observed: "}{label} + {stale && "Last observed: "}{label} ); } From 69ff9b06c50fe59a2043c85e3235a45e0039aa20 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Sun, 1 Nov 2026 13:42:35 +0100 Subject: [PATCH 3/3] feat: keep cached mailbox errors unconfirmed and campaign counts scoped to the current UTC day --- docs/content/docs/guides/mailboxes.mdx | 2 +- web/src/app/app/emails/page.test.tsx | 59 ++++++++++++++++++++++++-- web/src/app/app/emails/page.tsx | 35 +++++++++------ 3 files changed, 78 insertions(+), 18 deletions(-) diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index f347ed345..b52f56f0c 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -642,7 +642,7 @@ The Accounts list groups mailboxes as **Healthy** (sending normally), **Warming* Repeated reports of the same error code count once toward the health score, at their highest unresolved severity, rather than making one problem look like several. The drawer groups identical reports while keeping different error details and sending versus sync failures separate. Connection titles name Gmail, Microsoft Outlook or the mail server. **Reported** shows the stored report time: connection and temporary provider-limit observations refresh it, while other error categories may retain their original report time. It is not proof of an ongoing outage. -While visible, the Accounts list and mailbox drawer refresh their health and error reports every minute as well as on relevant live events. Returning to a tab refreshes stale reports too. The list keeps cached row measurements during a refresh or after a failed read, marked **Last observed**. A retained issue stays visible until a fresh successful result confirms recovery. These reads show the server's latest recovery evidence; they do not reconnect a mailbox or retry a send. A failed status refresh does not count as recovery. +While visible, the Accounts list and mailbox drawer refresh their health and error reports every minute as well as on relevant live events. Returning to a tab refreshes stale reports too. The list keeps cached row measurements during a refresh or after a failed read, marked **Last observed**, including cached **Error** and **Retrying** statuses. A recent issue is highlighted as **Last reported issue** for up to five minutes while recovery is unconfirmed; older cached reports remain marked **Last observed**. **Sent today** only shows campaign usage reported for the current UTC day. After the daily reset, an older count is withheld until today's usage arrives. These reads show the server's latest recovery evidence; they do not reconnect a mailbox or retry a send. A failed status refresh does not count as recovery. A later completed sync automatically clears earlier temporary sync errors. A provider-confirmed send clears earlier temporary sending errors, including provider throttling and quota warnings. Recovered reports no longer appear under **Needs attention** or reduce the health score. Older reports that do not identify which operation failed clear once both sending and sync have succeeded after the report; existing reports with that evidence are cleared on upgrade too. A newer failure remains visible, and simply waiting or completing a queued task does not count as recovery. Recoverable connection failures retry automatically while the mailbox is on; a connection warning alone is not a reason to reconnect. A temporary connection, server or throttling failure is not shown at all while the affected sync or sending has still succeeded within the last two hours, because the mailbox is working. It appears only when the failure lasts longer than that. Authentication, credential and policy errors retain their own instructions, and a switched-off mailbox must be switched back on before it can retry. diff --git a/web/src/app/app/emails/page.test.tsx b/web/src/app/app/emails/page.test.tsx index 29f2cad7e..b33c52f2d 100644 --- a/web/src/app/app/emails/page.test.tsx +++ b/web/src/app/app/emails/page.test.tsx @@ -6,6 +6,7 @@ import type Inbox from "@/lib/api/models/app/emails/Inbox"; import type Tag from "@/lib/api/models/app/Tag"; import type * as UserModule from "@/hooks/context/user"; import type AccountStatus from "@/lib/api/models/app/analytics/AccountStatus"; +import { utcToday } from "@/lib/campaignPeriod"; import AddressesPage from "./page"; const { tags, rows, statusState, confirm } = vi.hoisted(() => ({ @@ -74,7 +75,7 @@ function orderedEmails() { } function measuredStatus(row: Inbox): AccountStatus { - return { id: row.id, email: row.email, provider: "gmail", status: "active", last_synced_at: null, health: { status: "healthy", score: 100 }, errors: [], daily_usage: { date: "2026-10-09", campaign_sent: 0, campaign_limit: 50 }, in_campaign: false }; + return { id: row.id, email: row.email, provider: "gmail", status: "active", last_synced_at: null, health: { status: "healthy", score: 100 }, errors: [], daily_usage: { date: utcToday(), campaign_sent: 0, campaign_limit: 50 }, in_campaign: false }; } describe("mailbox ordering with a tag filter", () => { @@ -229,7 +230,7 @@ describe("mailbox status while account and Cloud checks settle", () => { it.each(["isFetching", "isError"] as const)("retains cached row metrics and marks only unconfirmed chunks stale during %s", async (state) => { statusState.data = rows.map(measuredStatus); - statusState.data[0].daily_usage = { date: "2026-11-01", campaign_sent: 7, campaign_limit: 50 }; + statusState.data[0].daily_usage = { date: utcToday(), campaign_sent: 7, campaign_limit: 50 }; statusState.observations = statusState.data.map((status) => ({ status, observedAt: Date.now(), current: true })); await renderPage(); @@ -247,6 +248,49 @@ describe("mailbox status while account and Cloud checks settle", () => { expect(within(kavya!).queryByText("Last observed: Healthy 100")).not.toBeInTheDocument(); }); + it("withholds prior-day campaign totals after UTC midnight until current usage arrives", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-11-01T19:59:59-04:00")); + try { + statusState.data = rows.map(measuredStatus); + statusState.data[0].daily_usage = { date: "2026-11-01", campaign_sent: 49, campaign_limit: 50 }; + await renderPage(); + expect(screen.getByTitle("49 of 50 campaign emails sent today")).toBeInTheDocument(); + + vi.setSystemTime(new Date("2026-11-01T20:00:01-04:00")); + statusState.isError = true; + statusState.data = statusState.data.map((status) => status.id === rows[1].id ? { ...status, daily_usage: { date: "2026-11-02", campaign_sent: 2, campaign_limit: 50 } } : status); + fireEvent.click(screen.getByRole("button", { name: /^Sent today/ })); + expect(screen.queryByTitle("49 of 50 campaign emails sent today")).not.toBeInTheDocument(); + expect(screen.getByTitle("2 of 50 campaign emails sent today")).toBeInTheDocument(); + expect(orderedEmails()[0]).toBe(rows[1].email); + expect(statusState.data[0].daily_usage?.campaign_sent).toBe(49); + + statusState.isError = false; + statusState.data = [{ ...measuredStatus(rows[0]), daily_usage: { date: "2026-11-02", campaign_sent: 1, campaign_limit: 50 } }]; + fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); + expect(screen.getByTitle("1 of 50 campaign emails sent today")).toBeInTheDocument(); + } finally { + vi.useRealTimers(); + } + }); + + it.each(["revoked", "inactive"])("keeps inventory %s status authoritative when account measurements are stale", async (status) => { + const original = rows[0].status; + rows[0].status = status; + try { + statusState.data = rows.map(measuredStatus); + statusState.isError = true; + await renderPage(); + const mailbox = within(screen.getByText(rows[0].email).closest("tr")!); + const label = status === "revoked" ? "Reconnect" : "Off"; + expect(mailbox.getAllByText(label).length).toBeGreaterThan(0); + expect(mailbox.queryByText(`Last observed: ${label}`)).not.toBeInTheDocument(); + } finally { + rows[0].status = original; + } + }); + it("keeps a retained issue ahead of cached healthy data until a fresh recovery arrives", async () => { const failed = { ...measuredStatus(rows[0]), health: { status: "error", score: 40 } } satisfies AccountStatus; statusState.data = [failed]; @@ -309,9 +353,12 @@ describe("mailbox status while account and Cloud checks settle", () => { expect(screen.getAllByText("Healthy 100").length).toBeGreaterThan(0); }); - it("expires an old unverified issue rather than displaying it indefinitely", async () => { + it.each([ + { severity: "critical", health: "error", label: "Error" }, + { severity: "warning", health: "warning", label: "Retrying" }, + ] as const)("keeps expired cached $label reports visibly unconfirmed", async ({ severity, health, label }) => { statusState.data = rows.map(measuredStatus); - statusState.data[0] = { ...measuredStatus(rows[0]), health: { status: "error", score: 40 }, errors: [{ id: "error-1", error_code: "PROVIDER_UNAVAILABLE", severity: "critical", title: "Provider unavailable", message: "Provider refused the last attempt", created_at: new Date("2026-10-09T00:00:00Z") }] }; + statusState.data[0] = { ...measuredStatus(rows[0]), health: { status: health, score: 40 }, errors: [{ id: "error-1", error_code: "PROVIDER_UNAVAILABLE", severity, title: "Provider unavailable", message: "Provider refused the last attempt", created_at: new Date("2026-10-09T00:00:00Z") }] }; const observedAt = Date.now(); statusState.observations = statusState.data.map((status) => ({ status, observedAt, current: true })); await renderPage(); @@ -322,6 +369,10 @@ describe("mailbox status while account and Cloud checks settle", () => { const clock = vi.spyOn(Date, "now").mockReturnValue(observedAt + 5 * 60_000 + 1); fireEvent.click(screen.getByRole("button", { name: "Mailbox" })); expect(screen.queryAllByText("Last reported issue")).toHaveLength(0); + const mailbox = within(screen.getByText(rows[0].email).closest("tr")!); + expect(mailbox.getAllByText(`Last observed: ${label}`).length).toBeGreaterThan(0); + expect(mailbox.queryByText(label)).not.toBeInTheDocument(); + expect(mailbox.getAllByTitle("Last observed: Provider unavailable. Current status unconfirmed.").length).toBeGreaterThan(0); clock.mockRestore(); }); diff --git a/web/src/app/app/emails/page.tsx b/web/src/app/app/emails/page.tsx index f74627f59..75aabaa01 100644 --- a/web/src/app/app/emails/page.tsx +++ b/web/src/app/app/emails/page.tsx @@ -5,6 +5,7 @@ import { browseString, mailboxSort, mailboxTab, type MailboxTab } from "@/lib/br import { useSearchParams } from "@/hooks/useSearchParams"; import useMailboxTagFilter from "@/hooks/useMailboxTagFilter"; import groupMailboxes from "@/lib/groupMailboxes"; +import { utcToday } from "@/lib/campaignPeriod"; import { cloudStandingUnavailable as cloudHealthUnavailable, mailboxColdActivity, reputationOnlyWarning } from "@/lib/mailboxStatus"; import { useAppStore } from "@/stores/useAppStore"; import toast from "react-hot-toast/headless"; @@ -116,6 +117,10 @@ const DefaultFolder = { const HEALTH_RANK: Record = { healthy: 0, warning: 1, error: 2 }; const LAST_REPORTED_ISSUE_MS = 5 * 60_000; +function dailyUsageOn(status: AccountStatus | undefined, day: string) { + return status?.daily_usage?.date === day ? status.daily_usage : undefined; +} + function healthTone(status?: AccountStatus): { dot: string; text: string; label: string; pulse: boolean } { const h = status?.health; if (!h) return { dot: "bg-slate-300", text: "text-slate-500", label: "—", pulse: false }; @@ -204,6 +209,7 @@ export default function AddressesPage() { () => (!cloudChecking && Array.isArray(statuses.data) ? statuses.data : []), [cloudChecking, statuses.data], ); + const today = utcToday(); const statusById = useMemo(() => { const m = new Map(); for (const s of accountStatuses) m.set(s.id, s); @@ -449,12 +455,12 @@ export default function AddressesPage() { const value = col.sortValue; const dir = sort.reverse ? 1 : -1; return [...list].sort((a, b) => { - const x = value(a, statusById.get(a.id)); - const y = value(b, statusById.get(b.id)); + const x = value(a, statusById.get(a.id), today); + const y = value(b, statusById.get(b.id), today); if (x === y) return 0; return (x > y ? 1 : -1) * dir; }); - }, [emailsData.emails, sort, statusById, p.user.tags]); + }, [emailsData.emails, sort, statusById, p.user.tags, today]); if (!canView) { return ; @@ -913,6 +919,7 @@ function MailboxRow({ const displayedHealth = historicalIssue?.status ?? status; const tone = healthTone(displayedHealth); const ws = status?.warmup_status; + const dailyUsage = dailyUsageOn(status, utcToday()); const inCampaign = status?.in_campaign; const cloudEnroll = useEnrollCloudLinkMailbox(); @@ -1166,15 +1173,15 @@ function MailboxRow({ - {status?.daily_usage ? ( + {dailyUsage ? ( 0 ? "text-sky-700" : "text-slate-500"}`} - title={`${status.daily_usage.campaign_sent} of ${status.daily_usage.campaign_limit || box.campaign_limit} campaign emails sent today`} + className={`inline-flex items-center gap-1.5 font-mono text-[12px] tabular-nums ${dailyUsage.campaign_sent > 0 ? "text-sky-700" : "text-slate-500"}`} + title={`${dailyUsage.campaign_sent} of ${dailyUsage.campaign_limit || box.campaign_limit} campaign emails sent today`} > - - /{status.daily_usage.campaign_limit || box.campaign_limit} + + /{dailyUsage.campaign_limit || box.campaign_limit} ) : ( @@ -1367,7 +1374,7 @@ interface MailboxColumn { align?: "right"; // Whether the first click sorts ascending (text) rather than descending. sortAsc?: boolean; - sortValue?: (box: Inbox, status?: AccountStatus) => string | number; + sortValue?: (box: Inbox, status: AccountStatus | undefined, today: string) => string | number; } interface MailboxSort { @@ -1400,7 +1407,7 @@ const MAILBOX_COLUMNS: MailboxColumn[] = [ header: , className: "w-32", show: "hidden @5xl:table-cell", - sortValue: (_, s) => s?.daily_usage?.campaign_sent ?? -1, + sortValue: (_, s, today) => dailyUsageOn(s, today)?.campaign_sent ?? -1, }, { id: "warmup", @@ -1493,11 +1500,13 @@ function MailboxStatusPill({ box, status, stale, historicalIssue, warming, compa } if (problem) { const { Icon } = problem; + const cachedError = stale && box.status === "active"; + const label = cachedError ? `Last observed: ${problem.label}` : problem.label; return ( - + - {problem.label} - {problem.label} + {label} + {label} ); }