From 23a6f85b0f718e8213575e4c1eee7086472f7468 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Sun, 15 Nov 2026 10:58:06 +0100 Subject: [PATCH 1/2] fix(sharing): drop an account read answered across a record switch Raising the record-session hold clears the query cache, which remounts the account query, so the switching tab has a GET /api/auth/me in flight beside its own POST /api/account/switch. When the server answered that read from the record being left and the answer was applied after the commit, fetchMe rewrote the scope mirror back to the old record. A peer tab that had already settled read that write as a foreign switch and published a hold expecting the old record, which no /me would ever confirm, so every tab sat behind the hydration gate until the stored transition aged out. The transition store now counts the changes a tab applies, and fetchMe repeats a read whose request straddled one instead of applying it. --- CHANGELOG.md | 6 + .../__tests__/use-auth-superseded-me.test.ts | 149 ++++++++++++++++++ src/hooks/use-auth.ts | 50 +++++- .../query-keys/record-session-transition.ts | 23 +++ 4 files changed, 220 insertions(+), 8 deletions(-) create mode 100644 src/hooks/__tests__/use-auth-superseded-me.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d4156079..69ca20e46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,12 @@ default was rejected as in the future, and onset dates could display as the wrong calendar day in non-UTC time zones. Saving now anchors to the current time when before local noon and preserves stored timestamps on edit. +- **Opening a record with the app open in a second tab.** Switching into or + out of a shared record could leave both tabs on the loading spinner, and a + reload within the next half minute did not help. An account check the + switching tab had started a moment before the switch could answer with the + record being left and overwrite the switch the other tabs were waiting on. + Such an answer is now discarded and asked again. ### Security diff --git a/src/hooks/__tests__/use-auth-superseded-me.test.ts b/src/hooks/__tests__/use-auth-superseded-me.test.ts new file mode 100644 index 000000000..86f1b154c --- /dev/null +++ b/src/hooks/__tests__/use-auth-superseded-me.test.ts @@ -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(); + }); +}); diff --git a/src/hooks/use-auth.ts b/src/hooks/use-auth.ts index 0c84e4924..580d4a7bf 100644 --- a/src/hooks/use-auth.ts +++ b/src/hooks/use-auth.ts @@ -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 & { + 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 { + for (let attempt = 0; ; attempt++) { + const before = recordSessionRevision(); + const data = await apiGet("/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 { // 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 { // 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 & { - 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. diff --git a/src/lib/query-keys/record-session-transition.ts b/src/lib/query-keys/record-session-transition.ts index c971883c3..d44f8d5a9 100644 --- a/src/lib/query-keys/record-session-transition.ts +++ b/src/lib/query-keys/record-session-transition.ts @@ -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 { From e84c358fdff5a68620d3979f756191ff3df8f31a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Sun, 15 Nov 2026 10:58:13 +0100 Subject: [PATCH 2/2] fix(charts): match chart loading shells to the charts they become The footer reserve under a day-linked chart's loading shell still held the caption line that was dropped from those charts, so every such shell stood 20 px taller than its chart (40 px on a phone). The dashboard's mood chart loaded behind the generic shell, which is about 30 px shorter than the mood card. When the shared chart chunk arrived late the dashboard's chart row changed height under a reader already scrolled past it; the tablet shell journey measured
right after such a swap and found it no longer at its end. The reserve now holds only the day rug, and the mood chart gets a shell built from the same card primitives and boxes. The tablet journey also waits for every chart cell to reveal and every loading shell to go before it scrolls to the end, instead of trusting two equal heights 250 ms apart. --- CHANGELOG.md | 5 ++ e2e/tablet-shell.spec.ts | 36 +++++++++++ src/app/insights/mood/page-client.tsx | 7 +- src/components/charts/chart-skeleton.tsx | 64 +++++++++++++++---- .../dashboard/tiles/chart-tiles.tsx | 7 +- 5 files changed, 103 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 69ca20e46..50a6d2152 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,11 @@ switching tab had started a moment before the switch could answer with the record being left and overwrite the switch the other tabs were waiting on. Such an answer is now discarded and asked again. +- **Charts no longer jump while they load.** The placeholder of every chart + that links its days was 20 px taller than the chart it turned into (40 px + on a phone), and the mood chart's placeholder was about 30 px shorter, so + the dashboard and the metric pages shifted under the reader when the charts + arrived. ### Security diff --git a/e2e/tablet-shell.spec.ts b/e2e/tablet-shell.spec.ts index ddd77e8a7..6f67b9cbb 100644 --- a/e2e/tablet-shell.spec.ts +++ b/e2e/tablet-shell.spec.ts @@ -54,6 +54,42 @@ async function openDashboard(page: Page) { ).toBeVisible(); // The module-gated destinations join the rail once `/api/auth/me` lands. await expect(page.locator('aside nav a[href="/medications"]')).toHaveCount(1); + await expectChartRowSettled(page); +} + +/** + * The dashboard's chart row has swapped every loading shell for its chart. + * + * The charts are one lazily loaded chunk, and each cell holds a skeleton until + * it lands and the row reveals. The swap changes the row's height, so a page + * measured before it is not the page the reader ends up with: on a loaded + * runner the chunk arrived a second after the dashboard painted, after + * `scrollMainToEnd` had already seen two equal heights, and `
` was no + * longer at its end when it was measured. Waited for on the cells' own state + * rather than on time. + */ +async function expectChartRowSettled(page: Page) { + await expect + .poll( + () => + page.evaluate(() => { + const main = document.getElementById("main-content")!; + const cells = main.querySelectorAll( + '[data-slot="dashboard-chart-cell"]', + ); + const held = main.querySelectorAll( + '[data-slot="dashboard-chart-cell"]:not([data-revealed="true"])', + ); + const shells = main.querySelectorAll('[data-slot="chart-skeleton"]'); + return { + cells: cells.length > 0, + held: held.length, + shells: shells.length, + }; + }), + { timeout: 15_000 }, + ) + .toEqual({ cells: true, held: 0, shells: 0 }); } /** The shell fills the window exactly and the document has nothing to scroll. */ diff --git a/src/app/insights/mood/page-client.tsx b/src/app/insights/mood/page-client.tsx index 00c75e12d..fa0f048cc 100644 --- a/src/app/insights/mood/page-client.tsx +++ b/src/app/insights/mood/page-client.tsx @@ -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: () => }, + { ssr: false, loading: () => }, ); /** diff --git a/src/components/charts/chart-skeleton.tsx b/src/components/charts/chart-skeleton.tsx index f160a07b3..828c24630 100644 --- a/src/components/charts/chart-skeleton.tsx +++ b/src/components/charts/chart-skeleton.tsx @@ -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 `` 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 (