Merge branch 'fix/e2e-flakes' into release/v1.47.6

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
Marc-André Bombeck committed 2026-11-15 10:59:09 +01:00
commit b4927e1ea4
8 files changed
+324 -24

No files matched your search

+5 -2
View File
@@ -12,7 +12,10 @@ import { queryKeys } from "@/lib/query-keys";
import { useTranslations } from "@/lib/i18n/context";
import { useInsightsLayoutPrefs } from "@/hooks/use-insights-layout-prefs";
import { Button } from "@/components/ui/button";
import { ChartSkeleton } from "@/components/charts/chart-skeleton";
import {
ChartSkeleton,
MoodChartSkeleton,
} from "@/components/charts/chart-skeleton";
import { MetricEmptyState } from "@/components/insights/metric-empty-state";
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
import {
@@ -54,7 +57,7 @@ const MoodChart = dynamic(
import("@/components/charts/chart-runtime").then((mod) => ({
default: mod.MoodChart,
})),
{ ssr: false, loading: () => <ChartSkeleton /> },
{ ssr: false, loading: () => <MoodChartSkeleton /> },
);
/**
+52 -12
View File
@@ -2,6 +2,7 @@
import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
@@ -50,12 +51,16 @@ const SLOW_HINT_DELAY_MS = 3_000;
/**
* The footer a loaded `<HealthChart>` paints under its plot: the row of day
* dots and its caption on a day-linked chart, and the collapsed "show as
* table" disclosure. A loading shell without it was ~100 px shorter than the
* card it turned into (CLS on every metric page, the BMI page most visibly),
* so the shells reserve the same boxes: `h-3` rug, `mt-1` caption (two lines
* on a phone, one from `sm`), and the disclosure's `mt-3 border-t pt-3` frame
* around its `min-h-11` button.
* dots on a day-linked chart, and the collapsed "show as table" disclosure. A
* loading shell without it was ~100 px shorter than the card it turned into
* (CLS on every metric page, the BMI page most visibly), so the shells reserve
* the same boxes: the `h-3` rug, and the disclosure's `mt-3 border-t pt-3`
* frame around its `min-h-11` button.
*
* The rug is all a day-linked chart paints under its plot. It used to carry a
* one-line caption as well, and the reserve kept that line after the caption
* went: every day-linked shell stood 20 px taller than its chart (40 px on a
* phone) and the page shrank under the reader when the chart arrived.
*/
export function ChartFooterReserve({
dayLinks = false,
@@ -67,12 +72,7 @@ export function ChartFooterReserve({
if (!dayLinks && !dataTable) return null;
return (
<div aria-hidden="true" data-slot="chart-footer-reserve">
{dayLinks ? (
<>
<div className="h-3" />
<div className="mt-1 h-9 sm:h-4" />
</>
) : null}
{dayLinks ? <div className="h-3" /> : null}
{dataTable ? (
<div className="border-border mt-3 border-t pt-3">
<div className="h-11" />
@@ -172,3 +172,43 @@ export function ChartSkeleton({
</div>
);
}
/**
* The loading shell for a full-size, day-linked `<MoodChart>`.
*
* The mood chart is drawn in a `Card` (vertical padding and a gap between
* header and plot, where `ChartSkeleton` has padding and a margin), its plot
* band is 200 / 220 px rather than 240 / 280, and it paints the day rug and
* the collapsed data-table disclosure under the plot. Shown in the generic
* shell, the card grew by about 30 px when the chart chunk arrived, under a
* reader already scrolled past it. So it gets the same primitives and the
* same boxes.
*/
export function MoodChartSkeleton() {
const { t } = useTranslations();
return (
<Card
data-slot="chart-skeleton"
role="status"
aria-busy="true"
aria-live="polite"
>
<span className="sr-only">{t("charts.loadingLabel")}</span>
<CardHeader>
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<Skeleton className="h-5 w-32" />
<div className="flex h-11 items-center gap-2">
<Skeleton className="h-6 w-12" />
<Skeleton className="h-6 w-12" />
<Skeleton className="h-6 w-12" />
<Skeleton className="h-6 w-12" />
</div>
</div>
</CardHeader>
<CardContent>
<Skeleton className="h-[var(--chart-height,200px)] w-full md:h-[var(--chart-height-md,220px)]" />
<ChartFooterReserve dayLinks dataTable />
</CardContent>
</Card>
);
}
@@ -4,7 +4,10 @@ import type { ComponentProps, ReactNode } from "react";
import dynamic from "next/dynamic";
import { ChartErrorBoundary } from "@/components/charts/chart-error-state";
import { ChartSkeleton } from "@/components/charts/chart-skeleton";
import {
ChartSkeleton,
MoodChartSkeleton,
} from "@/components/charts/chart-skeleton";
import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic";
import { RecentWorkoutsTile } from "@/components/dashboard/recent-workouts-tile";
import { RecentAchievementsCard } from "@/components/gamification/recent-achievements-card";
@@ -26,7 +29,7 @@ const MoodChartLazy = dynamic(
importWithRetry(() => import("@/components/charts/chart-runtime")).then(
(mod) => ({ default: mod.MoodChart }),
),
{ ssr: false, loading: () => <ChartSkeleton /> },
{ ssr: false, loading: () => <MoodChartSkeleton /> },
);
const MoodChart = (props: ComponentProps<typeof MoodChartLazy>) => (
<ChartErrorBoundary>
@@ -0,0 +1,149 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
__resetRecordFenceForTests,
currentRecordFenceState,
} from "@/lib/api/record-fence";
import {
__resetRecordScopeForTests,
getRecordScope,
setRecordScope,
} from "@/lib/query-keys/record-scope";
import {
__resetRecordSessionTransitionForTests,
beginRecordSessionTransition,
commitRecordSessionTransition,
getRecordSessionTransition,
} from "@/lib/query-keys/record-session-transition";
const apiGet = vi.fn();
vi.mock("@/lib/api/api-fetch", () => ({
apiGet: (...args: unknown[]) => apiGet(...args),
apiFetchRaw: vi.fn(),
ApiError: class ApiError extends Error {},
}));
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
}));
import { fetchMe } from "../use-auth";
/**
* A `/api/auth/me` answered across a record-session transition.
*
* The browser journey that found this: the switcher clears the query cache
* when it raises the hold, which remounts the account query, so the initiating
* tab has a `/me` in flight beside its own switch POST. The server answers it
* with the record being left. Applied after the commit, that answer rewrote the
* scope mirror to the old record, a settled peer read the write as a foreign
* switch, and every tab then waited for a `/me` naming a record the server had
* already left — behind the hydration gate, for good.
*/
const TARGET = "record-b";
const entry = {
accountId: TARGET,
username: "record-b",
displayName: null,
fullName: null,
access: "read",
level: "read",
recordKind: "shared",
sections: null,
canWrite: false,
writableDomains: [],
manageableDomains: [],
};
const base = {
id: "delegate",
username: "delegate",
role: "USER",
timezone: "Europe/Berlin",
};
/** What the server says before the switch lands: the caller's own record. */
const beforeSwitch = {
...base,
accountAccess: {
accounts: [entry],
active: null,
recordKind: "self",
canSwitch: true,
},
recordSession: { epoch: 4, scope: null },
};
/** And after it. */
const afterSwitch = {
...base,
accountAccess: {
accounts: [entry],
active: entry,
recordKind: "shared",
canSwitch: true,
},
recordSession: { epoch: 5, scope: TARGET },
};
beforeEach(() => {
apiGet.mockReset();
__resetRecordScopeForTests();
__resetRecordSessionTransitionForTests();
__resetRecordFenceForTests();
});
describe("fetchMe across a record-session transition", () => {
it("drops an answer that straddled the commit and reads again", async () => {
setRecordScope(null);
const id = beginRecordSessionTransition(TARGET);
apiGet
.mockImplementationOnce(async () => {
// The switch commits while this read is on the wire, and the server
// had already answered it from the record being left.
commitRecordSessionTransition(id, TARGET);
return beforeSwitch;
})
.mockResolvedValueOnce(afterSwitch);
const user = await fetchMe();
expect(apiGet).toHaveBeenCalledTimes(2);
expect(user.accountAccess?.active?.accountId).toBe(TARGET);
// The committed scope survives; the pre-switch answer never reached the
// mirror or the fence.
expect(getRecordScope()).toBe(TARGET);
expect(currentRecordFenceState()).toEqual({ epoch: 5, scope: TARGET });
// And the hold releases on the read that describes the switched session.
expect(getRecordSessionTransition().phase).toBe("ready");
});
it("applies an answer when nothing moved while it was in flight", async () => {
const id = beginRecordSessionTransition(TARGET);
commitRecordSessionTransition(id, TARGET);
apiGet.mockResolvedValueOnce(afterSwitch);
await fetchMe();
expect(apiGet).toHaveBeenCalledTimes(1);
expect(getRecordScope()).toBe(TARGET);
expect(getRecordSessionTransition().phase).toBe("ready");
});
it("gives up without applying anything when the session never holds still", async () => {
setRecordScope(null);
apiGet.mockImplementation(async () => {
// Every read straddles a fresh transition.
beginRecordSessionTransition(TARGET);
return beforeSwitch;
});
await expect(fetchMe()).rejects.toThrow(/kept moving/);
expect(apiGet).toHaveBeenCalledTimes(4);
expect(currentRecordFenceState()).toBeNull();
});
});
+42 -8
View File
@@ -36,6 +36,7 @@ import {
setRefusedRecordScope,
} from "@/lib/query-keys/record-scope";
import {
recordSessionRevision,
settleRecordSessionTransition,
settleRefusedRecordSessionTransition,
} from "@/lib/query-keys/record-session-transition";
@@ -361,6 +362,46 @@ export function isAuthVerdictUnknown(error: unknown): boolean {
return true;
}
/**
* How many times `fetchMe` asks again when a record-session transition moved
* while its request was in flight. Each repeat needs another transition inside
* one round trip, which only a browser switching records over and over
* produces.
*/
const SUPERSEDED_ME_RETRIES = 3;
type MePayload = Partial<AuthUser> & {
id: string;
username: string;
role: string;
timezone: string;
};
/**
* `GET /api/auth/me`, never answered across a record-session transition.
*
* Everything `fetchMe` does with the payload is a statement about which record
* this browser is in: it adopts the fence context, rewrites the cache-scope
* mirror every other tab watches, and may release the hold. A request issued
* before a transition and answered after it may have been read on the far side
* of a switch, and applying it is how a browser ended up wedged behind the
* hydration gate (see `recordSessionRevision`). Such an answer is dropped and
* the read repeated; the repeat is issued after the change, so it describes the
* session as it now is.
*/
async function getCurrentMe(): Promise<MePayload> {
for (let attempt = 0; ; attempt++) {
const before = recordSessionRevision();
const data = await apiGet<MePayload>("/api/auth/me");
if (recordSessionRevision() === before) return data;
if (attempt >= SUPERSEDED_ME_RETRIES) {
// Not an `ApiError`: no verdict on the session, so nothing is wiped and
// the hold stays until a later read settles it.
throw new Error("record session kept moving during /api/auth/me");
}
}
}
export async function fetchMe(): Promise<AuthUser> {
// v1.16.4 — routed through the typed wrapper; a non-OK /me (401)
// throws `ApiError`, which `useAuth` treats as "not authenticated"
@@ -369,14 +410,7 @@ export async function fetchMe(): Promise<AuthUser> {
// v1.4.47 — coerce `disableCoach` against `undefined` so a stale
// /me payload from a partial-deploy rollback (older server image
// without the field) keeps the Coach surface visible by default.
const data = await apiGet<
Partial<AuthUser> & {
id: string;
username: string;
role: string;
timezone: string;
}
>("/api/auth/me");
const data = await getCurrentMe();
// Hour-cycle preference: coerce against a stale /me payload, then mirror
// into localStorage so `useFormatters()` and the legacy format helpers
// (which cannot reach the query cache) render the same clock.
@@ -51,6 +51,8 @@ const READY: RecordSessionTransition = {
let transition = READY;
let seeded = false;
/** Bumped on every change this tab applies; see `recordSessionRevision`. */
let revision = 0;
const listeners = new Set<() => void>();
let channel: BroadcastChannel | null = null;
let storageListenerAttached = false;
@@ -107,6 +109,7 @@ function applyWire(next: WireTransition): void {
}
transition = toSnapshot(next);
seeded = true;
revision += 1;
notify();
}
@@ -228,6 +231,26 @@ export function getRecordSessionTransition(): RecordSessionTransition {
return transition;
}
/**
* A counter that moves whenever this tab applies a transition change — its own
* publish, or one received from another tab.
*
* `fetchMe` reads it on both sides of its request. A `/api/auth/me` answered
* across a change cannot say which side of that change the server read it on:
* the switcher's own `queryClient.clear()` remounts the account query the
* moment the hold goes up, so the initiator routinely has a `/me` in flight
* beside its own `POST /api/account/switch`, and that answer can describe the
* record the session has just left. Applied after the commit, it rewrites the
* scope mirror back to the old record; every peer that has already settled
* reads that write as a foreign switch and holds for a `/me` naming the old
* record, which no server answer will ever give. The counter is how `fetchMe`
* recognises such an answer and asks again instead of applying it.
*/
export function recordSessionRevision(): number {
seed();
return revision;
}
export function subscribeToRecordSessionTransition(
listener: () => void,
): () => void {