From 5de309c19a1492154f33c719839d94ea6da7e836 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 11:19:24 +0100 Subject: [PATCH 01/14] feat(nav): let the navigation counts be switched off (#1113) The counts on Medications and Checkups in the sidebar and the More sheet can now be turned off under Settings > Account > Display. On by default, which is how they behaved before. User.showNavCounts (migration 0559, BOOLEAN NOT NULL DEFAULT true) is written by PATCH /api/auth/me/show-nav-counts and published on /api/auth/me, so the account seed carries it into the first paint. useNavCounts reads it: while it is off no count is drawn and GET /api/nav/counts is never asked. The setting travels with the account settings backup in both purposes, is restored like the other interface preferences, and is kept by the data wipe. The settings round trip covers write, /me, backup and restore; the backup parity goldens gain the column. --- CHANGELOG.md | 4 +- docs/api/openapi.yaml | 78 +++++++++++++ docs/ops/deploy.md | 7 +- messages/de.json | 4 +- messages/en.json | 4 +- messages/es.json | 4 +- messages/fr.json | 4 +- messages/it.json | 4 +- messages/ko.json | 4 +- messages/nl.json | 4 +- messages/pl.json | 4 +- messages/pt-BR.json | 4 +- messages/ru.json | 4 +- .../0559_show_nav_counts/migration.sql | 21 ++++ prisma/schema.prisma | 6 + src/app/api/auth/me/show-nav-counts/route.ts | 72 ++++++++++++ .../__tests__/modules-section.test.tsx | 1 + .../__tests__/time-format-select.test.tsx | 1 + .../__tests__/unit-preference-select.test.tsx | 1 + .../settings/account-section/index.tsx | 3 + src/components/settings/nav-counts-switch.tsx | 64 +++++++++++ src/hooks/__tests__/use-nav-counts.test.tsx | 104 ++++++++++++++++++ src/hooks/use-auth.ts | 9 ++ src/hooks/use-nav-counts.ts | 11 +- src/lib/auth/account-seed.ts | 1 + src/lib/auth/me-payload.ts | 8 +- src/lib/auth/session-user.ts | 1 + src/lib/data-wipe/wipe-plan.ts | 2 + .../export/account-settings-backup-schema.ts | 1 + src/lib/export/account-settings-backup.ts | 2 + src/lib/openapi/routes/account-sharing.ts | 5 + src/lib/openapi/routes/profile.ts | 38 +++++++ src/lib/validations/user-prefs.ts | 5 + tests/browser/render.tsx | 1 + .../export-disaster-recovery.json | 2 + .../backup-parity/export-portable.json | 2 + .../restore-disaster-recovery-over-live.json | 2 +- .../restore-disaster-recovery.json | 4 +- .../backup-parity/restore-portable.json | 4 +- .../backup-parity/restore-skips.json | 1 + .../backup-parity/restore-version-1.json | 2 + .../backup-parity/seeded-account.json | 1 + tests/integration/settings-round-trip.test.ts | 15 +++ 43 files changed, 497 insertions(+), 22 deletions(-) create mode 100644 prisma/migrations/0559_show_nav_counts/migration.sql create mode 100644 src/app/api/auth/me/show-nav-counts/route.ts create mode 100644 src/components/settings/nav-counts-switch.tsx create mode 100644 src/hooks/__tests__/use-nav-counts.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index f5b0870ba1..ecca875d50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,7 +45,7 @@ - Capture menu: most-used types as rows, "Save and next", the last reading under the field; the save receipt has Undo and Edit. - Biomarker page lists its five newest values under the chart. - Time zone per reading from the iPhone; the Day view, list and daily charts follow it. -- The sidebar and the More sheet sort their entries under Tracking, Health record and Analysis. Medications and Checkups show a small number when a dose or a check-up is due. No address changes. Thanks to @Cnote43 for the sketch it follows. ([#1113](https://github.com/MBombeck/HealthLog/discussions/1113)) +- The sidebar and the More sheet sort their entries under Tracking, Health record and Analysis. Medications and Checkups show a small number when a dose or a check-up is due; the numbers can be switched off under Settings > Account > Display. No address changes. Thanks to @Cnote43 for the sketch it follows. ([#1113](https://github.com/MBombeck/HealthLog/discussions/1113)) - The search finds every page and every settings card, in every language also by keyword ("snooze", "dark mode", "Nextcloud", "ICE"). - Settings > Notifications has an "Alerts" group with account security and lasting change in a vital, visible before any channel is set up. - Settings > Data & privacy opens with "Who can reach your record": accounts and guardians, clinician links, the emergency card link, the care and cycle calendars, API tokens, MCP and sign-ins, each with its link. @@ -200,7 +200,7 @@ ### Updating - Take a backup first. With the `backups` volume the container writes a pre-migration dump before it migrates; without it, run `pg_dump` yourself. `docs/ops/deploy.md`, "v1.49.0 notes", has the operator detail. -- Thirty-six migrations, 0514 to 0558 (0516, 0523, 0527, 0528, 0541, 0548, 0550, 0552 and 0555 do not exist); the boot log says `36 database migrations pending`. Seven touch existing data: +- Thirty-seven migrations, 0514 to 0559 (0516, 0523, 0527, 0528, 0541, 0548, 0550, 0552 and 0555 do not exist); the boot log says `37 database migrations pending`. Seven touch existing data: - 0515 merges dose rows recorded twice for one slot (take, then skip, then the oldest pending row; the rest soft-deleted), refunds the stock of a merged take, clears the auto-miss mark on taken or skipped doses, and rewrites legacy single-time schedules into dose windows. - 0517 makes e-mail and username unique regardless of case. On a clash it stops, changes nothing, and the container does not start: list the accounts with the query in `docs/ops/deploy.md` ("Accounts that differ only in case"), ideally before the update, rename one of each pair, run `prisma migrate resolve --rolled-back 0517_case_insensitive_identity_and_retention_indexes` as shown there, and start again. It also drops six duplicate indexes, builds four retention indexes (bounded to five minutes) and checks the shape of text day keys, `NOT VALID` with a warning where old rows do not fit. - 0529 lowers APNs tokens; where two devices held one token in different case, the most recently seen keeps it and the other registers again on its next launch. diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index 52f0ef9ec2..d080f506d0 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -12196,6 +12196,43 @@ paths: "415": *a30 "422": *a4 "429": *a5 + /api/auth/me/show-nav-counts: + patch: + tags: + - Auth + summary: Show or hide the navigation counts + description: >- + Whether the sidebar and the More sheet show their counts: the doses due on Medications and the check-ups due on + Checkups. On by default. While it is off a client shows no count and does not call `GET /api/nav/counts`. The + current value is `showNavCounts` on `/api/auth/me`. + + + Hard-set, idempotent, audit-logged. Rate-limited 60 / min per user. The caller's own setting: under a switched + session it is still the caller's. + + + The body is capped at 1 KB and must carry `Content-Type: application/json`. Anything larger is 413, a wrong + content type is 415, and a body that is not JSON at all is 400. + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ShowNavCountsPatchRequest" + responses: + "200": + description: The stored flag. + content: + application/json: + schema: + $ref: "#/components/schemas/PatchShowNavCountsEnvelope" + "400": *a28 + "401": *a1 + "403": *a9 + "413": *a29 + "415": *a30 + "422": *a4 + "429": *a5 /api/auth/me/use-central-codex: get: tags: @@ -35824,6 +35861,14 @@ components: required: - storeWorkoutRoutes description: Keep or stop keeping the GPS track of new workouts. Off by default. + ShowNavCountsPatchRequest: + type: object + properties: + showNavCounts: + type: boolean + required: + - showNavCounts + description: Show or hide the counts in the navigation (doses due, check-ups due). On by default. UseCentralCodexPatchRequest: type: object properties: @@ -48916,6 +48961,8 @@ components: type: - string - "null" + showNavCounts: + type: boolean timeFormat: type: string dateFormat: @@ -71705,6 +71752,31 @@ components: - data - error additionalProperties: false + PatchShowNavCountsEnvelope: + type: object + properties: + data: + $ref: "#/components/schemas/ShowNavCountsResponse" + error: + type: "null" + meta: + type: object + properties: + requestId: + type: string + additionalProperties: false + required: + - data + - error + additionalProperties: false + ShowNavCountsResponse: + type: object + properties: + showNavCounts: + type: boolean + required: + - showNavCounts + additionalProperties: false GetUseCentralCodexEnvelope: type: object properties: @@ -100064,6 +100136,11 @@ components: two agree on one registry, otherwise `NONE`, and stored, so a later change of language does not move it. Set it with `PATCH /api/auth/me/medicine-registry`. Clients show and edit it; the link itself comes ready-built on the medication list and detail as `leafletSearch`.' + showNavCounts: + type: boolean + description: "#1113 — whether the navigation shows its counts (doses due on Medications, check-ups due on Checkups). + `true` by default. When `false`, show no count and do not call `GET /api/nav/counts`. Set it with `PATCH + /api/auth/me/show-nav-counts`." features: type: object properties: @@ -100160,6 +100237,7 @@ components: - timezone - glucoseUnit - medicineRegistry + - showNavCounts - features - push - accountAccess diff --git a/docs/ops/deploy.md b/docs/ops/deploy.md index da9dd86033..4ed9555c0e 100644 --- a/docs/ops/deploy.md +++ b/docs/ops/deploy.md @@ -214,9 +214,9 @@ always did, and finds nothing in the queue schema it did not create. ### v1.49.0 notes The sequence above covers this release, with one possible stop (`0517`, see -below). It brings thirty-six migrations, `0514` to `0558` (`0516`, `0523`, +below). It brings thirty-seven migrations, `0514` to `0559` (`0516`, `0523`, `0527`, `0528`, `0541`, `0548`, `0550`, `0552` and `0555` do not exist), so -the boot log says `36 database migrations pending`. Copy the pre-migration +the boot log says `37 database migrations pending`. Copy the pre-migration dump of step 0 off the host before you start: it is the way back. Seven migrations touch data you already have: @@ -338,7 +338,8 @@ quantities (`0514`, `0519`), nullable columns or columns with a default `devices.local_runway_until` in `0542`, `push_data_changes.intake_sync_owed_at` in `0544`, `live_activity_tokens.relay_started BOOLEAN NOT NULL DEFAULT false` in `0545`, `measurements.stats_computed_at` in `0547`, `users.medicine_registry` -and `medications.leaflet_url` in `0549`), and new tables (`0522`, `0524`, +and `medications.leaflet_url` in `0549`, `users.show_nav_counts BOOLEAN NOT +NULL DEFAULT true` in `0559`), and new tables (`0522`, `0524`, `0531`, `0532`, `0534`, `0535`, and `ai_job_failures` in `0553`, which holds why background AI work last stopped for a record: closed reason codes only, cleared by the next success, cascading with the account). diff --git a/messages/de.json b/messages/de.json index 821cf2e2be..512ef76c71 100644 --- a/messages/de.json +++ b/messages/de.json @@ -8200,7 +8200,9 @@ "displayCard": { "title": "Darstellung", "description": "Sprache, Einheiten und Formate, gespeichert, sobald du sie änderst.", - "themeDescription": "System folgt deinem Gerät zwischen hell und dunkel. Die Wahl gilt auf diesem Gerät." + "themeDescription": "System folgt deinem Gerät zwischen hell und dunkel. Die Wahl gilt auf diesem Gerät.", + "navCountsLabel": "Zahlen in der Navigation", + "navCountsDescription": "Zeigt in der Seitenleiste und im Menü „Mehr“ neben den Einträgen, wie viele Einnahmen und Vorsorgetermine fällig sind." }, "integrationCard": { "state": { diff --git a/messages/en.json b/messages/en.json index c2d230594f..80bae34e3c 100644 --- a/messages/en.json +++ b/messages/en.json @@ -8200,7 +8200,9 @@ "displayCard": { "title": "Display", "description": "Language, units and formats, saved as soon as you change them.", - "themeDescription": "System follows your device between light and dark. The choice is kept on this device." + "themeDescription": "System follows your device between light and dark. The choice is kept on this device.", + "navCountsLabel": "Counts in the navigation", + "navCountsDescription": "Shows how many doses and check-ups are due beside their entries in the sidebar and the More menu." }, "integrationCard": { "state": { diff --git a/messages/es.json b/messages/es.json index 1ab6d4155d..41befe9600 100644 --- a/messages/es.json +++ b/messages/es.json @@ -8200,7 +8200,9 @@ "displayCard": { "title": "Visualización", "description": "Idioma, unidades y formatos; se guardan en cuanto los cambias.", - "themeDescription": "Sistema sigue a tu dispositivo entre claro y oscuro. La elección se guarda en este dispositivo." + "themeDescription": "Sistema sigue a tu dispositivo entre claro y oscuro. La elección se guarda en este dispositivo.", + "navCountsLabel": "Contadores en la navegación", + "navCountsDescription": "Muestra junto a sus entradas, en la barra lateral y en el menú Más, cuántas tomas y revisiones están pendientes." }, "integrationCard": { "state": { diff --git a/messages/fr.json b/messages/fr.json index 64a4e58050..fb2706b900 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -8200,7 +8200,9 @@ "displayCard": { "title": "Affichage", "description": "Langue, unités et formats, enregistrés dès que vous les modifiez.", - "themeDescription": "Système suit votre appareil entre clair et sombre. Le choix est gardé sur cet appareil." + "themeDescription": "Système suit votre appareil entre clair et sombre. Le choix est gardé sur cet appareil.", + "navCountsLabel": "Compteurs dans la navigation", + "navCountsDescription": "Affiche, à côté des entrées de la barre latérale et du menu Plus, le nombre de prises et de bilans à faire." }, "integrationCard": { "state": { diff --git a/messages/it.json b/messages/it.json index f71342cbd8..0ef578569c 100644 --- a/messages/it.json +++ b/messages/it.json @@ -8200,7 +8200,9 @@ "displayCard": { "title": "Visualizzazione", "description": "Lingua, unità e formati, salvati appena li modifichi.", - "themeDescription": "Sistema segue il dispositivo tra chiaro e scuro. La scelta resta su questo dispositivo." + "themeDescription": "Sistema segue il dispositivo tra chiaro e scuro. La scelta resta su questo dispositivo.", + "navCountsLabel": "Conteggi nella navigazione", + "navCountsDescription": "Mostra accanto alle voci della barra laterale e del menu Altro quante dosi e quanti controlli sono in scadenza." }, "integrationCard": { "state": { diff --git a/messages/ko.json b/messages/ko.json index cac8d3cb5c..82cc648c9f 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -8200,7 +8200,9 @@ "displayCard": { "title": "표시", "description": "언어, 단위, 형식은 바꾸는 즉시 저장돼요.", - "themeDescription": "시스템은 기기 설정에 따라 밝은 테마와 어두운 테마를 오갑니다. 선택은 이 기기에 저장됩니다." + "themeDescription": "시스템은 기기 설정에 따라 밝은 테마와 어두운 테마를 오갑니다. 선택은 이 기기에 저장됩니다.", + "navCountsLabel": "내비게이션 숫자", + "navCountsDescription": "사이드바와 더 보기 메뉴의 항목 옆에 복용할 약과 받아야 할 검진이 몇 개인지 보여줘요." }, "integrationCard": { "state": { diff --git a/messages/nl.json b/messages/nl.json index 524f993c25..10d4e5a923 100644 --- a/messages/nl.json +++ b/messages/nl.json @@ -8200,7 +8200,9 @@ "displayCard": { "title": "Weergave", "description": "Taal, eenheden en notaties, opgeslagen zodra je ze wijzigt.", - "themeDescription": "Systeem volgt je apparaat tussen licht en donker. De keuze blijft op dit apparaat." + "themeDescription": "Systeem volgt je apparaat tussen licht en donker. De keuze blijft op dit apparaat.", + "navCountsLabel": "Aantallen in de navigatie", + "navCountsDescription": "Toont naast de items in de zijbalk en het menu Meer hoeveel innames en controles er openstaan." }, "integrationCard": { "state": { diff --git a/messages/pl.json b/messages/pl.json index df8f16b9ce..ae8791fc15 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -8200,7 +8200,9 @@ "displayCard": { "title": "Wyświetlanie", "description": "Język, jednostki i formaty zapisywane od razu po zmianie.", - "themeDescription": "Systemowy podąża za urządzeniem między jasnym a ciemnym. Wybór zostaje na tym urządzeniu." + "themeDescription": "Systemowy podąża za urządzeniem między jasnym a ciemnym. Wybór zostaje na tym urządzeniu.", + "navCountsLabel": "Liczniki w nawigacji", + "navCountsDescription": "Pokazuje przy pozycjach na pasku bocznym i w menu Więcej, ile dawek i badań kontrolnych jest do zrobienia." }, "integrationCard": { "state": { diff --git a/messages/pt-BR.json b/messages/pt-BR.json index 5a289542d2..b61e56bec7 100644 --- a/messages/pt-BR.json +++ b/messages/pt-BR.json @@ -8200,7 +8200,9 @@ "displayCard": { "title": "Exibição", "description": "Escolha como os dados são exibidos no HealthLog.", - "themeDescription": "Sistema acompanha o seu dispositivo entre claro e escuro. A escolha fica salva neste dispositivo." + "themeDescription": "Sistema acompanha o seu dispositivo entre claro e escuro. A escolha fica salva neste dispositivo.", + "navCountsLabel": "Contadores na navegação", + "navCountsDescription": "Mostra ao lado das entradas, na barra lateral e no menu Mais, quantas doses e consultas preventivas estão pendentes." }, "integrationCard": { "state": { diff --git a/messages/ru.json b/messages/ru.json index 9313884b5f..0bc1aac54e 100644 --- a/messages/ru.json +++ b/messages/ru.json @@ -8200,7 +8200,9 @@ "displayCard": { "title": "Отображение", "description": "Язык, единицы и форматы, сохраняются сразу при изменении.", - "themeDescription": "Системная следует за устройством между светлой и тёмной. Выбор хранится на этом устройстве." + "themeDescription": "Системная следует за устройством между светлой и тёмной. Выбор хранится на этом устройстве.", + "navCountsLabel": "Счётчики в навигации", + "navCountsDescription": "Показывает рядом с пунктами на боковой панели и в меню «Ещё», сколько приёмов и профилактических осмотров предстоит." }, "integrationCard": { "state": { diff --git a/prisma/migrations/0559_show_nav_counts/migration.sql b/prisma/migrations/0559_show_nav_counts/migration.sql new file mode 100644 index 0000000000..0818d4694b --- /dev/null +++ b/prisma/migrations/0559_show_nav_counts/migration.sql @@ -0,0 +1,21 @@ +-- The switch for the navigation counts (#1113): whether the sidebar and the +-- More sheet show the doses due on Medications and the check-ups due on +-- Checkups. +-- +-- `users.show_nav_counts`: on by default, which is how the counts behaved +-- before the switch existed, so every existing account keeps them. +-- +-- A NOT NULL column with a constant default: metadata-only since Postgres 11, +-- no rewrite. IF NOT EXISTS keeps a replay harmless. Reversibility: drop the +-- column. +-- +-- @retry-on-lock-timeout + +DO $migration$ +BEGIN + PERFORM set_config('lock_timeout', '5s', true); + + ALTER TABLE "users" + ADD COLUMN IF NOT EXISTS "show_nav_counts" BOOLEAN NOT NULL DEFAULT true; +END +$migration$; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 8509efee47..fa79d210db 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -469,6 +469,12 @@ model User { /// medication detail read, which builds the link. The server never fetches /// anything from a registry. medicineRegistry String? @map("medicine_registry") + /// #1113 — whether the navigation shows its counts (doses due on + /// Medications, check-ups due on Checkups) in the sidebar and the More + /// sheet. On by default. While it is off the client does not ask + /// `GET /api/nav/counts` at all. Written by + /// `PATCH /api/auth/me/show-nav-counts`; read through `/api/auth/me`. + showNavCounts Boolean @default(true) @map("show_nav_counts") // v1.18.6 — explicit "I have diabetes / clinician glucose targets" opt-in. // When `true`, the glucose target resolver applies the tighter ADA glycemic // GOAL bands (fasting 80–130, postprandial < 180) instead of the general diff --git a/src/app/api/auth/me/show-nav-counts/route.ts b/src/app/api/auth/me/show-nav-counts/route.ts new file mode 100644 index 0000000000..9a8ef8fb1d --- /dev/null +++ b/src/app/api/auth/me/show-nav-counts/route.ts @@ -0,0 +1,72 @@ +/** + * Whether the navigation shows its counts (#1113). + * + * PATCH /api/auth/me/show-nav-counts — body `{ showNavCounts: boolean }`. + * + * The sidebar and the More sheet show the doses due on Medications and the + * check-ups due on Checkups. On by default. While it is off the client shows + * no count and does not ask `GET /api/nav/counts`. The current value is + * published on `/api/auth/me` as `showNavCounts`. + * + * The per-user-scalar pattern of `medicine-registry` next door: 60/min rate + * limit, a 1 KB body cap, Zod safeParse with a 422, an audit row, a + * field-by-field write, and the resolved next state as the answer. + * Idempotent. + */ +import { apiHandler, requireAuth } from "@/lib/api-handler"; +import { apiError, apiSuccess, getClientIp } from "@/lib/api-response"; +import { parseJsonBody } from "@/lib/api/body"; +import { annotate } from "@/lib/logging/context"; +import { auditLog } from "@/lib/auth/audit"; +import { prisma } from "@/lib/db"; +import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit"; +import { showNavCountsPatchSchema } from "@/lib/validations/user-prefs"; + +export const dynamic = "force-dynamic"; + +const PATCH_RATE_LIMIT = 60; +const PATCH_WINDOW_MS = 60_000; + +export const PATCH = apiHandler(async (req: Request) => { + const { user } = await requireAuth(); + + const rl = await checkRateLimit( + `show-nav-counts:patch:${user.id}`, + PATCH_RATE_LIMIT, + PATCH_WINDOW_MS, + ); + if (!rl.allowed) { + const response = apiError("Too many requests", 429); + for (const [k, v] of Object.entries(rateLimitHeaders(rl))) { + response.headers.set(k, v); + } + return response; + } + + const parsed = await parseJsonBody(req, showNavCountsPatchSchema, { + maxBytes: 1024, + action: "auth.me.show-nav-counts.patch.invalid_shape", + }); + if (!parsed.ok) return parsed.error; + + const next = parsed.data.showNavCounts; + const previous = user.showNavCounts; + + await prisma.user.update({ + where: { id: user.id }, + data: { showNavCounts: next }, + }); + + await auditLog("user.show-nav-counts.update", { + userId: user.id, + ipAddress: getClientIp(req), + details: { previous, next }, + }); + + annotate({ + action: { name: "auth.me.show-nav-counts.patch" }, + meta: { showNavCounts: next }, + }); + + return apiSuccess({ showNavCounts: next }); +}); diff --git a/src/components/settings/__tests__/modules-section.test.tsx b/src/components/settings/__tests__/modules-section.test.tsx index b396ccabd1..49af5cd242 100644 --- a/src/components/settings/__tests__/modules-section.test.tsx +++ b/src/components/settings/__tests__/modules-section.test.tsx @@ -100,6 +100,7 @@ function buildUser( timeFormat: "AUTO", dateFormat: "AUTO", medicineRegistry: "NONE", + showNavCounts: true, disableCoach: false, fullName: null, insurerName: null, diff --git a/src/components/settings/__tests__/time-format-select.test.tsx b/src/components/settings/__tests__/time-format-select.test.tsx index 53f260eae5..916eed5abf 100644 --- a/src/components/settings/__tests__/time-format-select.test.tsx +++ b/src/components/settings/__tests__/time-format-select.test.tsx @@ -48,6 +48,7 @@ function buildUser(timeFormat: TimeFormatPreference): AuthUser { timeFormat, dateFormat: "AUTO", medicineRegistry: "NONE", + showNavCounts: true, disableCoach: false, fullName: null, insurerName: null, diff --git a/src/components/settings/__tests__/unit-preference-select.test.tsx b/src/components/settings/__tests__/unit-preference-select.test.tsx index 2f7d572be9..3799f58d0e 100644 --- a/src/components/settings/__tests__/unit-preference-select.test.tsx +++ b/src/components/settings/__tests__/unit-preference-select.test.tsx @@ -51,6 +51,7 @@ function buildUser(unitPreference: "metric" | "imperial"): AuthUser { timeFormat: "AUTO", dateFormat: "AUTO", medicineRegistry: "NONE", + showNavCounts: true, disableCoach: false, fullName: null, insurerName: null, diff --git a/src/components/settings/account-section/index.tsx b/src/components/settings/account-section/index.tsx index 131e4555ea..da8db41cc1 100644 --- a/src/components/settings/account-section/index.tsx +++ b/src/components/settings/account-section/index.tsx @@ -34,6 +34,7 @@ import { TimeFormatSelect } from "@/components/settings/time-format-select"; import { DateFormatSelect } from "@/components/settings/date-format-select"; import { UnitPreferenceSelect } from "@/components/settings/unit-preference-select"; import { GlucoseUnitSelect } from "@/components/settings/glucose-unit-select"; +import { NavCountsSwitch } from "@/components/settings/nav-counts-switch"; import { detectBrowserTimezone, userDayKey } from "@/lib/tz/format"; import { apiFetchRaw, apiGet } from "@/lib/api/api-fetch"; import { @@ -776,6 +777,8 @@ export function DisplayPreferencesCard({ {t("settings.displayCard.themeDescription")}

+ {/* #1113 — the counts on Medications and Checkups in the navigation. */} + ); } diff --git a/src/components/settings/nav-counts-switch.tsx b/src/components/settings/nav-counts-switch.tsx new file mode 100644 index 0000000000..6b17916812 --- /dev/null +++ b/src/components/settings/nav-counts-switch.tsx @@ -0,0 +1,64 @@ +"use client"; + +import { useState } from "react"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; + +import { toastWrittenOutcome } from "@/components/outcome/outcome-toast"; +import { SwitchRow } from "@/components/ui/switch-row"; +import { useAuth } from "@/hooks/use-auth"; +import { apiPatch } from "@/lib/api/api-fetch"; +import { showErrorToast } from "@/lib/errors/error-toast"; +import { useTranslations } from "@/lib/i18n/context"; +import { queryKeys } from "@/lib/query-keys"; + +/** + * Settings > Account > Display: whether the sidebar and the More sheet show + * their counts (#1113), the doses due on Medications and the check-ups due on + * Checkups. On by default. Saves on change through + * `PATCH /api/auth/me/show-nav-counts`, then re-reads `/api/auth/me`, which + * `useNavCounts` reads the choice from; while it is off the counts are not + * asked for at all. + */ +export function NavCountsSwitch({ + isAuthenticated, +}: { + isAuthenticated: boolean; +}) { + const { t } = useTranslations(); + const queryClient = useQueryClient(); + const { user } = useAuth(); + const [optimistic, setOptimistic] = useState(null); + const checked = optimistic ?? user?.showNavCounts !== false; + + const mutation = useMutation({ + mutationFn: (showNavCounts: boolean) => + apiPatch<{ showNavCounts: boolean }>("/api/auth/me/show-nav-counts", { + showNavCounts, + }), + onSuccess: async () => { + toastWrittenOutcome("success", t("settings.saved")); + await queryClient.invalidateQueries({ queryKey: queryKeys.authMe() }); + setOptimistic(null); + }, + onError: (err) => { + setOptimistic(null); + showErrorToast(t("settings.savingError"), { cause: err }); + }, + }); + + return ( + { + if (next === checked || mutation.isPending || !isAuthenticated) return; + setOptimistic(next); + mutation.mutate(next); + }} + /> + ); +} diff --git a/src/hooks/__tests__/use-nav-counts.test.tsx b/src/hooks/__tests__/use-nav-counts.test.tsx new file mode 100644 index 0000000000..f6139996a9 --- /dev/null +++ b/src/hooks/__tests__/use-nav-counts.test.tsx @@ -0,0 +1,104 @@ +/** + * The navigation counts follow the person's switch (#1113): on by default, + * and while it is off no count is drawn and `/api/nav/counts` is never asked. + */ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderToStaticMarkup } from "react-dom/server"; +import { Pill } from "lucide-react"; + +const useAuthMock = vi.fn(); +vi.mock("@/hooks/use-auth", () => ({ useAuth: () => useAuthMock() })); +const inSharedRecordMock = vi.fn(() => false); +vi.mock("@/hooks/use-record-capabilities", () => ({ + useRecordCapabilities: () => ({ inSharedRecord: inSharedRecordMock() }), +})); +vi.mock("@/hooks/use-mounted", () => ({ useMounted: () => true })); +const apiGetMock = vi.fn(); +vi.mock("@/lib/api/api-fetch", () => ({ + apiGet: (...args: unknown[]) => apiGetMock(...args), +})); + +// The query layer stands in as a recorder: it hands back the server's counts +// and runs the query function only when the options enable it, so the test +// sees both what the hook returns and whether it asked at all. +const queryOptions: Array<{ enabled?: boolean; queryFn: () => unknown }> = []; +vi.mock("@tanstack/react-query", () => ({ + useQuery: (options: { enabled?: boolean; queryFn: () => unknown }) => { + queryOptions.push(options); + if (options.enabled !== false) options.queryFn(); + return { data: { dosesDue: 2, checkupsDue: 1 } }; + }, +})); + +import { MoreHubGroups } from "@/components/layout/more-hub-groups"; +import { useNavCounts } from "@/hooks/use-nav-counts"; +import { I18nProvider } from "@/lib/i18n/context"; + +function Probe({ enabled }: { enabled: boolean }) { + return {JSON.stringify(useNavCounts(enabled))}; +} + +function counts(enabled = true): Record { + const html = renderToStaticMarkup(); + return JSON.parse( + html.replace(/^|<\/span>$/g, "").replace(/"/g, '"'), + ) as Record; +} + +function moreSheet(): string { + return renderToStaticMarkup( + + false} + onNavigate={() => {}} + /> + , + ); +} + +describe("useNavCounts and the switch", () => { + beforeEach(() => { + vi.clearAllMocks(); + queryOptions.length = 0; + inSharedRecordMock.mockReturnValue(false); + }); + + it("shows the counts and asks for them by default", () => { + useAuthMock.mockReturnValue({ user: { showNavCounts: true } }); + expect(counts()).toEqual({ "/medications": 2, "/checkups": 1 }); + expect(queryOptions.at(-1)?.enabled).toBe(true); + expect(apiGetMock).toHaveBeenCalledWith("/api/nav/counts"); + }); + + it("keeps them on before the account resolves", () => { + useAuthMock.mockReturnValue({ user: null }); + expect(counts()).toEqual({ "/medications": 2, "/checkups": 1 }); + }); + + it("shows nothing and never asks while the switch is off", () => { + useAuthMock.mockReturnValue({ user: { showNavCounts: false } }); + expect(counts()).toEqual({}); + expect(queryOptions.length).toBeGreaterThan(0); + expect(queryOptions.every((o) => o.enabled === false)).toBe(true); + expect(apiGetMock).not.toHaveBeenCalled(); + }); + + it("draws the badge in the More sheet only while the switch is on", () => { + useAuthMock.mockReturnValue({ user: { showNavCounts: true } }); + expect(moreSheet().match(/data-slot="nav-count"/g)).toHaveLength(1); + + useAuthMock.mockReturnValue({ user: { showNavCounts: false } }); + const html = moreSheet(); + expect(html).not.toContain('data-slot="nav-count"'); + expect(html).toContain("Medications"); + expect(apiGetMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/hooks/use-auth.ts b/src/hooks/use-auth.ts index 40f9b21a88..d547e28a4e 100644 --- a/src/hooks/use-auth.ts +++ b/src/hooks/use-auth.ts @@ -171,6 +171,12 @@ export interface AuthUser { * server. Coerced to `NONE` against a stale /me payload. */ medicineRegistry: MedicineRegistryChoice; + /** + * #1113 — whether the sidebar and the More sheet show their counts. Off + * means no count and no `/api/nav/counts` read. Coerced to `true` (the + * default) against a stale /me payload. + */ + showNavCounts: boolean; /** * v1.4.47 — the signed-in person's own stored Coach opt-out. It is * the value the Activate-Coach switch and the module toggle edit, and @@ -534,6 +540,9 @@ export function adoptMePayload( medicineRegistry: isMedicineRegistryChoice(data.medicineRegistry) ? data.medicineRegistry : "NONE", + // #1113 — on unless the payload says off, so a stale payload keeps the + // counts the way they were before the switch existed. + showNavCounts: data.showNavCounts !== false, // v1.15.0 — coerce against a stale /me payload so the cycle nav entry // stays hidden by default when the field is absent. cycleTrackingEnabled: data.cycleTrackingEnabled === true, diff --git a/src/hooks/use-nav-counts.ts b/src/hooks/use-nav-counts.ts index ce6f2646a9..54444ae570 100644 --- a/src/hooks/use-nav-counts.ts +++ b/src/hooks/use-nav-counts.ts @@ -9,10 +9,13 @@ * (`src/lib/navigation/nav-counts.ts`). The sidebar and the More sheet share * the cached answer; every dose write and every check-up write evicts it * (`queryKeys.navCounts()` in the dependent-key sets). Inside somebody else's - * record no count is shown and nothing is asked. + * record no count is shown and nothing is asked. Neither when the person + * switched the counts off (`showNavCounts`, Settings > Account > Display): + * no count, and no read either. */ import { useQuery } from "@tanstack/react-query"; +import { useAuth } from "@/hooks/use-auth"; import { useRecordCapabilities } from "@/hooks/use-record-capabilities"; import { apiGet } from "@/lib/api/api-fetch"; import type { NavCounts } from "@/lib/navigation/nav-counts"; @@ -28,7 +31,11 @@ export function navCountsByHref( export function useNavCounts(enabled: boolean): Record { const { inSharedRecord } = useRecordCapabilities(); - const active = enabled && !inSharedRecord; + const { user } = useAuth(); + // On unless the person switched them off; the account seed carries the + // choice, so the first paint already knows. + const shown = user?.showNavCounts !== false; + const active = enabled && shown && !inSharedRecord; const counts = useQuery({ queryKey: queryKeys.navCounts(), queryFn: () => apiGet("/api/nav/counts"), diff --git a/src/lib/auth/account-seed.ts b/src/lib/auth/account-seed.ts index b28f6a6128..10f35bc756 100644 --- a/src/lib/auth/account-seed.ts +++ b/src/lib/auth/account-seed.ts @@ -45,6 +45,7 @@ export const ACCOUNT_SEED_FIELDS = [ "timeFormat", "dateFormat", "medicineRegistry", + "showNavCounts", "notificationPrefs", "disableCoach", "displayName", diff --git a/src/lib/auth/me-payload.ts b/src/lib/auth/me-payload.ts index 1c0941c2da..cf148e9f7f 100644 --- a/src/lib/auth/me-payload.ts +++ b/src/lib/auth/me-payload.ts @@ -265,8 +265,9 @@ export async function buildAuthMePayload( /** * How the caller reads the app: the glucose unit, the unit system, the hour - * cycle, the date order and the medicine registry the leaflet search opens. - * Each is the caller's own preference, never the record's. + * cycle, the date order, the medicine registry the leaflet search opens and + * whether the navigation shows its counts. Each is the caller's own + * preference, never the record's. */ function displayPreferences( user: AuthContext["user"], @@ -291,6 +292,9 @@ function displayPreferences( // medication list and detail reads build the link (`leafletSearch`), so a // client only reads this to show and edit the setting. medicineRegistry, + // #1113 — whether the sidebar and the More sheet show their counts. Off + // means no count and no `/api/nav/counts` read. + showNavCounts: user.showNavCounts, }; } diff --git a/src/lib/auth/session-user.ts b/src/lib/auth/session-user.ts index 2629863a7c..9af3ea5b44 100644 --- a/src/lib/auth/session-user.ts +++ b/src/lib/auth/session-user.ts @@ -77,6 +77,7 @@ export const SESSION_USER_SELECT = { moodTagLayoutJson: true, glucoseUnit: true, medicineRegistry: true, + showNavCounts: true, hasDiabetes: true, labsLocalOcrEnabled: true, unitPreference: true, diff --git a/src/lib/data-wipe/wipe-plan.ts b/src/lib/data-wipe/wipe-plan.ts index 87dcf06eab..f6224948cd 100644 --- a/src/lib/data-wipe/wipe-plan.ts +++ b/src/lib/data-wipe/wipe-plan.ts @@ -622,6 +622,8 @@ export const USER_KEPT_FIELDS: Readonly> = { glucoseUnit: "an interface preference — mg/dL or mmol/L rendering", medicineRegistry: "an interface preference — which official registry the leaflet search opens, not record content", + showNavCounts: + "an interface preference — whether the navigation shows its counts, not record content", disclaimerAcknowledgedAt: "the account's acknowledgement of the medical disclaimer, which is about the app and not about the record", disclaimerAcknowledgedVersion: diff --git a/src/lib/export/account-settings-backup-schema.ts b/src/lib/export/account-settings-backup-schema.ts index 3f1bcc8f3b..c59ba17fc8 100644 --- a/src/lib/export/account-settings-backup-schema.ts +++ b/src/lib/export/account-settings-backup-schema.ts @@ -55,6 +55,7 @@ export const accountSettingsBackupSchema = z unitPreference: z.string().nullable().optional(), glucoseUnit: z.string().nullable().optional(), medicineRegistry: z.string().nullable().optional(), + showNavCounts: z.boolean().optional(), timeFormat: z.string().optional(), dateFormat: z.string().optional(), modulePreferencesJson: z.unknown().optional(), diff --git a/src/lib/export/account-settings-backup.ts b/src/lib/export/account-settings-backup.ts index e2aaa0f7a4..4fc68e16d1 100644 --- a/src/lib/export/account-settings-backup.ts +++ b/src/lib/export/account-settings-backup.ts @@ -595,6 +595,8 @@ const ACCOUNT_SETTING_CODECS = { ), // #1430 — which medicine registry the leaflet search opens. medicineRegistry: oneOf("medicineRegistry", MEDICINE_REGISTRY_CHOICES, true), + // #1113 — whether the navigation shows its counts. + showNavCounts: plain("showNavCounts"), timeFormat: oneOf("timeFormat", Object.values(TimeFormatPreference), false), dateFormat: oneOf("dateFormat", Object.values(DateFormatPreference), false), // What is switched on, what is shown where, and what counts as in range. diff --git a/src/lib/openapi/routes/account-sharing.ts b/src/lib/openapi/routes/account-sharing.ts index cd3d8231b2..6cd068d275 100644 --- a/src/lib/openapi/routes/account-sharing.ts +++ b/src/lib/openapi/routes/account-sharing.ts @@ -541,6 +541,11 @@ const accountPayload = z ), // #1430 — enumerated: the medication surfaces and the settings read it. medicineRegistry: medicineRegistryField, + showNavCounts: z + .boolean() + .describe( + "#1113 — whether the navigation shows its counts (doses due on Medications, check-ups due on Checkups). `true` by default. When `false`, show no count and do not call `GET /api/nav/counts`. Set it with `PATCH /api/auth/me/show-nav-counts`.", + ), features: accountFeaturesBlock, push: accountPushBlock, accountAccess: accountAccessBlock, diff --git a/src/lib/openapi/routes/profile.ts b/src/lib/openapi/routes/profile.ts index 2b61c27485..b59bf02ecc 100644 --- a/src/lib/openapi/routes/profile.ts +++ b/src/lib/openapi/routes/profile.ts @@ -34,6 +34,7 @@ import { injectionSitePrefsPatchSchema, labsLocalOcrPatchSchema, workoutRoutesPatchSchema, + showNavCountsPatchSchema, unitPreferencePatchSchema, glucoseUnitPatchSchema, useCentralCodexPatchSchema, @@ -1049,6 +1050,16 @@ const workoutRoutesResponse = z .object({ storeWorkoutRoutes: z.boolean() }) .meta({ id: "WorkoutRoutesResponse" }); +const showNavCountsPatchRequest = showNavCountsPatchSchema.meta({ + id: "ShowNavCountsPatchRequest", + description: + "Show or hide the counts in the navigation (doses due, check-ups due). On by default.", +}); + +const showNavCountsResponse = z + .object({ showNavCounts: z.boolean() }) + .meta({ id: "ShowNavCountsResponse" }); + const useCentralCodexPatchRequest = useCentralCodexPatchSchema.meta({ id: "UseCentralCodexPatchRequest", description: @@ -2361,6 +2372,33 @@ export const profilePaths: NonNullable = { }, }, }, + "/api/auth/me/show-nav-counts": { + patch: { + tags: ["Auth"], + summary: "Show or hide the navigation counts", + description: + "Whether the sidebar and the More sheet show their counts: the doses due on Medications and the check-ups due on Checkups. On by default. While it is off a client shows no count and does not call `GET /api/nav/counts`. The current value is `showNavCounts` on `/api/auth/me`.\n\nHard-set, idempotent, audit-logged. Rate-limited 60 / min per user. The caller's own setting: under a switched session it is still the caller's.\n\nThe body is capped at 1 KB and must carry `Content-Type: application/json`. Anything larger is 413, a wrong content type is 415, and a body that is not JSON at all is 400.", + requestBody: { + required: true, + content: { "application/json": { schema: showNavCountsPatchRequest } }, + }, + responses: { + "200": { + description: "The stored flag.", + content: { + "application/json": { + schema: dataEnvelope( + showNavCountsResponse, + "PatchShowNavCountsEnvelope", + ), + }, + }, + }, + ...cappedScalarBodyRefusals, + ...stdResponses, + }, + }, + }, "/api/auth/me/use-central-codex": { get: { tags: ["Auth"], diff --git a/src/lib/validations/user-prefs.ts b/src/lib/validations/user-prefs.ts index f6d3778137..dc3e5bf989 100644 --- a/src/lib/validations/user-prefs.ts +++ b/src/lib/validations/user-prefs.ts @@ -56,6 +56,11 @@ export const workoutRoutesPatchSchema = z.object({ storeWorkoutRoutes: z.boolean(), }); +/** `PATCH /api/auth/me/show-nav-counts` — the counts in the navigation. */ +export const showNavCountsPatchSchema = z.object({ + showNavCounts: z.boolean(), +}); + /** `PATCH /api/auth/me/use-central-codex` — the operator's shared Codex. */ export const useCentralCodexPatchSchema = z.object({ useCentralCodex: z.boolean(), diff --git a/tests/browser/render.tsx b/tests/browser/render.tsx index f38acb2c7a..eadefb8347 100644 --- a/tests/browser/render.tsx +++ b/tests/browser/render.tsx @@ -47,6 +47,7 @@ export function authUser(overrides: Partial = {}): AuthUser { timeFormat: "AUTO", dateFormat: "AUTO", medicineRegistry: "NONE", + showNavCounts: true, disableCoach: false, fullName: null, insurerName: null, diff --git a/tests/integration/__golden__/backup-parity/export-disaster-recovery.json b/tests/integration/__golden__/backup-parity/export-disaster-recovery.json index 9756200cb1..0b7222f205 100644 --- a/tests/integration/__golden__/backup-parity/export-disaster-recovery.json +++ b/tests/integration/__golden__/backup-parity/export-disaster-recovery.json @@ -81,6 +81,7 @@ "unitPreference": "imperial", "glucoseUnit": "mmol/L", "medicineRegistry": "GB", + "showNavCounts": false, "timeFormat": "H12", "dateFormat": "DMY", "modulePreferencesJson": { @@ -2811,6 +2812,7 @@ "unitPreference": "imperial", "glucoseUnit": "mmol/L", "medicineRegistry": "GB", + "showNavCounts": false, "timeFormat": "H12", "dateFormat": "DMY", "modulePreferencesJson": { diff --git a/tests/integration/__golden__/backup-parity/export-portable.json b/tests/integration/__golden__/backup-parity/export-portable.json index 2a62256f3a..cb1e8f8bbf 100644 --- a/tests/integration/__golden__/backup-parity/export-portable.json +++ b/tests/integration/__golden__/backup-parity/export-portable.json @@ -29,6 +29,7 @@ "unitPreference": "imperial", "glucoseUnit": "mmol/L", "medicineRegistry": "GB", + "showNavCounts": false, "timeFormat": "H12", "dateFormat": "DMY", "modulePreferencesJson": { @@ -2020,6 +2021,7 @@ "unitPreference": "imperial", "glucoseUnit": "mmol/L", "medicineRegistry": "GB", + "showNavCounts": false, "timeFormat": "H12", "dateFormat": "DMY", "modulePreferencesJson": { diff --git a/tests/integration/__golden__/backup-parity/restore-disaster-recovery-over-live.json b/tests/integration/__golden__/backup-parity/restore-disaster-recovery-over-live.json index 8ceb87498a..d504137194 100644 --- a/tests/integration/__golden__/backup-parity/restore-disaster-recovery-over-live.json +++ b/tests/integration/__golden__/backup-parity/restore-disaster-recovery-over-live.json @@ -345,7 +345,7 @@ "seizureTypes": 1, "seizureEvents": 2 }, - "accountSettingsApplied": 67, + "accountSettingsApplied": 68, "skipped": { "catalogueKeys": [], "links": 0 diff --git a/tests/integration/__golden__/backup-parity/restore-disaster-recovery.json b/tests/integration/__golden__/backup-parity/restore-disaster-recovery.json index 673b158ee4..bdb49c6d78 100644 --- a/tests/integration/__golden__/backup-parity/restore-disaster-recovery.json +++ b/tests/integration/__golden__/backup-parity/restore-disaster-recovery.json @@ -345,7 +345,7 @@ "seizureTypes": 0, "seizureEvents": 0 }, - "accountSettingsApplied": 67, + "accountSettingsApplied": 68, "skipped": { "catalogueKeys": [], "links": 0 @@ -3082,6 +3082,7 @@ }, "glucoseUnit": "mmol/L", "medicineRegistry": "GB", + "showNavCounts": false, "hasDiabetes": true, "labsLocalOcrEnabled": true, "storeWorkoutRoutes": true, @@ -3316,6 +3317,7 @@ "unitPreference": "imperial", "glucoseUnit": "mmol/L", "medicineRegistry": "GB", + "showNavCounts": false, "timeFormat": "H12", "dateFormat": "DMY", "modulePreferencesJson": { diff --git a/tests/integration/__golden__/backup-parity/restore-portable.json b/tests/integration/__golden__/backup-parity/restore-portable.json index a3064ee1d5..868287e91b 100644 --- a/tests/integration/__golden__/backup-parity/restore-portable.json +++ b/tests/integration/__golden__/backup-parity/restore-portable.json @@ -381,7 +381,7 @@ "seizureTypes": 0, "seizureEvents": 0 }, - "accountSettingsApplied": 67, + "accountSettingsApplied": 68, "skipped": { "catalogueKeys": [ { @@ -2574,6 +2574,7 @@ }, "glucoseUnit": "mmol/L", "medicineRegistry": "GB", + "showNavCounts": false, "hasDiabetes": true, "labsLocalOcrEnabled": true, "storeWorkoutRoutes": true, @@ -2756,6 +2757,7 @@ "unitPreference": "imperial", "glucoseUnit": "mmol/L", "medicineRegistry": "GB", + "showNavCounts": false, "timeFormat": "H12", "dateFormat": "DMY", "modulePreferencesJson": { diff --git a/tests/integration/__golden__/backup-parity/restore-skips.json b/tests/integration/__golden__/backup-parity/restore-skips.json index 7b668b1539..fd16070fea 100644 --- a/tests/integration/__golden__/backup-parity/restore-skips.json +++ b/tests/integration/__golden__/backup-parity/restore-skips.json @@ -942,6 +942,7 @@ "nutrientTargetsJson": null, "glucoseUnit": null, "medicineRegistry": null, + "showNavCounts": true, "hasDiabetes": false, "labsLocalOcrEnabled": false, "storeWorkoutRoutes": false, diff --git a/tests/integration/__golden__/backup-parity/restore-version-1.json b/tests/integration/__golden__/backup-parity/restore-version-1.json index ee5d339e85..fe91249258 100644 --- a/tests/integration/__golden__/backup-parity/restore-version-1.json +++ b/tests/integration/__golden__/backup-parity/restore-version-1.json @@ -1092,6 +1092,7 @@ "nutrientTargetsJson": null, "glucoseUnit": null, "medicineRegistry": null, + "showNavCounts": true, "hasDiabetes": false, "labsLocalOcrEnabled": false, "storeWorkoutRoutes": false, @@ -1298,6 +1299,7 @@ "unitPreference": null, "glucoseUnit": null, "medicineRegistry": null, + "showNavCounts": true, "timeFormat": "AUTO", "dateFormat": "AUTO", "modulePreferencesJson": null, diff --git a/tests/integration/__golden__/backup-parity/seeded-account.json b/tests/integration/__golden__/backup-parity/seeded-account.json index 232e1173a0..8d119fe8bf 100644 --- a/tests/integration/__golden__/backup-parity/seeded-account.json +++ b/tests/integration/__golden__/backup-parity/seeded-account.json @@ -2679,6 +2679,7 @@ }, "glucoseUnit": "mmol/L", "medicineRegistry": "GB", + "showNavCounts": false, "hasDiabetes": true, "labsLocalOcrEnabled": true, "storeWorkoutRoutes": true, diff --git a/tests/integration/settings-round-trip.test.ts b/tests/integration/settings-round-trip.test.ts index 8e0c22edf5..4486fcdbfa 100644 --- a/tests/integration/settings-round-trip.test.ts +++ b/tests/integration/settings-round-trip.test.ts @@ -43,6 +43,7 @@ import * as disableCoach from "@/app/api/auth/me/disable-coach/route"; import * as unitPreference from "@/app/api/auth/me/unit-preference/route"; import * as glucoseUnit from "@/app/api/auth/me/glucose-unit/route"; import * as medicineRegistry from "@/app/api/auth/me/medicine-registry/route"; +import * as showNavCounts from "@/app/api/auth/me/show-nav-counts/route"; import * as injectionSites from "@/app/api/auth/me/injection-site-prefs/route"; import * as modules from "@/app/api/auth/me/modules/route"; import * as healthScore from "@/app/api/auth/me/health-score-config/route"; @@ -444,6 +445,20 @@ function entries(user: Pick): Entry[] { expected: "BE", me: { pick: (me) => at(me, "medicineRegistry"), expected: "BE" }, }, + { + // #1113 — published on /me, which is also its read. Written off, the + // value that differs from the default. + columns: ["showNavCounts"], + write: { + handler: showNavCounts.PATCH, + method: "PATCH", + route: "/api/auth/me/show-nav-counts", + body: { showNavCounts: false }, + }, + read: get(getMe, "/api/auth/me", "showNavCounts"), + expected: false, + me: { pick: (me) => at(me, "showNavCounts"), expected: false }, + }, { columns: ["globalExcludedInjectionSites"], write: { From 4f6d7eeab512054f93d435a767e6c64c6f4427e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 11:31:55 +0100 Subject: [PATCH 02/14] feat(care): rename the checkups page to Care and move it to /care The preventive-care page reads Care in English and lives at /care, with the practitioners under /care/practitioners. German keeps Vorsorge; Brazilian Portuguese and Russian drop their transliterations for Prevencao and Profilaktika. Message keys, tour ids, the Arrangement sub-page and every API path stay as they were. /checkups and /checkups/* answer a permanent redirect to the same place under /care with the query kept, and /vorsorge now goes there in one hop. care-route-redirects.test.ts runs the old addresses through the Next.js matcher and checks status and Location. What the server sends keeps /checkups: push and webhook targets, and the href/path fields of the digest, day, search, related-records and onboarding answers, because released iPhone builds parse only those shapes. visit-links.ts now has a wire and a web spelling; care-wire-paths.test.ts pins the wire values and fails on a /care literal in server code. --- CHANGELOG.md | 3 +- bundle-budget.json | 4 +- docs/contributing/ui-standards.md | 2 +- docs/self-hosting/notifications.md | 2 +- docs/using/care-calendar-feed.md | 6 +- docs/using/search.md | 2 +- e2e/command-palette.spec.ts | 6 +- e2e/dashboard-ssr-prefetch-hydration.spec.ts | 6 +- e2e/tablet-shell.spec.ts | 2 +- e2e/vaccinations.spec.ts | 6 +- e2e/visits.spec.ts | 4 +- messages/en.json | 18 +-- messages/pt-BR.json | 16 +-- messages/ru.json | 2 +- next.config.ts | 24 +++- prisma/schema.prisma | 4 +- .../baselines/version-stamp-comments.json | 2 +- src/__tests__/care-route-redirects.test.ts | 106 ++++++++++++++++++ src/__tests__/care-wire-paths.test.ts | 93 +++++++++++++++ .../encounter-reminder-exclusion.test.ts | 2 +- .../prefetch-page-caching-guard.test.ts | 2 +- src/__tests__/session-surface-guard.test.ts | 2 +- .../shared-record-navigation.test.tsx | 22 ++-- src/__tests__/surface-registry-guard.test.ts | 2 +- src/__tests__/visit-link-guard.test.ts | 45 ++++---- src/app/api/measurement-reminders/route.ts | 2 +- .../api/vaccinations/[id]/booster/route.ts | 2 +- .../__tests__/page-client-view.test.tsx | 10 +- .../__tests__/page-prefetch.test.tsx | 18 +-- src/app/{checkups => care}/page-client.tsx | 4 +- src/app/{checkups => care}/page.tsx | 12 +- .../{checkups => care}/practitioners/page.tsx | 2 +- src/app/medications/page-client.tsx | 2 +- .../daily/__tests__/priority-card.test.tsx | 4 +- src/components/daily/priority-card.tsx | 2 +- src/components/daily/today-hero.tsx | 2 +- .../__tests__/document-record-links.test.tsx | 2 +- .../documents/document-record-links.tsx | 4 +- .../documents/vault/use-vault-library.ts | 2 +- .../__tests__/visits-section.test.tsx | 2 +- src/components/encounters/visits-section.tsx | 4 +- .../illness/episode-visits-card.tsx | 4 +- .../illness/illness-episode-detail.tsx | 4 +- .../__tests__/module-page-gate.test.tsx | 2 +- .../layout/__tests__/nav-model.test.ts | 18 ++- .../layout/__tests__/rail-nav-groups.test.tsx | 6 +- .../layout/__tests__/sidebar-nav.test.tsx | 2 +- src/components/layout/context-links.tsx | 2 +- src/components/layout/nav-model.ts | 2 +- src/components/links/related-records.tsx | 4 +- ...orsorge-dashboard-card-next-visit.test.tsx | 6 +- .../vorsorge-dashboard-card.tsx | 12 +- .../vorsorge-section.tsx | 4 +- .../practitioners/practitioner-list.tsx | 4 +- .../vaccinations/use-vaccinations.ts | 2 +- .../__tests__/deep-linked-record.test.ts | 2 +- src/hooks/use-deep-linked-record.ts | 2 +- src/hooks/use-nav-counts.ts | 2 +- src/lib/command-palette/synonyms.ts | 2 +- src/lib/daily/digest.ts | 2 +- src/lib/day/records.ts | 2 +- src/lib/encounters/visit-links.ts | 35 +++++- src/lib/measurement-reminders/due-day.ts | 2 +- src/lib/measurement-reminders/list-read.ts | 2 +- src/lib/navigation/shared-record.ts | 6 +- src/lib/notifications/tap-target.ts | 1 + src/lib/onboarding/tour-state.ts | 2 +- src/lib/vaccinations/booster-mint.ts | 2 +- src/lib/vaccinations/renewal.ts | 4 +- tests/durations/unit.json | 4 +- 70 files changed, 419 insertions(+), 180 deletions(-) create mode 100644 src/__tests__/care-route-redirects.test.ts create mode 100644 src/__tests__/care-wire-paths.test.ts rename src/app/{checkups => care}/__tests__/page-client-view.test.tsx (91%) rename src/app/{checkups => care}/__tests__/page-prefetch.test.tsx (87%) rename src/app/{checkups => care}/page-client.tsx (98%) rename src/app/{checkups => care}/page.tsx (92%) rename src/app/{checkups => care}/practitioners/page.tsx (98%) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5b0870ba1..671ceb065c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,6 +68,7 @@ - One snooze length per person under Settings > Notifications (10 minutes to two hours, 30 by default) on every surface, Telegram's reminder keyboard included, in the person's language. - One intake form for the medications page, the history and the capture menu, which names the dose it counts for; the medication page offers take, skip and snooze for the next dose. - The reminder card says in words what will happen; the reminder steps are offered for every scheduled medication. +- The preventive-care page is called Care in English and lives at `/care` (the practitioners under `/care/practitioners`). Old `/checkups` links, bookmarks and notifications already on a phone redirect there with their query intact. German keeps Vorsorge; Brazilian Portuguese and Russian name it Prevenção and Профилактика. - Deleting a dose happens at once with an Undo; "Take all due" has one Undo for the batch. - Dose times follow the 12 or 24 hour setting. - The medication setup asks less: the category is optional (Other by default), the dose step asks nothing twice, a disabled Next says what is missing, and the summary says from when each dose counts as missed. @@ -12663,7 +12664,7 @@ A feature release. The Coach reads its replies aloud, can draw the metric it is - Insight and Coach assessments are rewritten to connect signals into a motivating narrative rather than restate figures, with substantially expanded score summaries; generated text now renders in paragraphs and carries clearer "updated" timestamps — today with the time, yesterday, and a date for anything older. - The daily read folds in labs, preventive care, workouts, and glucose, and correlations surface emerging signals over a recent window alongside more cross-signal links. -- The preventive-care area is now "Checkups", reached at `/checkups`; the German interface keeps "Vorsorge". +- The preventive-care area is now "Checkups", reached at `/care`; the German interface keeps "Vorsorge". - Settings pages share one consistent layout, and the settings and admin sidebar stays pinned while the content scrolls. - Lab biomarkers are a compact, editable list with hide and restore. - Local AI servers stream their replies and honour the configurable timeout, so slower self-hosted models finish cleanly. diff --git a/bundle-budget.json b/bundle-budget.json index cb592693b2..d6059e62e3 100644 --- a/bundle-budget.json +++ b/bundle-budget.json @@ -18,8 +18,8 @@ "/auth/native-return/page": 289, "/auth/register/page": 294, "/c/[token]/view/page": 290, - "/checkups/page": 373, - "/checkups/practitioners/page": 295, + "/care/page": 373, + "/care/practitioners/page": 295, "/claim/[token]/page": 288, "/coach/conversations/page": 299, "/coach/page": 362, diff --git a/docs/contributing/ui-standards.md b/docs/contributing/ui-standards.md index 75fce4a945..202cb05e78 100644 --- a/docs/contributing/ui-standards.md +++ b/docs/contributing/ui-standards.md @@ -161,7 +161,7 @@ A two-column sub-shell that needs a "don't jump while loading" floor derives it Settings + Notifications are **account utilities, not feature destinations**. They live ONLY in the user/avatar menu (mobile top-bar `DropdownMenu`; desktop sidebar avatar menu, with Settings additionally in the sidebar footer). The mobile "More" overflow hub carries **feature destinations only** (Measurements, Mood, Cycle, Labs, Coach, …), never Settings or Notifications. The hub is `mobileMoreHubDestinations()` = `visibleNavDestinations` minus the primary slots (`/`, `/medications`, `/insights`); it does **not** append the utility tail. `NAV_UTILITY_DESTINATIONS` (`visibleUtilityDestinations()`) feeds the sidebar footer + user menus, not the mobile overflow. Never surface a utility in two menus reachable from the same screen. -The destination list is grouped by one ordered map, `NAV_GROUPS` in `nav-model.ts`: Dashboard alone on top, then **Tracking**, **Health record** and **Analysis**. The sidebar, the phone's More sheet and the search palette's page hints all read it. Headings are plain labels, never controls; collapsed, a hairline stands where a heading was and the heading stays for screen readers. A switched-off module's entry leaves no gap, and a group with no entry left has no heading. Medications and Checkups carry a count when something is due (read from the caches those pages already fill, no request of its own); nothing else does. The tab bar does not change. +The destination list is grouped by one ordered map, `NAV_GROUPS` in `nav-model.ts`: Dashboard alone on top, then **Tracking**, **Health record** and **Analysis**. The sidebar, the phone's More sheet and the search palette's page hints all read it. Headings are plain labels, never controls; collapsed, a hairline stands where a heading was and the heading stays for screen readers. A switched-off module's entry leaves no gap, and a group with no entry left has no heading. Medications and Care carry a count when something is due (read from the caches those pages already fill, no request of its own); nothing else does. The tab bar does not change. The rail's destination list is the one part of the rail that gives up height: the logo band, the footer group and the account row stay pinned, and the list scrolls between them (`overscroll-contain`, no native scrollbar, fades at an edge with more). A mouse gets the height-stepped row density; a finger keeps the 44 px rows, and at an edge with more destinations the rail shows a scroll cue (`sidebar-nav-scroll-cue`) that a tap follows. Guard: `e2e/tablet-shell.spec.ts`. diff --git a/docs/self-hosting/notifications.md b/docs/self-hosting/notifications.md index 15f1397417..9d7f10f683 100644 --- a/docs/self-hosting/notifications.md +++ b/docs/self-hosting/notifications.md @@ -464,7 +464,7 @@ once per event type, and every channel carries the same target: | Mood reminder | `/mood`, with the mood entry sheet already open | | Morning briefing | the dashboard | | Medication reminder, low supply, shared dose | `/medications` (low supply opens the medication) | -| Check-up and measurement reminders | `/checkups` | +| Check-up and measurement reminders | `/care` | | Proactive Coach nudge | the Coach conversation it started | | Cycle reminders | `/cycle` (the dashboard with discreet notifications on) | | New sign-in | Settings, Security | diff --git a/docs/using/care-calendar-feed.md b/docs/using/care-calendar-feed.md index 936a836b73..68c0540bbd 100644 --- a/docs/using/care-calendar-feed.md +++ b/docs/using/care-calendar-feed.md @@ -9,7 +9,7 @@ the data is kept. ## Turning it on Open **Settings**, then **Health record**, and find **Care calendar** under -**Calendar**. **Check-ups** and **Vaccinations** link to it from the row under +**Calendar**. **Care** and **Vaccinations** link to it from the row under their heading, and **Settings > Data & privacy** lists it under **Who can reach your record**. Before the button, the card says what it means: your calendar provider stores the dates on its servers, and turning the @@ -30,9 +30,9 @@ Adding it works as for the cycle feed: see - **Booked visits**: every visit you booked for the future, at its time, as a one-hour event. A visit stores a start, not an end, so the hour is a placeholder. -- **Check-ups coming due**: every check-up you set up under Check-ups, as an +- **Check-ups coming due**: every check-up you set up under Care, as an all-day event on the day it comes due. This is the same due day the - Check-ups page shows, so a skip, a snooze or a "done" moves it in your + Care page shows, so a skip, a snooze or a "done" moves it in your calendar too. - **Vaccination boosters coming due**, the same way. They follow the vaccinations module: with it switched off, they are left out. diff --git a/docs/using/search.md b/docs/using/search.md index 5351ea92bb..d637fba431 100644 --- a/docs/using/search.md +++ b/docs/using/search.md @@ -30,7 +30,7 @@ entries that match what you typed: - workouts - notes on mood entries, readings and illness days -Each hit opens where the entry lives: a visit on the check-ups page, a lab +Each hit opens where the entry lives: a visit on the Care page, a lab result on its analyte, a note on a mood entry or a reading on its day, a note on an illness day in its illness. diff --git a/e2e/command-palette.spec.ts b/e2e/command-palette.spec.ts index 6b6522b46c..357be0620e 100644 --- a/e2e/command-palette.spec.ts +++ b/e2e/command-palette.spec.ts @@ -219,7 +219,7 @@ test.describe("command palette", () => { const queries = await mockRecordSearch(page); // Start on the page the hit opens, on another tab: the link has to move // the open page, not only a fresh one. - await page.goto("/checkups"); + await page.goto("/care"); await shellReady(page); await expect( page.locator('[data-testid="checkups-tab-visits"]'), @@ -245,7 +245,7 @@ test.describe("command palette", () => { } await expect(hit).toHaveAttribute("aria-selected", "true"); await page.keyboard.press("Enter"); - await expect(page).toHaveURL(/\/checkups\?visit=e2e-visit$/); + await expect(page).toHaveURL(/\/care\?visit=e2e-visit$/); await expect(palette(page)).toHaveCount(0); await expect( page.locator('[data-testid="checkups-tab-visits"]'), @@ -317,6 +317,6 @@ test.describe("command palette", () => { .evaluate((el) => el.scrollWidth - el.clientWidth); expect(overflow).toBeLessThanOrEqual(0); await hit.click(); - await expect(page).toHaveURL(/\/checkups\?visit=e2e-visit$/); + await expect(page).toHaveURL(/\/care\?visit=e2e-visit$/); }); }); diff --git a/e2e/dashboard-ssr-prefetch-hydration.spec.ts b/e2e/dashboard-ssr-prefetch-hydration.spec.ts index bea2d3acf8..699aa72373 100644 --- a/e2e/dashboard-ssr-prefetch-hydration.spec.ts +++ b/e2e/dashboard-ssr-prefetch-hydration.spec.ts @@ -98,7 +98,7 @@ test.describe("dashboard hydration with the SSR prefetch on", () => { expect(witness?.replaced).toBe(0); }); - // The two list-page prefetch wrappers (`/checkups`, `/mood`) hand TanStack a + // The two list-page prefetch wrappers (`/care`, `/mood`) hand TanStack a // server-dehydrated state through the same HydrationBoundary mechanism the // dashboard uses. Their page-clients render behind a `useMounted` gate, so // the streamed HTML is the auth-gate shell by design — the node-identity @@ -108,8 +108,8 @@ test.describe("dashboard hydration with the SSR prefetch on", () => { // mocked suite runs with the prefetch OFF and can never see it). for (const target of [ { - path: "/checkups", - name: "checkups", + path: "/care", + name: "care", readySelector: '[data-testid="checkups-tab-vorsorge"]', }, { diff --git a/e2e/tablet-shell.spec.ts b/e2e/tablet-shell.spec.ts index 6f67b9cbbc..78a25f685a 100644 --- a/e2e/tablet-shell.spec.ts +++ b/e2e/tablet-shell.spec.ts @@ -446,7 +446,7 @@ test("a vertical swipe that starts on a tab strip is the page's", async ({ page, }) => { await page.setViewportSize({ width: 1180, height: 820 }); - await page.goto("/checkups", { waitUntil: "domcontentloaded" }); + await page.goto("/care", { waitUntil: "domcontentloaded" }); const strip = page.locator('#main-content [data-slot="tabs-list"]').first(); await expect(strip).toBeVisible(); // `pan-x` here refused the vertical pan, so the page did not move. diff --git a/e2e/vaccinations.spec.ts b/e2e/vaccinations.spec.ts index 40b43f27cd..8048369eed 100644 --- a/e2e/vaccinations.spec.ts +++ b/e2e/vaccinations.spec.ts @@ -11,7 +11,7 @@ * 2. Combination — one Tdap renders a row in each of its three component * groups, the render-only duplication the series design exists for. * 3. Mint + satisfy — confirming the booster prompt writes an ordinary - * Vorsorge reminder that shows on `/checkups`; logging the next dose moves + * Vorsorge reminder that shows on `/care`; logging the next dose moves * its due date forward through the real satisfy matcher. * 4. Module off — turning the module off in settings drops the nav entry and * the direct visit lands on the module-off notice, not a crash. @@ -226,10 +226,10 @@ test.describe("vaccinations", () => { expect(minted!.nextDueAt).toBeTruthy(); const dueBefore = new Date(minted!.nextDueAt!).getTime(); - // It presents on /checkups like every other Vorsorge reminder — the file-a + // It presents on /care like every other Vorsorge reminder — the file-a // -visit affordance only paints on a rendered reminder card, so it standing // in for "a reminder card is here" is a stable per-card slot. - await page.goto("/checkups"); + await page.goto("/care"); await expect( page.locator('[data-slot="vorsorge-file-visit"]').first(), ).toBeVisible({ timeout: 15_000 }); diff --git a/e2e/visits.spec.ts b/e2e/visits.spec.ts index de58676dd5..543ce87c85 100644 --- a/e2e/visits.spec.ts +++ b/e2e/visits.spec.ts @@ -45,13 +45,13 @@ test.describe.configure({ mode: "serial" }); test.describe("visits", () => { // The seeded account owns the visits and the document this flow drives, and // both the `page` and the `request` fixture read them under its session. - // Without this the whole file runs anonymous: `/checkups` redirects to login + // Without this the whole file runs anonymous: `/care` redirects to login // and every `/api/*` read answers 401, which is a test-setup gap, not a // product one. test.use({ storageState: STORAGE_STATE_PATH }); test("a visit saves with a date and nothing else", async ({ page }) => { - await page.goto("/checkups"); + await page.goto("/care"); await page.getByTestId("checkups-tab-visits").click(); const add = page.locator('[data-slot="visits-add"]').first(); diff --git a/messages/en.json b/messages/en.json index c2d230594f..02639b040b 100644 --- a/messages/en.json +++ b/messages/en.json @@ -628,7 +628,7 @@ "cycle": "Cycle", "labs": "Labs", "profile": "Profile", - "vorsorge": "Checkups", + "vorsorge": "Care", "illness": "Illness", "documents": "Documents", "vaccinations": "Vaccinations", @@ -5371,8 +5371,8 @@ "body": "The illness journal records acute episodes and chronic diagnoses with their flares. Hidden: correlate an episode with your readings, and Rest Mode that pauses reminders. That’s how the Coach understands why values drift for a while." }, "vorsorge": { - "title": "Checkups", - "body": "Checkups remind you of screenings and vaccinations on their own interval. Tip: “Done” can create a reading or a lab result directly. Due items appear as reminders and in the doctor report." + "title": "Care", + "body": "Care reminds you of screenings and vaccinations on their own interval. Tip: “Done” can create a reading or a lab result directly. Due items appear as reminders and in the doctor report." }, "cycle": { "title": "Cycle", @@ -6003,7 +6003,7 @@ "description": "List view and episode order." }, "checkups": { - "title": "Checkups", + "title": "Care", "description": "List view and reminder order." }, "documents": { @@ -11094,7 +11094,7 @@ "selectionBarLabel": "Selection actions" }, "measurementReminders": { - "sectionTitle": "Checkups", + "sectionTitle": "Care", "sectionDescription": "Reminders for what to measure or check, when, and where.", "markDone": "Done", "delete": "Delete", @@ -11198,7 +11198,7 @@ "startCheckIn": "Start check-in", "nextDueLabel": "Next due:", "lastDoneLabel": "Last done:", - "customize": "Customize checkups", + "customize": "Customize Care", "adherence": { "label": "Within interval", "onTrack": "On track", @@ -11213,7 +11213,7 @@ }, "dashboard": { "empty": "No upcoming checkup reminders.", - "openLink": "Open checkups" + "openLink": "Open Care" }, "showMeasurements": "Show measurements", "loadError": "Could not load your reminders.", @@ -13761,7 +13761,7 @@ "action": { "logDose": "Take", "reconnect": "Reconnect", - "viewCheckups": "View check-ups", + "viewCheckups": "Open Care", "viewAppointment": "View appointment", "viewAppointments": "View appointments", "checkinKeep": "Keep it", @@ -14557,7 +14557,7 @@ }, "checkups": { "viewSwitchLabel": "Show checkups, visits, procedures or body sites", - "tabVorsorge": "Checkups", + "tabVorsorge": "Care", "tabVisits": "Visits", "tabProcedures": "Procedures", "tabBodySites": "Body sites" diff --git a/messages/pt-BR.json b/messages/pt-BR.json index 5a289542d2..720dc4a3c9 100644 --- a/messages/pt-BR.json +++ b/messages/pt-BR.json @@ -628,7 +628,7 @@ "cycle": "Ciclo", "labs": "Exames", "profile": "Perfil", - "vorsorge": "Check-ups", + "vorsorge": "Prevenção", "illness": "Doenças", "documents": "Documentos", "vaccinations": "Vacinas", @@ -5371,7 +5371,7 @@ "body": "O diário de doenças registra episódios agudos e diagnósticos crônicos com seus surtos. Oculto: correlacione um episódio com suas leituras e o Modo de Repouso que pausa lembretes. É assim que o Coach entende por que os valores oscilam por um tempo." }, "vorsorge": { - "title": "Checks", + "title": "Prevenção", "body": "Checks lembram você de triagens e vacinas no seu próprio intervalo. Dica: “Concluído” pode criar uma leitura ou resultado laboratorial diretamente. Itens previstos aparecem como lembretes e no relatório médico." }, "cycle": { @@ -6003,7 +6003,7 @@ "description": "Visualização em lista e ordem dos episódios." }, "checkups": { - "title": "Check-ups", + "title": "Prevenção", "description": "Visualização em lista e ordem dos lembretes." }, "documents": { @@ -11094,7 +11094,7 @@ "selectionBarLabel": "Ações de seleção" }, "measurementReminders": { - "sectionTitle": "Check-ups", + "sectionTitle": "Prevenção", "sectionDescription": "Lembretes para o que medir ou verificar, quando e onde.", "markDone": "Concluído", "delete": "Excluir", @@ -11198,7 +11198,7 @@ "startCheckIn": "Iniciar check-in", "nextDueLabel": "Próximo vencimento:", "lastDoneLabel": "Última conclusão:", - "customize": "Personalizar check-ups", + "customize": "Personalizar prevenção", "adherence": { "label": "Dentro do intervalo", "onTrack": "No caminho", @@ -11213,7 +11213,7 @@ }, "dashboard": { "empty": "Nenhum lembrete de check-up futuro.", - "openLink": "Abrir check-ups" + "openLink": "Abrir prevenção" }, "showMeasurements": "Mostrar medições", "loadError": "Não foi possível carregar seus lembretes.", @@ -13761,7 +13761,7 @@ "action": { "logDose": "Tomar", "reconnect": "Reconectar", - "viewCheckups": "Ver checks", + "viewCheckups": "Ver prevenção", "viewAppointment": "Ver consulta", "viewAppointments": "Ver consultas", "checkinKeep": "Manter", @@ -14557,7 +14557,7 @@ }, "checkups": { "viewSwitchLabel": "Mostrar check-ups, consultas, procedimentos ou locais do corpo", - "tabVorsorge": "Check-ups", + "tabVorsorge": "Prevenção", "tabVisits": "Consultas", "tabProcedures": "Procedimentos", "tabBodySites": "Locais do corpo" diff --git a/messages/ru.json b/messages/ru.json index 9313884b5f..3aaf67e8f4 100644 --- a/messages/ru.json +++ b/messages/ru.json @@ -628,7 +628,7 @@ "cycle": "Цикл", "labs": "Анализы", "profile": "Профиль", - "vorsorge": "Чекапы", + "vorsorge": "Профилактика", "illness": "Заболевания", "documents": "Документы", "vaccinations": "Вакцинации", diff --git a/next.config.ts b/next.config.ts index 615023b928..48286529a7 100644 --- a/next.config.ts +++ b/next.config.ts @@ -254,18 +254,30 @@ const nextConfig: NextConfig = { permanent: true, }, // v1.22.0 — the preventive-care surface moved from the German slug - // `/vorsorge` to the English `/checkups` (the feature reads "Checkups" - // in every non-German locale now). 301-redirect so bookmarks, the PWA's - // cached navigation, and any push deep-link keep resolving. The - // persisted internal id stays `vorsorge`; only the URL changes. + // `/vorsorge` to the English `/checkups`; it was then renamed Care and + // moved to `/care`. Every older address goes straight to the new one + // in one hop, query string kept (Next.js carries it over), so bookmarks, + // the PWA's cached navigation and every push notification already sitting + // on a phone keep resolving. `permanent` answers 308. The persisted + // internal id stays `vorsorge`; only the URL changes. { source: "/vorsorge", - destination: "/checkups", + destination: "/care", permanent: true, }, { source: "/vorsorge/:path*", - destination: "/checkups/:path*", + destination: "/care/:path*", + permanent: true, + }, + { + source: "/checkups", + destination: "/care", + permanent: true, + }, + { + source: "/checkups/:path*", + destination: "/care/:path*", permanent: true, }, ]; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 8509efee47..240101853a 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -6788,7 +6788,7 @@ model MeasurementReminder { /// behaviour, so the published contract does not move — the `origin` enum /// stays two-armed, the cron still fires by `nextDueAt` regardless of why a /// row exists, and no Vorsorge surface excludes these rows. A booster - /// belongs on `/checkups`. That is also why a fourth nullable column here + /// belongs on `/care`. That is also why a fourth nullable column here /// is not the signal the appointment arm's warning described: an /// appointment had to be bent into this engine (one-shot, no cadence, /// excluded everywhere), whereas a booster is the engine's native case — @@ -10658,7 +10658,7 @@ model NutrientIntakeDay { /// than an oversight. The 18 `ModuleKey` entries have three shapes: an /// opt-out data vertical, an egress surface, and one output format. A /// visit is none of them — it is not a tracked signal, it egresses -/// nothing, and it is not an output. `/checkups` sets the precedent and +/// nothing, and it is not an output. `/care` sets the precedent and /// states the reasoning (`src/components/layout/nav-model.ts`): gating /// the entry would orphan reminders the user can still create. One gate /// over an encounter would also contradict its own members, since an diff --git a/src/__tests__/baselines/version-stamp-comments.json b/src/__tests__/baselines/version-stamp-comments.json index 61bb042db8..03a614f411 100644 --- a/src/__tests__/baselines/version-stamp-comments.json +++ b/src/__tests__/baselines/version-stamp-comments.json @@ -552,7 +552,7 @@ "app/auth/register/page.tsx": 3, "app/c/[token]/d/[id]/__tests__/route.test.ts": 1, "app/c/[token]/d/[id]/route.ts": 1, - "app/checkups/page-client.tsx": 4, + "app/care/page-client.tsx": 4, "app/claim/[token]/page.tsx": 1, "app/coach/__tests__/page-launch-params.test.tsx": 1, "app/coach/__tests__/page-prefetch.test.tsx": 1, diff --git a/src/__tests__/care-route-redirects.test.ts b/src/__tests__/care-route-redirects.test.ts new file mode 100644 index 0000000000..387ae394d1 --- /dev/null +++ b/src/__tests__/care-route-redirects.test.ts @@ -0,0 +1,106 @@ +/** + * The preventive-care page lives at `/care`; every address it had before keeps + * working. + * + * It started as `/vorsorge`, became `/checkups` and then `/care`. Push + * notifications already delivered to a phone, the PWA's cached + * navigation and bookmarks still carry the older paths, usually with a query + * (`?visit=`, `?view=visits`). This runs each one through the redirects + * in `next.config.ts` with Next.js's own matcher and destination builder, so + * the assertion is the URL the browser is actually sent to: a permanent (308) + * redirect to the same place under `/care`, query string intact, in one hop. + */ +import { existsSync } from "node:fs"; +import { join } from "node:path"; + +import { describe, expect, it } from "vitest"; +import { getRedirectStatus } from "next/dist/lib/redirect-status"; +import { getPathMatch } from "next/dist/shared/lib/router/utils/path-match"; +import { prepareDestination } from "next/dist/shared/lib/router/utils/prepare-destination"; + +import nextConfig from "../../next.config"; + +interface Redirect { + source: string; + destination: string; + permanent?: boolean; + statusCode?: number; +} + +async function redirects(): Promise { + return ((await nextConfig.redirects?.()) ?? []) as Redirect[]; +} + +/** Where one request is sent, the way the Next.js router resolves it. */ +function follow( + all: readonly Redirect[], + url: string, +): { status: number; location: string } | null { + const parsed = new URL(url, "https://health.example"); + const query = Object.fromEntries(parsed.searchParams); + for (const route of all) { + const params = getPathMatch(route.source, { + removeUnnamedParams: true, + strict: true, + })(parsed.pathname); + if (!params) continue; + const { parsedDestination } = prepareDestination({ + appendParamsToQuery: false, + destination: route.destination, + params, + query, + }); + const search = new URLSearchParams( + parsedDestination.query as Record, + ).toString(); + return { + status: getRedirectStatus(route), + location: `${parsedDestination.pathname}${search ? `?${search}` : ""}`, + }; + } + return null; +} + +const APP = join(process.cwd(), "src/app"); + +describe("old preventive-care addresses", () => { + it.each([ + ["/checkups", "/care"], + ["/checkups?visit=v1", "/care?visit=v1"], + ["/checkups?view=visits", "/care?view=visits"], + ["/checkups?site=Knee&side=LEFT", "/care?site=Knee&side=LEFT"], + ["/checkups/practitioners", "/care/practitioners"], + ["/vorsorge", "/care"], + ["/vorsorge?visit=v1", "/care?visit=v1"], + ["/vorsorge/practitioners", "/care/practitioners"], + ])("%s answers 308 to %s", async (from, to) => { + const all = await redirects(); + expect(follow(all, from)).toEqual({ status: 308, location: to }); + }); + + it("sends the new address nowhere", async () => { + const all = await redirects(); + expect(follow(all, "/care")).toBeNull(); + expect(follow(all, "/care?visit=v1")).toBeNull(); + expect(follow(all, "/care/practitioners")).toBeNull(); + }); + + it("leaves the API alone", async () => { + const all = await redirects(); + expect(follow(all, "/api/measurement-reminders")).toBeNull(); + expect(follow(all, "/checkupsx")).toBeNull(); + }); + + it("lands on pages that exist, and the old directory is gone", () => { + expect(existsSync(join(APP, "care/page.tsx"))).toBe(true); + expect(existsSync(join(APP, "care/practitioners/page.tsx"))).toBe(true); + expect(existsSync(join(APP, "checkups"))).toBe(false); + expect(existsSync(join(APP, "vorsorge"))).toBe(false); + }); + + it("the matcher is live: a made-up address finds no redirect", async () => { + const all = await redirects(); + expect(all.length).toBeGreaterThan(10); + expect(follow(all, "/no-such-page")).toBeNull(); + }); +}); diff --git a/src/__tests__/care-wire-paths.test.ts b/src/__tests__/care-wire-paths.test.ts new file mode 100644 index 0000000000..0fd34dd4d4 --- /dev/null +++ b/src/__tests__/care-wire-paths.test.ts @@ -0,0 +1,93 @@ +/** + * What leaves the server still says `/checkups`. + * + * The page moved to `/care` in the web app, but the released iPhone app + * parses only `/checkups`, `/checkups?visit=` and `/checkups?view=visits` + * in a push target and in an API `href` / `path` (the Today hero action, the + * next-visit line). `/checkups` stays on the wire for iOS builds before 1.7 and + * switches to `/care` in 1.50; the browser follows the permanent redirect. + * + * This pins the wire spellings, and walks the server code (`src/lib`, + * `src/app/api`) for a `/care` path literal, so a later edit cannot move a + * payload to `/care` ahead of the app. The few web-only modules under `src/lib` + * that name the page are listed with the reason. + */ +import { join } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { + CARE_VISITS_PATH, + VISITS_PATH, + careVisitPath, + visitPath, + visitsPath, +} from "@/lib/encounters/visit-links"; +import { NOTIFICATION_TAP_PATHS } from "@/lib/notifications/tap-target"; + +import { + readSource, + readSourceText, + walkSourceFiles, +} from "./helpers/source-files"; + +const SRC = join(__dirname, ".."); + +describe("wire paths for the care page", () => { + it("push targets and API links keep /checkups", () => { + expect(NOTIFICATION_TAP_PATHS.MEASUREMENT_REMINDER).toBe("/checkups"); + expect(visitPath("v1")).toBe("/checkups?visit=v1"); + expect(VISITS_PATH).toBe("/checkups?view=visits"); + expect(visitsPath(["v1"])).toBe("/checkups?visit=v1"); + expect(visitsPath(["v1", "v2"])).toBe("/checkups?view=visits"); + }); + + it("links the web renders itself use /care", () => { + expect(careVisitPath("v1")).toBe("/care?visit=v1"); + expect(CARE_VISITS_PATH).toBe("/care?view=visits"); + }); + + it("the digest and the day view carry the bare page as /checkups", () => { + // The anchor is the assertion: readSource throws when it is missing. + for (const file of ["src/lib/daily/digest.ts", "src/lib/day/records.ts"]) { + expect(readSource(file, 'href: "/checkups",')).toContain("/checkups"); + } + }); +}); + +/** Server modules that may name `/care`: none of them builds a payload. */ +const WEB_ONLY: Record = { + "lib/encounters/visit-links.ts": "the web spelling beside the wire one", + "lib/navigation/shared-record.ts": "browser route families, not links", + "lib/onboarding/tour-state.ts": "the tour step's route in the browser", +}; + +describe("server code does not send /care", () => { + const files = walkSourceFiles(SRC, { floor: 2500 }) + .filter( + (p) => + (p.startsWith("lib/") || p.startsWith("app/api/")) && + !p.includes("__tests__/") && + /\.tsx?$/.test(p), + ) + .map((path) => ({ path, source: readSourceText(join(SRC, path)) })); + + it("walks the server tree", () => { + expect(files.length).toBeGreaterThan(1000); + }); + + it("finds a /care path literal only in the web-only modules", () => { + const literal = /["'`]\/care(?:[?/"'`])/; + const hits = files + .filter(({ source }) => + source + .split("\n") + .some( + (line) => literal.test(line) && !/^\s*(\/\/|\*|\/\*)/.test(line), + ), + ) + .map(({ path }) => path) + .sort(); + expect(hits).toEqual(Object.keys(WEB_ONLY).sort()); + }); +}); diff --git a/src/__tests__/encounter-reminder-exclusion.test.ts b/src/__tests__/encounter-reminder-exclusion.test.ts index 5c09d32db2..1578179a3e 100644 --- a/src/__tests__/encounter-reminder-exclusion.test.ts +++ b/src/__tests__/encounter-reminder-exclusion.test.ts @@ -53,7 +53,7 @@ function read(relativePath: string): string { const VORSORGE_READ_SITES: ReadonlyArray<{ file: string; surface: string }> = [ { // The list query moved out of the route into the shared read so the - // `/checkups` SSR prefetch and `GET /api/measurement-reminders` cannot + // `/care` SSR prefetch and `GET /api/measurement-reminders` cannot // drift; the exclusion travels with the query. file: "src/lib/measurement-reminders/list-read.ts", surface: "the reminder list the checkups page and its SSR prefetch render", diff --git a/src/__tests__/prefetch-page-caching-guard.test.ts b/src/__tests__/prefetch-page-caching-guard.test.ts index 609b32256a..b7f305c287 100644 --- a/src/__tests__/prefetch-page-caching-guard.test.ts +++ b/src/__tests__/prefetch-page-caching-guard.test.ts @@ -172,7 +172,7 @@ const prefetchingPages = walk(APP_DIR) */ const PREFETCHING_ROUTES = [ "/", - "/checkups", + "/care", "/coach", "/insights", "/insights/mood", diff --git a/src/__tests__/session-surface-guard.test.ts b/src/__tests__/session-surface-guard.test.ts index 549edbc50e..45c57a52a0 100644 --- a/src/__tests__/session-surface-guard.test.ts +++ b/src/__tests__/session-surface-guard.test.ts @@ -148,7 +148,7 @@ describe("S1 — the direct session-resolution set is frozen", () => { // can only ever hold the caller's own. See // `prefetch-page-caching-guard.test.ts` for the rule that keeps a sixth // prefetching page from reaching for the bare helper. - "app/checkups/page.tsx": + "app/care/page.tsx": "RSC prefetch of the session user's reminder list, skipped under a switch", "app/coach/page.tsx": "RSC prefetch of the session user's coach state, skipped under a switch", diff --git a/src/__tests__/shared-record-navigation.test.tsx b/src/__tests__/shared-record-navigation.test.tsx index 93ac58b024..9e72b04b22 100644 --- a/src/__tests__/shared-record-navigation.test.tsx +++ b/src/__tests__/shared-record-navigation.test.tsx @@ -46,12 +46,12 @@ describe("shared-record navigation", () => { expect(SHARED_RECORD_DOMAIN_ROUTE_FAMILIES.profile).toEqual([ "/profile", - "/checkups", + "/care", "/vaccinations", ]); expect(navigation.destinationHrefs).toEqual([ "/profile", - "/checkups", + "/care", "/vaccinations", ]); expect(navigation.allowsPath("/profile")).toBe(true); @@ -66,17 +66,15 @@ describe("shared-record navigation", () => { // not. Before the visits section the `measurements` omission was invisible, // because a whole-record grant admits every path regardless. expect( - resolveSharedRecordNavigation(["measurements"]).allowsPath("/checkups"), + resolveSharedRecordNavigation(["measurements"]).allowsPath("/care"), ).toBe(true); - expect( - resolveSharedRecordNavigation(["profile"]).allowsPath("/checkups"), - ).toBe(true); - expect(resolveSharedRecordNavigation(null).allowsPath("/checkups")).toBe( + expect(resolveSharedRecordNavigation(["profile"]).allowsPath("/care")).toBe( true, ); - expect( - resolveSharedRecordNavigation(["labs"]).allowsPath("/checkups"), - ).toBe(false); + expect(resolveSharedRecordNavigation(null).allowsPath("/care")).toBe(true); + expect(resolveSharedRecordNavigation(["labs"]).allowsPath("/care")).toBe( + false, + ); // Listed twice, offered once: a grant holding both domains must not put // two identical entries in the navigation. @@ -84,8 +82,8 @@ describe("shared-record navigation", () => { resolveSharedRecordNavigation([ "measurements", "profile", - ]).destinationHrefs.filter((href) => href === "/checkups"), - ).toEqual(["/checkups"]); + ]).destinationHrefs.filter((href) => href === "/care"), + ).toEqual(["/care"]); }); /** diff --git a/src/__tests__/surface-registry-guard.test.ts b/src/__tests__/surface-registry-guard.test.ts index 35a00ae238..bd0ba8828a 100644 --- a/src/__tests__/surface-registry-guard.test.ts +++ b/src/__tests__/surface-registry-guard.test.ts @@ -147,7 +147,7 @@ const NOT_DESTINATIONS = [ * always a child of its list and needs no line here. */ const CHILD_PAGES: Readonly> = { - "/checkups/practitioners": "/checkups", + "/care/practitioners": "/care", "/coach/conversations": "/coach", "/coach/plans": "/coach", "/documents/deleted": "/documents", diff --git a/src/__tests__/visit-link-guard.test.ts b/src/__tests__/visit-link-guard.test.ts index 788b927135..7fc02858e1 100644 --- a/src/__tests__/visit-link-guard.test.ts +++ b/src/__tests__/visit-link-guard.test.ts @@ -1,8 +1,9 @@ /** * A link to a visit is built by `src/lib/encounters/visit-links.ts`, and a - * bare `/checkups` is a link to the checkups, never to a visit. + * bare `/care` (or `/checkups`, its spelling on the wire until 1.50) is a link + * to the checkups, never to a visit. * - * Visits are the second tab of `/checkups`. The bare path opens the first + * Visits are the second tab of `/care`. The bare path opens the first * one, the preventive-care list, which never lists an appointment. Four * surfaces showed an upcoming appointment and linked it to the bare path — * the dashboard's next-appointment line, the Today rail item, the Today @@ -11,9 +12,9 @@ * * Two rules, both over code lines (comments are skipped): * - * 1. The visit and tab query forms (`/checkups?visit=`, `/checkups?view=`) - * appear only in the builder. - * 2. The bare `/checkups` literal appears only where the target IS the + * 1. The visit and tab query forms (`/care?visit=`, `/care?view=`, and the + * same under `/checkups`) appear only in the builder. + * 2. The bare `/care` or `/checkups` literal appears only where the target IS the * checkups list, counted per file. A new occurrence fails the run until * someone decides whether it names a checkup (add it here, with the * reason) or a visit (use the builder). @@ -32,7 +33,7 @@ const SRC = join(__dirname, ".."); const BUILDER = "lib/encounters/visit-links.ts"; /** - * Where a bare `/checkups` is right, and how often: each names the + * Where a bare `/care` is right, and how often: each names the * preventive-care list itself, or lists routes rather than linking one. */ const BARE_CHECKUPS: Record = { @@ -61,12 +62,18 @@ const BARE_CHECKUPS: Record = { count: 2, why: "route lists for domain visibility, not links", }, - "lib/daily/digest.ts": { count: 1, why: "the due check-ups rail item" }, - "lib/day/records.ts": { count: 1, why: "a check-up satisfied that day" }, + "lib/daily/digest.ts": { + count: 1, + why: "the due check-ups rail item (wire spelling)", + }, + "lib/day/records.ts": { + count: 1, + why: "a check-up satisfied that day (wire spelling)", + }, "lib/onboarding/tour-state.ts": { count: 1, why: "the checkups tour step" }, "lib/notifications/tap-target.ts": { count: 1, - why: "a checkup push; an appointment's names its visit as override", + why: "a checkup push (wire spelling); an appointment's names its visit as override", }, }; @@ -112,9 +119,9 @@ function codeLines(source: string): string[] { return out; } -const QUERY_FORM = /\/checkups\?(visit|view)=/; +const QUERY_FORM = /\/(?:care|checkups)\?(visit|view)=/; // The bare page, or the page with a query the builder does not own. -const BARE = /["'`]\/checkups(?:["'`]|\?(?!visit=|view=))/g; +const BARE = /["'`]\/(?:care|checkups)(?:["'`]|\?(?!visit=|view=))/g; function scan(files: { path: string; source: string }[]) { const queryForms: string[] = []; @@ -154,7 +161,7 @@ describe("links to a visit go through the visit-links builder", () => { ); expect( bare, - "A new bare `/checkups`: if it leads to a visit, use the visit-links builder; if it really is the checkups list, add it to BARE_CHECKUPS with the reason.", + "A new bare `/care`: if it leads to a visit, use the visit-links builder; if it really is the checkups list, add it to BARE_CHECKUPS with the reason.", ).toEqual(expected); }); @@ -164,16 +171,16 @@ describe("links to a visit go through the visit-links builder", () => { path: "a.tsx", source: [ "/**", - " * `/checkups?visit=` in a docblock", + " * `/care?visit=` in a docblock", " */", - '// "/checkups" in a line comment', - '{/* a JSX comment naming "/checkups"', - ' over two lines "/checkups" */}', - 'const url = "https://example.test/x"; const bad = "/checkups";', + '// "/care" in a line comment', + '{/* a JSX comment naming "/care"', + ' over two lines "/care" */}', + 'const url = "https://example.test/x"; const bad = "/care";', ].join("\n"), }, - { path: "b.ts", source: "const p = `/checkups?visit=${id}`;" }, - { path: "c.ts", source: "const q = `/checkups?${params}`;" }, + { path: "b.ts", source: "const p = `/care?visit=${id}`;" }, + { path: "c.ts", source: "const q = `/care?${params}`;" }, ]); expect(queryForms).toEqual(["b.ts"]); expect(bare).toEqual({ "a.tsx": 1, "c.ts": 1 }); diff --git a/src/app/api/measurement-reminders/route.ts b/src/app/api/measurement-reminders/route.ts index e1bad22ac3..eaa0939b32 100644 --- a/src/app/api/measurement-reminders/route.ts +++ b/src/app/api/measurement-reminders/route.ts @@ -35,7 +35,7 @@ export const GET = apiHandler(async () => { const { user } = await requireRecordAuth("read", "measurements"); // The query (with its ENCOUNTER-origin exclusion) lives in the shared - // list read so this route and the `/checkups` SSR prefetch cannot drift. + // list read so this route and the `/care` SSR prefetch cannot drift. const reminders = await listMeasurementReminders(user.id); annotate({ diff --git a/src/app/api/vaccinations/[id]/booster/route.ts b/src/app/api/vaccinations/[id]/booster/route.ts index 9bed56f445..27f9367d5c 100644 --- a/src/app/api/vaccinations/[id]/booster/route.ts +++ b/src/app/api/vaccinations/[id]/booster/route.ts @@ -5,7 +5,7 @@ * Rung 2: the reminder only exists because the person confirmed it, prefilled * from the catalogue's interval and fully editable before this call. The minted * row is an ordinary `origin: VORSORGE` reminder that carries the dose's - * primary antigen as a match key; it lists on `/checkups` and rings through the + * primary antigen as a match key; it lists on `/care` and rings through the * same engine as every other checkup, with no new code. * * WRITE, classified `profile`: filing the owner's Impfpass and arming the diff --git a/src/app/checkups/__tests__/page-client-view.test.tsx b/src/app/care/__tests__/page-client-view.test.tsx similarity index 91% rename from src/app/checkups/__tests__/page-client-view.test.tsx rename to src/app/care/__tests__/page-client-view.test.tsx index 7e65a4a93e..b73e1eccb0 100644 --- a/src/app/checkups/__tests__/page-client-view.test.tsx +++ b/src/app/care/__tests__/page-client-view.test.tsx @@ -1,5 +1,5 @@ /** - * Which tab a link to `/checkups` opens. + * Which tab a link to `/care` opens. * * Visits are the page's second tab. `?visit=` opens one, `?view=visits` * the list, and the bare path keeps opening the checkups, which is what the @@ -12,7 +12,7 @@ let search = new URLSearchParams(); vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }), - usePathname: () => "/checkups", + usePathname: () => "/care", useSearchParams: () => search, })); vi.mock("@tanstack/react-query", async (importOriginal) => ({ @@ -43,19 +43,19 @@ vi.mock("@/components/body-sites/body-sites-section", () => ({ })); import { I18nProvider } from "@/lib/i18n/context"; -import CheckupsPageClient from "../page-client"; +import CarePageClient from "../page-client"; function openTab(query: string): string | null { search = new URLSearchParams(query); const html = renderToStaticMarkup( - + , ); return html.match(/data-section="([^"]+)"/)?.[1] ?? null; } -describe("/checkups — the tab a link opens", () => { +describe("/care — the tab a link opens", () => { it("opens the checkups on the bare path", () => { expect(openTab("")).toBe("vorsorge"); }); diff --git a/src/app/checkups/__tests__/page-prefetch.test.tsx b/src/app/care/__tests__/page-prefetch.test.tsx similarity index 87% rename from src/app/checkups/__tests__/page-prefetch.test.tsx rename to src/app/care/__tests__/page-prefetch.test.tsx index 3ca39318b4..6c9a969fed 100644 --- a/src/app/checkups/__tests__/page-prefetch.test.tsx +++ b/src/app/care/__tests__/page-prefetch.test.tsx @@ -5,9 +5,9 @@ import type { ReactElement } from "react"; import { queryKeys } from "@/lib/query-keys"; /** - * The `/checkups` server-prefetch key crux + fail-soft. + * The `/care` server-prefetch key crux + fail-soft. * - * The RSC wrapper (`src/app/checkups/page.tsx`) dehydrates the Vorsorge + * The RSC wrapper (`src/app/care/page.tsx`) dehydrates the Vorsorge * reminder list under the SAME zero-arg factory key the client hook * (`useMeasurementReminders`) mounts on, via the shared * `listMeasurementReminders` read — so the checkups list paints from the @@ -27,7 +27,7 @@ vi.mock("@/lib/measurement-reminders/list-read", () => ({ })); vi.mock("../page-client", () => ({ default: () => null })); -import CheckupsPage from "../page"; +import CarePage from "../page"; const SESSION = { user: { id: "u1", timezone: "Europe/Berlin" } }; @@ -46,14 +46,14 @@ function queriesOf( return props.state?.queries ?? []; } -describe("/checkups RSC prefetch", () => { +describe("/care RSC prefetch", () => { it("dehydrates the reminder list under the client's factory key", async () => { getUnswitchedSession.mockResolvedValue(SESSION); listMeasurementReminders.mockResolvedValue([ { id: "r1", label: "Blood pressure", nextDueAt: null }, ]); - const el = (await CheckupsPage()) as ReactElement; + const el = (await CarePage()) as ReactElement; const hashes = queriesOf(el).map((q) => q.queryHash); expect(hashes).toContain(hashKey(queryKeys.measurementReminders())); expect(listMeasurementReminders).toHaveBeenCalledWith("u1"); @@ -64,7 +64,7 @@ describe("/checkups RSC prefetch", () => { const createdAt = new Date("2026-07-18T06:00:00.000Z"); listMeasurementReminders.mockResolvedValue([{ id: "r1", createdAt }]); - const el = (await CheckupsPage()) as ReactElement; + const el = (await CarePage()) as ReactElement; const seeded = queriesOf(el).find( (q) => q.queryHash === hashKey(queryKeys.measurementReminders()), ); @@ -77,7 +77,7 @@ describe("/checkups RSC prefetch", () => { getUnswitchedSession.mockResolvedValue(SESSION); listMeasurementReminders.mockRejectedValue(new Error("db blip")); - const el = (await CheckupsPage()) as ReactElement; + const el = (await CarePage()) as ReactElement; expect(el.type).not.toBe(HydrationBoundary); }); @@ -85,14 +85,14 @@ describe("/checkups RSC prefetch", () => { // collapses both into the same answer, and the page treats them the same. it("fails soft when there is no session", async () => { getUnswitchedSession.mockResolvedValue(null); - const el = (await CheckupsPage()) as ReactElement; + const el = (await CarePage()) as ReactElement; expect(el.type).not.toBe(HydrationBoundary); expect(listMeasurementReminders).not.toHaveBeenCalled(); }); it("honours the DASHBOARD_SSR_PREFETCH kill-switch", async () => { process.env.DASHBOARD_SSR_PREFETCH = "false"; - const el = (await CheckupsPage()) as ReactElement; + const el = (await CarePage()) as ReactElement; expect(el.type).not.toBe(HydrationBoundary); expect(getUnswitchedSession).not.toHaveBeenCalled(); }); diff --git a/src/app/checkups/page-client.tsx b/src/app/care/page-client.tsx similarity index 98% rename from src/app/checkups/page-client.tsx rename to src/app/care/page-client.tsx index 3104cc66aa..0ddd3a5b38 100644 --- a/src/app/checkups/page-client.tsx +++ b/src/app/care/page-client.tsx @@ -21,7 +21,7 @@ import { useTranslations } from "@/lib/i18n/context"; import { invalidateKeys, queryKeys } from "@/lib/query-keys"; /** - * v1.17.1 — Checkups (preventive-care) reminders page. The dedicated + * v1.17.1 — Care (preventive-care) reminders page. The dedicated * feature surface for "wann muss ich was wo machen". Auth-gated; the * section component owns the list + create flow. * @@ -52,7 +52,7 @@ import { invalidateKeys, queryKeys } from "@/lib/query-keys"; * is how a page ends up showing a visit that closed a checkup still listed as * due. */ -export default function CheckupsPageClient() { +export default function CarePageClient() { const { isAuthenticated, isLoading } = useAuth(); const mounted = useMounted(); const queryClient = useQueryClient(); diff --git a/src/app/checkups/page.tsx b/src/app/care/page.tsx similarity index 92% rename from src/app/checkups/page.tsx rename to src/app/care/page.tsx index 512af7b526..0a5ebc38b8 100644 --- a/src/app/checkups/page.tsx +++ b/src/app/care/page.tsx @@ -8,10 +8,10 @@ import { getUnswitchedSession } from "@/lib/auth/acting-carrier"; import { listMeasurementReminders } from "@/lib/measurement-reminders/list-read"; import { queryKeys } from "@/lib/query-keys"; -import CheckupsPageClient from "./page-client"; +import CarePageClient from "./page-client"; /** - * Thin RSC wrapper around the (client) checkups page. + * Thin RSC wrapper around the (client) Care page. * * The page's above-the-fold content — the Vorsorge reminder list — waited for * the client `queryKeys.measurementReminders()` cell to fetch after hydrate, @@ -37,12 +37,12 @@ import CheckupsPageClient from "./page-client"; * - Fail-soft: no session or a read hiccup renders the page exactly as * before this wrapper existed — the client cell owns the fetch. */ -export default async function CheckupsPage() { +export default async function CarePage() { // Global SSR-prefetch kill-switch shared with the dashboard wrapper. The e2e // server sets `DASHBOARD_SSR_PREFETCH=false` so Playwright route mocks — which // only see CLIENT fetches — keep governing what every prefetched page paints. if (process.env.DASHBOARD_SSR_PREFETCH === "false") { - return ; + return ; } let dehydratedState = null; @@ -64,11 +64,11 @@ export default async function CheckupsPage() { } if (dehydratedState === null) { - return ; + return ; } return ( - + ); } diff --git a/src/app/checkups/practitioners/page.tsx b/src/app/care/practitioners/page.tsx similarity index 98% rename from src/app/checkups/practitioners/page.tsx rename to src/app/care/practitioners/page.tsx index 1a4d27e7f6..b3974848e6 100644 --- a/src/app/checkups/practitioners/page.tsx +++ b/src/app/care/practitioners/page.tsx @@ -10,7 +10,7 @@ import { useMounted } from "@/hooks/use-mounted"; * * Deliberately not in Settings. The Settings IA rule is that a settings surface * configures behaviour; a list of one's own doctors configures nothing and is - * record content like every other clinical list. Sitting under `/checkups` + * record content like every other clinical list. Sitting under `/care` * also means it inherits that page's route-family classification, so a * `profile`-scoped delegate reaches it exactly as they reach the visits. */ diff --git a/src/app/medications/page-client.tsx b/src/app/medications/page-client.tsx index ca1718e8f3..b7bd024240 100644 --- a/src/app/medications/page-client.tsx +++ b/src/app/medications/page-client.tsx @@ -276,7 +276,7 @@ export default function MedicationsPageClient() { refetchOnMount: refetchMedicationsOnMount("list"), }); - // v1.30.1 — pull-to-refresh parity with labs/checkups/mood/measurements. + // v1.30.1 — pull-to-refresh parity with labs/care/mood/measurements. // Medications is one of the sharpest PWA-resume-staleness surfaces (a // background-refreshed take/skip from a notification, or a cross-device // write, wouldn't otherwise show up until the 5-min staleTime lapses or a diff --git a/src/components/daily/__tests__/priority-card.test.tsx b/src/components/daily/__tests__/priority-card.test.tsx index 151f4b4744..67bb1607e6 100644 --- a/src/components/daily/__tests__/priority-card.test.tsx +++ b/src/components/daily/__tests__/priority-card.test.tsx @@ -158,7 +158,7 @@ describe("", () => { })} />, ); - expect(html).toContain("View check-ups"); + expect(html).toContain("Open Care"); }); // An appointment keeps the check-up label on the wire for the shipped iOS @@ -179,7 +179,7 @@ describe("", () => { />, ); expect(one).toContain("View appointment"); - expect(one).not.toContain("View check-ups"); + expect(one).not.toContain("Open Care"); expect(one).toContain('href="/checkups?visit=v1"'); const several = render( ` to its existing destination * by construction; S2 invents no new backend action. diff --git a/src/components/documents/__tests__/document-record-links.test.tsx b/src/components/documents/__tests__/document-record-links.test.tsx index 5d980d9084..602b20dcf3 100644 --- a/src/components/documents/__tests__/document-record-links.test.tsx +++ b/src/components/documents/__tests__/document-record-links.test.tsx @@ -251,7 +251,7 @@ describe("", () => { onChange={() => undefined} />, ); - expect(html).toContain('href="/checkups?visit=enc-1"'); + expect(html).toContain('href="/care?visit=enc-1"'); }); }); }); diff --git a/src/components/documents/document-record-links.tsx b/src/components/documents/document-record-links.tsx index c4de521b88..25de01825d 100644 --- a/src/components/documents/document-record-links.tsx +++ b/src/components/documents/document-record-links.tsx @@ -51,7 +51,7 @@ import { queryKeys } from "@/lib/query-keys"; import type { EncounterDTO, EncounterListDTO } from "@/lib/encounters/dto"; import type { EncounterKind } from "@/generated/prisma/client"; import type { InboundDocumentDetailDto } from "@/lib/validations/inbound-documents"; -import { visitPath } from "@/lib/encounters/visit-links"; +import { careVisitPath } from "@/lib/encounters/visit-links"; type Translate = ReturnType["t"]; @@ -111,7 +111,7 @@ export async function fetchEncounterPage( /** Where a visit opens: its sheet on the checkups page. */ function visitHref(encounterId: string): string { - return visitPath(encounterId); + return careVisitPath(encounterId); } /** Where a dose opens: its sheet on the vaccinations page. */ diff --git a/src/components/documents/vault/use-vault-library.ts b/src/components/documents/vault/use-vault-library.ts index 10ebf34b18..22cbe97aed 100644 --- a/src/components/documents/vault/use-vault-library.ts +++ b/src/components/documents/vault/use-vault-library.ts @@ -83,7 +83,7 @@ export function useVaultLibrary({ // persisted per user and changed behind the wrench. const { layout, isLayoutLoading } = useDocumentsLayout(moduleEnabled); - // Pull-to-refresh parity with labs/checkups/mood/ + // Pull-to-refresh parity with labs/care/mood/ // measurements/medications. The vault is one of the sharpest PWA-resume- // staleness surfaces named in the audit: a document indexed server-side // while the tab was backgrounded (auto-index / AI summary) otherwise diff --git a/src/components/encounters/__tests__/visits-section.test.tsx b/src/components/encounters/__tests__/visits-section.test.tsx index 0172b6ab2c..8f546866c7 100644 --- a/src/components/encounters/__tests__/visits-section.test.tsx +++ b/src/components/encounters/__tests__/visits-section.test.tsx @@ -165,7 +165,7 @@ describe("", () => { it("offers the address book beside the add action", () => { const html = render({ upcoming: [], past: [] }); - expect(html).toContain('href="/checkups/practitioners"'); + expect(html).toContain('href="/care/practitioners"'); }); }); diff --git a/src/components/encounters/visits-section.tsx b/src/components/encounters/visits-section.tsx index 19928d928c..72ed64203f 100644 --- a/src/components/encounters/visits-section.tsx +++ b/src/components/encounters/visits-section.tsx @@ -8,7 +8,7 @@ * ordering lives in one place. A client that split and re-sorted one array * would be the second place it lives. * - * No new nav entry and no new route. `/checkups` already owns exactly the right + * No new nav entry and no new route. `/care` already owns exactly the right * sentence — when do I have to do what, where — and is deliberately not module * gated, which is also why a visit carries no module key of its own. */ @@ -101,7 +101,7 @@ export function VisitsSection({ enabled = true }: { enabled?: boolean }) { actions={ <> @@ -242,11 +242,11 @@ export function VorsorgeDashboardCard() { {/* Visually distinct from a due checkup: a quiet line under the block rather than a fourth row with an action, because there is nothing to do about an appointment except keep it. It opens the visit - itself: a bare `/checkups` lands on the checkups tab, which is + itself: a bare `/care` lands on the checkups tab, which is exactly where the appointment is not. */} {nextAppointment ? ( diff --git a/src/components/measurement-reminders/vorsorge-section.tsx b/src/components/measurement-reminders/vorsorge-section.tsx index 5c594f66c1..4b3ccb2fa1 100644 --- a/src/components/measurement-reminders/vorsorge-section.tsx +++ b/src/components/measurement-reminders/vorsorge-section.tsx @@ -38,7 +38,7 @@ import { import { ReminderFormSheet } from "./checkups/reminder-form-sheet"; /** - * The checkups surface (the `/checkups` page and its settings card): the + * The checkups surface (the `/care` page and its settings card): the * reminder list, the create / edit sheet, the value capture that completes a * typed reminder with a real reading, and filing a visit against one. The * form, the card and the postpone sheet live in `./checkups/`. @@ -241,7 +241,7 @@ export function VorsorgeSection({ // profile) and the care calendar (Health record) stay one tap away // from the page they are about; the links decide what a shared // record shows. - + ) : null} {variant === "page" ? null : ( diff --git a/src/components/vaccinations/use-vaccinations.ts b/src/components/vaccinations/use-vaccinations.ts index 5d42584019..719a9eb5f4 100644 --- a/src/components/vaccinations/use-vaccinations.ts +++ b/src/components/vaccinations/use-vaccinations.ts @@ -229,7 +229,7 @@ export interface BoosterMintBody { * * The response is an ordinary Vorsorge reminder; the write fans out through the * dose dependent-keys and the reminder reads so the new checkup appears on - * `/checkups` the instant it is confirmed. + * `/care` the instant it is confirmed. */ export function useBoosterMint() { const qc = useQueryClient(); diff --git a/src/hooks/__tests__/deep-linked-record.test.ts b/src/hooks/__tests__/deep-linked-record.test.ts index a8b0aa48c8..44b1c99870 100644 --- a/src/hooks/__tests__/deep-linked-record.test.ts +++ b/src/hooks/__tests__/deep-linked-record.test.ts @@ -1,5 +1,5 @@ /** - * `/checkups?visit=` from a search hit. The visits list reads the newest + * `/care?visit=` from a search hit. The visits list reads the newest * hundred of each arm, and a search reaches back further than that, so a hit * can name a visit the list does not hold. That visit is read on its own and * opened like a listed one. diff --git a/src/hooks/use-deep-linked-record.ts b/src/hooks/use-deep-linked-record.ts index 5cfe09d3bf..c8a1d26ea1 100644 --- a/src/hooks/use-deep-linked-record.ts +++ b/src/hooks/use-deep-linked-record.ts @@ -5,7 +5,7 @@ import { useSearchParams } from "next/navigation"; /** * Open the record a link points at: `/vaccinations?dose=`, - * `/checkups?visit=`. + * `/care?visit=`. * * The link chips on a document name the record they point at, and a chip that * lands on a list with nothing selected leaves the person searching the list diff --git a/src/hooks/use-nav-counts.ts b/src/hooks/use-nav-counts.ts index ce6f2646a9..197970ac0c 100644 --- a/src/hooks/use-nav-counts.ts +++ b/src/hooks/use-nav-counts.ts @@ -23,7 +23,7 @@ export function navCountsByHref( counts: NavCounts | undefined, ): Record { if (!counts) return {}; - return { "/medications": counts.dosesDue, "/checkups": counts.checkupsDue }; + return { "/medications": counts.dosesDue, "/care": counts.checkupsDue }; } export function useNavCounts(enabled: boolean): Record { diff --git a/src/lib/command-palette/synonyms.ts b/src/lib/command-palette/synonyms.ts index c48daf3afd..e7ab3e0b35 100644 --- a/src/lib/command-palette/synonyms.ts +++ b/src/lib/command-palette/synonyms.ts @@ -24,7 +24,7 @@ export const PALETTE_SYNONYMS: Readonly>> = "arzneimittel", ], "nav:/labs": ["blood test", "bloodwork", "blutwerte", "labor", "labwerte"], - "nav:/checkups": ["preventive", "vorsorge", "screening", "reminders"], + "nav:/care": ["preventive", "vorsorge", "screening", "reminders"], "nav:/coach": ["chat", "ai", "ki", "assistant", "assistent"], "nav:/documents": ["pdf", "scan", "befunde", "arztbrief", "letters"], "nav:/timeline": ["history", "verlauf", "lebenslauf", "chronik"], diff --git a/src/lib/daily/digest.ts b/src/lib/daily/digest.ts index 143ac7a7bf..96b2ef7d85 100644 --- a/src/lib/daily/digest.ts +++ b/src/lib/daily/digest.ts @@ -672,7 +672,7 @@ function buildPreventiveCareItem( { labelKey: "daily.action.viewCheckups", intent: "checkup.view", - href: "/checkups", + href: "/checkups", // /checkups kept on the wire for iOS builds before 1.7; switch to /care in 1.50. }, ], }; diff --git a/src/lib/day/records.ts b/src/lib/day/records.ts index f2d2706d38..422d36b451 100644 --- a/src/lib/day/records.ts +++ b/src/lib/day/records.ts @@ -730,7 +730,7 @@ async function checkupsPart(frame: DayFrame): Promise { section: "checkups", id: row.id, title: row.reminder.label, - href: "/checkups", + href: "/checkups", // /checkups kept on the wire for iOS builds before 1.7; switch to /care in 1.50. }), ), }; diff --git a/src/lib/encounters/visit-links.ts b/src/lib/encounters/visit-links.ts index fc7bf497d1..a3ec678908 100644 --- a/src/lib/encounters/visit-links.ts +++ b/src/lib/encounters/visit-links.ts @@ -1,15 +1,17 @@ /** * Where a visit lives in the app, spelled once. * - * Visits have no page of their own: they are the second tab of `/checkups`, - * beside the preventive-care list that opens by default. A bare `/checkups` + * Visits have no page of their own: they are the second tab of `/care`, + * beside the preventive-care list that opens by default. A bare `/care` * therefore lands on the checkups, which is the wrong half of the page for an * appointment, and every surface that hand-spelled that path for a visit (the * dashboard's next-appointment line, the Today rail, the Today overview, the * appointment's push) sent the person to the list the appointment is not on. * - * Every link to one visit or to the visits list is built here. The checkups - * page reads both parameters: `visit` opens that visit on the visits tab + * Every link to one visit or to the visits list is built here, in two + * spellings: the wire one for what leaves the server, the web one for links + * the browser renders itself (see below). The page reads both + * parameters: `visit` opens that visit on the visits tab * (`src/hooks/use-deep-linked-record.ts`), `view` picks a tab. * `visit-link-guard.test.ts` refuses a hand-spelled copy elsewhere. * @@ -35,14 +37,35 @@ export function parseCheckupsView( : null; } -/** The visits list: the checkups page opened on its visits tab. */ +/* + * Two spellings of the page's address. + * + * The wire one, `/checkups`, is what the server sends to a client: push and + * webhook targets, and every `href` / `path` in an API response. `/checkups` + * kept on the wire for iOS builds before 1.7; switch to `/care` in 1.50. The + * released iPhone app parses only these `/checkups` shapes; the browser + * follows the permanent redirect from `/checkups` to `/care` in + * `next.config.ts`. `care-wire-paths.test.ts` pins the wire values. + * + * The web one, `/care`, is for links the browser renders itself. + */ + +/** The visits list on the wire: the page opened on its visits tab. */ export const VISITS_PATH = "/checkups?view=visits"; -/** One visit: the visits tab, scrolled to the visit and opened. */ +/** One visit on the wire: the visits tab, scrolled to the visit and opened. */ export function visitPath(id: string): string { return `/checkups?visit=${encodeURIComponent(id)}`; } +/** The visits list, as a link the web app renders itself. */ +export const CARE_VISITS_PATH = "/care?view=visits"; + +/** One visit, as a link the web app renders itself. */ +export function careVisitPath(id: string): string { + return `/care?visit=${encodeURIComponent(id)}`; +} + /** * Where a group of visits leads: the visit itself when there is one, the * visits list when several share one line (a day with two appointments). diff --git a/src/lib/measurement-reminders/due-day.ts b/src/lib/measurement-reminders/due-day.ts index 8f8da3ee27..3fe37327b1 100644 --- a/src/lib/measurement-reminders/due-day.ts +++ b/src/lib/measurement-reminders/due-day.ts @@ -2,7 +2,7 @@ * The one place a Vorsorge reminder's next-due instant becomes the words a * person reads: "heute" / "morgen" / "in N Tagen" / "überfällig seit N Tagen". * - * It used to live inside the two surfaces that render it — the `/checkups` + * It used to live inside the two surfaces that render it — the `/care` * page and the dashboard summary card — as two hand-copied bodies. The page * copy was fixed to compare CALENDAR days; the dashboard copy was not, and * kept differencing raw instants. So the same reminder read "morgen" on one diff --git a/src/lib/measurement-reminders/list-read.ts b/src/lib/measurement-reminders/list-read.ts index 15d9543e14..a0904bd59a 100644 --- a/src/lib/measurement-reminders/list-read.ts +++ b/src/lib/measurement-reminders/list-read.ts @@ -1,6 +1,6 @@ /** * The one Vorsorge-reminder list read, shared by `GET - * /api/measurement-reminders` and the `/checkups` RSC prefetch wrapper so the + * /api/measurement-reminders` and the `/care` RSC prefetch wrapper so the * two cannot drift in filter, order, or DTO shape — the SSR-seeded cell must * be byte-compatible with what the client `queryFn` gets from the wire. */ diff --git a/src/lib/navigation/shared-record.ts b/src/lib/navigation/shared-record.ts index a733a33889..707c4d405e 100644 --- a/src/lib/navigation/shared-record.ts +++ b/src/lib/navigation/shared-record.ts @@ -19,7 +19,7 @@ import { * fail closed in chrome until it has been intentionally classified. */ export const SHARED_RECORD_DOMAIN_ROUTE_FAMILIES = { - // `/checkups` carries content from two domains and is listed under both. + // `/care` carries content from two domains and is listed under both. // The preventive-care list has always been a `measurements` read // (`/api/measurement-reminders` declares it), and the page was in neither // list — under a whole-record grant it painted anyway, because a null @@ -31,7 +31,7 @@ export const SHARED_RECORD_DOMAIN_ROUTE_FAMILIES = { // domains means a grant naming either presents the page — and the handler // still evaluates the grant on every read, because this is a presentation // inventory and not an authorization table. - measurements: ["/measurements", "/checkups"], + measurements: ["/measurements", "/care"], medications: ["/medications"], labs: ["/labs"], // `/vaccinations` joins `profile`: an immunization history is health @@ -39,7 +39,7 @@ export const SHARED_RECORD_DOMAIN_ROUTE_FAMILIES = { // delegate scoped to `profile` must be able to present the page the API // already lets them read — without this line the grant reads the data and // the chrome hides the only page that shows it. - profile: ["/profile", "/checkups", "/vaccinations"], + profile: ["/profile", "/care", "/vaccinations"], // The seizure diary rides the illness section (`scope.ts`). illness: ["/illness", "/seizures"], mind: ["/mood", "/mental-wellbeing"], diff --git a/src/lib/notifications/tap-target.ts b/src/lib/notifications/tap-target.ts index b108d3e294..8924f76643 100644 --- a/src/lib/notifications/tap-target.ts +++ b/src/lib/notifications/tap-target.ts @@ -47,6 +47,7 @@ export const NOTIFICATION_TAP_PATHS: Record = { CYCLE_FERTILE_SOON: "/cycle", COACH_NUDGE: "/coach", MEDICATION_LOW_STOCK: "/medications", + // /checkups kept on the wire for iOS builds before 1.7; switch to /care in 1.50. MEASUREMENT_REMINDER: "/checkups", MEDICATION_INTAKE_SYNC: null, MEDICATION_INTAKE_RECORDED: "/medications", diff --git a/src/lib/onboarding/tour-state.ts b/src/lib/onboarding/tour-state.ts index 4d772c0475..d5c39081e6 100644 --- a/src/lib/onboarding/tour-state.ts +++ b/src/lib/onboarding/tour-state.ts @@ -129,7 +129,7 @@ const ALL_STOPS: readonly TourStop[] = [ id: "vorsorge", targetId: "vorsorge-hero", placement: "bottom", - route: "/checkups", + route: "/care", titleKey: "onboarding.tour.steps.vorsorge.title", bodyKey: "onboarding.tour.steps.vorsorge.body", }, diff --git a/src/lib/vaccinations/booster-mint.ts b/src/lib/vaccinations/booster-mint.ts index 8faeeb47aa..76b01d895e 100644 --- a/src/lib/vaccinations/booster-mint.ts +++ b/src/lib/vaccinations/booster-mint.ts @@ -11,7 +11,7 @@ * ── An ordinary Vorsorge reminder ────────────────────────────────────────── * * The minted row is `origin: VORSORGE` and carries `vaccinationAntigen` as a - * match key. Everything else — the cron, the digest, `/checkups`, the insights + * match key. Everything else — the cron, the digest, `/care`, the insights * block, `get_preventive_care` — reads it with zero new code, because a booster * reminder is the engine's native case. That nativeness is the whole Option-A * argument; the column is a key, not a behaviour change, and the published diff --git a/src/lib/vaccinations/renewal.ts b/src/lib/vaccinations/renewal.ts index 7bd4a25460..58a5dd4c16 100644 --- a/src/lib/vaccinations/renewal.ts +++ b/src/lib/vaccinations/renewal.ts @@ -6,7 +6,7 @@ * person confirms becomes an ordinary reminder keyed on the antigen * (`MeasurementReminder.vaccinationAntigen`, minted in `booster-mint.ts`). * Logging the next dose re-anchors it. Its `nextDueAt` is the renewal date. - * Until now it lived only on `/checkups`, and the vaccination page itself said + * Until now it lived only on `/care`, and the vaccination page itself said * nothing about it. * * This module reads that date and resolves it to a state, once, on the @@ -33,7 +33,7 @@ export type VaccinationRenewalState = "current" | "dueSoon" | "overdue"; export interface VaccinationRenewalDTO { /** The component antigen slug the booster reminder keys on. */ antigen: string; - /** The reminder behind it, for a deep link to `/checkups`. */ + /** The reminder behind it, for a deep link to `/care`. */ reminderId: string; /** ISO-8601 instant the booster is due. */ dueAt: string; diff --git a/tests/durations/unit.json b/tests/durations/unit.json index f2898cc5f6..35111cffa7 100644 --- a/tests/durations/unit.json +++ b/tests/durations/unit.json @@ -612,8 +612,8 @@ "src/app/c/[token]/__tests__/page.test.tsx": 0.3, "src/app/c/[token]/__tests__/report-download.test.ts": 1.6, "src/app/c/[token]/d/[id]/__tests__/route.test.ts": 0, - "src/app/checkups/__tests__/page-client-view.test.tsx": 0, - "src/app/checkups/__tests__/page-prefetch.test.tsx": 0, + "src/app/care/__tests__/page-client-view.test.tsx": 0, + "src/app/care/__tests__/page-prefetch.test.tsx": 0, "src/app/coach/__tests__/page-interrupted-resume.test.tsx": 0, "src/app/coach/__tests__/page-launch-params.test.tsx": 0, "src/app/coach/__tests__/page-prefetch.test.tsx": 0, From 3c4320d242345fd8b9a20a978aa62901ee450b04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 11:32:42 +0100 Subject: [PATCH 03/14] docs(changelog): name the Care page consistently in 1.49.0 --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e7e9546d3..a6f47e30b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,12 +45,12 @@ - Capture menu: most-used types as rows, "Save and next", the last reading under the field; the save receipt has Undo and Edit. - Biomarker page lists its five newest values under the chart. - Time zone per reading from the iPhone; the Day view, list and daily charts follow it. -- The sidebar and the More sheet sort their entries under Tracking, Health record and Analysis. Medications and Checkups show a small number when a dose or a check-up is due; the numbers can be switched off under Settings > Account > Display. No address changes. Thanks to @Cnote43 for the sketch it follows. ([#1113](https://github.com/MBombeck/HealthLog/discussions/1113)) +- The sidebar and the More sheet sort their entries under Tracking, Health record and Analysis. Medications and Care show a small number when a dose or a check-up is due; the numbers can be switched off under Settings > Account > Display. No address changes. Thanks to @Cnote43 for the sketch it follows. ([#1113](https://github.com/MBombeck/HealthLog/discussions/1113)) - The search finds every page and every settings card, in every language also by keyword ("snooze", "dark mode", "Nextcloud", "ICE"). - Settings > Notifications has an "Alerts" group with account security and lasting change in a vital, visible before any channel is set up. - Settings > Data & privacy opens with "Who can reach your record": accounts and guardians, clinician links, the emergency card link, the care and cycle calendars, API tokens, MCP and sign-ins, each with its link. - The theme can be chosen under Settings > Account > Display as well as in the avatar menu. -- Checkups, Vaccinations and Documents link to the care calendar and the report schedule under their page header. +- Care, Vaccinations and Documents link to the care calendar and the report schedule under their page header. - Admin > System status has a "Version and database" card: the version, the channel (release, edge or development), and the migrations applied, pending or failed. - An app can read the push state of its own device (`GET /api/devices/me/push-diagnostics`, feature `push.device-diagnostics`): route, relay binding, the hourly budget for silent pushes with a sync still owed, the last delivery of each kind, the last receipt, a masked APNs token, and whether the server or the app reminds the device of a dose. Only that device, no content. - API: `GET /api/version` lists `features`; `POST /api/measurements/batch` takes `timeZone` per entry; workouts carry `performance`; `GET /api/nutrients/energy-balance`; dose rows carry their resolved state and `alreadyTaken`; `medications.lastUpdatedAt` in `/api/sync/state`; `notificationPrefs.medication.snoozeMinutes`; questionnaire history rows carry `source` and `itemsUnavailable`; `push.device.liveActivityStarted` names the dose of a server-started Live Activity. @@ -79,7 +79,7 @@ - Admin keeps push in one place: "Push and channels" holds the channel switches, the Web Push keys, the relay and the delivery health with its test push. The sections are regrouped (System, Notifications, AI, Connectivity, Account, Server data) and "Integrations" is now "Monitoring". - The page with the switch per kind and channel is called "Notifications per channel" and lists the kinds also when no channel is set up yet. "Manage notification channels" on a medication leads to the channels. - Settings cards look alike: the button at the bottom of a card sits on the right at one size, also on a phone, most switches stand to the right of their name, field names have one shape, and status messages stand above the buttons. This covers the emergency card, "Create profile", the guardian's settings, the push relay card, the import cards and the notification rows on a phone. -- The tabs on Cycle, Checkups, a medication and the recovery kit look like the other view switches; on Checkups the title comes first, then the tabs; the admin's section strip on a phone works like the Insights pills. +- The tabs on Cycle, Care, a medication and the recovery kit look like the other view switches; on Care the title comes first, then the tabs; the admin's section strip on a phone works like the Insights pills. - Every settings save confirms. Cycle settings, the scheduled doctor report, the Health Connect folder, calendar feed options, a guardian's settings, withdrawing AI consent, disconnecting Garmin or Nightscout, the delivery test message and "Forget all devices" used to save without a word. - Getting started: with a medication schedule, the notification row comes right after the medication row. - The add form opens on the type last saved by hand, read from the account's own readings, instead of browser storage. From d4ecb0bfdac898112f9b61e3edbc822e1e73025d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 11:47:21 +0100 Subject: [PATCH 04/14] refactor(nav): open the emergency card from the account menu The emergency card is set up once and then waits in the background, so it no longer takes a slot in the sidebar or the phone's More sheet. It moves to NAV_ACCOUNT_MENU_DESTINATIONS and renders in both account menus (the sidebar's avatar menu and the top bar's on a phone) through one shared slice. Inside a shared record it keeps the rule the rail entry had: the guardian of a managed profile sees it, an adult's delegate does not. The search palette keeps the entry under its existing id, the button under Medical history and the card under Settings > Health record stay as they were. --- CHANGELOG.md | 2 +- docs/contributing/ui-standards.md | 2 +- docs/using/emergency-card.md | 9 +- e2e/v138-managed-record-capabilities.spec.ts | 11 +- src/__tests__/surface-registry-guard.test.ts | 19 ++- src/components/command-palette/build-index.ts | 15 +++ ...account-menu-record-items.browser.test.tsx | 110 ++++++++++++++++++ .../layout/__tests__/nav-model.test.ts | 49 +++++++- .../layout/account-menu-record-items.tsx | 50 ++++++++ src/components/layout/nav-model.ts | 63 +++++++--- src/components/layout/sidebar-nav.tsx | 5 + src/components/layout/surface-registry.ts | 20 +++- src/components/layout/top-bar.tsx | 3 + .../settings/emergency-card-entry-card.tsx | 2 +- 14 files changed, 329 insertions(+), 31 deletions(-) create mode 100644 src/components/layout/__tests__/account-menu-record-items.browser.test.tsx create mode 100644 src/components/layout/account-menu-record-items.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index a6f47e30b9..be948bb86e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ - An undone take or skip reaches the person's other devices as "Dose updated", so a phone that is not running the app shows the dose as open again instead of answered, for doses of the last 36 hours. It travels like the dose confirmation: the same switch, the same devices, sealed. A deletion in Apple Health stays silent. - Silent wakes when a server-side sync stores new readings and when the app's Apple Health upload is six hours behind, rationed per device. - Security notifications when a passkey is added or removed, an access or connector token is revoked, or a device is signed out by refresh token reuse; time-sensitive on the iPhone. -- Emergency card at `/emergency-card`: offline HTML copy, wallet card PDF, and a QR link that shows only the ticked items, can expire, can be revoked, and logs every opening. It has its own entry in the navigation (under More on a phone), a button under Medical history and a card under Settings > Health record. (`docs/using/emergency-card.md`) +- Emergency card at `/emergency-card`: offline HTML copy, wallet card PDF, and a QR link that shows only the ticked items, can expire, can be revoked, and logs every opening. It opens from the account menu, a button under Medical history and a card under Settings > Health record. (`docs/using/emergency-card.md`) - Pregnancy and the weeks after a birth as a cycle state: predictions and their reminders pause, the timeline and doctor report show the week, and the emergency card can show it. While it holds, no page rates the weight: no goal, no BMI category, no trend direction, no Coach hint, no BMI in the doctor report. "Delete all cycle data" clears it. (`docs/using/pregnancy.md`) - "Find leaflet" on a medication opens the official medicine registry of the chosen country (Poland, Germany, Spain, France, United Kingdom, Belgium, Netherlands, United States, Canada, Australia, Brazil, EU) in a new tab, with the name already searched for where the registry allows it. The server sends nothing to any registry. The registry is a setting of its own under Settings > Modules > Medications, independent of the app language, and can be picked right on the medication. A medication can keep the link to its official leaflet (https only), which shows as "Official leaflet" and travels with backups and the export. Thanks to @ferges123 for the idea and the registry research. ([#1430](https://github.com/MBombeck/HealthLog/issues/1430)) - A short server setup for the first admin: who may sign up, how notifications leave the server (with the push relay off unless switched on), what AI may do, what else leaves the server, and a setup check. Every step can be skipped; it is offered once on the admin start page and stays reachable from Admin > System status. Servers that already had accounts are not asked. diff --git a/docs/contributing/ui-standards.md b/docs/contributing/ui-standards.md index 202cb05e78..fe76c0b635 100644 --- a/docs/contributing/ui-standards.md +++ b/docs/contributing/ui-standards.md @@ -165,7 +165,7 @@ The destination list is grouped by one ordered map, `NAV_GROUPS` in `nav-model.t The rail's destination list is the one part of the rail that gives up height: the logo band, the footer group and the account row stay pinned, and the list scrolls between them (`overscroll-contain`, no native scrollbar, fades at an edge with more). A mouse gets the height-stepped row density; a finger keeps the 44 px rows, and at an edge with more destinations the rail shows a scroll cue (`sidebar-nav-scroll-cue`) that a tap follows. Guard: `e2e/tablet-shell.spec.ts`. -**Every surface is found where people look for it.** A page with an address is a navigation destination (`NAV_DESTINATIONS`) or a declared child of one; a Settings card with an anchor is a search entry (`SETTINGS_CARDS`). The search palette is built from one list, `src/components/layout/surface-registry.ts`, which reads the navigation, Settings and Admin lists, so a new surface is searchable by its name and its `palette.keywords.*` words in every locale. A setting that produces something on a feature page gets a link in that page's context row (`ContextLinks`, under the header), not only a home in Settings. Guard: `src/__tests__/surface-registry-guard.test.ts`. A page that is not about one section of the record (the emergency card, Settings > Health record) opens inside a shared record by its routes' guard (`RECORD_PAGE_SURFACES`), and `record-page-surfaces.test.ts` holds page and route to the same rule. +**Every surface is found where people look for it.** A page with an address is a navigation destination (`NAV_DESTINATIONS`), a record page the account menu opens (`NAV_ACCOUNT_MENU_DESTINATIONS`: the emergency card, set up once and then out of the way, so it takes no rail slot), or a declared child of one; a Settings card with an anchor is a search entry (`SETTINGS_CARDS`). The search palette is built from one list, `src/components/layout/surface-registry.ts`, which reads the navigation, Settings and Admin lists, so a new surface is searchable by its name and its `palette.keywords.*` words in every locale. A setting that produces something on a feature page gets a link in that page's context row (`ContextLinks`, under the header), not only a home in Settings. Guard: `src/__tests__/surface-registry-guard.test.ts`. A page that is not about one section of the record (the emergency card, Settings > Health record) opens inside a shared record by its routes' guard (`RECORD_PAGE_SURFACES`), and `record-page-surfaces.test.ts` holds page and route to the same rule. ## 11. Inline action row; the PageHeader pattern diff --git a/docs/using/emergency-card.md b/docs/using/emergency-card.md index 746dc9d32a..06462d8079 100644 --- a/docs/using/emergency-card.md +++ b/docs/using/emergency-card.md @@ -19,10 +19,11 @@ The card is assembled from what you already keep in HealthLog: state; - your date of birth. -Open **Emergency card** in the navigation (on a phone under **More**), or use -the button on **Emergency information** in **Settings > Medical history**, the -row in **Settings > Health record**, or search for "emergency card". The -address is `/emergency-card`. +Open **Emergency card** from the account menu (your avatar, at the bottom of +the sidebar or at the top right on a phone), or use the button on **Emergency +information** in **Settings > Medical history**, the row in **Settings > +Health record**, or search for "emergency card". The address is +`/emergency-card`. It is the card of the record on screen. In your own record that is yours. The guardian of a managed profile holds the profile's card, so inside that profile diff --git a/e2e/v138-managed-record-capabilities.spec.ts b/e2e/v138-managed-record-capabilities.spec.ts index 6141abe4df..bc200a8002 100644 --- a/e2e/v138-managed-record-capabilities.spec.ts +++ b/e2e/v138-managed-record-capabilities.spec.ts @@ -196,8 +196,15 @@ test.describe.serial("a guardian's controls inside a managed profile", () => { await expect(sidebar.locator('a[href="/notifications"]')).toHaveCount(0); // The guardian holds the profile's emergency card, and the page opens for - // them exactly as far as its routes admit (`RECORD_PAGE_SURFACES`). - await sidebar.locator('a[href="/emergency-card"]').click(); + // them exactly as far as its routes admit (`RECORD_PAGE_SURFACES`). It + // opens from the account menu, not the rail. + await expect(sidebar.locator('a[href="/emergency-card"]')).toHaveCount(0); + await sidebar + .locator('[data-slot="sidebar-account"] [aria-haspopup="menu"]') + .click(); + await page + .locator('[data-slot="account-menu-record-link"][href="/emergency-card"]') + .click(); await expect(page).toHaveURL(/\/emergency-card$/); await expect( page.locator('[data-slot="emergency-card-preview"]'), diff --git a/src/__tests__/surface-registry-guard.test.ts b/src/__tests__/surface-registry-guard.test.ts index bd0ba8828a..812a6b876b 100644 --- a/src/__tests__/surface-registry-guard.test.ts +++ b/src/__tests__/surface-registry-guard.test.ts @@ -35,6 +35,7 @@ import { ADMIN_SECTIONS } from "@/components/admin/admin-shell"; import { buildPaletteIndex } from "@/components/command-palette/build-index"; import { CONTEXT_LINKS } from "@/components/layout/context-links"; import { + NAV_ACCOUNT_MENU_DESTINATIONS, NAV_DESTINATIONS, NAV_UTILITY_DESTINATIONS, } from "@/components/layout/nav-model"; @@ -194,7 +195,7 @@ describe("1. every page route is an entry or a declared child of one", () => { } expect( registryHrefs.has(route), - `${route} has no way in: add it to NAV_DESTINATIONS (or the Insights strip), or declare it in CHILD_PAGES with the page that links it`, + `${route} has no way in: add it to NAV_DESTINATIONS (or the account menu, or the Insights strip), or declare it in CHILD_PAGES with the page that links it`, ).toBe(true); }); @@ -214,7 +215,7 @@ const UNINDEXED_ANCHORS: Readonly> = { "A list of pointers to where reminders are set; the targets are entries.", "sessions-link": "A link to Security > Active sessions, which is the entry.", "emergency-card": - "Settings > Health record's way to the emergency card, which is a navigation entry (`nav:/emergency-card`).", + "Settings > Health record's way to the emergency card, which opens from the account menu (`nav:/emergency-card`).", }; const ANCHOR_SOURCES = [ @@ -274,7 +275,10 @@ function entryPointExists(entry: SurfaceEntry): boolean { case "nav": return NAV_DESTINATIONS.some((d) => d.href === entry.href); case "menu": - return NAV_UTILITY_DESTINATIONS.some((d) => d.href === entry.href); + return [ + ...NAV_UTILITY_DESTINATIONS, + ...NAV_ACCOUNT_MENU_DESTINATIONS, + ].some((d) => d.href === entry.href); case "admin": return ADMIN_SECTIONS.some((s) => `/admin/${s.slug}` === entry.href); case "insights": @@ -307,8 +311,13 @@ describe("2. every entry has a navigation, menu, Settings or Admin row", () => { }, ); - it("the emergency card is a destination, two taps from More on a phone", () => { - expect(NAV_DESTINATIONS.map((d) => d.href)).toContain("/emergency-card"); + it("the emergency card opens from the account menu, not the rail", () => { + expect(NAV_ACCOUNT_MENU_DESTINATIONS.map((d) => d.href)).toContain( + "/emergency-card", + ); + expect(NAV_DESTINATIONS.map((d) => d.href)).not.toContain( + "/emergency-card", + ); }); }); diff --git a/src/components/command-palette/build-index.ts b/src/components/command-palette/build-index.ts index 4ee319159f..597a422cdf 100644 --- a/src/components/command-palette/build-index.ts +++ b/src/components/command-palette/build-index.ts @@ -8,6 +8,8 @@ import { } from "lucide-react"; import { + NAV_ACCOUNT_MENU_DESTINATIONS, + visibleAccountMenuDestinations, visibleNavDestinations, type NavRecordContext, } from "@/components/layout/nav-model"; @@ -146,6 +148,16 @@ export function buildPaletteIndex(input: PaletteIndexInput): PaletteEntry[] { input.record ?? null, ); const navHrefs = new Set(nav.map((d) => d.href)); + // The record pages the account menu opens, under that menu's own rule. + const accountMenuHrefs = new Set( + visibleAccountMenuDestinations({ + sharedRecord: input.inSharedRecord, + sections: input.sections, + record: input.record ?? null, + }).map((d) => d.href), + ); + const isAccountMenuPage = (href: string) => + NAV_ACCOUNT_MENU_DESTINATIONS.some((d) => d.href === href); // Settings sections the shell lists for the record on screen. const sectionTitle = new Map(); @@ -167,6 +179,9 @@ export function buildPaletteIndex(input: PaletteIndexInput): PaletteEntry[] { if (!navHrefs.has(entry.href)) return null; return point.groupKey ? { hint: t(point.groupKey) } : {}; case "menu": + if (isAccountMenuPage(entry.href)) { + return accountMenuHrefs.has(entry.href) ? {} : null; + } return input.inSharedRecord ? null : {}; case "admin": return input.isAdmin && !input.inSharedRecord diff --git a/src/components/layout/__tests__/account-menu-record-items.browser.test.tsx b/src/components/layout/__tests__/account-menu-record-items.browser.test.tsx new file mode 100644 index 0000000000..0191a3088e --- /dev/null +++ b/src/components/layout/__tests__/account-menu-record-items.browser.test.tsx @@ -0,0 +1,110 @@ +/** + * The emergency card in the account menu. + * + * The card is set up once and then waits in the background, so it left the + * rail and the phone's More sheet for the account menu. This mounts the phone's + * real account menu (the top bar's) and the desktop one's slice, opens them, + * and reads what a person sees: the entry in one's own record and inside a + * managed profile one looks after, and no entry inside an adult's shared + * record, which is the rule the rail entry followed before. + * + * Mutation check, run: dropping the shared-record filter in + * `visibleAccountMenuDestinations` turns "an adult's delegate does not see it" + * red. + */ +import { describe, expect, it, vi } from "vitest"; +import { page, userEvent } from "vitest/browser"; + +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import type { AccountAccessEntry } from "@/lib/sharing/account-access-view"; + +import { renderWithApp } from "../../../../tests/browser/render"; + +vi.mock("@/hooks/use-account-switch", () => ({ + useAccountSwitch: () => ({ + mutate: vi.fn(), + switchTo: vi.fn(), + isPending: false, + }), +})); + +import { AccountMenuRecordItems } from "../account-menu-record-items"; +import { TopBar } from "../top-bar"; + +function active( + recordKind: "shared" | "managed", + level: "read" | "write" | "manage", +): AccountAccessEntry { + return { + accountId: "acct-record", + username: "record", + displayName: null, + fullName: "Record Holder", + access: level === "read" ? "read" : "write", + level, + sections: null, + recordKind, + canWrite: level !== "read", + writableDomains: [], + manageableDomains: [], + }; +} + +function cardLink(): HTMLAnchorElement | null { + return document.querySelector( + '[data-slot="account-menu-record-link"][href="/emergency-card"]', + ); +} + +describe("the phone's account menu", () => { + it("offers the emergency card in one's own record", async () => { + await page.viewport(390, 844); + await renderWithApp(); + + await userEvent.click(page.getByRole("button", { name: "User menu" })); + await expect.poll(() => cardLink()).toBeTruthy(); + expect(cardLink()?.textContent).toBe("Emergency card"); + expect(cardLink()?.closest('[role="menu"]')).toBeTruthy(); + }); +}); + +async function mountSlice(entry: AccountAccessEntry | null) { + await renderWithApp( + + Account + + + + + , + { + user: { + accountAccess: { + accounts: entry ? [entry] : [], + active: entry, + canSwitch: entry !== null, + }, + }, + }, + ); + await page.getByRole("button", { name: "Account" }).click(); + await expect + .poll(() => document.querySelector('[data-slot="menu-open"]')) + .toBeTruthy(); +} + +describe("the account-menu slice inside a shared record", () => { + it("a managed profile's guardian sees the profile's card", async () => { + await mountSlice(active("managed", "manage")); + await expect.poll(() => cardLink()).toBeTruthy(); + }); + + it("an adult's delegate does not see it", async () => { + await mountSlice(active("shared", "manage")); + expect(cardLink()).toBeNull(); + }); +}); diff --git a/src/components/layout/__tests__/nav-model.test.ts b/src/components/layout/__tests__/nav-model.test.ts index 280be58412..b2c0bfc72f 100644 --- a/src/components/layout/__tests__/nav-model.test.ts +++ b/src/components/layout/__tests__/nav-model.test.ts @@ -8,10 +8,12 @@ * prefers the most-specific sibling under `/insights`. (v1.18.0 — * Workouts and Recovery left the left nav for their Insights pills.) */ +import { HeartPulse } from "lucide-react"; import { describe, expect, it } from "vitest"; import { BOTTOM_NAV_PRIMARY_SLOT_HREFS, + NAV_ACCOUNT_MENU_DESTINATIONS, NAV_DESTINATIONS, NAV_GROUPS, groupNavDestinations, @@ -19,6 +21,7 @@ import { NAV_UTILITY_DESTINATIONS, isNavDestinationActive, mobileMoreHubDestinations, + visibleAccountMenuDestinations, visibleNavDestinations, visibleUtilityDestinations, } from "../nav-model"; @@ -76,7 +79,6 @@ describe("nav-model destination list", () => { "/seizures", "/vaccinations", "/documents", - "/emergency-card", ], ], ["analysis", ["/timeline", "/insights", "/coach", "/achievements"]], @@ -327,3 +329,48 @@ describe("isNavDestinationActive most-specific resolution", () => { ); }); }); + +describe("the emergency card opens from the account menu", () => { + const menu = (opts: Parameters[0]) => + visibleAccountMenuDestinations(opts).map((d) => d.href); + + it("takes no slot in the rail or the phone's More sheet", () => { + expect(NAV_DESTINATIONS.map((d) => d.href)).not.toContain( + "/emergency-card", + ); + expect( + mobileMoreHubDestinations({ modules: {} }).map((d) => d.href), + ).not.toContain("/emergency-card"); + }); + + it("is an account-menu entry with the card's name and icon", () => { + const card = NAV_ACCOUNT_MENU_DESTINATIONS.find( + (d) => d.href === "/emergency-card", + ); + expect(card?.tKey).toBe("nav.emergencyCard"); + expect(card?.icon).toBe(HeartPulse); + }); + + it("shows in one's own record, whatever the module map", () => { + expect(menu({})).toEqual(["/emergency-card"]); + expect(menu({ sharedRecord: false })).toEqual(["/emergency-card"]); + }); + + it("follows the card's route rule inside a shared record", () => { + // The guardian of a managed profile holds the profile's card. + expect( + menu({ + sharedRecord: true, + record: { recordKind: "managed", level: "manage" }, + }), + ).toEqual(["/emergency-card"]); + // An adult's delegate never does, at any level or scope. + for (const level of ["read", "write", "manage"] as const) { + expect( + menu({ sharedRecord: true, record: { recordKind: "shared", level } }), + ).toEqual([]); + } + // A refused or pending switch carries no kind or level: nothing opens. + expect(menu({ sharedRecord: true, sections: [] })).toEqual([]); + }); +}); diff --git a/src/components/layout/account-menu-record-items.tsx b/src/components/layout/account-menu-record-items.tsx new file mode 100644 index 0000000000..33e7808287 --- /dev/null +++ b/src/components/layout/account-menu-record-items.tsx @@ -0,0 +1,50 @@ +"use client"; + +import Link from "next/link"; + +import { visibleAccountMenuDestinations } from "@/components/layout/nav-model"; +import { DropdownMenuItem } from "@/components/ui/dropdown-menu"; +import { useRecordCapabilities } from "@/hooks/use-record-capabilities"; +import { useTranslations } from "@/lib/i18n/context"; + +/** + * The record pages that open from the account menu (the emergency card), as a + * slice of the user menu. + * + * One component mounted in both user menus, the desktop sidebar's avatar + * dropdown and the phone's top-bar dropdown, for the reason the switcher beside + * it gives: two menus written twice drift. Which pages show is + * `visibleAccountMenuDestinations`, read with the record on screen as the + * server resolved it, so inside a shared record the entry follows the page's + * own route rule. + */ +export function AccountMenuRecordItems() { + const { t } = useTranslations(); + const { inSharedRecord, sections, recordKind, level } = + useRecordCapabilities(); + const items = visibleAccountMenuDestinations({ + sharedRecord: inSharedRecord, + sections, + record: { recordKind, level }, + }); + + return ( + <> + {items.map((item) => { + const Icon = item.icon; + return ( + + + + {t(item.tKey)} + + + ); + })} + + ); +} diff --git a/src/components/layout/nav-model.ts b/src/components/layout/nav-model.ts index 6dcde52b46..b3ba871368 100644 --- a/src/components/layout/nav-model.ts +++ b/src/components/layout/nav-model.ts @@ -270,21 +270,9 @@ export const NAV_DESTINATIONS: ReadonlyArray = [ icon: FileScan, tourId: "nav-documents", }, - // The emergency card: blood group, allergies, medications and - // contacts to show a stranger, with its offline copy, wallet card and QR - // link. A page people use rather than a setting, so it is a destination of - // its own after the record pages, and on a phone it sits in the More hub - // (two taps). Core: no module owns it. Inside a shared record it follows - // its routes' rule (`RECORD_PAGE_SURFACES`): the guardian of a managed - // profile holds the profile's card, an adult's delegate never does. - { - href: "/emergency-card", - group: "record", - sharedRecord: true, - tKey: "nav.emergencyCard", - icon: HeartPulse, - tourId: "nav-emergency-card", - }, + // The emergency card is not a destination here: it is set up once and then + // waits in the background, so it opens from the account menu + // (`NAV_ACCOUNT_MENU_DESTINATIONS` below) rather than taking a rail slot. // v1.42 (#613) — the life timeline, first under Analysis. // Owned by the opt-in `timeline` module in the surface map, so it appears // only once the person switches it on; on a phone it lands in the More hub @@ -416,6 +404,51 @@ export function visibleUtilityDestinations( ); } +/** + * Record pages that open from the account menu rather than the rail. + * + * The emergency card (blood group, allergies, medications and contacts to show + * a stranger, with its offline copy, wallet card and QR link) is set up once + * and then lives in the background, so it takes no slot in the sidebar or the + * phone's More sheet. It sits in both account menus beside the account + * utilities, and stays reachable from Medical history, Settings > Health + * record and the search palette. + * + * Unlike the utility tail these are pages OF THE RECORD, so inside a shared + * record they follow their routes' rule (`RECORD_PAGE_SURFACES`) exactly as a + * rail destination flagged `sharedRecord` does: the guardian of a managed + * profile holds the profile's card, an adult's delegate never does. Core: no + * module owns any of them. + */ +export interface NavAccountMenuDestination { + href: string; + /** i18n key under the `nav.*` namespace. */ + tKey: string; + icon: LucideIcon; +} + +export const NAV_ACCOUNT_MENU_DESTINATIONS: ReadonlyArray = + [{ href: "/emergency-card", tKey: "nav.emergencyCard", icon: HeartPulse }]; + +/** + * The account-menu record pages visible to this session. Both account menus + * and the search palette read it, so the three cannot disagree about when the + * emergency card is offered. + */ +export function visibleAccountMenuDestinations( + opts: { + sharedRecord?: boolean; + sections?: readonly ShareDomain[] | null; + record?: NavRecordContext | null; + } = {}, +): NavAccountMenuDestination[] { + if (!opts.sharedRecord) return [...NAV_ACCOUNT_MENU_DESTINATIONS]; + const viewer = sharedViewer(opts.sections ?? null, opts.record ?? null); + return NAV_ACCOUNT_MENU_DESTINATIONS.filter((d) => + isSharedRecordPathOpen(d.href, viewer), + ); +} + /** * A partial map of `ModuleKey → enabled`. This is the `modules` field * `GET /api/auth/me` returns (resolved server-side, with cycle + coach diff --git a/src/components/layout/sidebar-nav.tsx b/src/components/layout/sidebar-nav.tsx index 448d55ef29..3aaab53b5c 100644 --- a/src/components/layout/sidebar-nav.tsx +++ b/src/components/layout/sidebar-nav.tsx @@ -14,6 +14,7 @@ import { import Link from "next/link"; import { usePathname } from "next/navigation"; import { useQueryClient } from "@tanstack/react-query"; +import { AccountMenuRecordItems } from "@/components/layout/account-menu-record-items"; import { AccountSwitcherMenuItems } from "@/components/layout/account-switcher-menu"; import { openShortcutsHelp } from "@/components/layout/global-shortcuts"; import { medicationsPrefetchIntentProps } from "@/lib/queries/prefetch-medications"; @@ -202,6 +203,10 @@ function SidebarUserSection({ collapsed }: { collapsed: boolean }) { )} + {/* The emergency card: set up once, then out of the way, so it opens + from here rather than from the rail. Inside a shared record it + follows its routes' rule (a guardian yes, an adult's delegate no). */} + {/* v1.42 — the keyboard shortcuts, findable without knowing that `?` lists them. Desktop only, like this menu: the phone's account menu has no keyboard to describe. */} diff --git a/src/components/layout/surface-registry.ts b/src/components/layout/surface-registry.ts index 869d1d3e88..c031147bf3 100644 --- a/src/components/layout/surface-registry.ts +++ b/src/components/layout/surface-registry.ts @@ -22,6 +22,7 @@ import { ChartLine, Palette, type LucideIcon } from "lucide-react"; import { ADMIN_SECTIONS } from "@/components/admin/admin-shell"; import { SUB_PAGE_TABS } from "@/components/insights/insights-tab-strip"; import { + NAV_ACCOUNT_MENU_DESTINATIONS, NAV_DESTINATIONS, NAV_UTILITY_DESTINATIONS, isSettingsUtilityDestination, @@ -48,7 +49,10 @@ export type SurfaceEntryPoint = * heading (`NAV_GROUPS`); null for the unheaded top group. */ | { kind: "nav"; groupKey: string | null } - /** The avatar menu: an account utility (ui-standards §10). */ + /** + * The avatar menu: an account utility (ui-standards §10), or a record page + * that opens from there (`NAV_ACCOUNT_MENU_DESTINATIONS`). + */ | { kind: "menu" } /** The Admin console's rail, for an admin in their own record. */ | { kind: "admin" } @@ -152,6 +156,20 @@ function build(): SurfaceEntry[] { }), ); } + // The record pages the account menu opens (the emergency card). Their id + // keeps the `nav:` prefix the utilities use, so a recent search and a + // context link survive the move from the rail. + for (const d of NAV_ACCOUNT_MENU_DESTINATIONS) { + out.push( + withKeywords({ + id: `nav:${d.href}`, + href: d.href, + labelKey: d.tKey, + icon: d.icon, + entry: { kind: "menu" }, + }), + ); + } for (const section of ADMIN_SECTIONS) { out.push( withKeywords({ diff --git a/src/components/layout/top-bar.tsx b/src/components/layout/top-bar.tsx index 9c7bc1a775..f062d1eff7 100644 --- a/src/components/layout/top-bar.tsx +++ b/src/components/layout/top-bar.tsx @@ -2,6 +2,7 @@ import { ChevronDown, LogIn, LogOut, Shield } from "lucide-react"; import { CommandPaletteTrigger } from "@/components/command-palette/command-palette-trigger"; +import { AccountMenuRecordItems } from "@/components/layout/account-menu-record-items"; import { AccountSwitcherMenuItems } from "@/components/layout/account-switcher-menu"; import { isSettingsUtilityDestination, @@ -156,6 +157,8 @@ export function TopBar() { ); })} + {/* The emergency card, the same slice the sidebar menu mounts. */} + {!sharedRecord && isAdmin && ( diff --git a/src/components/settings/emergency-card-entry-card.tsx b/src/components/settings/emergency-card-entry-card.tsx index 0e81b0d479..4ec156af13 100644 --- a/src/components/settings/emergency-card-entry-card.tsx +++ b/src/components/settings/emergency-card-entry-card.tsx @@ -4,7 +4,7 @@ * Settings > Health record: the way to the emergency card, beside the other * ways the record leaves the app (the report, the clinician links, the care * calendar). The card is a page of its own (`/emergency-card`, also in the - * navigation); this row is here because its QR link is one more door out of + * account menu); this row is here because its QR link is one more door out of * the record, and that is where people look for those. */ import Link from "next/link"; From 8a703a01ea08bc2601514b8ca0f00bb49bd80ce8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 12:23:43 +0100 Subject: [PATCH 05/14] fix(medications): keep today's open doses on a save that repeats the schedule A medication save that sent back the same schedule archived no era but still tombstoned today's open pending rows. The next projecting read re-minted the same instants under new ids, and the edit woke every device with an intake sync and a data-changed push for nothing. The schedule replace now decides both consequences with one predicate, scheduleReplaceChangesCadence: the era is archived and the open slots are tombstoned only when tracking changes, the stretch is untracked, or the cadence materially differs. The edit tells the devices only when the stored medication, its schedules or its category actually changed. The integration test follows a time edit through the reminder worker, resolved-slots, dose-history, the MCP schedule, the today list, the dashboard and the digest, including a move to a time already past, and holds an unchanged save to the same row id and no wake. --- CHANGELOG.md | 1 + .../medications/[id]/__tests__/route.test.ts | 7 + .../medications/scheduling/schedule-eras.ts | 20 + .../update-medication/update-medication.ts | 38 +- .../medications/update-medication/write.ts | 27 +- .../medication-time-edit-today-slots.test.ts | 354 ++++++++++++++++++ 6 files changed, 432 insertions(+), 15 deletions(-) create mode 100644 tests/integration/medication-time-edit-today-slots.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index be948bb86e..ad3dc9b5fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -178,6 +178,7 @@ - Posting a single entry again that was deleted in HealthLog (mood, measurement, cycle day, AUDIT-C) answers `410` with the reason `deleted_in_healthlog` instead of bringing it back; a mood entry deleted in Apple Health comes back when Apple Health sends it again. - The iOS app's "sync with your other devices is disturbed" notice only appears for a real, current problem: a silent push iOS chose not to deliver no longer counts, and the next confirmed alert clears it. +- Saving a medication without changing its times no longer resets today's open doses or wakes the other devices. ### Security diff --git a/src/app/api/medications/[id]/__tests__/route.test.ts b/src/app/api/medications/[id]/__tests__/route.test.ts index f787636164..3511672846 100644 --- a/src/app/api/medications/[id]/__tests__/route.test.ts +++ b/src/app/api/medications/[id]/__tests__/route.test.ts @@ -164,6 +164,7 @@ beforeEach(() => { async (_id, category) => (category ?? "OTHER") as never, ); vi.mocked(prisma.medication.findUnique).mockResolvedValue({ + schedules: [], id: "m1", userId: "user-1", } as never); @@ -314,6 +315,7 @@ describe("PUT /api/medications/[id] — schedule replace archives a revision (v1 beforeEach(() => { vi.mocked(getSession).mockResolvedValue(SESSION_OK as never); vi.mocked(prisma.medication.findUnique).mockResolvedValue({ + schedules: [], id: "m1", userId: "user-1", active: true, @@ -413,6 +415,7 @@ describe("PUT /api/medications/[id] — schedule replace migrates open slots", ( beforeEach(() => { vi.mocked(getSession).mockResolvedValue(SESSION_OK as never); vi.mocked(prisma.medication.findUnique).mockResolvedValue({ + schedules: [], id: "m1", userId: "user-1", active: true, @@ -503,6 +506,7 @@ describe("PUT /api/medications/[id] — window / timesOfDay consistency", () => beforeEach(() => { vi.mocked(getSession).mockResolvedValue(SESSION_OK as never); vi.mocked(prisma.medication.findUnique).mockResolvedValue({ + schedules: [], id: "m1", userId: "user-1", active: true, @@ -673,6 +677,7 @@ describe("PUT /api/medications/[id] — as-needed (v1.16.11, #316)", () => { scheduleCount?: number; }) { vi.mocked(prisma.medication.findUnique).mockResolvedValue({ + schedules: [], id: "m1", userId: "user-1", active: true, @@ -878,6 +883,7 @@ describe("PUT /api/medications/[id] — intake tracking switch (#1033)", () => { function arrange(trackIntake: boolean) { vi.mocked(getSession).mockResolvedValue(SESSION_OK as never); vi.mocked(prisma.medication.findUnique).mockResolvedValue({ + schedules: [], id: "m1", userId: "user-1", active: true, @@ -1067,6 +1073,7 @@ describe("PUT /api/medications/[id] — shipped client on a record-only medicati function arrange(trackIntake: boolean) { vi.mocked(getSession).mockResolvedValue(SESSION_OK as never); vi.mocked(prisma.medication.findUnique).mockResolvedValue({ + schedules: [], id: "m1", userId: "user-1", active: true, diff --git a/src/lib/medications/scheduling/schedule-eras.ts b/src/lib/medications/scheduling/schedule-eras.ts index 481f5f5dc5..cc72df7645 100644 --- a/src/lib/medications/scheduling/schedule-eras.ts +++ b/src/lib/medications/scheduling/schedule-eras.ts @@ -376,3 +376,23 @@ export function schedulesMateriallyDiffer( const b = after.map(cadenceFingerprint).sort(); return a.some((fp, i) => fp !== b[i]); } + +/** + * Whether a schedule replace changes what is due: a tracking transition, an + * untracked stretch, or a cadence that materially differs. The one predicate + * for both consequences of a replace, the archived era and the tombstoned + * open slots of today and later. A save that repeats the schedule changes + * neither, so today's open rows keep their ids and nothing is re-minted. + */ +export function scheduleReplaceChangesCadence(input: { + before: ScheduleRevisionEntry[]; + after: ScheduleRevisionEntry[]; + wasTracked: boolean; + trackingChanged: boolean; +}): boolean { + return ( + input.trackingChanged || + !input.wasTracked || + schedulesMateriallyDiffer(input.before, input.after) + ); +} diff --git a/src/lib/medications/update-medication/update-medication.ts b/src/lib/medications/update-medication/update-medication.ts index 46dfc34006..1bd420e469 100644 --- a/src/lib/medications/update-medication/update-medication.ts +++ b/src/lib/medications/update-medication/update-medication.ts @@ -50,6 +50,7 @@ import { type MedicationEditWrite, } from "./write"; import { MEDICATION_SCHEDULE_ORDER } from "@/lib/medications/read-order"; +import { readMedicationNote } from "@/lib/medications/medication-note"; type EditUser = ReadUser; type EditedMedication = Awaited>; @@ -299,6 +300,32 @@ async function auditMedicationEdit( }); } +/** + * Everything an edit can change on the medication, as one comparable string: + * the row (the note decrypted, since the same note re-seals to a different + * ciphertext), its schedules without their ids (a replace re-creates them) + * and its category. Equal before and after means the save changed nothing a + * device shows, so no device is woken for it. + */ +async function medicationStateKey(id: string): Promise { + const row = await prisma.medication.findUnique({ + where: { id }, + include: { + schedules: true, + categoryAssignment: { select: { category: true } }, + }, + }); + if (!row) return null; + const { updatedAt: _updatedAt, noteEncrypted, schedules, ...rest } = row; + return JSON.stringify({ + ...rest, + note: readMedicationNote(noteEncrypted), + schedules: schedules + .map(({ id: _scheduleId, ...schedule }) => JSON.stringify(schedule)) + .sort(), + }); +} + /** Edit one medication the route found and authorised. */ export async function updateMedication(input: { user: EditUser; @@ -316,6 +343,7 @@ export async function updateMedication(input: { const plan = await planMedicationEdit(input); if (!plan.ok) return plan; const { write } = plan; + const stateBefore = await medicationStateKey(id); let medication: EditedMedication; try { @@ -363,8 +391,14 @@ export async function updateMedication(input: { // Bust per-user medications + compliance + achievement caches so the next // read reflects the schedule change. // A schedule, a pause, a course or intake tracking decides what is due on - // every device. - afterMedicationChange(user.id); + // every device. A save that changed nothing (the form echoing the stored + // medication back) tells no device: the silent budget is small. + if ( + (write.trail.tombstonedSlotCount ?? 0) > 0 || + (await medicationStateKey(id)) !== stateBefore + ) { + afterMedicationChange(user.id); + } // The read model, exactly as `GET /api/medications/{id}` answers it. const body = await medicationDetail({ diff --git a/src/lib/medications/update-medication/write.ts b/src/lib/medications/update-medication/write.ts index b4e4a76aa6..2a84decc89 100644 --- a/src/lib/medications/update-medication/write.ts +++ b/src/lib/medications/update-medication/write.ts @@ -15,7 +15,7 @@ import { annotate } from "@/lib/logging/context"; import type { SessionUser } from "@/lib/auth/session-user"; import { setCurrentWindow } from "@/lib/medications/courses"; import { - schedulesMateriallyDiffer, + scheduleReplaceChangesCadence, toRevisionPayloadEntry, } from "@/lib/medications/scheduling/schedule-eras"; import { moveAutoTakeFloorToNow } from "@/lib/medications/auto-take"; @@ -75,8 +75,8 @@ type RevisionSourceRow = Parameters[0]; /** * Tombstone today's and future open pending rows of this medication. Runs on - * a schedule replace (the old anchors are stale) and when intake tracking is - * switched off (nothing is due any more). + * a schedule replace that changes the cadence (the old anchors are stale) and + * when intake tracking is switched off (nothing is due any more). */ async function tombstoneOpenSlots( db: Prisma.TransactionClient, @@ -231,15 +231,13 @@ async function replaceSchedules( // archives with an empty payload whatever the rows said; and a tracking // transition is itself an era boundary even when the rows stay the same. const archivedEntries = wasTracked ? previousEntries : []; - if ( - previousRows.length > 0 && - (trackingChanged || - !wasTracked || - schedulesMateriallyDiffer( - previousEntries, - normalisedSchedules.map((n) => n.snapshot), - )) - ) { + const cadenceChanged = scheduleReplaceChangesCadence({ + before: previousEntries, + after: normalisedSchedules.map((n) => n.snapshot), + wasTracked, + trackingChanged, + }); + if (previousRows.length > 0 && cadenceChanged) { await archiveEra(tx, edit, archivedEntries, { schedule_revision_rows: archivedEntries.length, }); @@ -260,7 +258,10 @@ async function replaceSchedules( // expects nothing there — exactly the as-needed contract. await archiveEra(tx, edit, [], { schedule_revision_rows: 0 }); } - await tombstoneOpenSlots(tx, edit); + // Only a replace that changes what is due invalidates the open anchors. + // An echo of the same schedule leaves them: tombstoning would re-mint the + // same instants under new ids and wake every device for nothing. + if (cadenceChanged) await tombstoneOpenSlots(tx, edit); await tx.medicationSchedule.deleteMany({ where: { medicationId: id }, }); diff --git a/tests/integration/medication-time-edit-today-slots.test.ts b/tests/integration/medication-time-edit-today-slots.test.ts new file mode 100644 index 0000000000..4f54b904e1 --- /dev/null +++ b/tests/integration/medication-time-edit-today-slots.test.ts @@ -0,0 +1,354 @@ +/** + * A dose time moved during the day: every surface that derives today's slots + * must agree once the edit has committed. Replays a daily medication moved + * from 21:16 to 11:30 (Berlin) at 11:26, and to 09:00, a time already past. + * + * - the schedule replace tombstones today's open 21:16 row and wakes the + * devices once; + * - the reminder worker, resolved-slots, dose-history, the MCP schedule, + * the today list, the dashboard count and the digest then all name the + * new time (or, for a time already past, no slot today) and none names + * 21:16. + * + * And the echo: a save that repeats the schedule is no change. The open row + * keeps its id and sync version, no era is archived and no device is woken. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { NextRequest } from "next/server"; + +import { cookieJar, headerJar } from "./mock-next-headers"; +import { getPrismaClient, truncateAllTables } from "./setup"; +import { + DAY_MS, + TZ, + readDashboardCompliance, + readToday, +} from "./medication-dose-state-fixtures"; + +vi.mock("next/headers", async () => + (await import("./medication-dose-state-fixtures")).nextHeadersMock(), +); +vi.mock("@/lib/notifications/dispatcher", () => ({ + dispatchNotification: vi.fn().mockResolvedValue({ + dispatched: true, + channelsAttempted: 1, + channelsSucceeded: 1, + }), +})); + +vi.mock("@/lib/notifications/medication-intake-sync", async (orig) => ({ + ...(await orig()), + queueMedicationIntakeSync: vi.fn(), +})); +vi.mock("@/lib/push-relay/data-changed", async (orig) => ({ + ...(await orig()), + noteDataChanged: vi.fn().mockResolvedValue(undefined), +})); + +const { dispatchNotification } = await import("@/lib/notifications/dispatcher"); +const { queueMedicationIntakeSync } = + await import("@/lib/notifications/medication-intake-sync"); +const { noteDataChanged } = await import("@/lib/push-relay/data-changed"); +const { getMedicationScheduleTool } = + await import("@/lib/mcp/tools/get-medication-schedule"); +const { loadDailyDigest } = await import("@/lib/daily/load-digest"); +const { handleReminderCheck } = + await import("@/lib/jobs/reminder/medication-reminder-check"); + +const OLD_SLOT = "2026-11-23T20:16:00.000Z"; // 21:16 Berlin +const NEW_SLOT = "2026-11-23T10:30:00.000Z"; // 11:30 Berlin +const TOMORROW_PAST_SLOT = "2026-11-24T08:00:00.000Z"; // 09:00 Berlin + +type Handler = ( + r: NextRequest, + c: { params: Promise> }, +) => Promise; +type PlainHandler = (r: NextRequest) => Promise; + +const OLD_SCHEDULE = { + windowStart: "20:46", + windowEnd: "22:16", + timesOfDay: ["21:16"], + rrule: "FREQ=DAILY", +}; +const PAST_SCHEDULE = { + windowStart: "08:30", + windowEnd: "09:30", + timesOfDay: ["09:00"], + rrule: "FREQ=DAILY", +}; +const NEW_SCHEDULE = { + windowStart: "11:00", + windowEnd: "12:00", + timesOfDay: ["11:30"], + rrule: "FREQ=DAILY", +}; + +beforeEach(async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-11-23T10:19:00.000Z")); + vi.mocked(dispatchNotification).mockClear(); + vi.mocked(queueMedicationIntakeSync).mockClear(); + vi.mocked(noteDataChanged).mockClear(); + await truncateAllTables(getPrismaClient()); + cookieJar.clear(); + headerJar.clear(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +async function seed() { + const prisma = getPrismaClient(); + const user = await prisma.user.create({ + data: { + username: "time-edit", + email: "time-edit@example.test", + role: "USER", + timezone: TZ, + locale: "en", + }, + }); + const session = await prisma.session.create({ + data: { userId: user.id, expiresAt: new Date(Date.now() + DAY_MS) }, + }); + cookieJar.set("healthlog_session", session.id); + const created = new Date("2026-11-22T20:04:33.000Z"); + const med = await prisma.medication.create({ + data: { + userId: user.id, + name: "Test Medication C", + dose: "1", + active: true, + notificationsEnabled: true, + startsOn: created, + createdAt: created, + schedules: { + create: { ...OLD_SCHEDULE, scheduleType: "SCHEDULED" }, + }, + }, + }); + return { user, med }; +} + +async function putSchedule(medId: string, schedule: typeof OLD_SCHEDULE) { + const { PUT } = await import("@/app/api/medications/[id]/route"); + const res = await (PUT as unknown as Handler)( + new NextRequest(`http://localhost/api/medications/${medId}`, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ schedules: [schedule] }), + }), + { params: Promise.resolve({ id: medId }) }, + ); + expect(res.status).toBe(200); +} + +async function liveRowsToday(medId: string) { + return getPrismaClient().medicationIntakeEvent.findMany({ + where: { + medicationId: medId, + deletedAt: null, + scheduledFor: { + gte: new Date("2026-11-22T23:00:00.000Z"), + lt: new Date("2026-11-23T23:00:00.000Z"), + }, + }, + select: { id: true, scheduledFor: true }, + }); +} + +async function resolvedSlotsToday(medId: string) { + const { GET } = await import("@/app/api/medications/resolved-slots/route"); + const q = new URLSearchParams({ + from: "2026-11-22T23:00:00.000Z", + to: "2026-11-23T22:59:59.000Z", + }); + const res = await (GET as unknown as PlainHandler)( + new NextRequest(`http://localhost/api/medications/resolved-slots?${q}`), + ); + expect(res.status).toBe(200); + const body = (await res.json()) as { + data: { + medications: Array<{ + medicationId: string; + slots: Array<{ slotInstant: string }>; + }>; + }; + }; + return ( + body.data.medications + .find((m) => m.medicationId === medId) + ?.slots.map((s) => s.slotInstant) ?? [] + ); +} + +async function doseHistoryToday(medId: string) { + const { GET } = await import("@/app/api/medications/[id]/dose-history/route"); + const q = new URLSearchParams({ + from: "2026-11-22T23:00:00.000Z", + to: "2026-11-23T22:59:59.000Z", + }); + const res = await (GET as unknown as Handler)( + new NextRequest( + `http://localhost/api/medications/${medId}/dose-history?${q}`, + ), + { params: Promise.resolve({ id: medId }) }, + ); + expect(res.status).toBe(200); + const body = (await res.json()) as { + data: { rows: Array<{ kind: string; at: string }> }; + }; + return body.data.rows.filter((r) => r.kind === "slot").map((r) => r.at); +} + +async function mcpNextDue(userId: string, medId: string) { + const out = (await getMedicationScheduleTool.run( + { + userId, + tokenId: "t", + scopes: ["*"], + binding: `${userId}:t`, + canRead: true, + canWrite: false, + }, + {}, + )) as { medications: Array<{ id: string; nextDueAt: string | null }> }; + return out.medications.find((m) => m.id === `med:${medId}`)?.nextDueAt; +} + +async function digestMedicationsLine(userId: string) { + const user = await getPrismaClient().user.findUniqueOrThrow({ + where: { id: userId }, + }); + const digest = await loadDailyDigest(user, new Date(), { locale: "en" }); + return digest.today.find((f) => f.kind === "medications")?.value ?? null; +} + +function remindedSlots() { + return vi + .mocked(dispatchNotification) + .mock.calls.map( + (c) => (c[0].metadata as { scheduledAt?: string }).scheduledAt, + ); +} + +/** The silent wakes the edits sent: intake syncs and data-changed notes. */ +function wakes() { + return ( + vi.mocked(queueMedicationIntakeSync).mock.calls.length + + vi.mocked(noteDataChanged).mock.calls.length + ); +} + +describe("a dose time moved during the day", () => { + it("leaves every today surface on the new time", async () => { + const { user, med } = await seed(); + const prisma = getPrismaClient(); + + // 11:19 Berlin: the app's launch projects today's 21:16 slot. + const before = await readToday(); + expect( + before.filter((r) => r.medicationId === med.id).map((r) => r.scheduledAt), + ).toEqual([OLD_SLOT]); + + // 11:26:01 Berlin: the time moves to 11:30. + vi.setSystemTime(new Date("2026-11-23T10:26:01.000Z")); + await putSchedule(med.id, NEW_SCHEDULE); + expect( + await prisma.medicationScheduleRevision.count({ + where: { medicationId: med.id }, + }), + ).toBe(1); + // A real change wakes the devices. + expect(vi.mocked(queueMedicationIntakeSync)).toHaveBeenCalledTimes(1); + + // The 21:16 row is tombstoned and nothing has minted 11:30 yet. + expect(await liveRowsToday(med.id)).toEqual([]); + + // 11:30:23 Berlin: the reminder worker reads the schedule, not the rows. + vi.setSystemTime(new Date("2026-11-23T10:30:23.000Z")); + await handleReminderCheck([]); + expect(remindedSlots()).toEqual([NEW_SLOT]); + + // The schedule-derived readers name 11:30 before any projection ran. + expect(await resolvedSlotsToday(med.id)).toEqual([NEW_SLOT]); + expect(await doseHistoryToday(med.id)).toEqual([NEW_SLOT]); + expect(await mcpNextDue(user.id, med.id)).toBe(NEW_SLOT); + + // The today list projects, and the row table follows. + const after = await readToday(); + expect( + after.filter((r) => r.medicationId === med.id).map((r) => r.scheduledAt), + ).toEqual([NEW_SLOT]); + expect( + (await liveRowsToday(med.id)).map((r) => r.scheduledFor.toISOString()), + ).toEqual([NEW_SLOT]); + + // The dashboard and the digest count the one moved dose. + expect((await readDashboardCompliance()).scheduledToday).toBe(1); + expect(await digestMedicationsLine(user.id)).toBe("0 of 1 taken"); + }); + + it("names no slot today when the time moves to one already past", async () => { + const { user, med } = await seed(); + + await readToday(); + vi.setSystemTime(new Date("2026-11-23T10:26:01.000Z")); + await putSchedule(med.id, PAST_SCHEDULE); + expect(vi.mocked(queueMedicationIntakeSync)).toHaveBeenCalledTimes(1); + + vi.setSystemTime(new Date("2026-11-23T10:30:23.000Z")); + await handleReminderCheck([]); + expect(remindedSlots()).toEqual([]); + + expect(await resolvedSlotsToday(med.id)).toEqual([]); + expect(await doseHistoryToday(med.id)).toEqual([]); + expect(await mcpNextDue(user.id, med.id)).toBe(TOMORROW_PAST_SLOT); + + const after = await readToday(); + expect(after.filter((r) => r.medicationId === med.id)).toEqual([]); + expect(await liveRowsToday(med.id)).toEqual([]); + expect((await readDashboardCompliance()).scheduledToday).toBe(0); + expect(await digestMedicationsLine(user.id)).toBeNull(); + }); + + it("keeps the open row and wakes no device on a save that repeats the schedule", async () => { + const { med } = await seed(); + const prisma = getPrismaClient(); + + await readToday(); + const [minted] = await liveRowsToday(med.id); + expect(minted.scheduledFor.toISOString()).toBe(OLD_SLOT); + const { syncVersion } = + await prisma.medicationIntakeEvent.findUniqueOrThrow({ + where: { id: minted.id }, + select: { syncVersion: true }, + }); + + // 11:25:45 Berlin: the form saves the same schedule back. + vi.setSystemTime(new Date("2026-11-23T10:25:45.000Z")); + await putSchedule(med.id, OLD_SCHEDULE); + + // No era: the cadence did not change. + expect( + await prisma.medicationScheduleRevision.count({ + where: { medicationId: med.id }, + }), + ).toBe(0); + // The open row stays, under its id and sync version ... + expect(await liveRowsToday(med.id)).toEqual([minted]); + const kept = await prisma.medicationIntakeEvent.findUniqueOrThrow({ + where: { id: minted.id }, + select: { deletedAt: true, syncVersion: true }, + }); + expect(kept).toEqual({ deletedAt: null, syncVersion }); + // ... and no device is woken for it. + expect(wakes()).toBe(0); + + // The next projecting read finds the same row. + await readToday(); + expect(await liveRowsToday(med.id)).toEqual([minted]); + }); +}); From dddf93db5c429dd63a8524e00a865f4840bac924 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 13:35:07 +0100 Subject: [PATCH 06/14] fix(push-relay): decide Live Activity updates by who started the Activity An Activity the app started itself reads countdownTarget as seconds since 2001-01-01, while the relay template carries unix seconds, so a relay update showed it a time decades off. The relay's countdown bounds leave no room to send it the other unit. relayActivityKind() names each registered Activity relay-started or app-started from its per-token mark, and relayEventAllowed() is the one decision: an update goes only to a relay-started Activity, an end to both. Every relay update is built through relayUpdateItem(), which asks it. An end carries no state; the relay writes its fixed end state (countdown 0, status taken, dismissed at once), which neither attributes type reads as a time. --- CHANGELOG.md | 2 +- .../__tests__/live-activity-kind.test.ts | 137 ++++++++++++++++++ src/lib/push-relay/live-activity.ts | 105 +++++++++++--- src/lib/push-relay/medication-pushes.ts | 6 + 4 files changed, 226 insertions(+), 24 deletions(-) create mode 100644 src/lib/push-relay/__tests__/live-activity-kind.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ad3dc9b5fc..55ac795c6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -159,7 +159,7 @@ - First SSO sign-in failed when a username existed in other case; changing the e-mail to such an address says it is taken instead of a server error. - "Delete all data" unbinds the account's devices at the relay. - A device that signs out, is revoked or moves to another account loses its push credentials and its Live Activities; a phone that signed out and moves to another account receives the new account's pushes instead of a refusal. -- Live Activity updates over the relay go only to Activities the server started. +- A Live Activity the app started itself no longer shows a wrong time after a server update: updates over the relay go only to Activities the server started. - Sender key rotation takes each step once, after its notice period. - The import cards and the snooze setting show a failed read with a retry, and a failed folder removal says so. - Undo and Edit toasts stay in front of achievement toasts. diff --git a/src/lib/push-relay/__tests__/live-activity-kind.test.ts b/src/lib/push-relay/__tests__/live-activity-kind.test.ts new file mode 100644 index 0000000000..14c992c929 --- /dev/null +++ b/src/lib/push-relay/__tests__/live-activity-kind.test.ts @@ -0,0 +1,137 @@ +/** + * Which registered Live Activity the relay may update and end. Updates carry + * `countdownTarget` in unix seconds, which only the Activity the relay + * started (`HealthLogDoseAttributes`) reads; the app's own Activity + * (`MedicationActivityAttributes`) reads seconds since 2001-01-01, so it gets + * no relay update, only the end, whose fixed state carries no time. + */ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const sendRelayItems = vi.fn(); +vi.mock("@/lib/push-relay/relay-send", () => ({ + sendRelayItems: (...args: unknown[]) => sendRelayItems(...args), +})); +vi.mock("@/lib/db", () => ({ + prisma: { + pushRelayDelivery: { + deleteMany: vi.fn(async () => ({ count: 0 })), + findMany: vi.fn(async () => []), + }, + }, +})); +vi.mock("@/lib/push-relay/route-device", async (importOriginal) => ({ + ...(await importOriginal()), + routeOf: () => "relay", +})); + +import { + doseContentState, + relayActivityKind, + relayEventAllowed, + relayUpdateItem, +} from "@/lib/push-relay/live-activity"; +import { endActivitiesOverRelay } from "@/lib/push-relay/medication-pushes"; +import type { PushContext } from "@/lib/push-relay/route-device"; +import { resolveDoseState } from "@/lib/medications/dose-state/resolve"; + +const NOW = new Date("2026-11-23T08:00:00Z"); +const NOW_S = Math.floor(NOW.getTime() / 1000); +const BINDING_KEY = Buffer.alloc(32, 7).toString("base64url"); +const device = { id: "dev-1", relayBindingKey: BINDING_KEY }; + +function activity(relayStarted: boolean, token: string) { + return { + id: `row-${token.slice(0, 2)}`, + pushToken: token, + relayStarted, + activityStatement: { iat: NOW_S - 60, laTokenTag: "x" }, + activitySignature: "sig", + }; +} +const RELAY = activity(true, "AB".repeat(32)); +const APP = activity(false, "CD".repeat(32)); + +/** A pending dose due in 20 minutes, as the relay pass would show it. */ +function pendingState() { + const at = (s: number) => new Date(s * 1000); + const slot = NOW_S + 3600; + const band = { + at: at(slot), + earlyStart: at(slot - 5400), + onTimeStart: at(slot - 2400), + onTimeEnd: at(slot + 3600), + overdueEnd: at(slot + 4 * 3600), + }; + const state = doseContentState( + { resolved: resolveDoseState(band, null, NOW), snoozedUntil: null }, + "AUTO", + NOW, + ); + if (!state) throw new Error("no state"); + return { state, dueAtS: slot - 2400 }; +} + +describe("who started a registered Activity", () => { + it("reads the per-token mark", () => { + expect(relayActivityKind(RELAY)).toBe("relay_started"); + expect(relayActivityKind(APP)).toBe("app_started"); + }); + + it("allows an update only to the relay-started one, an end to both", () => { + expect(relayEventAllowed("relay_started", "update")).toBe(true); + expect(relayEventAllowed("app_started", "update")).toBe(false); + expect(relayEventAllowed("relay_started", "end")).toBe(true); + expect(relayEventAllowed("app_started", "end")).toBe(true); + }); +}); + +describe("a relay update", () => { + it("never goes to an Activity the app started", () => { + const { state } = pendingState(); + expect(relayUpdateItem(device, APP, state, NOW)).toBeNull(); + }); + + it("goes to the relay-started Activity with its countdown in unix seconds", () => { + const { state, dueAtS } = pendingState(); + const item = relayUpdateItem(device, RELAY, state, NOW); + expect(item?.activity).toMatchObject({ + event: "update", + token: RELAY.pushToken.toLowerCase(), + state: { status: "pending", countdownTarget: dueAtS }, + }); + // Unix seconds, not seconds since 2001-01-01 (978307200 s less). + expect(item?.activity?.state?.countdownTarget).toBeGreaterThan(NOW_S); + }); +}); + +describe("a relay end", () => { + beforeEach(() => { + sendRelayItems.mockReset(); + sendRelayItems.mockResolvedValue({ answers: [], activityGone: [] }); + }); + + it("reaches the app-started Activity, carrying no time of its own", async () => { + const ctx = { config: {} } as unknown as PushContext; + await endActivitiesOverRelay( + { ...device, relayBindingKey: BINDING_KEY } as Parameters< + typeof endActivitiesOverRelay + >[0], + [APP, RELAY], + ctx, + ); + expect(sendRelayItems).toHaveBeenCalledTimes(1); + const items = sendRelayItems.mock.calls[0]![0] as Array<{ + activity: Record; + }>; + expect(items.map((i) => i.activity.token)).toEqual([ + APP.pushToken.toLowerCase(), + RELAY.pushToken.toLowerCase(), + ]); + // No event (the relay's default is end) and no state: the relay writes + // its fixed end state, `countdownTarget: 0`, which no unit can misread. + for (const item of items) { + expect(item.activity).not.toHaveProperty("event"); + expect(item.activity).not.toHaveProperty("state"); + } + }); +}); diff --git a/src/lib/push-relay/live-activity.ts b/src/lib/push-relay/live-activity.ts index f13b28c0dd..c5f354be8d 100644 --- a/src/lib/push-relay/live-activity.ts +++ b/src/lib/push-relay/live-activity.ts @@ -573,6 +573,80 @@ async function startItem( type LaActivity = LaDevice["liveActivities"][number]; +/** + * Who started a registered Activity: the relay, by a push-to-start + * (`HealthLogDoseAttributes`, registered with `relayStart: true`, the dose + * the device's `liveActivityStarted` names), or the app itself + * (`MedicationActivityAttributes`). The mark is kept per token + * (`relayStarted`, migration 0545) and never changes for an Activity. + */ +export type RelayActivityKind = "relay_started" | "app_started"; + +export function relayActivityKind(activity: { + relayStarted: boolean; +}): RelayActivityKind { + return activity.relayStarted ? "relay_started" : "app_started"; +} + +/** + * Whether the relay may send `event` to a registered Activity of this kind. + * Every relay update is built through {@link relayUpdateItem}, which asks + * this; the end path (`endActivitiesOverRelay`) ends every kind. + * + * An end goes to both kinds: the relay writes its own fixed content state + * into an end (`status: "taken"`, `countdownTarget: 0`, a `dismissal-date` + * of now; the server may send no state with it), and both attributes types + * hide the countdown for a taken dose and dismiss at once. + * + * An update goes only to an Activity the relay started. The relay template + * carries `countdownTarget` in unix seconds, which `HealthLogDoseAttributes` + * reads; `MedicationActivityAttributes` reads it as seconds since + * 2001-01-01, so an update showed an app-started Activity a time 31 years + * off. The relay's bounds (one day back, two days ahead of its clock, or 0) + * leave no room to send it reference-date seconds instead. iOS builds before + * the next 1.7 build read app-started Activities in reference-date seconds; + * relaxing this waits until those builds are gone (1.50 at the earliest). + */ +export function relayEventAllowed( + kind: RelayActivityKind, + event: "update" | "end", +): boolean { + return event === "end" || kind === "relay_started"; +} + +/** + * The relay update item that shows `state` on `activity`, or null when the + * relay may not update it ({@link relayEventAllowed}). + */ +export function relayUpdateItem( + device: Pick, + activity: Pick< + LaActivity, + "pushToken" | "relayStarted" | "activityStatement" | "activitySignature" + >, + state: RelayContentState, + now: Date, +): RelayItemInput | null { + if (!relayEventAllowed(relayActivityKind(activity), "update")) return null; + if (!activity.activitySignature || !device.relayBindingKey) return null; + const nowS = Math.floor(now.getTime() / 1000); + return { + deviceId: device.id, + ref: `lau-${newUlid(now.getTime())}`, + pushClass: "liveactivity", + eventType: LA_UPDATE_EVENT, + activity: { + event: "update", + state, + token: activity.pushToken.toLowerCase(), + bindingKey: device.relayBindingKey, + statement: activity.activityStatement as Record, + signature: activity.activitySignature, + }, + expiresAt: new Date((nowS + PUSH_LIFETIME_S) * 1000), + }; +} + /** * The update items for `device`'s running Activities whose state changed, * and the Activities that end: those whose dose the resolver calls missed, @@ -601,7 +675,9 @@ async function updateItems( const nowS = Math.floor(now.getTime() / 1000); const updates = []; const ending: LaActivity[] = []; - const relayStarted = device.liveActivities.some((a) => a.relayStarted); + const relayOwned = (a: LaActivity) => + relayActivityKind(a) === "relay_started"; + const relayStarted = device.liveActivities.some(relayOwned); const startable = relayStarted ? new Set( ( @@ -610,7 +686,7 @@ async function updateItems( userId: device.userId, id: { in: device.liveActivities - .filter((a) => a.relayStarted) + .filter(relayOwned) .map((a) => a.medicationId), }, ...STARTABLE_MEDICATION_WHERE, @@ -638,7 +714,7 @@ async function updateItems( ) { continue; } - if (activity.relayStarted && !startable.has(activity.medicationId)) { + if (relayOwned(activity) && !startable.has(activity.medicationId)) { ending.push(activity); continue; } @@ -664,28 +740,11 @@ async function updateItems( ending.push(activity); continue; } - if (!activity.relayStarted || refused) continue; + if (refused) continue; if (inFlight.has(activity.pushToken.toLowerCase())) continue; if (sameState(state, activity.lastRelayState)) continue; - updates.push({ - rowId: activity.id, - state, - item: { - deviceId: device.id, - ref: `lau-${newUlid(now.getTime())}`, - pushClass: "liveactivity" as const, - eventType: LA_UPDATE_EVENT, - activity: { - event: "update" as const, - state, - token: activity.pushToken.toLowerCase(), - bindingKey: device.relayBindingKey as string, - statement: activity.activityStatement as Record, - signature: activity.activitySignature, - }, - expiresAt: new Date((nowS + PUSH_LIFETIME_S) * 1000), - }, - }); + const item = relayUpdateItem(device, activity, state, now); + if (item) updates.push({ rowId: activity.id, state, item }); } return { updates, ending }; } diff --git a/src/lib/push-relay/medication-pushes.ts b/src/lib/push-relay/medication-pushes.ts index 16351bb21d..671026bf82 100644 --- a/src/lib/push-relay/medication-pushes.ts +++ b/src/lib/push-relay/medication-pushes.ts @@ -335,6 +335,12 @@ export interface RelayActivityRow { * End these Activities of one relay-bound device over the relay. Returns the * ids of the Activity rows that are spent: the relay accepted the end, or * reported the Activity gone. + * + * Every kind of Activity may be ended, the app-started ones included + * (`relayEventAllowed` in `live-activity.ts`): an end item carries no + * `event` and no `state`, and the relay writes its fixed end state + * (`countdownTarget: 0`, status taken, dismissed at once), which both + * attributes types read without a time. */ export async function endActivitiesOverRelay( device: RoutableDevice & { relayBindingKey: string | null }, From 5f63631deb9cb1ceb72d354a6a7b414e3a9a57e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 13:57:46 +0100 Subject: [PATCH 07/14] fix(push-relay): keep one Live Activity per dose A relay start skips a dose the device already shows in an Activity of its own, matched by the slot rule the end path uses (same medication, slot within 60 s). When the app's own Activity follows a relay start for the same dose, the relay-started one ends: on the device registration that reports both, and on the next pass if that end did not go out. --- CHANGELOG.md | 1 + src/app/api/devices/route.ts | 18 +- .../__tests__/live-activity-one-owner.test.ts | 79 +++++++++ src/lib/push-relay/activity-slot.ts | 19 ++ src/lib/push-relay/live-activity-started.ts | 4 +- src/lib/push-relay/live-activity.ts | 98 ++++++++++- .../push-live-activity-consent.test.ts | 164 +++++++++++++++++- 7 files changed, 363 insertions(+), 20 deletions(-) create mode 100644 src/lib/push-relay/__tests__/live-activity-one-owner.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 55ac795c6e..b37b049c6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -174,6 +174,7 @@ - A dose change on another device always reaches a phone whose silent-push budget at the relay is spent: the relay's refusal is no longer counted as delivered, the sync is owed and goes out the first minute the relay takes one again. - A Live Activity started from the server through the push relay appears only for a medication with Live Activity turned on and only for a dose coming up or currently due, never for one that is long overdue or already answered; the earliest such dose gets it. +- A dose no longer shows two Live Activities when the iOS app already shows its own for it; one the server started through the push relay ends, and the app's, with its Take button, stays. - A dose the iOS app names by its slot binds to that slot on the bulk route exactly as on the single route, also when it is taken early and the windows of two doses overlap. - Posting a single entry again that was deleted in HealthLog (mood, measurement, cycle day, AUDIT-C) answers `410` with the reason `deleted_in_healthlog` instead of bringing it back; a mood entry deleted in Apple Health comes back when Apple Health sends it again. diff --git a/src/app/api/devices/route.ts b/src/app/api/devices/route.ts index 69f54bf804..3981dc86f2 100644 --- a/src/app/api/devices/route.ts +++ b/src/app/api/devices/route.ts @@ -59,6 +59,7 @@ import { import { drainQueuedUnbinds } from "@/lib/devices/signed-out-push"; import { sendSecurityAlert } from "@/lib/auth/security-alert"; import { endDeviceLiveActivities } from "@/lib/notifications/live-activity-end"; +import { endSupersededRelayActivities } from "@/lib/push-relay/live-activity"; import { activityStatementSchema, applyPushFields, @@ -623,5 +624,20 @@ export const POST = apiHandler(async (request: NextRequest) => { action: { name: "devices.register", entity_type: "device", entity_id: id }, }); - return apiSuccess({ id, push: await applyPushFields(id, parsed.data) }, 201); + const pushBlock = await applyPushFields(id, parsed.data); + if (parsed.data.liveActivityTokens !== undefined) { + // One owner per dose: a relay-started Activity the app's own one of the + // same dose now stands beside ends at once; the Live Activity pass + // retries an end the relay did not take. + try { + const ended = await endSupersededRelayActivities(id); + if (ended > 0) annotate({ meta: { live_activity_superseded: ended } }); + } catch (err) { + getEvent()?.addWarning( + `live_activity_superseded_end_failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + } + + return apiSuccess({ id, push: pushBlock }, 201); }); diff --git a/src/lib/push-relay/__tests__/live-activity-one-owner.test.ts b/src/lib/push-relay/__tests__/live-activity-one-owner.test.ts new file mode 100644 index 0000000000..102736c3b2 --- /dev/null +++ b/src/lib/push-relay/__tests__/live-activity-one-owner.test.ts @@ -0,0 +1,79 @@ +/** + * One owner per dose: a relay start never joins an Activity the app already + * shows for the dose, and a relay-started Activity the app's own one of the + * same dose follows is the one that goes. Both use the slot match the end + * path makes (`activityShowsDose`, within the tolerance of + * `activitySlotWindow`). + */ +import { describe, expect, it } from "vitest"; + +import { + activityShowsDose, + activitySlotWindow, +} from "@/lib/push-relay/activity-slot"; +import { supersededRelayActivities } from "@/lib/push-relay/live-activity"; + +const SLOT = new Date("2026-11-23T08:00:00Z"); +const off = (s: number) => new Date(SLOT.getTime() + s * 1000); + +function row( + id: string, + relayStarted: boolean, + slotInstant: Date | null, + medicationId = "med-a", +) { + return { id, medicationId, slotInstant, relayStarted }; +} + +describe("activityShowsDose", () => { + it("matches the same medication within the end path's window", () => { + for (const s of [0, 59, -59]) { + expect(activityShowsDose(row("a", false, off(s)), "med-a", SLOT)).toBe( + true, + ); + } + for (const s of [61, -61]) { + expect(activityShowsDose(row("a", false, off(s)), "med-a", SLOT)).toBe( + false, + ); + } + expect( + activityShowsDose(row("a", false, SLOT, "med-b"), "med-a", SLOT), + ).toBe(false); + expect(activityShowsDose(row("a", false, null), "med-a", SLOT)).toBe(true); + }); + + it("agrees with the window the end path queries", () => { + for (const s of [-61, -60, -59.999, 0, 59.999, 60, 61]) { + const window = activitySlotWindow(off(s)); + const inWindow = window.gte <= SLOT && SLOT <= window.lte; + expect(activityShowsDose(row("a", false, off(s)), "med-a", SLOT)).toBe( + inWindow, + ); + } + }); +}); + +describe("supersededRelayActivities", () => { + it("names the relay one the app's own Activity of the dose stands beside", () => { + const relay = row("relay", true, SLOT); + expect( + supersededRelayActivities([relay, row("app", false, off(59))]), + ).toEqual([relay]); + }); + + it("leaves it alone for another slot or medication, or with no app one", () => { + const relay = row("relay", true, SLOT); + expect( + supersededRelayActivities([relay, row("app", false, off(61))]), + ).toEqual([]); + expect( + supersededRelayActivities([relay, row("app", false, SLOT, "med-b")]), + ).toEqual([]); + expect(supersededRelayActivities([relay])).toEqual([]); + // Two relay-started rows never supersede each other, nor an app one. + expect( + supersededRelayActivities([relay, row("relay-2", true, off(30))]), + ).toEqual([]); + }); +}); diff --git a/src/lib/push-relay/activity-slot.ts b/src/lib/push-relay/activity-slot.ts index f3b91a5433..6782cc63be 100644 --- a/src/lib/push-relay/activity-slot.ts +++ b/src/lib/push-relay/activity-slot.ts @@ -27,6 +27,25 @@ export function sameActivitySlot(named: Date, stored: Date): boolean { ); } +/** + * Whether a registered Activity shows the dose of `medicationId` stored at + * `slot`: the same medication, and its named slot within the tolerance + * ({@link sameActivitySlot}, the match the end path makes in the database + * through {@link activitySlotWindow}). An Activity registered without a slot + * shows every dose of its medication. + */ +export function activityShowsDose( + activity: { medicationId: string; slotInstant: Date | null }, + medicationId: string, + slot: Date, +): boolean { + return ( + activity.medicationId === medicationId && + (activity.slotInstant === null || + sameActivitySlot(activity.slotInstant, slot)) + ); +} + /** * The medications the server may start a Live Activity for, and keep one it * started running: tracked, active, neither paused nor ended, and with the diff --git a/src/lib/push-relay/live-activity-started.ts b/src/lib/push-relay/live-activity-started.ts index f61cf5028a..07ddb21e2b 100644 --- a/src/lib/push-relay/live-activity-started.ts +++ b/src/lib/push-relay/live-activity-started.ts @@ -17,7 +17,9 @@ * off. The server ends an Activity only in those cases * (`liveActivityEndState`, and the relay pass for a server-started Activity * whose medication may no longer have one), so an ended Activity reads null - * too. An Activity + * too. A server-started Activity ended because the app's own Activity shows + * the same dose (`supersededRelayActivities`) keeps the value: the dose + * stays held, so no second start follows. An Activity * the person dismissed on the device keeps the value until the slot is * answered; the app knows it dismissed it, and the stored dose also keeps * the next pass from starting the same dose again. diff --git a/src/lib/push-relay/live-activity.ts b/src/lib/push-relay/live-activity.ts index c5f354be8d..107de0daff 100644 --- a/src/lib/push-relay/live-activity.ts +++ b/src/lib/push-relay/live-activity.ts @@ -57,8 +57,8 @@ import type { ResolvedDose } from "@/lib/medications/dose-state/resolve"; import { slotsHeldBySnooze } from "@/lib/medications/snooze-scope"; import { resolveUserTimezone } from "@/lib/tz/resolver"; import { + activityShowsDose, activitySlotWindow, - sameActivitySlot, STARTABLE_MEDICATION_WHERE, } from "@/lib/push-relay/activity-slot"; import { liveActivityRelayEnabled } from "@/lib/push-relay/config"; @@ -544,13 +544,18 @@ async function startItem( return null; } if (await refusedRecently(device.id, LA_START_EVENT, now)) return null; - const running = device.liveActivities.some( - (a) => - a.medicationId === dose.medicationId && - (a.slotInstant === null || - sameActivitySlot(a.slotInstant, dose.scheduledFor)), - ); - if (running) return null; + // One owner per dose: an Activity the device already runs for it, the + // app's own (`MedicationActivityAttributes`, with its Take button) above + // all, keeps the relay from starting a second one beside it. The reverse + // order, a relay start the app's own Activity follows, ends the relay one + // ({@link supersededRelayActivities}). + if ( + device.liveActivities.some((a) => + activityShowsDose(a, dose.medicationId, dose.scheduledFor), + ) + ) { + return null; + } return { dose, item: { @@ -588,6 +593,75 @@ export function relayActivityKind(activity: { return activity.relayStarted ? "relay_started" : "app_started"; } +/** + * The relay-started Activities that show a dose an app-started Activity of + * the same device shows too, matched by {@link activityShowsDose}, the + * match the start and the end path make. + * + * One owner per dose. iOS builds up to 1.7 start their own Activity for a + * dose whatever the relay started, so a relay start that came first stands + * beside the app's own one, which alone has the Take button. The relay one + * ends and the app's stays. The dose stays held on the device + * (`laStartedMedicationId`, `laStartedSlot`), so no second relay start + * follows. From the next 1.7 build the app starts none of its own while a + * relay Activity runs for the dose, and the relay Activity gets a Take + * button of its own. + */ +export function supersededRelayActivities< + T extends { + medicationId: string; + slotInstant: Date | null; + relayStarted: boolean; + }, +>(activities: readonly T[]): T[] { + const appStarted = activities.filter( + (a) => relayActivityKind(a) === "app_started", + ); + return activities.filter((relay): relay is T & { slotInstant: Date } => { + const slot = relay.slotInstant; + return ( + relayActivityKind(relay) === "relay_started" && + slot !== null && + appStarted.some((app) => activityShowsDose(app, relay.medicationId, slot)) + ); + }); +} + +/** + * End the relay-started Activities of a device that an app-started one of the + * same dose made redundant ({@link supersededRelayActivities}), and forget + * their tokens once the relay took the end or reported the Activity gone. + * Run when the device registers its Activities, so the second one goes at + * once; the pass ends one whose end the relay did not take. Returns how many + * ended. Nothing is sent when none is redundant, so a repeat is a no-op. + */ +export async function endSupersededRelayActivities( + deviceId: string, +): Promise { + const device = await prisma.device.findUnique({ + where: { id: deviceId }, + select: { + ...ROUTABLE_DEVICE_SELECT, + relayBindingKey: true, + liveActivities: { select: DEVICE_SELECT.liveActivities.select }, + }, + }); + if (!device) return 0; + const superseded = supersededRelayActivities(device.liveActivities); + if (superseded.length === 0) return 0; + const spent = await endActivitiesOverRelay( + device, + superseded, + await loadPushContext(), + ); + if (spent.length > 0) { + await prisma.liveActivityToken.deleteMany({ + where: { id: { in: spent } }, + }); + } + return spent.length; +} + /** * Whether the relay may send `event` to a registered Activity of this kind. * Every relay update is built through {@link relayUpdateItem}, which asks @@ -698,6 +772,9 @@ async function updateItems( : new Set(); // An update is final only once accepted: one still in flight is not sent // twice, and after a refusal the device's updates wait out the cool-down. + const superseded = new Set( + supersededRelayActivities(device.liveActivities).map((a) => a.id), + ); const [inFlight, refused] = relayStarted ? await Promise.all([ updatesInFlight(device.id), @@ -714,7 +791,10 @@ async function updateItems( ) { continue; } - if (relayOwned(activity) && !startable.has(activity.medicationId)) { + if ( + superseded.has(activity.id) || + (relayOwned(activity) && !startable.has(activity.medicationId)) + ) { ending.push(activity); continue; } diff --git a/tests/integration/push-live-activity-consent.test.ts b/tests/integration/push-live-activity-consent.test.ts index e382143f42..35fff5cd71 100644 --- a/tests/integration/push-live-activity-consent.test.ts +++ b/tests/integration/push-live-activity-consent.test.ts @@ -845,15 +845,21 @@ describe("who started the Activity", () => { await t.reg({ liveActivityConsent: t.consent() }); // Past the daily band's on-time hour after the slot: overdue. const { medication, slot, at } = await dueDose(t.session.userId, -90); + const other = await dueDose(t.session.userId, -90); const dose = { medicationId: medication.id, slotInstant: slot.toISOString(), }; + // The app's own Activity of another dose, its own attributes type (one + // of the same dose would end the relay one: "one owner per dose"). + const appDose = { + medicationId: other.medication.id, + slotInstant: other.slot.toISOString(), + }; await t.reg({ liveActivityTokens: [ t.activityEntry({ ...dose, relayStart: true }), - // The app's own Activity of the same dose, its own attributes type. - t.activityEntry(dose, APP_LA_TOKEN), + t.activityEntry(appDose, APP_LA_TOKEN), ], }); const rows = await getPrismaClient().liveActivityToken.findMany({ @@ -875,7 +881,7 @@ describe("who started the Activity", () => { await t.reg({ liveActivityTokens: [ t.activityEntry(dose), - t.activityEntry(dose, APP_LA_TOKEN), + t.activityEntry(appDose, APP_LA_TOKEN), ], }); expect( @@ -914,6 +920,137 @@ describe("who started the Activity", () => { }); }); +describe("one owner per dose", () => { + const APP_LA_TOKEN = "7c".repeat(32); + const events = (from = 0) => + laPushes() + .slice(from) + .map((p) => [p.token, (p.payload.aps as { event: string }).event]); + + async function consented() { + const t = await setUp(); + await t.reg({ + liveActivityConsent: t.consent(), + liveActivityStart: t.startField(), + }); + return t; + } + + async function fresh() { + await truncateAllTables(getPrismaClient()); + fake = new FakeRelay(); + relay.current = fake; + } + + /** The app's own Activity of a dose, its slot `offsetS` from the stored one. */ + const appEntry = ( + t: Awaited>, + medicationId: string, + slot: Date, + offsetS = 0, + ) => + t.activityEntry( + { + medicationId, + slotInstant: new Date(slot.getTime() + offsetS * 1000).toISOString(), + }, + APP_LA_TOKEN, + ); + + it("starts nothing beside the app's own Activity of the dose", async () => { + for (const offsetS of [0, 59, -59]) { + await fresh(); + const t = await consented(); + const { medication, slot } = await dueDose(t.session.userId, 30); + await t.reg({ + liveActivityTokens: [appEntry(t, medication.id, slot, offsetS)], + }); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 0 }); + expect(laPushes()).toHaveLength(0); + } + }); + + it("starts when the app's Activity shows another slot or medication", async () => { + for (const variant of ["61s", "-61s", "other"] as const) { + await fresh(); + const t = await consented(); + const { medication, slot } = await dueDose(t.session.userId, 30); + const other = await dueDose(t.session.userId, 100, undefined, { + liveActivityEnabled: false, + }); + const entry = + variant === "other" + ? appEntry(t, other.medication.id, slot) + : appEntry(t, medication.id, slot, variant === "61s" ? 61 : -61); + await t.reg({ liveActivityTokens: [entry] }); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); + expect(events()).toEqual([[START_TOKEN, "start"]]); + } + }); + + it("ends the relay one once the app's own Activity of the dose follows", async () => { + const t = await consented(); + const { medication, slot } = await dueDose(t.session.userId, 30); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); + // The app registers the relay-started Activity, then starts its own. + await t.reg({ + liveActivityTokens: [t.activityEntry({ relayStart: true })], + }); + const before = laPushes().length; + await t.reg({ + liveActivityTokens: [ + t.activityEntry({ relayStart: true }), + appEntry(t, medication.id, slot, 30), + ], + }); + // Ended at once, on the registration: the relay one, never the app's. + expect(events(before)).toEqual([[LA_TOKEN, "end"]]); + expect( + await getPrismaClient().liveActivityToken.findMany({ + select: { pushToken: true, relayStarted: true }, + }), + ).toEqual([{ pushToken: APP_LA_TOKEN, relayStarted: false }]); + + // Idempotent: the next pass and the next post of the set send nothing, + // and no second start follows. + const after = laPushes().length; + expect(await runLiveActivityRelayPass()).toMatchObject({ + started: 0, + updated: 0, + }); + await t.reg({ liveActivityTokens: [appEntry(t, medication.id, slot, 30)] }); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 0 }); + expect(events(after)).toEqual([]); + }); + + it("the pass ends it when the registration's end did not go out", async () => { + const t = await consented(); + const { medication, slot } = await dueDose(t.session.userId, 30); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); + await t.reg({ + liveActivityTokens: [t.activityEntry({ relayStart: true })], + }); + // The app's row as a registration whose end never reached the relay + // would leave it beside the relay one. + const device = await getPrismaClient().device.findFirstOrThrow({}); + await getPrismaClient().liveActivityToken.create({ + data: { + deviceId: device.id, + pushToken: APP_LA_TOKEN, + medicationId: medication.id, + slotInstant: slot, + }, + }); + const before = laPushes().length; + await runLiveActivityRelayPass(); + expect(events(before)).toEqual([[LA_TOKEN, "end"]]); + const after = laPushes().length; + await runLiveActivityRelayPass(); + expect(events(after)).toEqual([]); + expect(await getPrismaClient().liveActivityToken.count()).toBe(1); + }); +}); + describe("a device leaving the account", () => { const APP_LA_TOKEN = "8d".repeat(32); const endedTokens = (from: number) => @@ -927,14 +1064,23 @@ describe("a device leaving the account", () => { const t = await setUp(); await t.reg({ liveActivityConsent: t.consent() }); const { medication, slot } = await dueDose(t.session.userId, 10); - const dose = { - medicationId: medication.id, - slotInstant: slot.toISOString(), - }; + const other = await dueDose(t.session.userId, 10); + // Two doses: one Activity of each kind on one dose would end the relay + // one at once ("one owner per dose"). await t.reg({ liveActivityTokens: [ - t.activityEntry({ ...dose, relayStart: true }), - t.activityEntry(dose, APP_LA_TOKEN), + t.activityEntry({ + medicationId: medication.id, + slotInstant: slot.toISOString(), + relayStart: true, + }), + t.activityEntry( + { + medicationId: other.medication.id, + slotInstant: other.slot.toISOString(), + }, + APP_LA_TOKEN, + ), ], }); return t; From 1d421371ed7827ce12398ef19a5adb9eef23bc21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 14:17:03 +0100 Subject: [PATCH 08/14] fix(push-relay): start a Live Activity once per dose from the start record Once per dose rested on the device row, which names only the last relay start. A start for another dose replaced that record, so when the newer dose turned overdue the earlier one was the earliest startable dose again and started a second time, before the app had reported the first Activity. Each start's outbox row now keeps the dose it was for (migration 0560, `push_relay_deliveries.medication_id` and `slot_instant`), and the pass asks those rows whether a start for the dose is in flight or accepted. The check holds before the device reports its token, across restarts and whatever the device row says about its last start. A start that failed for good holds nothing; a sign-out clears the record. --- CHANGELOG.md | 2 +- .../migration.sql | 28 ++++++ prisma/schema.prisma | 17 +++- src/__tests__/relay-consent-pin.test.ts | 7 ++ src/lib/devices/signed-out-push.ts | 5 ++ src/lib/push-relay/live-activity-settle.ts | 44 ++++++--- src/lib/push-relay/live-activity.ts | 33 +++---- src/lib/push-relay/relay-send.ts | 11 +++ .../push-live-activity-consent.test.ts | 89 +++++++++++++++++++ 9 files changed, 198 insertions(+), 38 deletions(-) create mode 100644 prisma/migrations/0560_live_activity_start_dose/migration.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index b37b049c6a..4e68de5005 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -174,7 +174,7 @@ - A dose change on another device always reaches a phone whose silent-push budget at the relay is spent: the relay's refusal is no longer counted as delivered, the sync is owed and goes out the first minute the relay takes one again. - A Live Activity started from the server through the push relay appears only for a medication with Live Activity turned on and only for a dose coming up or currently due, never for one that is long overdue or already answered; the earliest such dose gets it. -- A dose no longer shows two Live Activities when the iOS app already shows its own for it; one the server started through the push relay ends, and the app's, with its Take button, stays. +- A dose no longer shows two Live Activities when the iOS app already shows its own for it; one the server started through the push relay ends, and the app's, with its Take button, stays. The server also starts at most one for a dose through the relay, by its own record of what it started: a start for another dose in between, the dose turning due, or a restart no longer lead to a second one before the app has reported the first. - A dose the iOS app names by its slot binds to that slot on the bulk route exactly as on the single route, also when it is taken early and the windows of two doses overlap. - Posting a single entry again that was deleted in HealthLog (mood, measurement, cycle day, AUDIT-C) answers `410` with the reason `deleted_in_healthlog` instead of bringing it back; a mood entry deleted in Apple Health comes back when Apple Health sends it again. diff --git a/prisma/migrations/0560_live_activity_start_dose/migration.sql b/prisma/migrations/0560_live_activity_start_dose/migration.sql new file mode 100644 index 0000000000..3ed69d6fb9 --- /dev/null +++ b/prisma/migrations/0560_live_activity_start_dose/migration.sql @@ -0,0 +1,28 @@ +-- The dose a Live Activity start was for, on the start's own outbox row. +-- +-- Once per dose used to rest on the device row, which holds only the last +-- start: a second dose's start replaced the first one's record, and the +-- first dose could start again. The start row keeps its dose for as long as +-- the outbox keeps the row (30 days), so the check reads the server's own +-- record of every start, before the device reports the Activity and across +-- restarts. +-- +-- Two nullable columns: metadata-only, no rewrite. The index is small (only +-- start rows carry a value) and is built on a table the maintenance pass +-- prunes to 30 days. IF NOT EXISTS keeps a replay harmless. Reversibility: +-- drop the index and the columns. +-- +-- @retry-on-lock-timeout + +DO $migration$ +BEGIN + PERFORM set_config('lock_timeout', '5s', true); + + ALTER TABLE "push_relay_deliveries" + ADD COLUMN IF NOT EXISTS "medication_id" TEXT, + ADD COLUMN IF NOT EXISTS "slot_instant" TIMESTAMP(3); + + CREATE INDEX IF NOT EXISTS "push_relay_deliveries_device_id_medication_id_slot_instant_idx" + ON "push_relay_deliveries" ("device_id", "medication_id", "slot_instant"); +END +$migration$; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index eff88bcaee..cca6fca4b7 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -6669,9 +6669,11 @@ model Device { laStartToken String? @map("la_start_token") laStartStatement Json? @map("la_start_statement") laStartSignature String? @map("la_start_signature") - /// The dose the last relay start was for, so a dose starts once and the - /// app's registration of the started Activity (`relayStart: true`) finds - /// its dose. Reader and writer: `push-relay/live-activity.ts`. + /// The dose the last relay start was for, so the app's registration of + /// the started Activity (`relayStart: true`) finds its dose. Only the + /// last: once per dose is kept by the start's outbox row + /// (`PushRelayDelivery.medicationId`, `slotInstant`). Reader and writer: + /// `push-relay/live-activity.ts`. laStartedMedicationId String? @map("la_started_medication_id") laStartedSlot DateTime? @map("la_started_slot") /// When the relay accepted the last start; null while it is in flight. @@ -11731,6 +11733,14 @@ model PushRelayDelivery { acceptedAt DateTime? @map("accepted_at") confirmedAt DateTime? @map("confirmed_at") receiptReportedAt DateTime? @map("receipt_reported_at") + /// A Live Activity start only: the dose it was for. The record that keeps + /// a dose to one start per device, whatever the device row holds and + /// whether the device has reported the Activity yet. A sign-out clears + /// it, so a dose may start again on the next sign-in. Writer: + /// `push-relay/relay-send.ts`; reader: `push-relay/live-activity-settle.ts` + /// (`doseStartHeld`). + medicationId String? @map("medication_id") + slotInstant DateTime? @map("slot_instant") createdAt DateTime @default(now()) @map("created_at") device Device @relation(fields: [deviceId], references: [id], onDelete: Cascade) @@ -11738,6 +11748,7 @@ model PushRelayDelivery { @@unique([deviceId, ref]) @@index([status, nextAttemptAt]) @@index([deviceId, pushClass, createdAt]) + @@index([deviceId, medicationId, slotInstant]) @@map("push_relay_deliveries") } diff --git a/src/__tests__/relay-consent-pin.test.ts b/src/__tests__/relay-consent-pin.test.ts index 61c9657861..5ffa526f50 100644 --- a/src/__tests__/relay-consent-pin.test.ts +++ b/src/__tests__/relay-consent-pin.test.ts @@ -99,6 +99,13 @@ const PINS: ReadonlyArray<{ covered: "The owed intake sync reads which devices a send spent budget on and which the relay refused (`budgetSpentBy`, `owedBy` from `wakes.ts`). No new kind and no new occasion: a silent push the relay refuses for its budget is no longer retried with the same envelope but owed, and the minute pass sends one fresh sync (or puts a wake's domains back) once the relay's window frees. That is the owed sync the texts already cover: a silent sync to the person's own device after a dose changed (`seesWhen`, `seesTiming`), now never more of them than before and never before the relay said it takes one.", }, + { + version: "2026-11-22", + fingerprint: + "9f9fe47a4ef87b86fe16ca06f6360b4e52d41baae0a8cc666c6fcf2749765792", + covered: + "A Live Activity start's outbox row keeps the dose it was for (`dose` on the item in `relay-send.ts`), stored on this server and never sent. No new kind, no new occasion, nothing more on the wire: the start the texts already name (`seesWhen`, a Live Activity start or update) now goes at most once per dose, where a start for another dose could make an earlier dose start twice.", + }, ]; /** diff --git a/src/lib/devices/signed-out-push.ts b/src/lib/devices/signed-out-push.ts index 502a788067..4f5a0f4b06 100644 --- a/src/lib/devices/signed-out-push.ts +++ b/src/lib/devices/signed-out-push.ts @@ -91,6 +91,11 @@ export async function stripDevicePush( await db.pushRelayDelivery.deleteMany({ where: { deviceId: { in: ids }, status: "pending" }, }); + // The Activities end with the sign-out: no start holds its dose any more. + await db.pushRelayDelivery.updateMany({ + where: { deviceId: { in: ids }, medicationId: { not: null } }, + data: { medicationId: null, slotInstant: null }, + }); await db.device.updateMany({ where: { id: { in: ids } }, data: clearedPushCredentials(), diff --git a/src/lib/push-relay/live-activity-settle.ts b/src/lib/push-relay/live-activity-settle.ts index 28da5e77ed..da2d8a9403 100644 --- a/src/lib/push-relay/live-activity-settle.ts +++ b/src/lib/push-relay/live-activity-settle.ts @@ -6,12 +6,14 @@ * A start or update counts as done only once the relay answered `accepted`, * which it does once Apple took the push: * - * - a start: the dose it was for is held on the device while it is in flight - * (`laStartedMedicationId`, `laStartedSlot`, `laStartRef`), so the next - * pass does not start it twice. `accepted` sets `laStartedAt`, and only - * then does `push.device.liveActivityStarted` name the dose. A start that - * failed for good (refused, or dropped at its deadline) clears the dose - * again, so a later pass starts it anew. + * - a start: its outbox row keeps the dose it was for (`medicationId`, + * `slotInstant`), so no later pass starts that dose twice + * ({@link doseStartHeld}). The device row names the last start + * (`laStartedMedicationId`, `laStartedSlot`, `laStartRef`); `accepted` + * sets `laStartedAt`, and only then does `push.device.liveActivityStarted` + * name the dose. A start that failed for good (refused, or dropped at its + * deadline) clears the device's dose again, and its row no longer holds + * it, so a later pass starts it anew. * - an update: `accepted` stores its content state as the Activity's * `lastRelayState`; a failed one leaves the state that is really showing, * so the next pass sends the change again. @@ -23,6 +25,7 @@ import { Prisma } from "@/generated/prisma/client"; import { prisma } from "@/lib/db"; import { textEquals } from "@/lib/db-like"; +import { activitySlotWindow } from "@/lib/push-relay/activity-slot"; export const LA_START_EVENT = "LIVE_ACTIVITY_START"; export const LA_UPDATE_EVENT = "LIVE_ACTIVITY_UPDATE"; @@ -112,17 +115,30 @@ export async function refusedRecently( return last?.status === "failed" || last?.status === "dropped"; } -/** Whether the start under `ref` is still in flight or already accepted. */ -export async function startHeld( +/** + * Whether the device has a start for this dose in flight or accepted: the + * server's own record of what it started, on each start's outbox row + * (`medicationId`, `slotInstant`). It holds the dose before the device + * reports the Activity, and whatever the device row says about its last + * start, which a start for another dose replaces. A start that failed for + * good holds nothing; the cool-down decides when it is tried again. + */ +export async function doseStartHeld( deviceId: string, - ref: string | null, + medicationId: string, + slot: Date, ): Promise { - if (!ref) return false; - const row = await prisma.pushRelayDelivery.findUnique({ - where: { deviceId_ref: { deviceId, ref } }, - select: { status: true }, + const row = await prisma.pushRelayDelivery.findFirst({ + where: { + deviceId, + eventType: LA_START_EVENT, + medicationId, + slotInstant: activitySlotWindow(slot), + status: { in: ["pending", "accepted"] }, + }, + select: { id: true }, }); - return row?.status === "pending" || row?.status === "accepted"; + return row !== null; } /** The Activity tokens an update is still in flight for, lower case. */ diff --git a/src/lib/push-relay/live-activity.ts b/src/lib/push-relay/live-activity.ts index 107de0daff..45d3351765 100644 --- a/src/lib/push-relay/live-activity.ts +++ b/src/lib/push-relay/live-activity.ts @@ -21,7 +21,9 @@ * * The pass (`push-live-activity`, every five minutes) starts an Activity for * one dose of each eligible device, once per dose, unless the device already - * runs one for it. The dose is the earliest of those entering their window + * runs one for it. Once per dose is the server's own record: each start's + * outbox row keeps its dose (`doseStartHeld`), before the device reports the + * Activity and across restarts. The dose is the earliest of those entering their window * ({@link pickStartDose}): its medication has the person's Live Activity * opt-in (`liveActivityEnabled`), it lies no more than the lead ahead, and * the resolver calls it pending or due. A dose already overdue, missed, @@ -80,7 +82,7 @@ import { LA_START_EVENT, LA_UPDATE_EVENT, refusedRecently, - startHeld, + doseStartHeld, updatesInFlight, } from "@/lib/push-relay/live-activity-settle"; @@ -275,10 +277,6 @@ const DEVICE_SELECT = { laStartToken: true, laStartStatement: true, laStartSignature: true, - laStartedMedicationId: true, - laStartedSlot: true, - laStartedAt: true, - laStartRef: true, liveActivities: { select: { id: true, @@ -530,17 +528,12 @@ async function startItem( if (!dose) return null; const state = doseContentState(dose, timeFormat, now); if (!state) return null; - const slot = dose.scheduledFor.getTime(); - // Once per dose: a start the relay accepted, or one still in flight. A - // start that failed for good no longer holds the dose - // (`live-activity-settle.ts`), and one whose outbox row is gone is no - // start at all. - if ( - device.laStartedMedicationId === dose.medicationId && - device.laStartedSlot?.getTime() === slot && - (device.laStartedAt !== null || - (await startHeld(device.id, device.laStartRef))) - ) { + // Once per dose: a start the relay accepted, or one still in flight, read + // from the start rows themselves. The device row names only the last + // start, which a start for another dose replaces, and the device reports + // the Activity only once the app runs again. A start that failed for good + // no longer holds the dose (`live-activity-settle.ts`). + if (await doseStartHeld(device.id, dose.medicationId, dose.scheduledFor)) { return null; } if (await refusedRecently(device.id, LA_START_EVENT, now)) return null; @@ -572,6 +565,7 @@ async function startItem( signature: device.laStartSignature, }, expiresAt: new Date((nowS + PUSH_LIFETIME_S) * 1000), + dose: { medicationId: dose.medicationId, slotInstant: dose.scheduledFor }, }, }; } @@ -601,9 +595,8 @@ export function relayActivityKind(activity: { * One owner per dose. iOS builds up to 1.7 start their own Activity for a * dose whatever the relay started, so a relay start that came first stands * beside the app's own one, which alone has the Take button. The relay one - * ends and the app's stays. The dose stays held on the device - * (`laStartedMedicationId`, `laStartedSlot`), so no second relay start - * follows. From the next 1.7 build the app starts none of its own while a + * ends and the app's stays. The dose stays held by its start row + * (`doseStartHeld`), so no second relay start follows. From the next 1.7 build the app starts none of its own while a * relay Activity runs for the dose, and the relay Activity gets a Take * button of its own. */ diff --git a/src/lib/push-relay/relay-send.ts b/src/lib/push-relay/relay-send.ts index 1a298d5383..d2e92e99b7 100644 --- a/src/lib/push-relay/relay-send.ts +++ b/src/lib/push-relay/relay-send.ts @@ -90,6 +90,11 @@ export interface RelayItemInput { * them back for the next one. */ domains?: readonly string[]; + /** + * A Live Activity start only: the dose it is for, kept on its outbox row + * so the dose starts once (`doseStartHeld`, `live-activity-settle.ts`). + */ + dose?: { medicationId: string; slotInstant: Date }; } /** @@ -243,6 +248,12 @@ export async function sendRelayItems( }, expiresAt: item.expiresAt, nextAttemptAt: now, + ...(item.dose + ? { + medicationId: item.dose.medicationId, + slotInstant: item.dose.slotInstant, + } + : {}), })), skipDuplicates: true, }); diff --git a/tests/integration/push-live-activity-consent.test.ts b/tests/integration/push-live-activity-consent.test.ts index 35fff5cd71..da61135ef2 100644 --- a/tests/integration/push-live-activity-consent.test.ts +++ b/tests/integration/push-live-activity-consent.test.ts @@ -1121,3 +1121,92 @@ describe("a device leaving the account", () => { expect(await getPrismaClient().liveActivityToken.count()).toBe(0); }); }); + +describe("once per dose, from the server's own start record", () => { + const startsOnWire = () => + laPushes().filter( + (p) => (p.payload.aps as { event?: string }).event === "start", + ); + + async function consented() { + const t = await setUp(); + await t.reg({ + liveActivityConsent: t.consent(), + liveActivityStart: t.startField(), + }); + return t; + } + + it("starts a dose at its lead time and never again before the device reports it", async () => { + const t = await consented(); + const dose = await dueDose(t.session.userId, 100); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); + // Pending turns due at the slot, then five and twenty minutes on: the + // device has reported no Activity token, and nothing starts twice. + for (const minutes of [0, 5, 20]) { + expect(await runLiveActivityRelayPass(dose.at(minutes))).toMatchObject({ + started: 0, + }); + } + expect(startsOnWire()).toHaveLength(1); + }); + + it("keeps a dose started once when a start for another dose replaced the device's record", async () => { + const t = await consented(); + // The first dose starts at its lead time. + const first = await dueDose(t.session.userId, 30, { start: -30, end: 90 }); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); + // A dose with an earlier slot shows up due (its row written late): it + // is the earliest now, and its start becomes the device's last one. + const earlier = await dueDose(t.session.userId, -20); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); + expect( + await getPrismaClient().device.findFirstOrThrow({ + where: { apnsToken: TOKEN }, + }), + ).toMatchObject({ laStartedMedicationId: earlier.medication.id }); + // Once that one is overdue, the first is the earliest startable again. + // It already runs: no second start, at the turn or later. + for (const minutes of [61, 66, 81]) { + expect(await runLiveActivityRelayPass(earlier.at(minutes))).toMatchObject( + { started: 0 }, + ); + } + expect(startsOnWire()).toHaveLength(2); + expect(first.slot.getTime()).toBeGreaterThan(earlier.slot.getTime()); + }); + + it("holds the dose across a restart, and starts a different dose", async () => { + const t = await consented(); + const dose = await dueDose(t.session.userId, 20); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); + + // A fresh process: no module state survives, only the database. + vi.resetModules(); + const fresh = await import("@/lib/push-relay/live-activity"); + expect(await fresh.runLiveActivityRelayPass(dose.at(0))).toMatchObject({ + started: 0, + }); + expect(startsOnWire()).toHaveLength(1); + + // The dose is answered; the next one is a different dose and starts. + await getPrismaClient().medicationIntakeEvent.updateMany({ + where: { medicationId: dose.medication.id }, + data: { takenAt: new Date() }, + }); + const next = await dueDose(t.session.userId, 40); + expect(await fresh.runLiveActivityRelayPass()).toMatchObject({ + started: 1, + }); + expect( + await getPrismaClient().pushRelayDelivery.findMany({ + where: { eventType: "LIVE_ACTIVITY_START" }, + select: { medicationId: true }, + orderBy: { createdAt: "asc" }, + }), + ).toEqual([ + { medicationId: dose.medication.id }, + { medicationId: next.medication.id }, + ]); + }); +}); From 0a2305176fa8e80ad81f296f94b30d51f4b51474 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 14:48:10 +0100 Subject: [PATCH 09/14] fix(push-relay): run at most one relay-started Live Activity per device App builds that register a relay-started Activity without its dose leave the server to name it, and the device route named the device's latest start. With two relay-started Activities running, both tokens got the newer dose: the lock screen labelled both with it, taking that dose ended both, and the earlier one stayed after its own dose was taken. The pass now runs at most one relay-started Activity per device. A start for a new dose first ends the relay-started Activities still running and goes out only once the relay took every one of those ends, in the same pass; otherwise it waits. A start whose Activity the app has not registered yet cannot be ended, so a new one waits until it is registered or its dose is over. The device route names a dose for a token without one only when the post carries exactly one such token and the server's records show exactly one relay start running. Otherwise the token is kept without a dose (migration 0561 drops NOT NULL on `live_activity_tokens.medication_id`) and the pass ends it. Tokens that carry their dose are unchanged. Both rules are to be lifted once the app echoes a per-start id. --- CHANGELOG.md | 4 +- docs/ops/deploy.md | 11 +- .../migration.sql | 23 ++ prisma/schema.prisma | 7 +- src/app/api/devices/route.ts | 108 ++++++--- src/lib/push-relay/activity-slot.ts | 2 +- src/lib/push-relay/live-activity.ts | 106 +++++++-- .../push-live-activity-consent.test.ts | 207 +++++++++++++++++- 8 files changed, 413 insertions(+), 55 deletions(-) create mode 100644 prisma/migrations/0561_live_activity_token_unattributed/migration.sql diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e68de5005..169d852ce1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -174,7 +174,7 @@ - A dose change on another device always reaches a phone whose silent-push budget at the relay is spent: the relay's refusal is no longer counted as delivered, the sync is owed and goes out the first minute the relay takes one again. - A Live Activity started from the server through the push relay appears only for a medication with Live Activity turned on and only for a dose coming up or currently due, never for one that is long overdue or already answered; the earliest such dose gets it. -- A dose no longer shows two Live Activities when the iOS app already shows its own for it; one the server started through the push relay ends, and the app's, with its Take button, stays. The server also starts at most one for a dose through the relay, by its own record of what it started: a start for another dose in between, the dose turning due, or a restart no longer lead to a second one before the app has reported the first. +- A dose no longer shows two Live Activities when the iOS app already shows its own for it; one the server started through the push relay ends, and the app's, with its Take button, stays. The server also starts at most one for a dose through the relay, by its own record of what it started: a start for another dose in between, the dose turning due, or a restart no longer lead to a second one before the app has reported the first. It also runs at most one such Activity per phone: before it starts one for the next dose it ends the one still running, so the lock screen no longer labels two Activities with the newer dose, and taking the earlier dose no longer ends the newer one's Activity. - A dose the iOS app names by its slot binds to that slot on the bulk route exactly as on the single route, also when it is taken early and the windows of two doses overlap. - Posting a single entry again that was deleted in HealthLog (mood, measurement, cycle day, AUDIT-C) answers `410` with the reason `deleted_in_healthlog` instead of bringing it back; a mood entry deleted in Apple Health comes back when Apple Health sends it again. @@ -203,7 +203,7 @@ ### Updating - Take a backup first. With the `backups` volume the container writes a pre-migration dump before it migrates; without it, run `pg_dump` yourself. `docs/ops/deploy.md`, "v1.49.0 notes", has the operator detail. -- Thirty-seven migrations, 0514 to 0559 (0516, 0523, 0527, 0528, 0541, 0548, 0550, 0552 and 0555 do not exist); the boot log says `37 database migrations pending`. Seven touch existing data: +- Thirty-nine migrations, 0514 to 0561 (0516, 0523, 0527, 0528, 0541, 0548, 0550, 0552 and 0555 do not exist); the boot log says `39 database migrations pending`. Seven touch existing data: - 0515 merges dose rows recorded twice for one slot (take, then skip, then the oldest pending row; the rest soft-deleted), refunds the stock of a merged take, clears the auto-miss mark on taken or skipped doses, and rewrites legacy single-time schedules into dose windows. - 0517 makes e-mail and username unique regardless of case. On a clash it stops, changes nothing, and the container does not start: list the accounts with the query in `docs/ops/deploy.md` ("Accounts that differ only in case"), ideally before the update, rename one of each pair, run `prisma migrate resolve --rolled-back 0517_case_insensitive_identity_and_retention_indexes` as shown there, and start again. It also drops six duplicate indexes, builds four retention indexes (bounded to five minutes) and checks the shape of text day keys, `NOT VALID` with a warning where old rows do not fit. - 0529 lowers APNs tokens; where two devices held one token in different case, the most recently seen keeps it and the other registers again on its next launch. diff --git a/docs/ops/deploy.md b/docs/ops/deploy.md index 4ed9555c0e..a6e4041ee1 100644 --- a/docs/ops/deploy.md +++ b/docs/ops/deploy.md @@ -214,9 +214,9 @@ always did, and finds nothing in the queue schema it did not create. ### v1.49.0 notes The sequence above covers this release, with one possible stop (`0517`, see -below). It brings thirty-seven migrations, `0514` to `0559` (`0516`, `0523`, +below). It brings thirty-nine migrations, `0514` to `0561` (`0516`, `0523`, `0527`, `0528`, `0541`, `0548`, `0550`, `0552` and `0555` do not exist), so -the boot log says `37 database migrations pending`. Copy the pre-migration +the boot log says `39 database migrations pending`. Copy the pre-migration dump of step 0 off the host before you start: it is the way back. Seven migrations touch data you already have: @@ -339,7 +339,8 @@ quantities (`0514`, `0519`), nullable columns or columns with a default in `0544`, `live_activity_tokens.relay_started BOOLEAN NOT NULL DEFAULT false` in `0545`, `measurements.stats_computed_at` in `0547`, `users.medicine_registry` and `medications.leaflet_url` in `0549`, `users.show_nav_counts BOOLEAN NOT -NULL DEFAULT true` in `0559`), and new tables (`0522`, `0524`, +NULL DEFAULT true` in `0559`, `push_relay_deliveries.medication_id` and +`slot_instant` with their index in `0560`), and new tables (`0522`, `0524`, `0531`, `0532`, `0534`, `0535`, and `ai_job_failures` in `0553`, which holds why background AI work last stopped for a record: closed reason codes only, cleared by the next success, cascading with the account). @@ -353,7 +354,9 @@ the update gets a single 409 on its next save, reads again, and saves. `0545` is metadata-only: existing Live Activity rows read `false`, and relay updates go only to an Activity the server started over the relay. `0538` only drops an index on `live_activity_tokens` that another index already -covers. `0518` builds an index on `measurements` `CONCURRENTLY` at boot. +covers. `0561` only drops `NOT NULL` from +`live_activity_tokens.medication_id`, a catalog change on a table new in this +release. `0518` builds an index on `measurements` `CONCURRENTLY` at boot. Writes carry on, but on a very large table the build can take a while; the app's healthcheck allows ten minutes for the start. If it is interrupted, see "A concurrent index build that failed" above. diff --git a/prisma/migrations/0561_live_activity_token_unattributed/migration.sql b/prisma/migrations/0561_live_activity_token_unattributed/migration.sql new file mode 100644 index 0000000000..2cf50d71c2 --- /dev/null +++ b/prisma/migrations/0561_live_activity_token_unattributed/migration.sql @@ -0,0 +1,23 @@ +-- A Live Activity token the server cannot attribute to a dose. +-- +-- iOS builds that register a relay-started Activity without its dose leave +-- the server to name the dose, and it named the device's latest start: with +-- two relay-started Activities running, both were labelled with the newer +-- dose. The server now runs at most one relay-started Activity per device and +-- attributes such a token only when its records show exactly one running; +-- otherwise it keeps the token without a dose, and the relay pass ends it. +-- +-- Drops NOT NULL on one column of a table this release creates (0515): a +-- catalog change, no rewrite, harmless on replay. Reversibility: delete the +-- rows whose `medication_id` is null and set the column NOT NULL again. +-- +-- @retry-on-lock-timeout + +DO $migration$ +BEGIN + PERFORM set_config('lock_timeout', '5s', true); + + ALTER TABLE "live_activity_tokens" + ALTER COLUMN "medication_id" DROP NOT NULL; +END +$migration$; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index cca6fca4b7..95a417f4b0 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -6556,7 +6556,12 @@ model LiveActivityToken { id String @id @default(cuid()) deviceId String @map("device_id") pushToken String @map("push_token") - medicationId String @map("medication_id") + /// The dose's medication; null for a relay-started Activity the app + /// registered without its dose while the server's records did not show + /// exactly one running relay start to attribute it to (migration 0561). + /// The relay pass ends such an Activity. Writer: `POST /api/devices`; + /// reader: `push-relay/live-activity.ts`. + medicationId String? @map("medication_id") /// The slot the Activity counts down to; null for a medication-level one. slotInstant DateTime? @map("slot_instant") /// The device's `hl-activity-v1` statement for this Activity diff --git a/src/app/api/devices/route.ts b/src/app/api/devices/route.ts index 3981dc86f2..21f2688df2 100644 --- a/src/app/api/devices/route.ts +++ b/src/app/api/devices/route.ts @@ -60,6 +60,7 @@ import { drainQueuedUnbinds } from "@/lib/devices/signed-out-push"; import { sendSecurityAlert } from "@/lib/auth/security-alert"; import { endDeviceLiveActivities } from "@/lib/notifications/live-activity-end"; import { endSupersededRelayActivities } from "@/lib/push-relay/live-activity"; +import { sameActivitySlot } from "@/lib/push-relay/activity-slot"; import { activityStatementSchema, applyPushFields, @@ -216,37 +217,39 @@ async function replaceLiveActivityTokens( // A token the app once registered as relay-started stays so when a later // post of the set omits `relayStart`: the mark is the Activity's // attributes type, which never changes. + const storedRelay = await tx.liveActivityToken.findMany({ + where: { deviceId, relayStarted: true }, + select: { pushToken: true, medicationId: true, slotInstant: true }, + }); const relayStarted = new Set( - ( - await tx.liveActivityToken.findMany({ - where: { deviceId, relayStarted: true }, - select: { pushToken: true }, - }) - ).map((row) => row.pushToken.toLowerCase()), + storedRelay.map((row) => row.pushToken.toLowerCase()), ); await tx.liveActivityToken.deleteMany({ where: { deviceId } }); if (sent.liveActivityTokens.length === 0) return; - // The dose a relay start was for, for an Activity that knows none. - const started = sent.liveActivityTokens.some((a) => !a.medicationId) - ? await tx.device.findUnique({ - where: { id: deviceId }, - select: { laStartedMedicationId: true, laStartedSlot: true }, - }) - : null; - const rows = sent.liveActivityTokens.flatMap((a) => { - const medicationId = a.medicationId ?? started?.laStartedMedicationId; - if (!medicationId) return []; - return [ - { - ...a, - medicationId, - slotInstant: a.medicationId - ? a.slotInstant - : (started?.laStartedSlot ?? undefined), - }, - ]; - }); - if (rows.length === 0) return; + // The dose of a relay-started Activity the app registers without one + // (iOS builds up to 322): the one relay start running on the device, and + // only when there is exactly one. Anything else is a guess: the token is + // kept without a dose and the relay pass ends it. + const idLess = sent.liveActivityTokens.filter((a) => !a.medicationId); + const running = + idLess.length === 1 + ? singleRunningRelayStart( + storedRelay, + await tx.device.findUnique({ + where: { id: deviceId }, + select: { + laStartRef: true, + laStartedMedicationId: true, + laStartedSlot: true, + }, + }), + ) + : null; + const rows = sent.liveActivityTokens.map((a) => ({ + ...a, + medicationId: a.medicationId ?? running?.medicationId ?? null, + slotInstant: a.medicationId ? a.slotInstant : running?.slotInstant, + })); await tx.liveActivityToken.createMany({ data: rows.map((a) => ({ deviceId, @@ -266,6 +269,57 @@ async function replaceLiveActivityTokens( }); } +/** + * The dose of the one relay-started Activity the server's records show + * running on a device, or null when they show none or more than one: the + * relay-started Activities registered so far, and the last relay start + * (in flight or accepted; a start that failed for good clears it). A + * registered Activity without a dose makes the records ambiguous. + * + * The pass runs at most one relay-started Activity per device + * (`runDeviceLiveActivities`), so the last start is the one running. Lift + * this when the app echoes a per-start id (1.50). + */ +function singleRunningRelayStart( + stored: ReadonlyArray<{ + medicationId: string | null; + slotInstant: Date | null; + }>, + latest: { + laStartRef: string | null; + laStartedMedicationId: string | null; + laStartedSlot: Date | null; + } | null, +): { medicationId: string; slotInstant: Date | null } | null { + type Dose = { medicationId: string; slotInstant: Date | null }; + const doses: Dose[] = []; + const add = (dose: Dose) => { + const known = doses.some( + (d) => + d.medicationId === dose.medicationId && + (d.slotInstant === null || dose.slotInstant === null + ? d.slotInstant === dose.slotInstant + : sameActivitySlot(d.slotInstant, dose.slotInstant)), + ); + if (!known) doses.push(dose); + }; + for (const row of stored) { + if (row.medicationId === null) return null; + add({ medicationId: row.medicationId, slotInstant: row.slotInstant }); + } + if ( + latest?.laStartRef && + latest.laStartedMedicationId && + latest.laStartedSlot + ) { + add({ + medicationId: latest.laStartedMedicationId, + slotInstant: latest.laStartedSlot, + }); + } + return doses.length === 1 ? doses[0]! : null; +} + const DEVICE_MERGE_SELECT = { id: true, userId: true, diff --git a/src/lib/push-relay/activity-slot.ts b/src/lib/push-relay/activity-slot.ts index 6782cc63be..c0bb404b51 100644 --- a/src/lib/push-relay/activity-slot.ts +++ b/src/lib/push-relay/activity-slot.ts @@ -35,7 +35,7 @@ export function sameActivitySlot(named: Date, stored: Date): boolean { * shows every dose of its medication. */ export function activityShowsDose( - activity: { medicationId: string; slotInstant: Date | null }, + activity: { medicationId: string | null; slotInstant: Date | null }, medicationId: string, slot: Date, ): boolean { diff --git a/src/lib/push-relay/live-activity.ts b/src/lib/push-relay/live-activity.ts index 45d3351765..8779af19ca 100644 --- a/src/lib/push-relay/live-activity.ts +++ b/src/lib/push-relay/live-activity.ts @@ -277,6 +277,9 @@ const DEVICE_SELECT = { laStartToken: true, laStartStatement: true, laStartSignature: true, + laStartRef: true, + laStartedMedicationId: true, + laStartedSlot: true, liveActivities: { select: { id: true, @@ -602,7 +605,7 @@ export function relayActivityKind(activity: { */ export function supersededRelayActivities< T extends { - medicationId: string; + medicationId: string | null; slotInstant: Date | null; relayStarted: boolean; }, @@ -610,12 +613,13 @@ export function supersededRelayActivities< const appStarted = activities.filter( (a) => relayActivityKind(a) === "app_started", ); - return activities.filter((relay): relay is T & { slotInstant: Date } => { - const slot = relay.slotInstant; + return activities.filter((relay) => { + const { medicationId, slotInstant: slot } = relay; return ( relayActivityKind(relay) === "relay_started" && + medicationId !== null && slot !== null && - appStarted.some((app) => activityShowsDose(app, relay.medicationId, slot)) + appStarted.some((app) => activityShowsDose(app, medicationId, slot)) ); }); } @@ -754,7 +758,7 @@ async function updateItems( id: { in: device.liveActivities .filter(relayOwned) - .map((a) => a.medicationId), + .flatMap((a) => (a.medicationId ? [a.medicationId] : [])), }, ...STARTABLE_MEDICATION_WHERE, }, @@ -777,26 +781,28 @@ async function updateItems( for (const activity of device.liveActivities) { const iat = statementIat(activity.activityStatement); if ( - !activity.slotInstant || !activity.activitySignature || iat === null || nowS - iat > ACTIVITY_STATEMENT_MAX_AGE_S ) { continue; } + const { medicationId, slotInstant } = activity; + // Registered without a dose the server could name (`POST /api/devices` + // attributes one only to the single running relay start): it ends. + if (medicationId === null) { + ending.push(activity); + continue; + } + if (!slotInstant) continue; if ( superseded.has(activity.id) || - (relayOwned(activity) && !startable.has(activity.medicationId)) + (relayOwned(activity) && !startable.has(medicationId)) ) { ending.push(activity); continue; } - const dose = await doseAt( - device.userId, - activity.medicationId, - activity.slotInstant, - now, - ); + const dose = await doseAt(device.userId, medicationId, slotInstant, now); // Taken and skipped end the Activity on their own paths: the intake // flush at once, and this job's retry of an end the relay did not take // (`notifications/live-activity-answered.ts`). @@ -822,6 +828,39 @@ async function updateItems( return { updates, ending }; } +/** + * Whether the device's last relay start may still be running unseen: in + * flight or accepted, not yet registered by the app (no registered Activity + * shows its dose), and its dose still open for a medication that keeps a + * relay Activity. Such an Activity cannot be ended (its token is unknown), + * so no other relay start may join it. + */ +async function unreportedRelayStart( + device: LaDevice, + now: Date, +): Promise { + const { laStartRef, laStartedMedicationId: medicationId } = device; + const slot = device.laStartedSlot; + if (!laStartRef || !medicationId || !slot) return false; + if ( + device.liveActivities.some((a) => activityShowsDose(a, medicationId, slot)) + ) { + return false; + } + const startable = await prisma.medication.count({ + where: { + id: medicationId, + userId: device.userId, + ...STARTABLE_MEDICATION_WHERE, + }, + }); + if (startable === 0) return false; + const dose = await doseAt(device.userId, medicationId, slot, now); + return ( + dose !== null && ["pending", "due", "overdue"].includes(dose.resolved.state) + ); +} + /** Start and update the Live Activities of one device. */ export async function runDeviceLiveActivities( device: LaDevice, @@ -835,19 +874,48 @@ export async function runDeviceLiveActivities( select: { timeFormat: true }, }); const timeFormat = user?.timeFormat ?? null; - const start = await startItem(device, timeFormat, now); - const { updates, ending } = await updateItems(device, timeFormat, now); - if (ending.length > 0) { + let start = await startItem(device, timeFormat, now); + const { updates: proposed, ending } = await updateItems( + device, + timeFormat, + now, + ); + // At most one relay-started Activity per device. An app build that + // registers such an Activity without its dose leaves the server to name + // it, and the server names the one relay start it has running + // (`POST /api/devices`); with two running both got the newer dose. So a + // start for a new dose first ends the relay-started Activities still + // running, and goes out only once the relay took every one of those ends, + // in the same pass; otherwise it waits for a later pass. A start whose + // Activity the app has not registered yet cannot be ended: the new one + // waits until it is registered or its dose is over. Lift this when the + // app echoes a per-start id (1.50). + if (start && (await unreportedRelayStart(device, now))) start = null; + const making = start + ? device.liveActivities.filter( + (a) => relayActivityKind(a) === "relay_started" && !ending.includes(a), + ) + : []; + const spent = new Set(); + if (ending.length > 0 || making.length > 0) { // A missed dose has nothing left to show, and a medication without the // opt-in gets no server-started Activity: end it, and forget the token // once the relay took the end or reported the Activity gone. - const spent = await endActivitiesOverRelay(device, ending, ctx); - if (spent.length > 0) { + for (const id of await endActivitiesOverRelay( + device, + [...ending, ...making], + ctx, + )) { + spent.add(id); + } + if (spent.size > 0) { await prisma.liveActivityToken.deleteMany({ - where: { id: { in: spent } }, + where: { id: { in: [...spent] } }, }); } } + if (making.some((a) => !spent.has(a.id))) start = null; + const updates = proposed.filter((u) => !spent.has(u.rowId)); const items = [...(start ? [start.item] : []), ...updates.map((u) => u.item)]; if (items.length === 0) return { started: 0, updated: 0 }; if (start) { diff --git a/tests/integration/push-live-activity-consent.test.ts b/tests/integration/push-live-activity-consent.test.ts index da61135ef2..0f830469bf 100644 --- a/tests/integration/push-live-activity-consent.test.ts +++ b/tests/integration/push-live-activity-consent.test.ts @@ -1157,8 +1157,15 @@ describe("once per dose, from the server's own start record", () => { const first = await dueDose(t.session.userId, 30, { start: -30, end: 90 }); expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); // A dose with an earlier slot shows up due (its row written late): it - // is the earliest now, and its start becomes the device's last one. + // is the earliest now. The first one's Activity is not registered yet, + // so it cannot be ended, and nothing starts beside it. const earlier = await dueDose(t.session.userId, -20); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 0 }); + // Once the app registered it, the pass ends it and starts the earlier + // dose, which becomes the device's last start. + await t.reg({ + liveActivityTokens: [t.activityEntry({ relayStart: true })], + }); expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); expect( await getPrismaClient().device.findFirstOrThrow({ @@ -1210,3 +1217,201 @@ describe("once per dose, from the server's own start record", () => { ]); }); }); + +describe("one relay-started Activity per device", () => { + const B_TOKEN = "8d".repeat(32); + const events = (from = 0) => + laPushes() + .slice(from) + .map((p) => [p.token, (p.payload.aps as { event: string }).event]); + const tokens = () => + getPrismaClient().liveActivityToken.findMany({ + orderBy: { pushToken: "asc" }, + select: { pushToken: true, medicationId: true, slotInstant: true }, + }); + + async function consented() { + const t = await setUp(); + await t.reg({ + liveActivityConsent: t.consent(), + liveActivityStart: t.startField(), + }); + return t; + } + + /** The end path a take runs (`medication-intake-sync.ts`), for one device. */ + async function endAnswered(userId: string) { + const { ACTIVITY_DEVICE_SELECT, endAnsweredActivities, memoEndState } = + await import("@/lib/notifications/live-activity-answered"); + const { loadPushContext } = await import("@/lib/push-relay/route-device"); + const device = await getPrismaClient().device.findFirstOrThrow({ + where: { apnsToken: TOKEN }, + select: ACTIVITY_DEVICE_SELECT, + }); + return endAnsweredActivities( + device, + { ctx: await loadPushContext(), bundleId: null }, + memoEndState(userId), + ); + } + + it("ends the running one before it starts the next dose, and names each token's own dose", async () => { + const t = await consented(); + // C is due now and turns overdue an hour after its slot; B comes 90 + // minutes after C. + const c = await dueDose(t.session.userId, -50); + const b = await dueDose(t.session.userId, 40); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); + expect(events()).toEqual([[START_TOKEN, "start"]]); + // The app registers C's Activity without its dose: the one relay start + // running is C's. + await t.reg({ + liveActivityTokens: [t.activityEntry({ relayStart: true })], + }); + expect(await tokens()).toEqual([ + { + pushToken: LA_TOKEN, + medicationId: c.medication.id, + slotInstant: c.slot, + }, + ]); + + // C overdue, B startable: C ends first, then B starts, in one pass. + const before = laPushes().length; + expect(await runLiveActivityRelayPass(c.at(61))).toMatchObject({ + started: 1, + }); + expect(events(before)).toEqual([ + [LA_TOKEN, "end"], + [START_TOKEN, "start"], + ]); + expect(await tokens()).toEqual([]); + + // B's Activity, registered without its dose, is B's. + await t.reg({ + liveActivityTokens: [t.activityEntry({ relayStart: true }, B_TOKEN)], + }); + expect(await tokens()).toEqual([ + { + pushToken: B_TOKEN, + medicationId: b.medication.id, + slotInstant: b.slot, + }, + ]); + + // Taking C ends nothing of B's. + await getPrismaClient().medicationIntakeEvent.updateMany({ + where: { medicationId: c.medication.id }, + data: { takenAt: new Date() }, + }); + const afterC = laPushes().length; + expect((await endAnswered(t.session.userId)).activityIds).toEqual([]); + expect(await runLiveActivityRelayPass(c.at(62))).toMatchObject({ + started: 0, + }); + expect(events(afterC).filter(([, e]) => e === "end")).toEqual([]); + // Taking B ends B's. + await getPrismaClient().medicationIntakeEvent.updateMany({ + where: { medicationId: b.medication.id }, + data: { takenAt: new Date() }, + }); + expect((await endAnswered(t.session.userId)).activityIds).toHaveLength(1); + expect(events(afterC).filter(([, e]) => e === "end")).toEqual([ + [B_TOKEN, "end"], + ]); + }); + + it("starts nothing new while the running one's end is not taken", async () => { + const t = await consented(); + const c = await dueDose(t.session.userId, -50); + await dueDose(t.session.userId, 40); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); + await t.reg({ + liveActivityTokens: [t.activityEntry({ relayStart: true })], + }); + // The relay refuses the end (a statement it no longer accepts): C keeps + // running, so B does not start beside it. + await getPrismaClient().liveActivityToken.updateMany({ + data: { activitySignature: Buffer.alloc(64, 1).toString("base64url") }, + }); + const before = laPushes().length; + expect(await runLiveActivityRelayPass(c.at(61))).toMatchObject({ + started: 0, + }); + expect(events(before)).toEqual([]); + expect(await getPrismaClient().liveActivityToken.count()).toBe(1); + }); + + it("names no dose when the records show more than one relay start", async () => { + const t = await consented(); + const c = await dueDose(t.session.userId, -50); + expect(await runLiveActivityRelayPass()).toMatchObject({ started: 1 }); + // Two relay-started Activities posted without their dose, as a device + // left from before this rule reports them: neither is guessed. + await t.reg({ + liveActivityTokens: [ + t.activityEntry({ relayStart: true }), + t.activityEntry({ relayStart: true }, B_TOKEN), + ], + }); + expect(await tokens()).toEqual([ + { pushToken: LA_TOKEN, medicationId: null, slotInstant: null }, + { pushToken: B_TOKEN, medicationId: null, slotInstant: null }, + ]); + // One registered for C, and a last start for another dose on record: + // a third token without its dose is not guessed either. + const other = await dueDose(t.session.userId, 30); + await t.reg({ + liveActivityTokens: [ + t.activityEntry({ + relayStart: true, + medicationId: c.medication.id, + slotInstant: c.slot.toISOString(), + }), + ], + }); + await getPrismaClient().device.updateMany({ + data: { + laStartedMedicationId: other.medication.id, + laStartedSlot: other.slot, + }, + }); + await t.reg({ + liveActivityTokens: [ + t.activityEntry({ + relayStart: true, + medicationId: c.medication.id, + slotInstant: c.slot.toISOString(), + }), + t.activityEntry({ relayStart: true }, B_TOKEN), + ], + }); + expect((await tokens()).find((r) => r.pushToken === B_TOKEN)).toMatchObject( + { medicationId: null }, + ); + + // The pass ends what it cannot name, and both relay-started ones go + // before anything new starts. + const before = laPushes().length; + await runLiveActivityRelayPass(); + expect(events(before)).toContainEqual([B_TOKEN, "end"]); + expect( + await getPrismaClient().liveActivityToken.count({ + where: { medicationId: null }, + }), + ).toBe(0); + }); + + it("names no dose when no relay start is on record", async () => { + const t = await consented(); + await t.reg({ + liveActivityTokens: [t.activityEntry({ relayStart: true })], + }); + expect(await tokens()).toEqual([ + { pushToken: LA_TOKEN, medicationId: null, slotInstant: null }, + ]); + await runLiveActivityRelayPass(); + expect(events()).toEqual([[LA_TOKEN, "end"]]); + expect(await tokens()).toEqual([]); + }); +}); From cdfc9936475e8389ced2eea787cff5f8b3d6066e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 14:58:27 +0100 Subject: [PATCH 10/14] fix(medications): order schedules in the save-change predicate read --- src/lib/medications/update-medication/update-medication.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/medications/update-medication/update-medication.ts b/src/lib/medications/update-medication/update-medication.ts index 1bd420e469..d825c01fba 100644 --- a/src/lib/medications/update-medication/update-medication.ts +++ b/src/lib/medications/update-medication/update-medication.ts @@ -311,7 +311,7 @@ async function medicationStateKey(id: string): Promise { const row = await prisma.medication.findUnique({ where: { id }, include: { - schedules: true, + schedules: { orderBy: MEDICATION_SCHEDULE_ORDER }, categoryAssignment: { select: { category: true } }, }, }); From 03c6f9c6955c0add7c4e11024593fa32bc3066da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 14:58:28 +0100 Subject: [PATCH 11/14] test(nav): expect the Care count under the /care nav key --- src/hooks/__tests__/use-nav-counts.test.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/hooks/__tests__/use-nav-counts.test.tsx b/src/hooks/__tests__/use-nav-counts.test.tsx index f6139996a9..76f753a841 100644 --- a/src/hooks/__tests__/use-nav-counts.test.tsx +++ b/src/hooks/__tests__/use-nav-counts.test.tsx @@ -73,14 +73,14 @@ describe("useNavCounts and the switch", () => { it("shows the counts and asks for them by default", () => { useAuthMock.mockReturnValue({ user: { showNavCounts: true } }); - expect(counts()).toEqual({ "/medications": 2, "/checkups": 1 }); + expect(counts()).toEqual({ "/medications": 2, "/care": 1 }); expect(queryOptions.at(-1)?.enabled).toBe(true); expect(apiGetMock).toHaveBeenCalledWith("/api/nav/counts"); }); it("keeps them on before the account resolves", () => { useAuthMock.mockReturnValue({ user: null }); - expect(counts()).toEqual({ "/medications": 2, "/checkups": 1 }); + expect(counts()).toEqual({ "/medications": 2, "/care": 1 }); }); it("shows nothing and never asks while the switch is off", () => { From 3d143cbcd83cfdff55460b2ee3e043f93b214f24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 14:58:28 +0100 Subject: [PATCH 12/14] refactor(push-relay): split the Live Activity content state and ownership rules out of the pass The pass module grew past the source-size ratchet. The relay content-state template and the per-dose state now live in live-activity-content.ts, the started-by kind, the event rule and the superseded match in live-activity-owner.ts; both are pure. The device registration route moves its superseded-end step into a helper. --- src/app/api/devices/route.ts | 28 +- .../__tests__/live-activity-kind.test.ts | 6 +- .../__tests__/live-activity-one-owner.test.ts | 2 +- .../__tests__/live-activity-units.test.ts | 2 +- src/lib/push-relay/live-activity-content.ts | 176 ++++++++++++ src/lib/push-relay/live-activity-owner.ts | 81 ++++++ src/lib/push-relay/live-activity.ts | 258 +----------------- 7 files changed, 291 insertions(+), 262 deletions(-) create mode 100644 src/lib/push-relay/live-activity-content.ts create mode 100644 src/lib/push-relay/live-activity-owner.ts diff --git a/src/app/api/devices/route.ts b/src/app/api/devices/route.ts index 21f2688df2..6e65304944 100644 --- a/src/app/api/devices/route.ts +++ b/src/app/api/devices/route.ts @@ -489,6 +489,22 @@ async function registrationRateLimited(userId: string) { return apiError("Too many device registrations, please slow down", 429); } +/** + * One owner per dose: a relay-started Activity the app's own one of the same + * dose now stands beside ends at once; the Live Activity pass retries an end + * the relay did not take. A failure is a warning, never the registration's. + */ +async function endSupersededAfterRegistration(deviceId: string) { + try { + const ended = await endSupersededRelayActivities(deviceId); + if (ended > 0) annotate({ meta: { live_activity_superseded: ended } }); + } catch (err) { + getEvent()?.addWarning( + `live_activity_superseded_end_failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } +} + export const POST = apiHandler(async (request: NextRequest) => { const { user } = await requireAuth(); @@ -680,17 +696,7 @@ export const POST = apiHandler(async (request: NextRequest) => { const pushBlock = await applyPushFields(id, parsed.data); if (parsed.data.liveActivityTokens !== undefined) { - // One owner per dose: a relay-started Activity the app's own one of the - // same dose now stands beside ends at once; the Live Activity pass - // retries an end the relay did not take. - try { - const ended = await endSupersededRelayActivities(id); - if (ended > 0) annotate({ meta: { live_activity_superseded: ended } }); - } catch (err) { - getEvent()?.addWarning( - `live_activity_superseded_end_failed: ${err instanceof Error ? err.message : String(err)}`, - ); - } + await endSupersededAfterRegistration(id); } return apiSuccess({ id, push: pushBlock }, 201); diff --git a/src/lib/push-relay/__tests__/live-activity-kind.test.ts b/src/lib/push-relay/__tests__/live-activity-kind.test.ts index 14c992c929..586f0d4112 100644 --- a/src/lib/push-relay/__tests__/live-activity-kind.test.ts +++ b/src/lib/push-relay/__tests__/live-activity-kind.test.ts @@ -24,12 +24,12 @@ vi.mock("@/lib/push-relay/route-device", async (importOriginal) => ({ routeOf: () => "relay", })); +import { relayUpdateItem } from "@/lib/push-relay/live-activity"; +import { doseContentState } from "@/lib/push-relay/live-activity-content"; import { - doseContentState, relayActivityKind, relayEventAllowed, - relayUpdateItem, -} from "@/lib/push-relay/live-activity"; +} from "@/lib/push-relay/live-activity-owner"; import { endActivitiesOverRelay } from "@/lib/push-relay/medication-pushes"; import type { PushContext } from "@/lib/push-relay/route-device"; import { resolveDoseState } from "@/lib/medications/dose-state/resolve"; diff --git a/src/lib/push-relay/__tests__/live-activity-one-owner.test.ts b/src/lib/push-relay/__tests__/live-activity-one-owner.test.ts index 102736c3b2..21b15bfe21 100644 --- a/src/lib/push-relay/__tests__/live-activity-one-owner.test.ts +++ b/src/lib/push-relay/__tests__/live-activity-one-owner.test.ts @@ -11,7 +11,7 @@ import { activityShowsDose, activitySlotWindow, } from "@/lib/push-relay/activity-slot"; -import { supersededRelayActivities } from "@/lib/push-relay/live-activity"; +import { supersededRelayActivities } from "@/lib/push-relay/live-activity-owner"; const SLOT = new Date("2026-11-23T08:00:00Z"); const off = (s: number) => new Date(SLOT.getTime() + s * 1000); diff --git a/src/lib/push-relay/__tests__/live-activity-units.test.ts b/src/lib/push-relay/__tests__/live-activity-units.test.ts index 933dbb04ae..060bfe899b 100644 --- a/src/lib/push-relay/__tests__/live-activity-units.test.ts +++ b/src/lib/push-relay/__tests__/live-activity-units.test.ts @@ -4,7 +4,7 @@ import { ContentStateError, doseContentState, relayContentState, -} from "@/lib/push-relay/live-activity"; +} from "@/lib/push-relay/live-activity-content"; import { resolveDoseState } from "@/lib/medications/dose-state/resolve"; const NOW = 1_795_000_000; diff --git a/src/lib/push-relay/live-activity-content.ts b/src/lib/push-relay/live-activity-content.ts new file mode 100644 index 0000000000..4fdc065480 --- /dev/null +++ b/src/lib/push-relay/live-activity-content.ts @@ -0,0 +1,176 @@ +/** + * The relay's Live Activity content-state template and the state one dose + * shows in it. Pure: no database, no send. The pass in `live-activity.ts` + * builds every start and update from here. + */ +import type { ResolvedDose } from "@/lib/medications/dose-state/resolve"; + +export const RELAY_LA_STATUSES = [ + "pending", + "due", + "overdue", + "snoozed", + "taken", + "skipped", +] as const; +export type RelayLaStatus = (typeof RELAY_LA_STATUSES)[number]; +const TIME_FORMATS = ["AUTO", "H12", "H24"] as const; + +/** The relay's closed content-state template. */ +export type RelayContentState = { + status: RelayLaStatus; + countdownTarget: number; + isOverdue: boolean; + confirmed: boolean; + pendingConfirm: boolean; + timeFormatRaw: (typeof TIME_FORMATS)[number]; +}; + +const KEYS = [ + "status", + "countdownTarget", + "isOverdue", + "confirmed", + "pendingConfirm", + "timeFormatRaw", +] as const; + +/** `countdownTarget` bounds around the relay clock (`0` = no countdown). */ +export const COUNTDOWN_PAST_S = 24 * 3600; +const COUNTDOWN_FUTURE_S = 48 * 3600; +export class ContentStateError extends Error {} + +/** + * The content state exactly as the relay accepts it: every one of the six + * keys, no other key, each in its closed range at `nowS`. Throws + * {@link ContentStateError} otherwise; nothing outside the template can ever + * reach a relay item. + */ +export function relayContentState( + input: unknown, + nowS: number, +): RelayContentState { + if (!input || typeof input !== "object" || Array.isArray(input)) { + throw new ContentStateError("not an object"); + } + const value = input as Record; + const keys = Object.keys(value).sort(); + if (keys.join() !== [...KEYS].sort().join()) { + throw new ContentStateError(`keys ${keys.join()}`); + } + const { status, countdownTarget, timeFormatRaw } = value; + if (!(RELAY_LA_STATUSES as readonly unknown[]).includes(status)) { + throw new ContentStateError("status"); + } + if (!(TIME_FORMATS as readonly unknown[]).includes(timeFormatRaw)) { + throw new ContentStateError("timeFormatRaw"); + } + if ( + typeof countdownTarget !== "number" || + !Number.isInteger(countdownTarget) || + (countdownTarget !== 0 && + (countdownTarget < nowS - COUNTDOWN_PAST_S || + countdownTarget > nowS + COUNTDOWN_FUTURE_S)) + ) { + throw new ContentStateError("countdownTarget"); + } + for (const key of ["isOverdue", "confirmed", "pendingConfirm"] as const) { + if (typeof value[key] !== "boolean") throw new ContentStateError(key); + } + return { + status: status as RelayLaStatus, + countdownTarget, + isOverdue: value.isOverdue as boolean, + confirmed: value.confirmed as boolean, + pendingConfirm: value.pendingConfirm as boolean, + timeFormatRaw: timeFormatRaw as RelayContentState["timeFormatRaw"], + }; +} + +/** Whether a stored state (key order lost in JSONB) equals `state`. */ +export function sameState(state: RelayContentState, stored: unknown): boolean { + if (!stored || typeof stored !== "object") return false; + const other = stored as Record; + return KEYS.every((key) => other[key] === state[key]); +} + +/** A countdown in unix seconds, or 0 when the relay would refuse it. */ +function countdown(at: Date | null, nowS: number): number { + if (!at) return 0; + const s = Math.floor(at.getTime() / 1000); + return s < nowS - COUNTDOWN_PAST_S || s > nowS + COUNTDOWN_FUTURE_S ? 0 : s; +} + +/** One dose an Activity shows: its slot, its resolved state, its snooze. */ +export interface ActivityDose { + medicationId: string; + scheduledFor: Date; + resolved: ResolvedDose; + /** The running snooze, only when it holds this slot. */ + snoozedUntil: Date | null; + /** The medication's Live Activity opt-in. */ + liveActivityEnabled: boolean; +} + +/** + * The content state of one dose at `now`, inside the template, or null when + * the dose is missed: then there is nothing left to show, and the Activity + * ends. + * + * `countdownTarget` is the next boundary of the dose's own band, read the + * way the app reads it: before the target it counts down ("due in"), past it + * it counts up ("overdue by"). Pending counts to `dueAt`; due counts to + * `overdueSince`; overdue counts up from `overdueSince`; snoozed counts to + * the end of the snooze. + */ +export function doseContentState( + dose: Pick, + timeFormat: string | null | undefined, + now: Date, +): RelayContentState | null { + const nowS = Math.floor(now.getTime() / 1000); + const format = (TIME_FORMATS as readonly string[]).includes(timeFormat ?? "") + ? (timeFormat as RelayContentState["timeFormatRaw"]) + : "AUTO"; + const base = { + confirmed: false, + pendingConfirm: false, + timeFormatRaw: format, + isOverdue: false, + }; + const { resolved } = dose; + let state: RelayContentState; + switch (resolved.state) { + case "missed": + return null; + case "taken": + case "taken_late": + state = { ...base, status: "taken", countdownTarget: 0, confirmed: true }; + break; + case "skipped": + state = { ...base, status: "skipped", countdownTarget: 0 }; + break; + default: + if (dose.snoozedUntil && dose.snoozedUntil > now) { + state = { + ...base, + status: "snoozed", + countdownTarget: countdown(dose.snoozedUntil, nowS), + }; + } else if (resolved.state === "pending") { + state = { + ...base, + status: "pending", + countdownTarget: countdown(resolved.dueAt, nowS), + }; + } else { + state = { + ...base, + status: resolved.state, + countdownTarget: countdown(resolved.overdueSince, nowS), + isOverdue: resolved.state === "overdue", + }; + } + } + return relayContentState(state, nowS); +} diff --git a/src/lib/push-relay/live-activity-owner.ts b/src/lib/push-relay/live-activity-owner.ts new file mode 100644 index 0000000000..3de4204ba1 --- /dev/null +++ b/src/lib/push-relay/live-activity-owner.ts @@ -0,0 +1,81 @@ +/** + * Who started a registered Live Activity, which relay events it may take, + * and which relay-started ones an app-started Activity of the same dose + * makes redundant. Pure: no database, no send. + */ +import { activityShowsDose } from "@/lib/push-relay/activity-slot"; + +/** + * Who started a registered Activity: the relay, by a push-to-start + * (`HealthLogDoseAttributes`, registered with `relayStart: true`, the dose + * the device's `liveActivityStarted` names), or the app itself + * (`MedicationActivityAttributes`). The mark is kept per token + * (`relayStarted`, migration 0545) and never changes for an Activity. + */ +export type RelayActivityKind = "relay_started" | "app_started"; + +export function relayActivityKind(activity: { + relayStarted: boolean; +}): RelayActivityKind { + return activity.relayStarted ? "relay_started" : "app_started"; +} + +/** + * The relay-started Activities that show a dose an app-started Activity of + * the same device shows too, matched by {@link activityShowsDose}, the + * match the start and the end path make. + * + * One owner per dose. iOS builds up to 1.7 start their own Activity for a + * dose whatever the relay started, so a relay start that came first stands + * beside the app's own one, which alone has the Take button. The relay one + * ends and the app's stays. The dose stays held by its start row + * (`doseStartHeld`), so no second relay start follows. From the next 1.7 build the app starts none of its own while a + * relay Activity runs for the dose, and the relay Activity gets a Take + * button of its own. + */ +export function supersededRelayActivities< + T extends { + medicationId: string | null; + slotInstant: Date | null; + relayStarted: boolean; + }, +>(activities: readonly T[]): T[] { + const appStarted = activities.filter( + (a) => relayActivityKind(a) === "app_started", + ); + return activities.filter((relay) => { + const { medicationId, slotInstant: slot } = relay; + return ( + relayActivityKind(relay) === "relay_started" && + medicationId !== null && + slot !== null && + appStarted.some((app) => activityShowsDose(app, medicationId, slot)) + ); + }); +} + +/** + * Whether the relay may send `event` to a registered Activity of this kind. + * Every relay update is built through {@link relayUpdateItem}, which asks + * this; the end path (`endActivitiesOverRelay`) ends every kind. + * + * An end goes to both kinds: the relay writes its own fixed content state + * into an end (`status: "taken"`, `countdownTarget: 0`, a `dismissal-date` + * of now; the server may send no state with it), and both attributes types + * hide the countdown for a taken dose and dismiss at once. + * + * An update goes only to an Activity the relay started. The relay template + * carries `countdownTarget` in unix seconds, which `HealthLogDoseAttributes` + * reads; `MedicationActivityAttributes` reads it as seconds since + * 2001-01-01, so an update showed an app-started Activity a time 31 years + * off. The relay's bounds (one day back, two days ahead of its clock, or 0) + * leave no room to send it reference-date seconds instead. iOS builds before + * the next 1.7 build read app-started Activities in reference-date seconds; + * relaxing this waits until those builds are gone (1.50 at the earliest). + */ +export function relayEventAllowed( + kind: RelayActivityKind, + event: "update" | "end", +): boolean { + return event === "end" || kind === "relay_started"; +} diff --git a/src/lib/push-relay/live-activity.ts b/src/lib/push-relay/live-activity.ts index 8779af19ca..2e41ff74ff 100644 --- a/src/lib/push-relay/live-activity.ts +++ b/src/lib/push-relay/live-activity.ts @@ -55,7 +55,6 @@ import { pendingDeletionOf } from "@/lib/account-deletion/pending"; import { getEvent } from "@/lib/logging/context"; import { TRACKED_INTAKE_EVENT_WHERE } from "@/lib/medications/intake-tracking"; import { resolveDosesByRow } from "@/lib/medications/dose-state/today"; -import type { ResolvedDose } from "@/lib/medications/dose-state/resolve"; import { slotsHeldBySnooze } from "@/lib/medications/snooze-scope"; import { resolveUserTimezone } from "@/lib/tz/resolver"; import { @@ -78,6 +77,18 @@ import { sendRelayItems, type RelayItemInput, } from "@/lib/push-relay/relay-send"; +import { + COUNTDOWN_PAST_S, + doseContentState, + sameState, + type ActivityDose, + type RelayContentState, +} from "@/lib/push-relay/live-activity-content"; +import { + relayActivityKind, + relayEventAllowed, + supersededRelayActivities, +} from "@/lib/push-relay/live-activity-owner"; import { LA_START_EVENT, LA_UPDATE_EVENT, @@ -86,39 +97,6 @@ import { updatesInFlight, } from "@/lib/push-relay/live-activity-settle"; -export const RELAY_LA_STATUSES = [ - "pending", - "due", - "overdue", - "snoozed", - "taken", - "skipped", -] as const; -export type RelayLaStatus = (typeof RELAY_LA_STATUSES)[number]; -const TIME_FORMATS = ["AUTO", "H12", "H24"] as const; - -/** The relay's closed content-state template. */ -export type RelayContentState = { - status: RelayLaStatus; - countdownTarget: number; - isOverdue: boolean; - confirmed: boolean; - pendingConfirm: boolean; - timeFormatRaw: (typeof TIME_FORMATS)[number]; -}; - -const KEYS = [ - "status", - "countdownTarget", - "isOverdue", - "confirmed", - "pendingConfirm", - "timeFormatRaw", -] as const; - -/** `countdownTarget` bounds around the relay clock (`0` = no countdown). */ -const COUNTDOWN_PAST_S = 24 * 3600; -const COUNTDOWN_FUTURE_S = 48 * 3600; /** * How long before its scheduled time a dose gets an Activity. The app owns * this: `MedicationLiveActivityPlan.leadWindow` in the iOS client, which @@ -132,143 +110,6 @@ const ACTIVITY_STATEMENT_MAX_AGE_S = 12 * 3600 - 300; /** A start or update is worth nothing late. */ const PUSH_LIFETIME_S = 15 * 60; -export class ContentStateError extends Error {} - -/** - * The content state exactly as the relay accepts it: every one of the six - * keys, no other key, each in its closed range at `nowS`. Throws - * {@link ContentStateError} otherwise; nothing outside the template can ever - * reach a relay item. - */ -export function relayContentState( - input: unknown, - nowS: number, -): RelayContentState { - if (!input || typeof input !== "object" || Array.isArray(input)) { - throw new ContentStateError("not an object"); - } - const value = input as Record; - const keys = Object.keys(value).sort(); - if (keys.join() !== [...KEYS].sort().join()) { - throw new ContentStateError(`keys ${keys.join()}`); - } - const { status, countdownTarget, timeFormatRaw } = value; - if (!(RELAY_LA_STATUSES as readonly unknown[]).includes(status)) { - throw new ContentStateError("status"); - } - if (!(TIME_FORMATS as readonly unknown[]).includes(timeFormatRaw)) { - throw new ContentStateError("timeFormatRaw"); - } - if ( - typeof countdownTarget !== "number" || - !Number.isInteger(countdownTarget) || - (countdownTarget !== 0 && - (countdownTarget < nowS - COUNTDOWN_PAST_S || - countdownTarget > nowS + COUNTDOWN_FUTURE_S)) - ) { - throw new ContentStateError("countdownTarget"); - } - for (const key of ["isOverdue", "confirmed", "pendingConfirm"] as const) { - if (typeof value[key] !== "boolean") throw new ContentStateError(key); - } - return { - status: status as RelayLaStatus, - countdownTarget, - isOverdue: value.isOverdue as boolean, - confirmed: value.confirmed as boolean, - pendingConfirm: value.pendingConfirm as boolean, - timeFormatRaw: timeFormatRaw as RelayContentState["timeFormatRaw"], - }; -} - -/** Whether a stored state (key order lost in JSONB) equals `state`. */ -function sameState(state: RelayContentState, stored: unknown): boolean { - if (!stored || typeof stored !== "object") return false; - const other = stored as Record; - return KEYS.every((key) => other[key] === state[key]); -} - -/** A countdown in unix seconds, or 0 when the relay would refuse it. */ -function countdown(at: Date | null, nowS: number): number { - if (!at) return 0; - const s = Math.floor(at.getTime() / 1000); - return s < nowS - COUNTDOWN_PAST_S || s > nowS + COUNTDOWN_FUTURE_S ? 0 : s; -} - -/** One dose an Activity shows: its slot, its resolved state, its snooze. */ -export interface ActivityDose { - medicationId: string; - scheduledFor: Date; - resolved: ResolvedDose; - /** The running snooze, only when it holds this slot. */ - snoozedUntil: Date | null; - /** The medication's Live Activity opt-in. */ - liveActivityEnabled: boolean; -} - -/** - * The content state of one dose at `now`, inside the template, or null when - * the dose is missed: then there is nothing left to show, and the Activity - * ends. - * - * `countdownTarget` is the next boundary of the dose's own band, read the - * way the app reads it: before the target it counts down ("due in"), past it - * it counts up ("overdue by"). Pending counts to `dueAt`; due counts to - * `overdueSince`; overdue counts up from `overdueSince`; snoozed counts to - * the end of the snooze. - */ -export function doseContentState( - dose: Pick, - timeFormat: string | null | undefined, - now: Date, -): RelayContentState | null { - const nowS = Math.floor(now.getTime() / 1000); - const format = (TIME_FORMATS as readonly string[]).includes(timeFormat ?? "") - ? (timeFormat as RelayContentState["timeFormatRaw"]) - : "AUTO"; - const base = { - confirmed: false, - pendingConfirm: false, - timeFormatRaw: format, - isOverdue: false, - }; - const { resolved } = dose; - let state: RelayContentState; - switch (resolved.state) { - case "missed": - return null; - case "taken": - case "taken_late": - state = { ...base, status: "taken", countdownTarget: 0, confirmed: true }; - break; - case "skipped": - state = { ...base, status: "skipped", countdownTarget: 0 }; - break; - default: - if (dose.snoozedUntil && dose.snoozedUntil > now) { - state = { - ...base, - status: "snoozed", - countdownTarget: countdown(dose.snoozedUntil, nowS), - }; - } else if (resolved.state === "pending") { - state = { - ...base, - status: "pending", - countdownTarget: countdown(resolved.dueAt, nowS), - }; - } else { - state = { - ...base, - status: resolved.state, - countdownTarget: countdown(resolved.overdueSince, nowS), - isOverdue: resolved.state === "overdue", - }; - } - } - return relayContentState(state, nowS); -} - const DEVICE_SELECT = { ...ROUTABLE_DEVICE_SELECT, userId: true, @@ -575,55 +416,6 @@ async function startItem( type LaActivity = LaDevice["liveActivities"][number]; -/** - * Who started a registered Activity: the relay, by a push-to-start - * (`HealthLogDoseAttributes`, registered with `relayStart: true`, the dose - * the device's `liveActivityStarted` names), or the app itself - * (`MedicationActivityAttributes`). The mark is kept per token - * (`relayStarted`, migration 0545) and never changes for an Activity. - */ -export type RelayActivityKind = "relay_started" | "app_started"; - -export function relayActivityKind(activity: { - relayStarted: boolean; -}): RelayActivityKind { - return activity.relayStarted ? "relay_started" : "app_started"; -} - -/** - * The relay-started Activities that show a dose an app-started Activity of - * the same device shows too, matched by {@link activityShowsDose}, the - * match the start and the end path make. - * - * One owner per dose. iOS builds up to 1.7 start their own Activity for a - * dose whatever the relay started, so a relay start that came first stands - * beside the app's own one, which alone has the Take button. The relay one - * ends and the app's stays. The dose stays held by its start row - * (`doseStartHeld`), so no second relay start follows. From the next 1.7 build the app starts none of its own while a - * relay Activity runs for the dose, and the relay Activity gets a Take - * button of its own. - */ -export function supersededRelayActivities< - T extends { - medicationId: string | null; - slotInstant: Date | null; - relayStarted: boolean; - }, ->(activities: readonly T[]): T[] { - const appStarted = activities.filter( - (a) => relayActivityKind(a) === "app_started", - ); - return activities.filter((relay) => { - const { medicationId, slotInstant: slot } = relay; - return ( - relayActivityKind(relay) === "relay_started" && - medicationId !== null && - slot !== null && - appStarted.some((app) => activityShowsDose(app, medicationId, slot)) - ); - }); -} - /** * End the relay-started Activities of a device that an app-started one of the * same dose made redundant ({@link supersededRelayActivities}), and forget @@ -659,32 +451,6 @@ export async function endSupersededRelayActivities( return spent.length; } -/** - * Whether the relay may send `event` to a registered Activity of this kind. - * Every relay update is built through {@link relayUpdateItem}, which asks - * this; the end path (`endActivitiesOverRelay`) ends every kind. - * - * An end goes to both kinds: the relay writes its own fixed content state - * into an end (`status: "taken"`, `countdownTarget: 0`, a `dismissal-date` - * of now; the server may send no state with it), and both attributes types - * hide the countdown for a taken dose and dismiss at once. - * - * An update goes only to an Activity the relay started. The relay template - * carries `countdownTarget` in unix seconds, which `HealthLogDoseAttributes` - * reads; `MedicationActivityAttributes` reads it as seconds since - * 2001-01-01, so an update showed an app-started Activity a time 31 years - * off. The relay's bounds (one day back, two days ahead of its clock, or 0) - * leave no room to send it reference-date seconds instead. iOS builds before - * the next 1.7 build read app-started Activities in reference-date seconds; - * relaxing this waits until those builds are gone (1.50 at the earliest). - */ -export function relayEventAllowed( - kind: RelayActivityKind, - event: "update" | "end", -): boolean { - return event === "end" || kind === "relay_started"; -} - /** * The relay update item that shows `state` on `activity`, or null when the * relay may not update it ({@link relayEventAllowed}). From 0e8727c671f156d61c9b5dfa67467878f65f9ad2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 15:11:10 +0100 Subject: [PATCH 13/14] test(parity): record no tombstone pass on a schedule echo A save that repeats the stored schedule no longer tombstones today's open slots, so its audit row carries tombstonedSlotCount null instead of 0. The change is that one field of the echo's audit row, carried through every later snapshot of the walk. --- .../__snapshots__/medication-detail.13-schedule-echo.json.snap | 2 +- .../__snapshots__/medication-detail.14-grace-bridge.json.snap | 2 +- .../parity/__snapshots__/medication-detail.15a-pause.json.snap | 2 +- .../parity/__snapshots__/medication-detail.15b-resume.json.snap | 2 +- .../medication-detail.16-auto-mark-taken.json.snap | 2 +- .../medication-detail.17a-custom-category.json.snap | 2 +- .../medication-detail.17b-native-other-kept.json.snap | 2 +- .../__snapshots__/medication-detail.17c-web-other.json.snap | 2 +- .../medication-detail.17d-unknown-category.json.snap | 2 +- .../medication-detail.18a-record-schedule-kept.json.snap | 2 +- .../__snapshots__/medication-detail.18b-tracking-on.json.snap | 2 +- .../__snapshots__/medication-detail.18c-tracking-off.json.snap | 2 +- .../medication-detail.19a-scheduled-without-schedules.json.snap | 2 +- .../__snapshots__/medication-detail.19b-scheduled.json.snap | 2 +- .../medication-detail.19c-as-needed-keeping-schedules.json.snap | 2 +- .../__snapshots__/medication-detail.19d-as-needed.json.snap | 2 +- .../medication-detail.20a-one-shot-two-schedules.json.snap | 2 +- .../medication-detail.20b-one-shot-recurrence.json.snap | 2 +- .../__snapshots__/medication-detail.20c-one-shot.json.snap | 2 +- .../medication-detail.21a-course-overlap.json.snap | 2 +- .../medication-detail.21b-course-window-required.json.snap | 2 +- .../__snapshots__/medication-detail.21c-course-end.json.snap | 2 +- .../medication-detail.22-composition-units.json.snap | 2 +- .../__snapshots__/medication-detail.23a-invalid.json.snap | 2 +- .../__snapshots__/medication-detail.23b-not-found.json.snap | 2 +- .../parity/__snapshots__/medication-detail.24a-writer.json.snap | 2 +- .../__snapshots__/medication-detail.24b-manager.json.snap | 2 +- .../__snapshots__/medication-detail.24c-anonymous.json.snap | 2 +- .../parity/__snapshots__/medication-detail.31-delete.json.snap | 2 +- .../__snapshots__/medication-detail.32-not-found.json.snap | 2 +- .../__snapshots__/medication-detail.33a-manager.json.snap | 2 +- .../__snapshots__/medication-detail.33b-anonymous.json.snap | 2 +- 32 files changed, 32 insertions(+), 32 deletions(-) diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.13-schedule-echo.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.13-schedule-echo.json.snap index da4a5783bc..2ae2c98c8b 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.13-schedule-echo.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.13-schedule-echo.json.snap @@ -846,7 +846,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.14-grace-bridge.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.14-grace-bridge.json.snap index bfd6ead2ea..8aca25093e 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.14-grace-bridge.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.14-grace-bridge.json.snap @@ -846,7 +846,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.15a-pause.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.15a-pause.json.snap index 992cf0355c..e7e6082f87 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.15a-pause.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.15a-pause.json.snap @@ -870,7 +870,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.15b-resume.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.15b-resume.json.snap index aa7f659a12..1f1d56077c 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.15b-resume.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.15b-resume.json.snap @@ -885,7 +885,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.16-auto-mark-taken.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.16-auto-mark-taken.json.snap index 52afd1f947..5c7bda32c5 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.16-auto-mark-taken.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.16-auto-mark-taken.json.snap @@ -900,7 +900,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.17a-custom-category.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.17a-custom-category.json.snap index d9ba73adc7..8ea2ae5d86 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.17a-custom-category.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.17a-custom-category.json.snap @@ -905,7 +905,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.17b-native-other-kept.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.17b-native-other-kept.json.snap index a833ff5dc7..be909e85c6 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.17b-native-other-kept.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.17b-native-other-kept.json.snap @@ -907,7 +907,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.17c-web-other.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.17c-web-other.json.snap index 95963faba9..59bb582321 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.17c-web-other.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.17c-web-other.json.snap @@ -905,7 +905,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.17d-unknown-category.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.17d-unknown-category.json.snap index 20ac9f0418..d4ebaa40f2 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.17d-unknown-category.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.17d-unknown-category.json.snap @@ -801,7 +801,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.18a-record-schedule-kept.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.18a-record-schedule-kept.json.snap index 486653f5fe..c80cc380f1 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.18a-record-schedule-kept.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.18a-record-schedule-kept.json.snap @@ -898,7 +898,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.18b-tracking-on.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.18b-tracking-on.json.snap index bc95f8c724..f6146386d3 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.18b-tracking-on.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.18b-tracking-on.json.snap @@ -921,7 +921,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.18c-tracking-off.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.18c-tracking-off.json.snap index 6bd4c29c35..262700fbb1 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.18c-tracking-off.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.18c-tracking-off.json.snap @@ -965,7 +965,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.19a-scheduled-without-schedules.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.19a-scheduled-without-schedules.json.snap index f181d4705e..11eb3ee686 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.19a-scheduled-without-schedules.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.19a-scheduled-without-schedules.json.snap @@ -884,7 +884,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.19b-scheduled.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.19b-scheduled.json.snap index 1436957741..56a00ca0d5 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.19b-scheduled.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.19b-scheduled.json.snap @@ -1013,7 +1013,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.19c-as-needed-keeping-schedules.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.19c-as-needed-keeping-schedules.json.snap index 6f9fcc5309..48db72a74f 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.19c-as-needed-keeping-schedules.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.19c-as-needed-keeping-schedules.json.snap @@ -934,7 +934,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.19d-as-needed.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.19d-as-needed.json.snap index 4c14e5c244..418be7ef95 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.19d-as-needed.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.19d-as-needed.json.snap @@ -1019,7 +1019,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.20a-one-shot-two-schedules.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.20a-one-shot-two-schedules.json.snap index 5c0577c4f4..061ec0d58c 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.20a-one-shot-two-schedules.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.20a-one-shot-two-schedules.json.snap @@ -962,7 +962,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.20b-one-shot-recurrence.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.20b-one-shot-recurrence.json.snap index 1aed130092..143ca2a158 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.20b-one-shot-recurrence.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.20b-one-shot-recurrence.json.snap @@ -962,7 +962,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.20c-one-shot.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.20c-one-shot.json.snap index 2c5e1a888d..203e877b4d 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.20c-one-shot.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.20c-one-shot.json.snap @@ -1110,7 +1110,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.21a-course-overlap.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.21a-course-overlap.json.snap index 2d9cbedb56..c841e594ab 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.21a-course-overlap.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.21a-course-overlap.json.snap @@ -1021,7 +1021,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.21b-course-window-required.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.21b-course-window-required.json.snap index ee2ec6bc4c..b1d91b368f 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.21b-course-window-required.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.21b-course-window-required.json.snap @@ -1021,7 +1021,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.21c-course-end.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.21c-course-end.json.snap index 917cb5ac6d..6ae3f3c3de 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.21c-course-end.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.21c-course-end.json.snap @@ -1132,7 +1132,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.22-composition-units.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.22-composition-units.json.snap index 1a7a879881..b44b1229ce 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.22-composition-units.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.22-composition-units.json.snap @@ -1130,7 +1130,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.23a-invalid.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.23a-invalid.json.snap index 00d61269be..034088c5a5 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.23a-invalid.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.23a-invalid.json.snap @@ -1061,7 +1061,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.23b-not-found.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.23b-not-found.json.snap index 96b6cc545b..cb5df940e8 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.23b-not-found.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.23b-not-found.json.snap @@ -1036,7 +1036,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.24a-writer.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.24a-writer.json.snap index 190c1e4811..2e786031f1 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.24a-writer.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.24a-writer.json.snap @@ -1041,7 +1041,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.24b-manager.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.24b-manager.json.snap index c53ac67fb4..d6b1f85a50 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.24b-manager.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.24b-manager.json.snap @@ -1155,7 +1155,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.24c-anonymous.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.24c-anonymous.json.snap index c961ee5ad3..6733c7ab79 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.24c-anonymous.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.24c-anonymous.json.snap @@ -1054,7 +1054,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.31-delete.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.31-delete.json.snap index 0060975265..c2d9d490aa 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.31-delete.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.31-delete.json.snap @@ -1000,7 +1000,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.32-not-found.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.32-not-found.json.snap index d94edb8e53..b85fc621c4 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.32-not-found.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.32-not-found.json.snap @@ -991,7 +991,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.33a-manager.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.33a-manager.json.snap index c3b31292ac..f5e987dcce 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.33a-manager.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.33a-manager.json.snap @@ -996,7 +996,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, diff --git a/tests/integration/routes/parity/__snapshots__/medication-detail.33b-anonymous.json.snap b/tests/integration/routes/parity/__snapshots__/medication-detail.33b-anonymous.json.snap index 9558c98174..4af554a5ad 100644 --- a/tests/integration/routes/parity/__snapshots__/medication-detail.33b-anonymous.json.snap +++ b/tests/integration/routes/parity/__snapshots__/medication-detail.33b-anonymous.json.snap @@ -994,7 +994,7 @@ "previous": {}, "replacedCadence": "11:30 FREQ=DAILY | 20:00 i2;1,3,5", "replacedScheduleCount": 2, - "tombstonedSlotCount": 0, + "tombstonedSlotCount": null, "tombstonedFrom": null, "tombstonedTo": null }, From c1f5a9cc8f9572d5ee5beaffacc3f851d3dcfa6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Mon, 23 Nov 2026 15:29:27 +0100 Subject: [PATCH 14/14] fix(medications): evict the medication caches on a save that changes nothing Skipping the device wake on an unchanged save also skipped the cache eviction that rode on it, so a compliance or list cell memoised before the save kept answering for its full TTL. The save now always evicts the record's medication caches and only the wake stays conditional. The integration test holds an unchanged save to evicting a memoised compliance and list cell. --- .../update-medication/update-medication.ts | 11 ++++++++--- .../medication-time-edit-today-slots.test.ts | 10 ++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/lib/medications/update-medication/update-medication.ts b/src/lib/medications/update-medication/update-medication.ts index d825c01fba..1e3d76005d 100644 --- a/src/lib/medications/update-medication/update-medication.ts +++ b/src/lib/medications/update-medication/update-medication.ts @@ -9,6 +9,7 @@ */ import type { MedicineRegistryChoice } from "@/lib/medications/leaflet-registries"; import { afterMedicationChange } from "@/lib/medications/after-dose-change"; +import { invalidateUserMedications } from "@/lib/cache/invalidate"; import { medicationDetail, type ReadUser, @@ -388,16 +389,20 @@ export async function updateMedication(input: { }, }); - // Bust per-user medications + compliance + achievement caches so the next - // read reflects the schedule change. // A schedule, a pause, a course or intake tracking decides what is due on // every device. A save that changed nothing (the form echoing the stored - // medication back) tells no device: the silent budget is small. + // medication back) tells no device: the silent budget is small. It still + // evicts the per-user medications, compliance and achievement caches: a + // save is the documented way to make the next read reflect the stored row, + // and a cell memoised before an out-of-band edit would otherwise outlive + // the save by its full TTL. if ( (write.trail.tombstonedSlotCount ?? 0) > 0 || (await medicationStateKey(id)) !== stateBefore ) { afterMedicationChange(user.id); + } else { + invalidateUserMedications(user.id, { evict: true }); } // The read model, exactly as `GET /api/medications/{id}` answers it. diff --git a/tests/integration/medication-time-edit-today-slots.test.ts b/tests/integration/medication-time-edit-today-slots.test.ts index 4f54b904e1..bfd82be324 100644 --- a/tests/integration/medication-time-edit-today-slots.test.ts +++ b/tests/integration/medication-time-edit-today-slots.test.ts @@ -54,6 +54,7 @@ const { getMedicationScheduleTool } = const { loadDailyDigest } = await import("@/lib/daily/load-digest"); const { handleReminderCheck } = await import("@/lib/jobs/reminder/medication-reminder-check"); +const { caches } = await import("@/lib/cache/server-cache"); const OLD_SLOT = "2026-11-23T20:16:00.000Z"; // 21:16 Berlin const NEW_SLOT = "2026-11-23T10:30:00.000Z"; // 11:30 Berlin @@ -327,6 +328,11 @@ describe("a dose time moved during the day", () => { select: { syncVersion: true }, }); + const staleCell = `${med.userId}|${med.id}|stale-probe`; + const staleListCell = `${med.userId}|stale-probe`; + caches.medicationCompliance.set(staleCell, { stale: true }); + caches.medications.set(staleListCell, { stale: true }); + // 11:25:45 Berlin: the form saves the same schedule back. vi.setSystemTime(new Date("2026-11-23T10:25:45.000Z")); await putSchedule(med.id, OLD_SCHEDULE); @@ -346,6 +352,10 @@ describe("a dose time moved during the day", () => { expect(kept).toEqual({ deletedAt: null, syncVersion }); // ... and no device is woken for it. expect(wakes()).toBe(0); + // The save still evicts the record's memoised medication cells: a cell + // written before the save must not answer the next read. + expect(caches.medicationCompliance.get(staleCell)).toBeNull(); + expect(caches.medications.get(staleListCell)).toBeNull(); // The next projecting read finds the same row. await readToday();