fix(daily): refresh the Today digest after a dose, drop the hero ring cluster

The Today digest went stale after logging a dose: nothing invalidated the
`["daily","digest"]` query, and it reads meds from the same server snapshot
the intake routes already hard-evict — so the "dose due" rail item lingered
until a hard reload. Add the digest key to the medication-dependent bundle and
force the inactive digest (unmounted while the user is on the medication card)
to refetch alongside the dashboard snapshot; the server snapshot eviction seam
is reused, so the refetch returns post-write dose state immediately.

Remove the score-ring cluster from the Today hero — it read as uneven and
wasted tile space. The health-score ring is the hero's only ring now; the
score-ring selection contract stays server-side for the native client. Tighten
the hero's vertical rhythm so the worth-a-look rail sits close under the lead
instead of floating below a half-empty column.

Wire the remaining sleep transports into the morning-refresh trigger: Google
Health, Fitbit, Oura, and Polar now enqueue the debounced morning refresh on a
last-night segment landing, matching the Withings / WHOOP / Apple seams — those
sources had no trigger at all. Make the trigger observable: each early-return
gate now annotates a distinct `daily.morning_refresh.skipped` reason (the
not-last-night gate also carries the samples' resolved local dates, today's key
and the tz) so a real landing shows exactly which gate fired.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018V8V9qapgHi7fhgtMJ8SkM
This commit is contained in:
Marc-André BombeckandClaude Opus 4.8 committed 2026-07-17 11:00:22 +02:00
1 parent f8c0ea5120
commit 65f90160c7
20 files changed
+350 -210

No files matched your search

+8
View File
@@ -317,6 +317,14 @@ describe("dependent-key bundles", () => {
const keyStrings = medicationDependentKeys.map((k) => JSON.stringify(k));
expect(keyStrings).toContain(JSON.stringify(["dashboard", "snapshot"]));
});
// v1.29.1 — the Today digest reads `medsToday` from the same server
// snapshot the intake routes hard-evict, but nothing invalidated the client
// query, so the digest's dose-window rail item lingered until a hard reload.
it("medicationDependentKeys bundles the daily digest (v1.29.1)", () => {
const keyStrings = medicationDependentKeys.map((k) => JSON.stringify(k));
expect(keyStrings).toContain(JSON.stringify(["daily", "digest"]));
});
});
/**
@@ -31,6 +31,23 @@ vi.mock("@/lib/db", () => ({
prisma: { user: { findUnique: () => userFindUniqueMock() } },
}));
// v1.29.1 — every gate now annotates a distinct `reason`; the spy captures the
// wide-event so each early return is observable in prod.
const annotateMock = vi.fn();
vi.mock("@/lib/logging/context", () => ({
annotate: (event: unknown) => annotateMock(event),
}));
/** The `meta` of the single wide-event the trigger emitted this call. */
function lastAnnotateMeta(): Record<string, unknown> {
const call = annotateMock.mock.calls.at(-1);
return (call?.[0] as { meta?: Record<string, unknown> })?.meta ?? {};
}
function lastAnnotateName(): string | undefined {
const call = annotateMock.mock.calls.at(-1);
return (call?.[0] as { action?: { name?: string } })?.action?.name;
}
import {
isLastNightLocal,
maybeEnqueueMorningRefresh,
@@ -84,6 +101,7 @@ describe("maybeEnqueueMorningRefresh", () => {
resolveModuleMapMock.mockResolvedValue({});
userFindUniqueMock.mockReset();
userFindUniqueMock.mockResolvedValue({ morningDigestRefreshedOn: null });
annotateMock.mockReset();
});
it("enqueues exactly one debounced refresh for many last-night samples", async () => {
@@ -101,30 +119,47 @@ describe("maybeEnqueueMorningRefresh", () => {
expect((opts as { singletonKey: string }).singletonKey).toBe(
"morning-refresh:u1:2026-07-16",
);
// The success path stays observable too.
expect(lastAnnotateName()).toBe("daily.morning_refresh.triggered");
});
it("does NOT trigger for an old/backfilled sleep only", async () => {
it("does NOT trigger for an old/backfilled sleep only, and annotates the gate", async () => {
await maybeEnqueueMorningRefresh("u1", [oldNight, oldNight], NOW);
expect(sendMock).not.toHaveBeenCalled();
expect(lastAnnotateName()).toBe("daily.morning_refresh.skipped");
const meta = lastAnnotateMeta();
expect(meta.reason).toBe("not_last_night");
// The diagnostic payload: today's local key, tz, and the samples' resolved
// local dates so a real landing shows exactly why the gate rejected them.
expect(meta.today).toBe("2026-07-16");
expect(meta.tz).toBe("America/Los_Angeles");
// 06:00Z on the 10th = 23:00 on the 9th in LA (UTC-7).
expect(meta.sample_local_dates).toEqual(["2026-07-09", "2026-07-09"]);
});
it("no-ops when the sleep module is off", async () => {
it("no-ops when the sleep module is off, and annotates the gate", async () => {
resolveModuleMapMock.mockResolvedValue({ sleep: false });
await maybeEnqueueMorningRefresh("u1", [lastNight], NOW);
expect(sendMock).not.toHaveBeenCalled();
expect(lastAnnotateName()).toBe("daily.morning_refresh.skipped");
expect(lastAnnotateMeta().reason).toBe("sleep_module_off");
});
it("skips the enqueue when the day is already finalised (marker == today)", async () => {
it("skips the enqueue when the day is already finalised (marker == today), and annotates the gate", async () => {
userFindUniqueMock.mockResolvedValue({
morningDigestRefreshedOn: "2026-07-16",
});
await maybeEnqueueMorningRefresh("u1", [lastNight], NOW);
expect(sendMock).not.toHaveBeenCalled();
expect(lastAnnotateName()).toBe("daily.morning_refresh.skipped");
expect(lastAnnotateMeta().reason).toBe("already_refreshed");
});
it("no-ops with no sleep samples", async () => {
it("no-ops with no sleep samples, and annotates the gate", async () => {
await maybeEnqueueMorningRefresh("u1", [], NOW);
expect(sendMock).not.toHaveBeenCalled();
expect(lastAnnotateName()).toBe("daily.morning_refresh.skipped");
expect(lastAnnotateMeta().reason).toBe("no_sleep_rows");
});
it("never throws when a dependency fails", async () => {
+52 -12
View File
@@ -4,18 +4,18 @@
* The nightly insight pre-pass (`insight-pregenerate`, 04:30) runs before last
* night's sleep has synced, so the morning digest + health score reference the
* day WITHOUT the current sleep. This trigger closes that gap the event-driven
* way: when a completed sleep segment for LAST NIGHT lands from any of the
* three sleep transports (Withings sync-sleep / the WHOOP sync / the
* Apple-Health measurement batch), it enqueues a debounced
* way: when a completed sleep segment for LAST NIGHT lands from any sleep
* transport (Withings sync-sleep / the WHOOP sync / the Apple-Health
* measurement batch / Google Health / Fitbit / Oura / Polar), it enqueues a debounced
* `morning-digest-refresh` job that re-runs the sleep-dependent generation and
* flips the day `provisional → final`.
*
* There is no single canonical sleep-persist function in the tree — each
* transport upserts through its own helper — so the three write seams each call
* `maybeEnqueueMorningRefresh` with the measuredAt of every sleep row they just
* transport upserts through its own helper — so every write seam calls
* `maybeEnqueueMorningRefresh` with the measuredAt of every sleep row it just
* wrote. The debounce (queue `singletonKey` + the `User.morningDigestRefreshedOn`
* marker) collapses the many samples of one night, and across all three
* sources, into ONE refresh per user per local morning.
* marker) collapses the many samples of one night, and across all sources,
* into ONE refresh per user per local morning.
*
* Timezone correctness is load-bearing: "last night" is judged in the user's
* PROFILE timezone, never UTC, so a 30-day backfill re-sync never re-triggers
@@ -76,24 +76,64 @@ export async function maybeEnqueueMorningRefresh(
now: Date = new Date(),
): Promise<void> {
try {
if (sleepMeasuredAts.length === 0) return;
// Gate 1 — nothing to refresh on. Every early return annotates a distinct
// `reason` so a real landing shows exactly which gate fired (the gates were
// silent before, so a "insight stuck on the nightly stamp" report could not
// be traced to a gate without a code change).
if (sleepMeasuredAts.length === 0) {
annotate({
action: { name: "daily.morning_refresh.skipped" },
meta: { reason: "no_sleep_rows" },
});
return;
}
const modules = await resolveModuleMap(userId);
if (modules.sleep === false) return;
if (modules.sleep === false) {
annotate({
action: { name: "daily.morning_refresh.skipped" },
meta: { reason: "sleep_module_off" },
});
return;
}
const tz = await resolveUserTimezone(userId);
const todayKey = userDayKey(now, tz);
const hasLastNight = sleepMeasuredAts.some((at) =>
isLastNightLocal(at, now, tz),
);
if (!hasLastNight) return;
if (!hasLastNight) {
// The most diagnostic gate: carry the samples' resolved LOCAL dates (up
// to 5) alongside today's key + tz, so the next real landing tells us
// exactly why `isLastNightLocal` rejected every segment (a tz mismatch, a
// backfill of only-old nights, or a clock-skewed future sample).
annotate({
action: { name: "daily.morning_refresh.skipped" },
meta: {
reason: "not_last_night",
today: todayKey,
tz,
sample_local_dates: sleepMeasuredAts
.slice(0, 5)
.map((at) => userDayKey(at, tz)),
},
});
return;
}
const localDate = userDayKey(now, tz);
const localDate = todayKey;
const row = await prisma.user.findUnique({
where: { id: userId },
select: { morningDigestRefreshedOn: true },
});
if (row?.morningDigestRefreshedOn === localDate) return;
if (row?.morningDigestRefreshedOn === localDate) {
annotate({
action: { name: "daily.morning_refresh.skipped" },
meta: { reason: "already_refreshed", local_date: localDate },
});
return;
}
await enqueueMorningDigestRefresh({ userId, localDate });
annotate({
+11
View File
@@ -33,6 +33,7 @@ import {
} from "./sync";
import { annotate } from "@/lib/logging/context";
import { resolveUserTimezone } from "@/lib/tz/resolver";
import { maybeEnqueueMorningRefresh } from "@/lib/daily/morning-refresh-trigger";
export async function syncUserSleep(
userId: string,
@@ -78,6 +79,16 @@ export async function syncUserSleep(
})
).imported;
// `markSynced` is owned by the orchestrator (`syncUserFitbit`).
// S4 — trigger the debounced morning refresh on a last-night segment landing
// (mirrors the Withings / WHOOP / Apple seams).
void maybeEnqueueMorningRefresh(
userId,
readings
.filter((r) => r.type === "SLEEP_DURATION")
.map((r) => r.measuredAt),
).catch(() => {});
annotate({ action: { name: "fitbit.sleep.sync", details: { imported } } });
return imported;
}
@@ -0,0 +1,112 @@
/**
* v1.29.1 — pins the S4 morning-digest-refresh wiring on the Google Health
* sleep transport. Google Health is a first-class sleep source, but the
* sleep-arrival trigger (`maybeEnqueueMorningRefresh`) was only hooked into
* Withings / WHOOP / Apple, so a Google-Health user's morning refresh never
* fired and their day stayed stuck at the 04:30 nightly pre-pass.
*
* This asserts a Google-sourced last-night sleep segment landing enqueues the
* debounced refresh EXACTLY once, with the segment's `measuredAt` — mirroring
* the existing transport trigger contract. The debounce itself (one refresh
* per user per local morning) is covered in `morning-refresh-trigger.test.ts`.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
const sleepMeasuredAt = new Date("2026-06-02T05:30:00.000Z");
const {
fetchDataPointsMock,
mapSleepSessionDetailedMock,
upsertMock,
maybeEnqueueMorningRefreshMock,
} = vi.hoisted(() => ({
fetchDataPointsMock: vi.fn(),
mapSleepSessionDetailedMock: vi.fn(),
upsertMock: vi.fn(),
maybeEnqueueMorningRefreshMock: vi.fn(async () => {}),
}));
vi.mock("../client", () => ({
GOOGLE_HEALTH_ACTIVITY_PAGE_SIZE: 100,
GOOGLE_HEALTH_DATA_TYPES: { sleep: "sleep" },
fetchDataPoints: fetchDataPointsMock,
mapSleepSessionDetailed: mapSleepSessionDetailedMock,
}));
vi.mock("../sync", () => ({
getValidToken: vi.fn(async () => ({ accessToken: "tok" })),
handleCollectionFetchError: vi.fn(() => 0),
noteHardFailure: vi.fn(),
replaceStaleGoogleHealthSleep: vi.fn(async () => 0),
upsertGoogleHealthMeasurements: upsertMock,
}));
vi.mock("@/lib/tz/resolver", () => ({
resolveUserTimezone: vi.fn(async () => "Europe/Berlin"),
}));
vi.mock("@/lib/logging/context", () => ({
annotate: vi.fn(),
getEvent: vi.fn(() => null),
}));
vi.mock("@/lib/daily/morning-refresh-trigger", () => ({
maybeEnqueueMorningRefresh: maybeEnqueueMorningRefreshMock,
}));
import { syncUserSleep } from "../sync-sleep";
beforeEach(() => {
vi.clearAllMocks();
fetchDataPointsMock.mockResolvedValue([{ raw: "point" }]);
mapSleepSessionDetailedMock.mockReturnValue({
rows: [
{
type: "SLEEP_DURATION",
value: 480,
unit: "min",
measuredAt: sleepMeasuredAt,
fieldTag: "anchor:sleep:a",
sleepStage: null,
},
],
windowStart: new Date("2026-06-01T22:00:00.000Z"),
windowEnd: sleepMeasuredAt,
});
upsertMock.mockResolvedValue({ imported: 1 });
});
describe("google-health syncUserSleep — S4 morning-refresh trigger", () => {
it("enqueues exactly one morning refresh with the sleep segment's measuredAt", async () => {
await syncUserSleep("user-1");
expect(maybeEnqueueMorningRefreshMock).toHaveBeenCalledTimes(1);
expect(maybeEnqueueMorningRefreshMock).toHaveBeenCalledWith("user-1", [
sleepMeasuredAt,
]);
});
it("passes no sleep timestamps when the night carried no SLEEP_DURATION rows", async () => {
mapSleepSessionDetailedMock.mockReturnValue({
rows: [
{
type: "HEART_RATE",
value: 55,
unit: "bpm",
measuredAt: sleepMeasuredAt,
fieldTag: "hr:a",
sleepStage: null,
},
],
windowStart: new Date("2026-06-01T22:00:00.000Z"),
windowEnd: sleepMeasuredAt,
});
await syncUserSleep("user-1");
// Still called once (the trigger self-gates on an empty array), but with no
// sleep timestamps — so it no-ops rather than refreshing on non-sleep rows.
expect(maybeEnqueueMorningRefreshMock).toHaveBeenCalledTimes(1);
expect(maybeEnqueueMorningRefreshMock).toHaveBeenCalledWith("user-1", []);
});
});
+13
View File
@@ -38,6 +38,7 @@ import {
} from "./sync";
import { annotate, getEvent } from "@/lib/logging/context";
import { resolveUserTimezone } from "@/lib/tz/resolver";
import { maybeEnqueueMorningRefresh } from "@/lib/daily/morning-refresh-trigger";
export async function syncUserSleep(
userId: string,
@@ -113,6 +114,18 @@ export async function syncUserSleep(
})
).imported;
// `markSynced` is owned by the orchestrator (`syncUserGoogleHealth`).
// S4 — trigger the debounced morning refresh on a last-night segment landing
// (mirrors the Withings / WHOOP / Apple seams). Google Health is a first-
// class sleep transport, so without this a Google-Health user's morning
// refresh never fired and their day stayed stuck at the 04:30 pre-pass.
void maybeEnqueueMorningRefresh(
userId,
readings
.filter((r) => r.type === "SLEEP_DURATION")
.map((r) => r.measuredAt),
).catch(() => {});
annotate({
action: { name: "googleHealth.sleep.sync", details: { imported } },
});
+11
View File
@@ -47,6 +47,7 @@ import {
recomputeBucketsForMeasurement,
} from "@/lib/rollups/measurement-rollups";
import { invalidateStatusInsightsForTypes } from "@/lib/insights/comprehensive-generate";
import { maybeEnqueueMorningRefresh } from "@/lib/daily/morning-refresh-trigger";
import {
sweepStaleSleepSegments,
type SleepSegmentSweep,
@@ -369,6 +370,16 @@ export async function syncUserOura(
// sibling collection failed — one bad collection must not blank the source.
const imported = await upsertOuraMeasurements(userId, result.readings);
// S4 — trigger the debounced morning refresh on a last-night segment landing
// (mirrors the Withings / WHOOP / Apple seams). Fires whether or not a
// sibling collection failed, since the sleep readings were still imported.
void maybeEnqueueMorningRefresh(
userId,
result.readings
.filter((r) => r.type === "SLEEP_DURATION")
.map((r) => r.measuredAt),
).catch(() => {});
if (result.failures.length > 0) {
// Partial failure: keep the cycle honest. Record the failure and do NOT
// stamp success, so the freshness surface reflects that some collections
+11
View File
@@ -35,6 +35,7 @@ import {
recomputeBucketsForMeasurement,
} from "@/lib/rollups/measurement-rollups";
import { invalidateStatusInsightsForTypes } from "@/lib/insights/comprehensive-generate";
import { maybeEnqueueMorningRefresh } from "@/lib/daily/morning-refresh-trigger";
import {
fetchActivities,
fetchCardioLoads,
@@ -161,6 +162,16 @@ export async function syncUserPolar(userId: string): Promise<number> {
await sweepStaleSleepSegments(userId, "POLAR", sleepSweeps);
const imported = await upsertPolarMeasurements(userId, readings);
// S4 — trigger the debounced morning refresh on a last-night segment landing
// (mirrors the Withings / WHOOP / Apple seams).
void maybeEnqueueMorningRefresh(
userId,
readings
.filter((r) => r.type === "SLEEP_DURATION")
.map((r) => r.measuredAt),
).catch(() => {});
await recordSyncSuccess(userId, "polar");
return imported;
}
+10
View File
@@ -158,6 +158,15 @@ export const moodDependentKeys = [
* minutes. The intake routes already hard-evict the server-side
* snapshot bucket, so the refetch this triggers returns post-write data
* immediately.
*
* v1.29.1 — `dailyDigest` joins the bundle. The Today hero's digest reads
* `medsToday` from the same server snapshot the intake routes hard-evict,
* but nothing invalidated the client query, so the digest's "dose due"
* rail item lingered until a hard reload. Like the snapshot, the digest
* query runs with refetchOnMount/WindowFocus tuned off, so the intake
* seam ALSO forces an inactive refetch (it is unmounted while the user is
* on the medication card); this bundle membership covers the case where
* the dashboard is the active surface.
*/
export const medicationDependentKeys = [
queryKeys.medications(),
@@ -166,6 +175,7 @@ export const medicationDependentKeys = [
queryKeys.insightsTargets(),
queryKeys.gamificationAchievements(),
queryKeys.dashboardSnapshot(),
queryKeys.dailyDigest(),
["dashboard-medication-compliance"] as const,
["compliance-chart-inline"] as const,
];