mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-17 08:18:51 +00:00
feat: preserve mailbox freshness and per-row Cloud availability with mixed report regression coverage
This commit is contained in:
@@ -644,6 +644,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. 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.
|
||||
|
||||
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/).
|
||||
|
||||
@@ -7,6 +7,7 @@ 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 type { CloudLinkMailboxRow } from "@/lib/api/models/app/cloudlink/CloudLink";
|
||||
import { utcToday } from "@/lib/campaignPeriod";
|
||||
import AddressesPage from "./page";
|
||||
|
||||
const { tags, rows, statusState, confirm, cloudRows } = vi.hoisted(() => ({
|
||||
@@ -35,7 +36,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: [] } }) }));
|
||||
@@ -76,7 +77,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 };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -247,12 +248,102 @@ 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: utcToday(), 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("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];
|
||||
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 () => {
|
||||
@@ -262,7 +353,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);
|
||||
});
|
||||
|
||||
@@ -273,10 +364,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;
|
||||
@@ -293,18 +385,26 @@ 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();
|
||||
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);
|
||||
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();
|
||||
});
|
||||
|
||||
|
||||
@@ -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<string, number> = { 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 };
|
||||
@@ -201,14 +206,19 @@ 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 today = utcToday();
|
||||
const statusById = useMemo(() => {
|
||||
const m = new Map<string, AccountStatus>();
|
||||
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 +258,20 @@ export default function AddressesPage() {
|
||||
// Proactively notify the user when a mailbox's health drops.
|
||||
const prevHealth = useRef<Map<string, string>>(new Map());
|
||||
useEffect(() => {
|
||||
if (accountStatuses.length === 0) return;
|
||||
if (cloudChecking || cloudUnavailable) return;
|
||||
const prev = prevHealth.current;
|
||||
const next = new Map<string, string>();
|
||||
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;
|
||||
@@ -446,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 <NoAccess feature="email accounts" permissionLabel="Manage mailboxes" />;
|
||||
@@ -631,6 +640,7 @@ export default function AddressesPage() {
|
||||
box={box}
|
||||
tags={p?.user.tags ?? []}
|
||||
status={rowCloudUnavailable && statusById.get(box.id)?.health?.status === "healthy" && !statusById.get(box.id)?.errors?.length ? undefined : statusById.get(box.id)}
|
||||
statusCurrent={!cloudChecking && !rowCloudUnavailable && currentStatusIds.has(box.id)}
|
||||
lastReportedIssue={lastReportedIssues.get(box.id)}
|
||||
statusPending={statusChecking && !inventoryUnavailable && !rowCloudUnavailable && !statuses.isError}
|
||||
cloudStatusPending={cloudChecking || rowCloudUnavailable}
|
||||
@@ -826,6 +836,7 @@ function MailboxRow({
|
||||
box,
|
||||
tags,
|
||||
status,
|
||||
statusCurrent,
|
||||
lastReportedIssue,
|
||||
statusPending,
|
||||
cloudStatusPending,
|
||||
@@ -843,6 +854,7 @@ function MailboxRow({
|
||||
box: Inbox;
|
||||
tags: Tag[];
|
||||
status?: AccountStatus;
|
||||
statusCurrent: boolean;
|
||||
lastReportedIssue?: { status: AccountStatus; observedAt: number };
|
||||
statusPending: boolean;
|
||||
cloudStatusPending: boolean;
|
||||
@@ -906,9 +918,12 @@ 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 dailyUsage = dailyUsageOn(status, utcToday());
|
||||
const inCampaign = status?.in_campaign;
|
||||
|
||||
const cloudEnroll = useEnrollCloudLinkMailbox();
|
||||
@@ -1134,7 +1149,7 @@ function MailboxRow({
|
||||
</div>
|
||||
{/* Too narrow for the metric columns: the same readings, labelled, under the address. */}
|
||||
<div className="@2xl:hidden mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1 min-w-0 leading-tight">
|
||||
<MailboxStatusPill box={box} status={status} historicalIssue={historicalIssue} warming={inCloud ? !cloudPaused : warming} compact pending={statusPending} />
|
||||
<MailboxStatusPill box={box} status={status} stale={stale} historicalIssue={historicalIssue} warming={inCloud ? !cloudPaused : warming} compact pending={statusPending} />
|
||||
<span className="inline-flex items-center gap-1.5 whitespace-nowrap">
|
||||
<span className="text-[10.5px] text-slate-400">Warmup</span>
|
||||
<span className={`font-mono text-[11.5px] tabular-nums ${warmupTone}`}>{cloudStatusPending ? statusPending ? "Checking…" : "Unavailable" : warmupCell}</span>
|
||||
@@ -1147,8 +1162,8 @@ function MailboxRow({
|
||||
<span className="text-[10.5px] text-slate-400">Health</span>
|
||||
<span className={`inline-flex items-center gap-1 font-mono text-[11.5px] font-medium tabular-nums ${tone.text}`}>
|
||||
<span className={`inline-flex w-1.5 h-1.5 rounded-full ${tone.dot}`} />
|
||||
{historicalIssue && <span className="text-slate-500">Last observed</span>}
|
||||
{status?.health?.score ?? historicalIssue?.status.health?.score ?? "—"}
|
||||
{(historicalIssue || stale) && <span className="text-slate-500">Last observed</span>}
|
||||
{displayedHealth?.health?.score ?? "—"}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
@@ -1159,18 +1174,18 @@ function MailboxRow({
|
||||
</div>
|
||||
</td>
|
||||
<td className={`px-3 overflow-hidden ${colShow("status")}`}>
|
||||
<MailboxStatusPill box={box} status={status} historicalIssue={historicalIssue} warming={inCloud ? !cloudPaused : warming} pending={statusPending} />
|
||||
<MailboxStatusPill box={box} status={status} stale={stale} historicalIssue={historicalIssue} warming={inCloud ? !cloudPaused : warming} pending={statusPending} />
|
||||
</td>
|
||||
<td className={`px-3 overflow-hidden ${colShow("sent")}`}>
|
||||
{status?.daily_usage ? (
|
||||
{dailyUsage ? (
|
||||
<span
|
||||
className={`inline-flex items-center gap-1.5 font-mono text-[12px] tabular-nums ${status.daily_usage.campaign_sent > 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`}
|
||||
>
|
||||
<SendIcon className="w-3 h-3 shrink-0 text-sky-500" />
|
||||
<span>
|
||||
<AnimatedNumber value={status.daily_usage.campaign_sent} />
|
||||
<span className="text-slate-400">/{status.daily_usage.campaign_limit || box.campaign_limit}</span>
|
||||
<AnimatedNumber value={dailyUsage.campaign_sent} />
|
||||
<span className="text-slate-400">/{dailyUsage.campaign_limit || box.campaign_limit}</span>
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
@@ -1196,10 +1211,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"}
|
||||
>
|
||||
<span className={`inline-flex w-1.5 h-1.5 rounded-full shrink-0 ${tone.dot}`} />
|
||||
<span className={`uppercase tracking-[0.08em] hidden @4xl:inline truncate ${tone.pulse && !historicalIssue ? "text-shimmer" : ""}`}>{historicalIssue && "Last observed: "}{tone.label}</span>
|
||||
<span className={`uppercase tracking-[0.08em] hidden @4xl:inline truncate ${tone.pulse && statusCurrent ? "text-shimmer" : ""}`}>{(historicalIssue || stale) && "Last observed: "}{tone.label}</span>
|
||||
</button>
|
||||
</td>
|
||||
<td className="px-3" onClick={(e) => e.stopPropagation()}>
|
||||
@@ -1363,7 +1378,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 {
|
||||
@@ -1396,7 +1411,7 @@ const MAILBOX_COLUMNS: MailboxColumn[] = [
|
||||
header: <InfoHeader label="Sent today" title="Campaign emails sent from this mailbox today, against its daily cap." aria="How sends are counted" />,
|
||||
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",
|
||||
@@ -1468,8 +1483,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 <span className="text-[10.5px] text-amber-700" title={`Last observed ${new Date(historicalIssue.observedAt).toLocaleString()}. Current status unavailable.`}>Last reported issue</span>;
|
||||
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 <span className="text-[10.5px] text-amber-700" title={`Last observed ${new Date(historicalIssue.observedAt).toLocaleString()}. Current status unavailable.`}>Last reported issue</span>;
|
||||
const critical = status?.errors?.find((e) => e.severity?.toUpperCase() === "CRITICAL");
|
||||
const error = critical ?? status?.errors?.[0];
|
||||
const stopped = !!critical || status?.health?.status === "error";
|
||||
@@ -1489,11 +1504,13 @@ function MailboxStatusPill({ box, status, historicalIssue, warming, compact = fa
|
||||
}
|
||||
if (problem) {
|
||||
const { Icon } = problem;
|
||||
const cachedError = stale && box.status === "active";
|
||||
const label = cachedError ? `Last observed: ${problem.label}` : problem.label;
|
||||
return (
|
||||
<span className={`inline-flex items-center gap-1.5 max-w-full text-[10.5px] font-medium uppercase tracking-[0.08em] ${problem.text}`} title={problem.title}>
|
||||
<span className={`inline-flex items-center gap-1.5 max-w-full text-[10.5px] font-medium uppercase tracking-[0.08em] ${problem.text}`} title={cachedError ? `Last observed: ${problem.title}. Current status unconfirmed.` : problem.title}>
|
||||
<Icon className="w-3 h-3 shrink-0" />
|
||||
<span className="sr-only">{problem.label}</span>
|
||||
<span aria-hidden className={`${compact ? "inline" : "hidden @4xl:inline"} truncate`}>{problem.label}</span>
|
||||
<span className="sr-only">{label}</span>
|
||||
<span aria-hidden className={`${compact ? "inline" : "hidden @4xl:inline"} truncate`}>{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1514,15 +1531,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 (
|
||||
<span className={`inline-flex items-center gap-1.5 max-w-full text-[10.5px] font-medium uppercase tracking-[0.08em] ${text}`} title={title}>
|
||||
<span className={`inline-flex items-center gap-1.5 max-w-full text-[10.5px] font-medium uppercase tracking-[0.08em] ${text}`} title={stale ? `Last observed: ${title}. Current status unconfirmed.` : title}>
|
||||
<span className="inline-flex items-center gap-0.5 shrink-0">
|
||||
{sending && <SendIcon className="w-3 h-3 text-sky-600" />}
|
||||
{resting && <MoonIcon className="w-3 h-3 text-violet-500" />}
|
||||
{warming && <FlameIcon className="w-3 h-3 text-orange-500" />}
|
||||
{!sending && !resting && !warming && <CircleSlashIcon className="w-3 h-3" />}
|
||||
</span>
|
||||
<span className="sr-only">{label}</span>
|
||||
<span aria-hidden className={`hidden @4xl:inline truncate ${sending || warming ? "text-shimmer" : ""}`}>{label}</span>
|
||||
<span className="sr-only">{stale && "Last observed: "}{label}</span>
|
||||
<span aria-hidden className={`hidden @4xl:inline truncate ${!stale && (sending || warming) ? "text-shimmer" : ""}`}>{stale && "Last observed: "}{label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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) => <QueryClientProvider client={client}>{children}</QueryClientProvider>;
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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],
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user