diff --git a/CHANGELOG.md b/CHANGELOG.md
index f5b0870ba1..169d852ce1 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.
@@ -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. 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.
@@ -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.
@@ -78,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.
@@ -158,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.
@@ -173,10 +174,12 @@
- 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. 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.
- 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
@@ -200,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-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-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.
@@ -12663,7 +12666,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/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/contributing/ui-standards.md b/docs/contributing/ui-standards.md
index 75fce4a945..fe76c0b635 100644
--- a/docs/contributing/ui-standards.md
+++ b/docs/contributing/ui-standards.md
@@ -161,11 +161,11 @@ 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`.
-**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/ops/deploy.md b/docs/ops/deploy.md
index da9dd86033..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-six migrations, `0514` to `0558` (`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 `36 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:
@@ -338,7 +338,9 @@ 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`, `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).
@@ -352,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/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/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/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/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/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/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..6ba0d5eeba 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": {
@@ -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": {
@@ -11094,7 +11096,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 +11200,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 +11215,7 @@
},
"dashboard": {
"empty": "No upcoming checkup reminders.",
- "openLink": "Open checkups"
+ "openLink": "Open Care"
},
"showMeasurements": "Show measurements",
"loadError": "Could not load your reminders.",
@@ -13761,7 +13763,7 @@
"action": {
"logDose": "Take",
"reconnect": "Reconnect",
- "viewCheckups": "View check-ups",
+ "viewCheckups": "Open Care",
"viewAppointment": "View appointment",
"viewAppointments": "View appointments",
"checkinKeep": "Keep it",
@@ -14557,7 +14559,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/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..81d72bbcc1 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": {
@@ -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": {
@@ -11094,7 +11096,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 +11200,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 +11215,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 +13763,7 @@
"action": {
"logDose": "Tomar",
"reconnect": "Reconectar",
- "viewCheckups": "Ver checks",
+ "viewCheckups": "Ver prevenção",
"viewAppointment": "Ver consulta",
"viewAppointments": "Ver consultas",
"checkinKeep": "Manter",
@@ -14557,7 +14559,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..a079a90e6f 100644
--- a/messages/ru.json
+++ b/messages/ru.json
@@ -628,7 +628,7 @@
"cycle": "Цикл",
"labs": "Анализы",
"profile": "Профиль",
- "vorsorge": "Чекапы",
+ "vorsorge": "Профилактика",
"illness": "Заболевания",
"documents": "Документы",
"vaccinations": "Вакцинации",
@@ -8200,7 +8200,9 @@
"displayCard": {
"title": "Отображение",
"description": "Язык, единицы и форматы, сохраняются сразу при изменении.",
- "themeDescription": "Системная следует за устройством между светлой и тёмной. Выбор хранится на этом устройстве."
+ "themeDescription": "Системная следует за устройством между светлой и тёмной. Выбор хранится на этом устройстве.",
+ "navCountsLabel": "Счётчики в навигации",
+ "navCountsDescription": "Показывает рядом с пунктами на боковой панели и в меню «Ещё», сколько приёмов и профилактических осмотров предстоит."
},
"integrationCard": {
"state": {
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/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/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/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 8509efee47..95a417f4b0 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
@@ -6550,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
@@ -6663,9 +6674,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.
@@ -6788,7 +6801,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 +10671,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
@@ -11725,6 +11738,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)
@@ -11732,6 +11753,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__/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__/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/__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..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";
@@ -147,7 +148,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",
@@ -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/__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/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/app/api/devices/route.ts b/src/app/api/devices/route.ts
index 69f54bf804..6e65304944 100644
--- a/src/app/api/devices/route.ts
+++ b/src/app/api/devices/route.ts
@@ -59,6 +59,8 @@ 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 { sameActivitySlot } from "@/lib/push-relay/activity-slot";
import {
activityStatementSchema,
applyPushFields,
@@ -215,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,
@@ -265,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,
@@ -434,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();
@@ -623,5 +694,10 @@ 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) {
+ await endSupersededAfterRegistration(id);
+ }
+
+ return apiSuccess({ id, push: pushBlock }, 201);
});
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/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/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/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/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={
<>
+ {/* #1113 — the counts on Medications and Checkups in the navigation. */}
+
);
}
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";
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/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/__tests__/use-nav-counts.test.tsx b/src/hooks/__tests__/use-nav-counts.test.tsx
new file mode 100644
index 0000000000..76f753a841
--- /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, "/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, "/care": 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-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..a746b93c85 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";
@@ -23,12 +26,16 @@ 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 {
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/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/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/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/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/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/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/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/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..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,
@@ -50,6 +51,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 +301,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: { orderBy: MEDICATION_SCHEDULE_ORDER },
+ 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 +344,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 {
@@ -360,11 +389,21 @@ 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. 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.
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/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/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/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..586f0d4112
--- /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