fix(client): correct recentChecks ordering on the dashboard

recentChecks is oldest-first, not newest-first. The server appends each
snapshot with `$push … $slice: -N` (monitor.repository.mongo.ts:218) and
returns it unreversed, and every existing consumer reads
recentChecks[length - 1] as the latest. I had it backwards, which broke
three things:

- downSince() walked from index 0 and broke on the first element. For any
  monitor that was up before it failed — the normal case — the very first
  check is an "up", so the loop exited immediately and the downtime
  duration never rendered at all.
- The sparkline reversed already-ascending data, drawing every trend line
  mirrored: climbing latency appeared to be improving.
- The status code read index 0, the oldest retained check, so a monitor
  that served 200s before failing showed a green 200 beside a red dot.

Also from review:

- Drop `initializing` from the "Currently down" ranking. On a fresh
  install every new monitor starts there, so the card opened red claiming
  a fleet-wide outage. It means "not checked yet", not "broken".
- Add the maintenance count to Monitor status. The summary reports it and
  the server counts it; omitting it left the tiles summing to less than
  totalMonitors with nothing explaining the gap.
- Link the status tiles to plain /uptime. The monitors list never reads
  query params, so ?status= was silently dropped and the link lied.
- Render the status code as plain text instead of StatusCodeLabel, whose
  Tooltip put a focusable element inside the row's link where no keyboard
  user could reach it.
- Stop sending `limit`: findByTeamIdWithStats derives its page size from
  rowsPerPage alone and never reads it, so it only implied a truncation
  that was not in effect.
- Persist a deliberately emptied dashboard instead of resetting it to the
  defaults on reload.
- Pass isStale on every card. The prop and its dimming were implemented
  but never wired, so background refetches gave no feedback.

Claude-Session: https://claude.ai/code/session_01AbYLvwpEaZFXktHVcqrFRd
This commit is contained in:
gorkem-bwl committed 2026-08-29 09:30:12 -04:00
1 parent c58087c787
commit 23b00401ca
9 files changed
+69 -31

No files matched your search

@@ -60,7 +60,7 @@ const MetricLine = ({
export const CheckmateServerCard = () => {
const theme = useTheme();
const { t } = useTranslation();
const { data, isLoading, error } = useGet<Diagnostics>(
const { data, isLoading, isValidating, error } = useGet<Diagnostics>(
"/diagnostic/system",
{},
{ refreshInterval: 30000 }
@@ -86,6 +86,7 @@ export const CheckmateServerCard = () => {
to="/logs"
isLoading={isLoading && !data}
error={error}
isStale={isValidating && Boolean(data)}
>
{data && (
<Stack gap={theme.spacing(LAYOUT.SM)}>
@@ -5,10 +5,11 @@ import { useTheme } from "@mui/material/styles";
import { useTranslation } from "react-i18next";
import { useMemo } from "react";
import { Dot, StatusCodeLabel } from "@/Components/design-elements";
import { Dot } from "@/Components/design-elements";
import { LAYOUT } from "@/Utils/Theme/constants";
import { typographyLevels } from "@/Utils/Theme/Palette";
import { getStatusColor, getMonitorPath } from "@/Utils/MonitorUtils";
import { formatStatusCode } from "@/Utils/statusCode";
import { formatDuration } from "@/Utils/TimeUtils";
import { DashboardCard, CardMessage } from "../DashboardCard";
import { CardRow, CardRowLabel } from "../CardPrimitives";
@@ -19,34 +20,45 @@ import type { Monitor, MonitorStatus } from "@/Types/Monitor";
// Ordering, not a severity scale — Checkmate has none. Every input already
// exists in the API response.
//
// `initializing` is deliberately excluded: on a fresh install every new monitor
// starts there, and counting it would open the card red claiming a fleet-wide
// outage that does not exist. It is "not checked yet", not "broken".
const STATUS_RANK: Partial<Record<MonitorStatus, number>> = {
down: 1,
breached: 2,
initializing: 3,
};
const isProblem = (monitor: Monitor) => STATUS_RANK[monitor.status] !== undefined;
/**
* How long the monitor has been in its current state, inferred from the oldest
* consecutive failing check. recentChecks is newest-first.
* consecutive failing check.
*
* recentChecks is oldest-first — the server appends each snapshot with
* `$push … $slice: -N` — so the run of current failures is walked backwards
* from the end.
*/
const downSince = (monitor: Monitor): string | null => {
const checks = monitor.recentChecks ?? [];
let oldestFailing: string | null = null;
for (const check of checks) {
if (check.status === true) {
for (let index = checks.length - 1; index >= 0; index -= 1) {
if (checks[index].status === true) {
break;
}
oldestFailing = check.createdAt;
oldestFailing = checks[index].createdAt;
}
return oldestFailing;
};
/** The newest retained check — recentChecks is oldest-first. */
const latestCheck = (monitor: Monitor) =>
monitor.recentChecks?.[monitor.recentChecks.length - 1];
export const CurrentlyDownCard = () => {
const theme = useTheme();
const { t } = useTranslation();
const { data, isLoading, error } = useMonitors();
const { data, isLoading, isValidating, error } = useMonitors();
const problems = useMemo(() => {
const monitors = data?.monitors ?? [];
@@ -70,6 +82,7 @@ export const CurrentlyDownCard = () => {
to="/incidents"
isLoading={isLoading && !data}
error={error}
isStale={isValidating && Boolean(data)}
action={
problems.length > 0 ? (
<Typography
@@ -128,9 +141,21 @@ export const CurrentlyDownCard = () => {
color={theme.palette.error.main}
/>
</Box>
<Box flexShrink={0}>
<StatusCodeLabel statusCode={monitor.recentChecks?.[0]?.statusCode} />
</Box>
{/*
* Plain text rather than StatusCodeLabel: that component wraps
* its body in a Tooltip, and a focusable element nested inside
* the row's link is unreachable by keyboard — tabbing lands on
* the link and activating it navigates away.
*/}
<Typography
fontSize={typographyLevels.s}
color={theme.palette.text.secondary}
flexShrink={0}
minWidth={32}
textAlign="right"
>
{formatStatusCode(latestCheck(monitor)?.statusCode, t)}
</Typography>
</CardRow>
))}
</Stack>
@@ -16,7 +16,7 @@ const SUMMARY_URL = "/checks/team/summary?dateRange=day";
export const FailedChecksCard = () => {
const theme = useTheme();
const { t } = useTranslation();
const { data, isLoading, error } = useGet<ChecksSummary>(SUMMARY_URL);
const { data, isLoading, isValidating, error } = useGet<ChecksSummary>(SUMMARY_URL);
const total = data?.totalChecks ?? 0;
const failed = data?.downChecks ?? 0;
@@ -29,6 +29,7 @@ export const FailedChecksCard = () => {
to="/checks"
isLoading={isLoading && !data}
error={error}
isStale={isValidating && Boolean(data)}
>
{total === 0 ? (
<CardMessage text={t("pages.dashboard.cards.failedChecks.empty")} />
@@ -13,12 +13,14 @@ import { useMonitors } from "../../useDashboardData";
import type { MonitorStatus, MonitorsSummary } from "@/Types/Monitor";
// The five counts, in the order they read: healthy first, then what is wrong,
// then what is not being checked.
// Every state the summary reports, in the order they read: healthy first, then
// what is wrong, then what is not being checked. All six are listed so the
// tiles always sum to totalMonitors — omitting one leaves an unexplained gap.
const COUNTS: { key: string; status: MonitorStatus; field: keyof MonitorsSummary }[] = [
{ key: "up", status: "up", field: "upMonitors" },
{ key: "down", status: "down", field: "downMonitors" },
{ key: "breached", status: "breached", field: "breachedMonitors" },
{ key: "maintenance", status: "maintenance", field: "maintenanceMonitors" },
{ key: "paused", status: "paused", field: "pausedMonitors" },
{ key: "initializing", status: "initializing", field: "initializingMonitors" },
];
@@ -26,7 +28,7 @@ const COUNTS: { key: string; status: MonitorStatus; field: keyof MonitorsSummary
export const MonitorStatusCard = () => {
const theme = useTheme();
const { t } = useTranslation();
const { data, isLoading, error } = useMonitors();
const { data, isLoading, isValidating, error } = useMonitors();
const summary = data?.summary ?? null;
return (
@@ -35,6 +37,7 @@ export const MonitorStatusCard = () => {
to="/uptime"
isLoading={isLoading && !summary}
error={error}
isStale={isValidating && Boolean(data)}
>
{!summary || summary.totalMonitors === 0 ? (
<CardMessage text={t("pages.dashboard.cards.monitorStatus.empty")} />
@@ -48,7 +51,10 @@ export const MonitorStatusCard = () => {
<Stack
key={key}
component={RouterLink}
to={`/uptime?status=${key}`}
// Plain /uptime: the monitors list does not read query
// params, so a ?status= filter would be silently dropped and
// the link would lie about where it goes.
to="/uptime"
gap={theme.spacing(LAYOUT.XXS)}
flex="1 1 0"
minWidth={96}
@@ -23,7 +23,7 @@ interface TypeBucket {
export const MonitorsByTypeCard = () => {
const theme = useTheme();
const { t } = useTranslation();
const { data, isLoading, error } = useMonitors();
const { data, isLoading, isValidating, error } = useMonitors();
const buckets = useMemo<TypeBucket[]>(() => {
const byType = new Map<MonitorType, TypeBucket>();
@@ -50,6 +50,7 @@ export const MonitorsByTypeCard = () => {
to="/uptime"
isLoading={isLoading && !data}
error={error}
isStale={isValidating && Boolean(data)}
>
{buckets.length === 0 ? (
<CardMessage text={t("pages.dashboard.cards.monitorsByType.empty")} />
@@ -28,7 +28,9 @@ const incidentDuration = (incident: IncidentSummaryItem): string | null => {
export const RecentIncidentsCard = () => {
const theme = useTheme();
const { t } = useTranslation();
const { data, isLoading, error } = useGet<IncidentSummary>("/incidents/team/summary");
const { data, isLoading, isValidating, error } = useGet<IncidentSummary>(
"/incidents/team/summary"
);
const incidents = (data?.latestIncidents ?? []).slice(0, MAX_ROWS);
@@ -38,6 +40,7 @@ export const RecentIncidentsCard = () => {
to="/incidents"
isLoading={isLoading && !data}
error={error}
isStale={isValidating && Boolean(data)}
action={
data && data.totalActive > 0 ? (
<Typography
@@ -10,7 +10,7 @@ const VIEWBOX_HEIGHT = 24;
* Response times as a bare polyline. Deliberately axis-free and label-free —
* at this size the shape is the only readable signal.
*
* `checks` arrives newest-first, so it is reversed to read left-to-right.
* `checks` arrives oldest-first, which is already left-to-right reading order.
*/
export const Sparkline = ({
checks,
@@ -22,8 +22,7 @@ export const Sparkline = ({
const points = useMemo(() => {
const values = checks
.map((check) => check.responseTime)
.filter((value): value is number => typeof value === "number")
.reverse();
.filter((value): value is number => typeof value === "number");
if (values.length < 2) {
return null;
@@ -26,8 +26,11 @@ const readStored = (): CardId[] | null => {
if (!Array.isArray(parsed)) {
return null;
}
const valid = parsed.filter(isCardId);
return valid.length > 0 ? valid : null;
// An empty array is a real choice — a dashboard the user emptied — and
// must not fall back to the defaults. Only an absent or malformed key
// returns null. Unknown ids are dropped so a card removed in a later
// release cannot break the page.
return parsed.filter(isCardId);
} catch (error) {
logger.error(
"Could not read dashboard card selection",
@@ -1,21 +1,20 @@
import { createContext, useContext } from "react";
import { useGet } from "@/Hooks/UseApi";
import {
MAX_RECENT_CHECKS,
MonitorTypes,
type MonitorsWithChecksResponse,
} from "@/Types/Monitor";
import { MonitorTypes, type MonitorsWithChecksResponse } from "@/Types/Monitor";
const REFRESH_INTERVAL = 30000;
// One request feeds every monitor-derived card. Cards read it from context so
// adding a monitor card costs no extra call.
//
// No rowsPerPage: the repository treats 0 as "no limit", so every monitor comes
// back. The dashboard summarises the whole fleet, it never pages. `limit` is
// deliberately not sent — findByTeamIdWithStats derives its page size from
// rowsPerPage alone and never reads it, so passing it would only imply a
// recent-check truncation that is not actually in effect.
const buildMonitorsUrl = () => {
const params = new URLSearchParams();
MonitorTypes.forEach((type) => params.append("type", type));
// No rowsPerPage: the repository treats 0 as "no limit", so every monitor
// comes back. The dashboard summarises the whole fleet, it never pages.
params.append("limit", String(MAX_RECENT_CHECKS));
return `/monitors/team/with-checks?${params.toString()}`;
};