Merge pull request #238 from MBombeck/release/v1.8.7

v1.8.7 — Instant insight assessments, GLP-1 blood-level chart, tile + caption polish
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-06-02 10:17:32 +02:00
commit 3ea6bde8a3
29 files changed
+576 -360

No files matched your search

+13
View File
@@ -1,5 +1,18 @@
# Changelog
## [1.8.7] — 2026-06-02 — Instant insight assessments, GLP-1 blood-level chart, tile + caption polish
### Fixed
- **Insight assessments are instant again.** A category's assessment was being re-prepared on almost every visit: the constant Apple Health / Withings sync kept evicting the cached text, and a miss only ever deleted-and-waited. Assessments now serve the last good text immediately (stale-while-revalidate) and refresh in the background — "preparing" shows only when an assessment has genuinely never been generated. The background refresh is also debounced per metric, so a sync burst no longer triggers a storm of regenerations, and it warms only the active language (halving the work).
- **The dashboard tiles never truncate the value.** In a dense tile strip the number could clip or wrap mid-value (e.g. "130 mmHg" showing as "13"); the value now always renders in full and the unit yields the space instead.
- **GLP-1 medications show the drug-level-in-blood estimate by default.** The estimated concentration curve was hidden behind the Research-Mode opt-in and below the dose-strength curve; for GLP-1 medications it now shows by default, above the dose-strength curve, with the "educational estimate, not a measurement" disclaimer kept clearly attached.
- **The Trends captions read consistently.** Metrics without an advisor note previously rendered their caption in a different, plainer style that broke the row; every Trends caption now uses the same treatment.
### Changed
- **The mood assessment sits directly under the first chart** on the mood insights page.
## [1.8.6] — 2026-06-01 — Compliance two-row return, insights polish, targets deprecation
### Added
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: HealthLog API
version: 1.8.6
version: 1.8.7
description: >-
Self-hosted personal-health-tracking PWA — public API surface for the iOS native client and external ingest.
+1 -7
View File
@@ -1127,11 +1127,6 @@
"emptyState": "Noch keine Einnahmen erfasst.",
"emptyStateCta": "Trage eine Dosis ein, damit die geschätzte Verlaufskurve Gestalt annimmt.",
"estimateNote": "Edukative Schätzung aus EMA-publizierter Populations-Pharmakokinetik. Keine Messung.",
"gatedTitle": "Forschungsmodus ist aus",
"gatedBody": "Aktiviere den Forschungsmodus in den Einstellungen, um die geschätzte Wirkstoffkurve zu sehen. Die Kurve ist opt-in, weil sie eine Lernhilfe und keine klinische Messung ist.",
"gatedStaleTitle": "Disclaimer muss neu bestätigt werden",
"gatedStaleBody": "Der Disclaimer des Forschungsmodus wurde seit deiner letzten Bestätigung aktualisiert. Lies ihn in den Einstellungen erneut und bestätige, um die Kurve wieder einzublenden.",
"gatedCta": "Forschungsmodus in den Einstellungen öffnen",
"unknownDrug": "{name} ist nicht im EMA-zugelassenen GLP-1-Katalog enthalten. HealthLog kann dafür keine Populations-Pharmakokinetik-Kurve erzeugen."
}
},
@@ -1306,8 +1301,7 @@
"history": {
"back": "Zurück zum Medikament",
"subtitle": "Vollständiger Einnahmeverlauf",
"plannedSuffix": "geplant",
"drugLevelDisclosure": "Geschätzte Wirkstoffkurve anzeigen"
"plannedSuffix": "geplant"
}
},
"logInjectionSiteTitle": "Injektionsstelle erfassen",
+1 -7
View File
@@ -1127,11 +1127,6 @@
"emptyState": "No intake events yet.",
"emptyStateCta": "Log a dose to see the estimated level take shape.",
"estimateNote": "Educational estimate from EMA-published population pharmacokinetics. Not a measurement.",
"gatedTitle": "Research Mode is off",
"gatedBody": "Turn on Research Mode in Settings to see the estimated drug-level curve. The curve is opt-in because it is a learning aid, not a clinical measurement.",
"gatedStaleTitle": "Disclaimer needs re-acknowledgment",
"gatedStaleBody": "The Research Mode disclaimer was updated since you last acknowledged it. Re-read and confirm in Settings to bring the chart back.",
"gatedCta": "Open Research Mode in Settings",
"unknownDrug": "{name} is not in the EMA-approved GLP-1 catalog, so HealthLog cannot render a population-PK curve for it."
}
},
@@ -1306,8 +1301,7 @@
"history": {
"back": "Back to medication",
"subtitle": "Full intake history",
"plannedSuffix": "planned",
"drugLevelDisclosure": "Show estimated drug-level curve"
"plannedSuffix": "planned"
}
},
"logInjectionSiteTitle": "Log injection site",
+1 -7
View File
@@ -1127,11 +1127,6 @@
"emptyState": "Sin tomas registradas todavía.",
"emptyStateCta": "Registra una dosis para ver la curva estimada cobrar forma.",
"estimateNote": "Estimación educativa a partir de la farmacocinética poblacional publicada por la EMA. No es una medición.",
"gatedTitle": "Modo Investigación desactivado",
"gatedBody": "Activa el modo Investigación en los ajustes para ver la curva estimada del nivel de fármaco. La curva es de inclusión voluntaria porque es una ayuda de aprendizaje, no una medición clínica.",
"gatedStaleTitle": "El disclaimer requiere reconfirmación",
"gatedStaleBody": "El disclaimer del modo Investigación se actualizó desde tu última confirmación. Relelo en los ajustes y confirma de nuevo para volver a ver la curva.",
"gatedCta": "Abrir el modo Investigación en los ajustes",
"unknownDrug": "{name} no está en el catálogo de GLP-1 aprobado por la EMA, por lo que HealthLog no puede trazar una curva de farmacocinética poblacional."
}
},
@@ -1306,8 +1301,7 @@
"history": {
"back": "Volver al medicamento",
"subtitle": "Historial completo de tomas",
"plannedSuffix": "planificado",
"drugLevelDisclosure": "Mostrar curva estimada del principio activo"
"plannedSuffix": "planificado"
}
},
"logInjectionSiteTitle": "Registrar sitio de inyección",
+1 -7
View File
@@ -1127,11 +1127,6 @@
"emptyState": "Aucune prise enregistrée.",
"emptyStateCta": "Enregistrez une dose pour voir la courbe estimée prendre forme.",
"estimateNote": "Estimation éducative à partir de la pharmacocinétique de population publiée par l'EMA. Pas une mesure.",
"gatedTitle": "Mode Recherche désactivé",
"gatedBody": "Activez le mode Recherche dans les paramètres pour voir la courbe estimée du niveau de médicament. La courbe est en opt-in parce que c'est un outil d'apprentissage, pas une mesure clinique.",
"gatedStaleTitle": "Le disclaimer doit être reconfirmé",
"gatedStaleBody": "Le disclaimer du mode Recherche a été mis à jour depuis votre dernière confirmation. Relisez-le dans les paramètres et confirmez à nouveau pour réafficher la courbe.",
"gatedCta": "Ouvrir le mode Recherche dans les paramètres",
"unknownDrug": "{name} n'est pas dans le catalogue GLP-1 approuvé par l'EMA, donc HealthLog ne peut pas tracer de courbe de pharmacocinétique de population."
}
},
@@ -1306,8 +1301,7 @@
"history": {
"back": "Retour au médicament",
"subtitle": "Historique complet des prises",
"plannedSuffix": "prévu",
"drugLevelDisclosure": "Afficher la courbe estimée du principe actif"
"plannedSuffix": "prévu"
}
},
"logInjectionSiteTitle": "Enregistrer le site d'injection",
+1 -7
View File
@@ -1127,11 +1127,6 @@
"emptyState": "Nessuna assunzione registrata.",
"emptyStateCta": "Registra una dose per vedere prendere forma la curva stimata.",
"estimateNote": "Stima educativa dalla farmacocinetica di popolazione pubblicata dall'EMA. Non è una misura.",
"gatedTitle": "Modalità Ricerca disattivata",
"gatedBody": "Attiva la modalità Ricerca nelle impostazioni per vedere la curva stimata del livello del farmaco. La curva è opt-in perché è uno strumento di apprendimento, non una misura clinica.",
"gatedStaleTitle": "Il disclaimer richiede una nuova conferma",
"gatedStaleBody": "Il disclaimer della modalità Ricerca è stato aggiornato dall'ultima tua conferma. Rileggilo nelle impostazioni e conferma di nuovo per rivedere la curva.",
"gatedCta": "Apri la modalità Ricerca nelle impostazioni",
"unknownDrug": "{name} non è nel catalogo GLP-1 approvato dall'EMA, quindi HealthLog non può tracciare una curva di farmacocinetica di popolazione."
}
},
@@ -1306,8 +1301,7 @@
"history": {
"back": "Torna al farmaco",
"subtitle": "Cronologia completa delle assunzioni",
"plannedSuffix": "pianificato",
"drugLevelDisclosure": "Mostra la curva stimata del principio attivo"
"plannedSuffix": "pianificato"
}
},
"logInjectionSiteTitle": "Registra il sito di iniezione",
+1 -7
View File
@@ -1127,11 +1127,6 @@
"emptyState": "Brak zarejestrowanych przyjęć.",
"emptyStateCta": "Zarejestruj dawkę, aby zobaczyć kształtującą się krzywą szacunkową.",
"estimateNote": "Edukacyjne oszacowanie z opublikowanej przez EMA farmakokinetyki populacyjnej. To nie jest pomiar.",
"gatedTitle": "Tryb Badawczy wyłączony",
"gatedBody": "Włącz tryb Badawczy w Ustawieniach, aby zobaczyć szacowaną krzywą poziomu leku. Krzywa jest opt-in, ponieważ to pomoc edukacyjna, a nie pomiar kliniczny.",
"gatedStaleTitle": "Disclaimer wymaga ponownego potwierdzenia",
"gatedStaleBody": "Disclaimer trybu Badawczego został zaktualizowany od czasu twojego ostatniego potwierdzenia. Przeczytaj go ponownie w Ustawieniach i potwierdź, aby krzywa znów się pojawiła.",
"gatedCta": "Otwórz tryb Badawczy w Ustawieniach",
"unknownDrug": "{name} nie znajduje się w katalogu GLP-1 zatwierdzonym przez EMA, więc HealthLog nie może wyrysować krzywej farmakokinetyki populacyjnej."
}
},
@@ -1306,8 +1301,7 @@
"history": {
"back": "Powrót do leku",
"subtitle": "Pełna historia przyjęć",
"plannedSuffix": "zaplanowane",
"drugLevelDisclosure": "Pokaż szacowaną krzywą stężenia leku"
"plannedSuffix": "zaplanowane"
}
},
"logInjectionSiteTitle": "Zarejestruj miejsce iniekcji",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "healthlog",
"version": "1.8.6",
"version": "1.8.7",
"description": "Self-hosted personal-health-tracking PWA with Withings integration, AI insights, and doctor-report PDF export.",
"license": "AGPL-3.0-only",
"homepage": "https://healthlog.dev",
+7 -4
View File
@@ -106,10 +106,9 @@ export default function InsightsStimmungPage() {
userTimezone={user?.timezone}
/>
<MetricTargetSummary slug="mood" />
<MoodInsightsSections />
{/* v1.8.7 — the AI assessment reads best directly under the first
chart: the reader sees the trend, then the narration of it,
before the calendar / distribution / correlation breakdowns. */}
<InsightStatusCard
title={t("insights.assessmentTitle")}
icon={<Smile className="h-5 w-5" />}
@@ -120,6 +119,10 @@ export default function InsightsStimmungPage() {
loading={isStatusLoading}
preparing={status?.preparing ?? false}
/>
<MetricTargetSummary slug="mood" />
<MoodInsightsSections />
</SubPageShell>
);
}
+15 -24
View File
@@ -129,31 +129,22 @@ export default function IntakeHistoryPage({
/>
)}
{/* O-2 — dose-strength (titration) curve + estimated
active-ingredient curve as a default-CLOSED disclosure for
GLP-1 medications. Genuine context, but opt-in so the intake
table stays the dominant surface. The dose-strength curve plots
the user's own logged dose-change history; the drug-level chart
gates further on Research Mode. */}
{/* Estimated drug-level curve (the modelled active-ingredient
level) + dose-strength (titration) curve for GLP-1 medications.
Visible by default — the drug-level estimate is the one the
medication concerns, so it leads; the dose-strength curve plots
the user's own logged dose-change history below it. */}
{medication && isGlp1 && (
<details
className="border-border/60 rounded-md border"
data-slot="history-drug-level-disclosure"
>
<summary className="text-foreground flex min-h-11 cursor-pointer items-center px-3 text-sm font-medium select-none sm:min-h-9">
{t("medications.detail.history.drugLevelDisclosure")}
</summary>
<div className="border-border/60 space-y-6 border-t px-3 py-3">
<DoseStrengthCurve medicationId={id} />
<DrugLevelChart
medication={{
id: medication.id,
name: medication.name,
dose: medication.dose,
}}
/>
</div>
</details>
<div className="space-y-6" data-slot="history-drug-level-section">
<DrugLevelChart
medication={{
id: medication.id,
name: medication.name,
dose: medication.dose,
}}
/>
<DoseStrengthCurve medicationId={id} />
</div>
)}
{importOpen && (
+15 -23
View File
@@ -235,30 +235,22 @@ export default function MedicationDetailPage({
(genuine history context). */}
{isGlp1 && <SideEffectsSection medicationId={id} />}
{/* GLP-1 dose-strength (titration) curve + estimated drug-level
chart as a default-CLOSED disclosure — genuine history context,
opt-in so the intake table stays the dominant surface. The
dose-strength curve plots the user's own logged dose-change
history; the drug-level chart gates further on Research Mode. */}
{/* GLP-1 estimated drug-level curve (the modelled active-ingredient
level) + dose-strength (titration) curve. Visible by default for
GLP-1 medications — the drug-level estimate is the one the
medication concerns, so it leads; the dose-strength curve plots
the user's own logged dose-change history below it. */}
{isGlp1 && (
<details
className="border-border/60 rounded-md border"
data-slot="detail-drug-level-disclosure"
>
<summary className="text-foreground flex min-h-11 cursor-pointer items-center px-3 text-sm font-medium select-none sm:min-h-9">
{t("medications.detail.history.drugLevelDisclosure")}
</summary>
<div className="border-border/60 space-y-6 border-t px-3 py-3">
<DoseStrengthCurve medicationId={id} />
<DrugLevelChart
medication={{
id: medication.id,
name: medication.name,
dose: medication.dose,
}}
/>
</div>
</details>
<div className="space-y-6" data-slot="detail-drug-level-section">
<DrugLevelChart
medication={{
id: medication.id,
name: medication.name,
dose: medication.dose,
}}
/>
<DoseStrengthCurve medicationId={id} />
</div>
)}
</div>
);
@@ -123,6 +123,93 @@ describe("<TrendCard> directionSentiment", () => {
});
});
describe("<TrendCard> value is never truncated", () => {
// v1.8.7 — the maintainer is emphatic: the numeric value must always
// render in full at any tile width (dense strip → narrowest column).
// The value span keeps its full intrinsic width (`shrink-0
// whitespace-nowrap`) and never carries `truncate`/`min-w-0`; when
// space is tight the UNIT yields instead. These guards pin the
// contract so a future layout churn can't reintroduce the clip.
function valueSpan(html: string): string {
const marker = 'data-slot="trend-card-value"';
const idx = html.indexOf(marker);
expect(idx).toBeGreaterThan(-1);
// Walk back to the opening "<span" of the value node.
const open = html.lastIndexOf("<span", idx);
const close = html.indexOf("</span>", idx);
return html.slice(open, close);
}
it("renders the full BP value (130) — never clipped to '13'", () => {
const html = render(
<TrendCard
label="BP systolic"
latest={130}
unit="mmHg"
avg7={128}
avg30={129}
slope30={null}
icon={Activity}
/>,
);
// Value span renders the full reading (formatter adds one decimal).
expect(valueSpan(html)).toContain("130.0");
});
it("renders the full paired BP value (131/85)", () => {
const html = render(
<TrendCard
label="BP"
latest={131}
unit="mmHg"
avg7={130}
avg30={130}
slope30={null}
icon={Activity}
secondary={{ latest: 85, avg7: 84, avg30: 84 }}
/>,
);
expect(valueSpan(html)).toContain("131.0/85.0");
});
it("does not put truncate or min-w-0 on the value node", () => {
const html = render(
<TrendCard
label="Weight"
latest={80.4}
unit="kg"
avg7={80}
avg30={80}
slope30={null}
icon={Activity}
/>,
);
const value = valueSpan(html);
expect(value).not.toContain("truncate");
expect(value).not.toContain("min-w-0");
// The value holds its width and the number stays on one line.
expect(value).toContain("shrink-0");
expect(value).toContain("whitespace-nowrap");
});
it("lets the unit yield (min-w-0 truncate) instead of the value", () => {
const html = render(
<TrendCard
label="VO2"
latest={42}
unit="mL/(kg·min)"
avg7={42}
avg30={42}
slope30={null}
icon={Activity}
/>,
);
// The unit text renders in full in the markup; the truncate is a
// density safeguard that only engages when the column is too narrow.
expect(html).toContain("mL/(kg·min)");
});
});
describe("<TrendCard> responsive layout", () => {
it("keeps long BP target tile content wrappable inside the card", () => {
// v1.4.28 FB-C2 — the BD-Zielbereich tile dropped `avgAllTime`
+21 -11
View File
@@ -238,7 +238,7 @@ export function TrendCard({
};
return (
<div className="bg-card border-border flex h-full w-full min-w-0 flex-col rounded-xl border p-4 md:p-6">
<div className="bg-card border-border flex h-full w-full min-w-0 flex-col overflow-hidden rounded-xl border p-4 md:p-6">
{/* v1.4.25 W20a — single-line discipline + deterministic height for
the heading row so the value row below sits at the same baseline
across every tile. The label is locale-abbreviated upstream (see
@@ -265,21 +265,30 @@ export function TrendCard({
ask: "rechts neben der Zahl … der Pfeil [ist], wie gerade der
Trend ist". */}
<div
className="mt-2 flex min-w-0 items-baseline gap-x-1.5"
className="mt-2 flex items-baseline gap-x-1.5"
data-slot="trend-card-value-row"
>
<span
className={cn(
"min-w-0 truncate font-semibold tracking-tight tabular-nums",
"shrink-0 whitespace-nowrap font-semibold tracking-tight tabular-nums",
// v1.8.7 — the value NEVER truncates, clips, or wraps
// mid-number. The maintainer is emphatic: every digit of
// the reading must render in full ("130 mmHg" must read as
// "130", never "13" then "3 mmHg"). The headline value span
// is `shrink-0 whitespace-nowrap` so it keeps its full
// intrinsic width and wins the horizontal-space contest
// against the unit. When the strip is dense (many tiles →
// narrow column) the UNIT yields — it shrinks (`min-w-0
// truncate`) and may ellipsis — rather than losing any
// digit of the number. The earlier `min-w-0 truncate` on
// this span was the bug: it let the value shrink below its
// content width and clip the number.
//
// v1.4.49.4 — paired values (BP systolic/diastolic) render
// as `131/85` and outgrow the `text-3xl` footprint on the
// narrowest grid columns, ellipsis-clipping to "13…" on the
// dashboard. The truncate stays as a defence-in-depth safety
// net, but paired tiles drop one font step (text-3xl →
// text-2xl) so the full pair stays visible at every column
// width. Single-value tiles (weight, pulse, glucose, …)
// keep text-3xl because their value never threatens the
// budget on its own.
// narrowest grid columns. Paired tiles drop one font step
// (text-3xl → text-2xl) so the full pair fits; single-value
// tiles (weight, pulse, glucose, …) keep text-3xl.
secondary ? "text-2xl" : "text-3xl",
// `leading-none` must come AFTER the font-size class in the
// cn() arg list. Tailwind v4 `text-3xl` / `text-2xl` ship
@@ -290,10 +299,11 @@ export function TrendCard({
// across every tile in the strip).
"leading-none",
)}
data-slot="trend-card-value"
>
{latest !== null ? renderPair(latest, secondary?.latest) : "—"}
</span>
<span className="text-muted-foreground shrink-0 text-sm tabular-nums">
<span className="text-muted-foreground min-w-0 truncate text-sm tabular-nums">
{unit}
</span>
<span
+63 -30
View File
@@ -43,6 +43,55 @@ export type TrendAnnotationConfidenceBand = "low" | "moderate" | "high";
export type TrendAnnotationStatus = "pending" | "needs_data" | "generated";
/**
* Shared presentational shell for a filled trend caption — the bordered
* card + Sparkles affordance + `text-foreground` prose treatment. Both
* the advisor-authored annotation (the legacy triple) and the additive
* metric's standard description (`captionKey`) render through this shell
* so the Trends row reads with a single typographic rhythm and the two
* paths can't drift apart. `children` carries the line(s) below the
* caption prose (e.g. a confidence chip). `slot` / `metric` pass through
* to the wrapper's `data-*` hooks so each call site keeps its own
* test-stable selector.
*/
export function TrendCaptionCard({
text,
slot,
metric,
children,
}: {
text: string;
slot: string;
metric: string;
children?: React.ReactNode;
}) {
return (
<div
data-slot={slot}
data-metric={metric}
className="border-border/60 bg-card/40 flex items-start gap-2 rounded-md border p-3"
>
<Sparkles
className="text-dracula-purple mt-0.5 h-3.5 w-3.5 shrink-0"
aria-hidden="true"
/>
<div className="min-w-0 flex-1 space-y-1">
{/* v1.4.28 R3c-Insights — `line-clamp-3` bounds caption
variance (FB-K2). A 1-sentence BP annotation paints
~3 lines wrapped; a 4-line mood annotation used to push
the cell taller, which `auto-rows-fr` propagated to
every neighbour cell. With the clamp the longest
annotation ends with an ellipsis at 3 lines and the
row stays at a single visual rhythm. */}
<p className="text-foreground line-clamp-3 text-xs leading-snug">
{text}
</p>
{children}
</div>
</div>
);
}
interface TrendAnnotationProps {
/** The metric this annotation describes. Drives the empty-state copy. */
metric: "bp" | "weight" | "mood";
@@ -122,36 +171,20 @@ export function TrendAnnotation({
}
return (
<div
data-slot="trend-annotation"
data-metric={metric}
className="border-border/60 bg-card/40 flex items-start gap-2 rounded-md border p-3"
<TrendCaptionCard
slot="trend-annotation"
metric={metric}
text={stripChartTokens(annotation)}
>
<Sparkles
className="text-dracula-purple mt-0.5 h-3.5 w-3.5 shrink-0"
aria-hidden="true"
/>
<div className="min-w-0 flex-1 space-y-1">
{/* v1.4.28 R3c-Insights — `line-clamp-3` bounds caption
variance (FB-K2). A 1-sentence BP annotation paints
~3 lines wrapped; a 4-line mood annotation used to push
the cell taller, which `auto-rows-fr` propagated to
every neighbour cell. With the clamp the longest
annotation ends with an ellipsis at 3 lines and the
row stays at a single visual rhythm. */}
<p className="text-foreground line-clamp-3 text-xs leading-snug">
{stripChartTokens(annotation)}
</p>
{confidence ? (
<Badge
data-slot="trend-annotation-confidence"
variant="outline"
className={cn("text-[10px]", CONFIDENCE_BADGE_CLASS[confidence])}
>
{t(CONFIDENCE_LABEL_KEY[confidence])}
</Badge>
) : null}
</div>
</div>
{confidence ? (
<Badge
data-slot="trend-annotation-confidence"
variant="outline"
className={cn("text-[10px]", CONFIDENCE_BADGE_CLASS[confidence])}
>
{t(CONFIDENCE_LABEL_KEY[confidence])}
</Badge>
) : null}
</TrendCaptionCard>
);
}
+11 -7
View File
@@ -13,6 +13,7 @@ import {
} from "@/lib/insights/trend-chart-select";
import {
TrendAnnotation,
TrendCaptionCard,
type TrendAnnotationConfidenceBand,
type TrendAnnotationStatus,
} from "./trend-annotation";
@@ -216,13 +217,16 @@ export function TrendsRow({
// v1.8.6 W8 — additive metrics carry no advisor
// annotation. Paint the metric's standard one-line
// description so the card is never caption-less.
<p
data-slot="trends-row-caption"
data-metric={config.metric}
className="text-muted-foreground line-clamp-3 text-xs"
>
{t(config.captionKey)}
</p>
// v1.8.7 W-E — render that description through the same
// `<TrendCaptionCard>` shell the advisor caption uses, so
// the fallback caption shares the bordered card, Sparkles
// affordance, and `text-foreground` typography rather than
// standing out as a plain muted line.
<TrendCaptionCard
slot="trends-row-caption"
metric={config.metric}
text={t(config.captionKey)}
/>
)}
</div>
);
+20 -94
View File
@@ -1,11 +1,13 @@
"use client";
/**
* v1.4.25 W19c-Frontend — Estimated drug-level chart for GLP-1
* medications. Opt-in behind Research Mode (the acknowledgment dialog
* in this directory gates entry); even when enabled the chart paints
* "Estimated level (relative)" on the y-axis without tick labels —
* research §2.3 + W19c-Backend round report carry the rationale.
* Estimated drug-level chart for GLP-1 medications. Visible by default
* for any recognised GLP-1 drug — the curve is the modelled
* active-ingredient level the medication concerns. The y-axis paints
* "Estimated level (relative)" without tick labels and the persistent
* estimate disclaimer makes the pharmacokinetic-ESTIMATE framing
* explicit: this is a modelled value, not a measured blood
* concentration.
*
* Inputs (read-only):
* - Drug id resolved from the medication name (catalog lookup via
@@ -18,10 +20,6 @@
* applicable dose by walking the dose-change timeline; intakes
* that pre-date every dose-change row fall back to the
* medication's headline dose string.
* - Research-mode state from `GET /api/auth/me/research-mode`. The
* chart gates on `enabled === true && acknowledgedVersion ===
* currentDisclaimerVersion` — defence-in-depth alongside the
* server-side 400 the POST returns for stale versions.
*
* Pure math: `computeOneCompartment(drug, doses, asOf)` from
* `glp1-pk.ts`. The chart renders a 21-day window so three weekly
@@ -38,8 +36,7 @@
import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { AlertTriangle, Loader2, Syringe } from "lucide-react";
import { Loader2, Syringe } from "lucide-react";
import {
Area,
AreaChart,
@@ -50,7 +47,6 @@ import {
YAxis,
} from "recharts";
import { Button } from "@/components/ui/button";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import {
@@ -62,7 +58,6 @@ import {
type Glp1DrugId,
} from "@/lib/medications/glp1-knowledge";
import { parseDoseMg } from "@/lib/medications/dose-string";
import type { ResearchModeStatus } from "@/lib/medications/research-mode-types";
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
import { MedicationDetailSection } from "@/components/medications/medication-detail-section";
@@ -128,23 +123,6 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
[medication.name],
);
const { data: researchMode, isLoading: rmLoading } =
useQuery<ResearchModeStatus | null>({
queryKey: queryKeys.researchMode(),
queryFn: async () => {
const res = await fetch("/api/auth/me/research-mode");
if (!res.ok) return null;
const json = await res.json();
return json.data as ResearchModeStatus;
},
staleTime: 60 * 1000,
});
const versionsAligned =
!!researchMode &&
researchMode.acknowledgedVersion === researchMode.currentDisclaimerVersion;
const gateOpen = !!researchMode?.enabled && versionsAligned;
const { data: details, isLoading: detailsLoading } =
useQuery<Glp1DetailsResponse | null>({
queryKey: queryKeys.medicationGlp1Details(medication.id),
@@ -154,9 +132,7 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
const json = await res.json();
return json.data as Glp1DetailsResponse;
},
// Only fetch when the user has opted in; saves a round-trip for
// anyone who hasn't enabled Research Mode.
enabled: gateOpen && !!drugId,
enabled: !!drugId,
staleTime: 60 * 1000,
});
@@ -170,7 +146,7 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
const json = await res.json();
return json.data as { events: IntakeEvent[] };
},
enabled: gateOpen && !!drugId,
enabled: !!drugId,
staleTime: 60 * 1000,
});
@@ -194,7 +170,7 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
// ── Section header always renders so the parent's "Estimated drug
// level" anchor stays stable; the body switches between gated /
// loading / empty / chart states.
const isLoading = rmLoading || (gateOpen && (detailsLoading || intakeLoading));
const isLoading = !!drugId && (detailsLoading || intakeLoading);
const hasDoses = doses.length > 0;
const animationsEnabled = !prefersReducedMotion();
// Single-window contract — three weekly cycles with the sample step
@@ -214,19 +190,12 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
) : null;
// Decision tree:
// 1. drug not in catalog → gated-unknown-drug placeholder
// 2. !researchMode.enabled OR → gated placeholder + Settings CTA
// versions !== aligned (the defence-in-depth rule)
// 3. loading → skeleton
// 4. no intake events → empty-state with log CTA
// 5. otherwise → AreaChart
// 1. drug not in catalog → unknown-drug placeholder
// 2. loading → skeleton
// 3. no intake events → empty-state with log CTA
// 4. otherwise → AreaChart
const body = !drugId ? (
<GatedUnknownDrug medicationName={medication.name} />
) : !gateOpen ? (
<GatedPlaceholder
versionsAligned={versionsAligned}
knownState={researchMode}
/>
) : isLoading ? (
// v1.4.43 W11-L6 — match the loaded chart height (240 px) so the
// dashboard tile doesn't reflow when the levels render.
@@ -257,9 +226,12 @@ export function DrugLevelChart({ medication, asOf }: DrugLevelChartProps) {
dataSlot="drug-level-chart"
>
{body}
{gateOpen && hasDoses && (
{/* The pharmacokinetic-ESTIMATE disclaimer stays attached whenever
a recognised GLP-1 drug renders the chart — the curve is a
modelled value, never a measured blood concentration. */}
{!!drugId && (
<p
className="text-muted-foreground mt-2 text-xs italic"
className="text-foreground/80 border-border bg-muted/40 mt-3 rounded-md border-l-2 px-3 py-2 text-xs font-medium"
data-slot="drug-level-chart-disclaimer"
>
{t("medications.researchMode.chart.estimateNote")}
@@ -306,52 +278,6 @@ function GatedUnknownDrug({ medicationName }: { medicationName: string }) {
);
}
function GatedPlaceholder({
versionsAligned,
knownState,
}: {
versionsAligned: boolean;
knownState: ResearchModeStatus | null | undefined;
}) {
const { t } = useTranslations();
// Three distinguishable states:
// - Research Mode is off entirely.
// - Research Mode is on but the acknowledged version is stale.
// - We don't know yet (server returned null) — still render the
// opt-in CTA so the user has a path forward.
const stale = !!knownState?.enabled && !versionsAligned;
return (
<div
className="bg-muted/40 border-border space-y-3 rounded-md border p-4 text-sm"
data-slot="drug-level-chart-gated"
data-stale={stale ? "true" : "false"}
>
<div className="flex items-start gap-2">
<AlertTriangle
className="text-warning mt-0.5 h-4 w-4 shrink-0"
aria-hidden="true"
/>
<div className="space-y-1">
<p className="text-foreground font-medium">
{stale
? t("medications.researchMode.chart.gatedStaleTitle")
: t("medications.researchMode.chart.gatedTitle")}
</p>
<p className="text-muted-foreground">
{stale
? t("medications.researchMode.chart.gatedStaleBody")
: t("medications.researchMode.chart.gatedBody")}
</p>
</div>
</div>
<Button asChild variant="outline" size="sm">
<Link href="/settings/advanced">
{t("medications.researchMode.chart.gatedCta")}
</Link>
</Button>
</div>
);
}
function EmptyState() {
const { t } = useTranslations();
@@ -1,15 +1,16 @@
/**
* v1.4.25 W19c-Frontend — Drug-level chart tests.
* Drug-level chart tests.
*
* Pins the gating decision tree (research §2.3 + §12.4 + W19c-Backend
* phase report). The chart MUST hide until:
* - the medication's brand resolves to a Glp1DrugId, AND
* - `enabled === true` AND
* - `acknowledgedVersion === currentDisclaimerVersion`.
* The estimated drug-level curve is visible by default for any
* recognised GLP-1 brand — it does NOT require Research Mode. The
* decision tree is now:
* - the medication's brand resolves to a Glp1DrugId → render, ELSE
* the unknown-drug placeholder.
* - no intake events → empty state.
* - otherwise → the AreaChart, always with the pharmacokinetic
* estimate disclaimer attached.
*
* Each gate failure renders a distinct placeholder so the SSR markup
* carries an unambiguous data-slot for assertion. Recharts in
* `renderToStaticMarkup` only paints the static frame (the
* Recharts in `renderToStaticMarkup` only paints the static frame (the
* `<ResponsiveContainer>` mounts but doesn't measure), so we assert on
* `data-slot="drug-level-chart-area"` presence + the gradient
* definition + the y-axis having no `<text>` tick labels.
@@ -25,8 +26,7 @@ import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
// Capture queryKey routing so different tests can stub different
// query results. The component reads three queries:
// - ["research-mode"]
// query results. The component reads two queries:
// - ["medications", id, "glp1-details"]
// - ["medications", id, "intake", "drug-level-chart"]
const queryResults: Record<string, unknown> = {};
@@ -109,15 +109,8 @@ beforeEach(() => {
pkCalls.length = 0;
});
describe("<DrugLevelChart> — gating decision tree", () => {
describe("<DrugLevelChart> — default-on decision tree", () => {
it("renders the unknown-drug placeholder for a non-GLP-1 brand", () => {
setQueryResult("research-mode", {
enabled: true,
acknowledgedAt: "2026-05-14T00:00:00Z",
acknowledgedVersion: "2026-05-14.1",
currentDisclaimerVersion: "2026-05-14.1",
});
const html = render(<DrugLevelChart medication={ramipril} />);
expect(html).toContain('data-slot="drug-level-chart-unknown-drug"');
@@ -128,48 +121,46 @@ describe("<DrugLevelChart> — gating decision tree", () => {
expect(pkCalls).toHaveLength(0);
});
it("renders the gated placeholder when Research Mode is OFF", () => {
setQueryResult("research-mode", {
enabled: false,
acknowledgedAt: null,
acknowledgedVersion: null,
currentDisclaimerVersion: "2026-05-14.1",
it("renders the chart for a GLP-1 med WITHOUT any Research Mode opt-in", () => {
// No research-mode query is stubbed at all — the chart must still
// render the curve for a recognised GLP-1 brand.
setQueryResult("medications/med-1/glp1-details", {
doseChanges: [
{
id: "dc-1",
effectiveFrom: "2026-04-01T00:00:00Z",
doseValue: 7.5,
doseUnit: "mg",
},
],
});
setQueryResult("medications/med-1/intake/drug-level-chart", {
events: [
{
id: "ev-1",
takenAt: "2026-05-13T08:00:00Z",
skipped: false,
scheduledFor: "2026-05-13T08:00:00Z",
},
],
});
const html = render(<DrugLevelChart medication={mounjaro} />);
const html = render(
<DrugLevelChart
medication={mounjaro}
asOf={new Date("2026-05-14T12:00:00Z")}
/>,
);
expect(html).toContain('data-slot="drug-level-chart-gated"');
expect(html).toContain('data-stale="false"');
expect(html).toContain("Research Mode is off");
expect(html).toContain("Open Research Mode");
expect(html).not.toContain('data-slot="drug-level-chart-area"');
expect(pkCalls).toHaveLength(0);
expect(html).toContain('data-slot="drug-level-chart-area"');
// The gated placeholder must never appear now.
expect(html).not.toContain('data-slot="drug-level-chart-gated"');
// The estimate disclaimer is always attached.
expect(html).toContain('data-slot="drug-level-chart-disclaimer"');
expect(pkCalls).toHaveLength(1);
});
it("renders the stale-disclaimer placeholder when versions differ", () => {
setQueryResult("research-mode", {
enabled: true,
acknowledgedAt: "2026-04-01T00:00:00Z",
acknowledgedVersion: "2026-04-01.1",
currentDisclaimerVersion: "2026-05-14.1",
});
const html = render(<DrugLevelChart medication={mounjaro} />);
expect(html).toContain('data-slot="drug-level-chart-gated"');
expect(html).toContain('data-stale="true"');
expect(html).toContain("re-acknowledgment");
expect(html).not.toContain('data-slot="drug-level-chart-area"');
expect(pkCalls).toHaveLength(0);
});
it("renders the empty state when gate is open but no intake events exist", () => {
setQueryResult("research-mode", {
enabled: true,
acknowledgedAt: "2026-05-14T00:00:00Z",
acknowledgedVersion: "2026-05-14.1",
currentDisclaimerVersion: "2026-05-14.1",
});
it("renders the empty state when no intake events exist", () => {
setQueryResult("medications/med-1/glp1-details", { doseChanges: [] });
setQueryResult("medications/med-1/intake/drug-level-chart", {
events: [],
@@ -180,16 +171,41 @@ describe("<DrugLevelChart> — gating decision tree", () => {
expect(html).toContain('data-slot="drug-level-chart-empty"');
expect(html).toContain("No intake events yet");
expect(html).not.toContain('data-slot="drug-level-chart-area"');
// The estimate disclaimer stays attached even without data.
expect(html).toContain('data-slot="drug-level-chart-disclaimer"');
expect(pkCalls).toHaveLength(0);
});
it("renders the chart when gate is open AND intake events exist", () => {
setQueryResult("research-mode", {
enabled: true,
acknowledgedAt: "2026-05-14T00:00:00Z",
acknowledgedVersion: "2026-05-14.1",
currentDisclaimerVersion: "2026-05-14.1",
it("falls back to the headline dose when no dose-change rows exist", () => {
// No doseChanges rows — every intake resolves to the headline
// "7.5 mg" dose so the curve still renders for a typical med.
setQueryResult("medications/med-1/glp1-details", { doseChanges: [] });
setQueryResult("medications/med-1/intake/drug-level-chart", {
events: [
{
id: "ev-1",
takenAt: "2026-05-13T08:00:00Z",
skipped: false,
scheduledFor: "2026-05-13T08:00:00Z",
},
],
});
const html = render(
<DrugLevelChart
medication={mounjaro}
asOf={new Date("2026-05-14T12:00:00Z")}
/>,
);
expect(html).toContain('data-slot="drug-level-chart-area"');
expect(pkCalls).toHaveLength(1);
const [call] = pkCalls;
expect(call.doses).toHaveLength(1);
expect(call.doses.every((d) => d.doseMg === 7.5)).toBe(true);
});
it("renders the chart when intake events exist", () => {
setQueryResult("medications/med-1/glp1-details", {
doseChanges: [
{
@@ -245,18 +261,11 @@ describe("<DrugLevelChart> — gating decision tree", () => {
});
it("wraps the chart inside the canonical MedicationDetailSection chrome (UI-H1)", () => {
// v1.4.28 — the dashboard tile retired and the standalone
// mount on `/medications/[id]/history` lifts onto the shared
// `<MedicationDetailSection>` chrome alongside Titration /
// The standalone mount on `/medications/[id]/history` lifts onto the
// shared `<MedicationDetailSection>` chrome alongside Titration /
// Scheduling / SideEffects. The aria-labelledby thread + the
// `border-border/60 rounded-md border` shell are the
// load-bearing seams.
setQueryResult("research-mode", {
enabled: true,
acknowledgedAt: "2026-05-14T00:00:00Z",
acknowledgedVersion: "2026-05-14.1",
currentDisclaimerVersion: "2026-05-14.1",
});
const html = render(<DrugLevelChart medication={mounjaro} />);
expect(html).toContain('data-slot="drug-level-chart"');
expect(html).toContain('aria-labelledby="drug-level-chart-title"');
@@ -268,12 +277,6 @@ describe("<DrugLevelChart> — gating decision tree", () => {
});
it("hides the y-axis tick labels (research §2.3, unit-less)", () => {
setQueryResult("research-mode", {
enabled: true,
acknowledgedAt: "2026-05-14T00:00:00Z",
acknowledgedVersion: "2026-05-14.1",
currentDisclaimerVersion: "2026-05-14.1",
});
setQueryResult("medications/med-1/glp1-details", { doseChanges: [] });
setQueryResult("medications/med-1/intake/drug-level-chart", {
events: [
@@ -11,20 +11,40 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const deleteMany = vi.fn();
const enqueueStatusGeneration = vi.fn();
const userFindUnique = vi.fn();
vi.mock("@/lib/db", () => ({
prisma: {
auditLog: { deleteMany: (...a: unknown[]) => deleteMany(...a) },
user: { findUnique: (...a: unknown[]) => userFindUnique(...a) },
},
}));
vi.mock("@/lib/jobs/insight-status-generate-shared", () => ({
enqueueStatusGeneration: (...a: unknown[]) => enqueueStatusGeneration(...a),
}));
import { invalidateStatusInsightsForTypes } from "../comprehensive-generate";
beforeEach(() => {
vi.clearAllMocks();
deleteMany.mockResolvedValue({ count: 0 });
enqueueStatusGeneration.mockResolvedValue(undefined);
userFindUnique.mockResolvedValue({ locale: "de" });
});
/** Distinct scopes the invalidator enqueued a regenerate for. */
function enqueuedScopes(): string[] {
return [
...new Set(
enqueueStatusGeneration.mock.calls.map(
(c) => (c[0] as { metric: string }).metric,
),
),
].sort();
}
function deletedScopes(): string[] {
const arg = deleteMany.mock.calls[0][0];
// Each OR clause is `{ action: { startsWith: "insights.<scope>-status." } }`.
@@ -80,5 +100,40 @@ describe("invalidateStatusInsightsForTypes", () => {
it("is a no-op for an empty type set (no DB call)", async () => {
await invalidateStatusInsightsForTypes("u1", []);
expect(deleteMany).not.toHaveBeenCalled();
expect(enqueueStatusGeneration).not.toHaveBeenCalled();
});
it("enqueues a debounced regenerate for every dirtied scope, the user's locale only", async () => {
userFindUnique.mockResolvedValue({ locale: "de" });
await invalidateStatusInsightsForTypes("u1", ["WEIGHT"]);
// weight + bmi + general, each warmed once for the user's resolved locale.
expect(enqueuedScopes()).toEqual(["bmi", "general", "weight"]);
expect(enqueueStatusGeneration).toHaveBeenCalledTimes(3);
const locales = new Set(
enqueueStatusGeneration.mock.calls.map(
(c) => (c[0] as { locale: string }).locale,
),
);
expect([...locales]).toEqual(["de"]);
});
it("resolves the user's locale (en) for the regenerate, never the unused one", async () => {
userFindUnique.mockResolvedValue({ locale: "en" });
await invalidateStatusInsightsForTypes("u1", ["WEIGHT"]);
const locales = new Set(
enqueueStatusGeneration.mock.calls.map(
(c) => (c[0] as { locale: string }).locale,
),
);
expect([...locales]).toEqual(["en"]);
});
it("does not blanket-evict general for an unrelated synced type", async () => {
// A steps sample touches only the general overview, never the weight /
// pulse / bp scopes — the constant Apple-Health sync must not thrash
// every card's cache.
await invalidateStatusInsightsForTypes("u1", ["ACTIVITY_STEPS"]);
expect(deletedScopes()).toEqual(["general"]);
expect(enqueuedScopes()).toEqual(["general"]);
});
});
@@ -2,7 +2,7 @@ import { describe, expect, it, vi, beforeEach } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
auditLog: { findFirst: vi.fn() },
auditLog: { findFirst: vi.fn(), findMany: vi.fn() },
},
}));
@@ -137,6 +137,11 @@ describe("readFreshStatusText", () => {
});
describe("resolveReadOnlyStatusMiss", () => {
beforeEach(() => {
// Default: no prior assessment to serve stale (readLastGoodStatusText).
vi.mocked(prisma.auditLog.findMany).mockResolvedValue([] as never);
});
it("returns no-provider without enqueuing when the user has no provider", async () => {
hasUsableStatusProvider.mockResolvedValue(false);
const outcome = await resolveReadOnlyStatusMiss({
@@ -144,7 +149,7 @@ describe("resolveReadOnlyStatusMiss", () => {
metric: "weight",
locale: "en",
});
expect(outcome).toBe("no-provider");
expect(outcome.kind).toBe("no-provider");
expect(enqueueStatusGeneration).not.toHaveBeenCalled();
});
@@ -157,7 +162,8 @@ describe("resolveReadOnlyStatusMiss", () => {
metric: "pulse",
locale: "de",
});
expect(outcome).toBe("preparing");
expect(outcome.kind).toBe("preparing");
expect(outcome).toEqual({ kind: "preparing", lastGood: null });
expect(enqueueStatusGeneration).toHaveBeenCalledWith({
userId: "u1",
metric: "pulse",
@@ -165,6 +171,28 @@ describe("resolveReadOnlyStatusMiss", () => {
});
});
it("serves the last good assessment stale-while-revalidate on a clean miss", async () => {
hasUsableStatusProvider.mockResolvedValue(true);
vi.mocked(prisma.auditLog.findFirst).mockResolvedValue(null as never);
// A prior (e.g. yesterday's) real assessment is on record.
vi.mocked(prisma.auditLog.findMany).mockResolvedValue([
cacheRow(
{ dateKey: "2026-05-30", text: "Steady upward trend.", model: "gpt-4o-mini" },
new Date("2026-05-30T04:30:00.000Z"),
),
] as never);
const outcome = await resolveReadOnlyStatusMiss({
userId: "u1",
metric: "weight",
locale: "en",
});
expect(outcome.kind).toBe("preparing");
if (outcome.kind !== "preparing") throw new Error("expected preparing");
expect(outcome.lastGood?.text).toBe("Steady upward trend.");
// A refresh is still enqueued behind the stale serve.
expect(enqueueStatusGeneration).toHaveBeenCalledTimes(1);
});
it("suppresses re-enqueue while a fresh timeout stub exists", async () => {
hasUsableStatusProvider.mockResolvedValue(true);
vi.mocked(prisma.auditLog.findFirst).mockResolvedValue(
@@ -180,7 +208,7 @@ describe("resolveReadOnlyStatusMiss", () => {
metric: "mood",
locale: "en",
});
expect(outcome).toBe("preparing");
expect(outcome.kind).toBe("preparing");
expect(enqueueStatusGeneration).not.toHaveBeenCalled();
});
@@ -199,7 +227,7 @@ describe("resolveReadOnlyStatusMiss", () => {
metric: "bmi",
locale: "de",
});
expect(outcome).toBe("preparing");
expect(outcome.kind).toBe("preparing");
expect(enqueueStatusGeneration).toHaveBeenCalledTimes(1);
});
});
+8 -5
View File
@@ -134,7 +134,7 @@ export async function generateBloodPressureStatusForUser(
metric: "blood-pressure",
locale,
});
if (outcome === "no-provider") {
if (outcome.kind === "no-provider") {
return {
hasProvider: false,
text: getNoKeyBloodPressureStatusText(locale),
@@ -142,12 +142,15 @@ export async function generateBloodPressureStatusForUser(
updatedAt: null,
};
}
// v1.8.7 — stale-while-revalidate: serve the last good assessment
// (if any) instantly while the worker re-warms; only fall to the empty
// preparing skeleton when none was ever produced.
return {
hasProvider: true,
text: null,
cached: false,
updatedAt: null,
preparing: true,
text: outcome.lastGood?.text ?? null,
cached: outcome.lastGood !== null,
updatedAt: outcome.lastGood?.updatedAt ?? null,
preparing: outcome.lastGood === null,
};
}
+8 -5
View File
@@ -72,7 +72,7 @@ export async function generateBmiStatusForUser(
metric: "bmi",
locale,
});
if (outcome === "no-provider") {
if (outcome.kind === "no-provider") {
return {
hasProvider: false,
text: getNoKeyBmiStatusText(locale),
@@ -80,12 +80,15 @@ export async function generateBmiStatusForUser(
updatedAt: null,
};
}
// v1.8.7 — stale-while-revalidate: serve the last good assessment
// (if any) instantly while the worker re-warms; only fall to the empty
// preparing skeleton when none was ever produced.
return {
hasProvider: true,
text: null,
cached: false,
updatedAt: null,
preparing: true,
text: outcome.lastGood?.text ?? null,
cached: outcome.lastGood !== null,
updatedAt: outcome.lastGood?.updatedAt ?? null,
preparing: outcome.lastGood === null,
};
}
@@ -47,6 +47,8 @@ import {
runRawCompletionWithFallback,
} from "@/lib/ai/provider-runner";
import { invalidateUserInsights } from "@/lib/cache/invalidate";
import { enqueueStatusGeneration } from "@/lib/jobs/insight-status-generate-shared";
import { normalizeLocale } from "@/lib/insights/status-shared";
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
@@ -231,6 +233,31 @@ export async function invalidateStatusInsightsForTypes(
})),
},
});
// v1.8.7 — regenerate-on-invalidate. Deleting the today-row alone left
// the card to re-warm only on the user's next category open (a miss → a
// worker round-trip while they wait) or the nightly cron. Instead,
// proactively enqueue a debounced regenerate for each dirtied scope so
// the cache is re-warmed in the background. The enqueue is coalesced per
// `(user, metric, locale)` via the queue's `singletonKey` (120 s window),
// so the constant Apple-Health sync cannot fan out a storm of jobs — a
// burst of samples collapses into one regenerate per scope.
// The stale-while-revalidate read keeps the previous assessment visible
// until the fresh one lands, so the user never waits on a card.
//
// v1.8.7 — regenerate only the user's resolved locale, matching the
// read-path (every `*-status` GET serves `normalizeLocale(user.locale)`).
// Warming both locales doubled provider spend on every sync, half of it
// for a language the user never opens. The nightly warm pass still covers
// both locales for the rare locale switch.
const localeRow = await prisma.user.findUnique({
where: { id: userId },
select: { locale: true },
});
const locale = normalizeLocale(localeRow?.locale);
for (const scope of scopes) {
void enqueueStatusGeneration({ userId, metric: scope, locale });
}
}
interface GenerateOptions {
+8 -5
View File
@@ -87,7 +87,7 @@ export async function generateGeneralStatusForUser(
metric: "general",
locale,
});
if (outcome === "no-provider") {
if (outcome.kind === "no-provider") {
return {
hasProvider: false,
text: getNoKeyGeneralStatusText(locale),
@@ -95,12 +95,15 @@ export async function generateGeneralStatusForUser(
updatedAt: null,
};
}
// v1.8.7 — stale-while-revalidate: serve the last good assessment
// (if any) instantly while the worker re-warms; only fall to the empty
// preparing skeleton when none was ever produced.
return {
hasProvider: true,
text: null,
cached: false,
updatedAt: null,
preparing: true,
text: outcome.lastGood?.text ?? null,
cached: outcome.lastGood !== null,
updatedAt: outcome.lastGood?.updatedAt ?? null,
preparing: outcome.lastGood === null,
};
}
@@ -121,7 +121,7 @@ export async function generateMedicationComplianceStatusForUser(
metric: "medication-compliance",
locale,
});
if (outcome === "no-provider") {
if (outcome.kind === "no-provider") {
return {
hasProvider: false,
summary: getNoKeyMedicationComplianceStatusText(locale),
@@ -130,13 +130,16 @@ export async function generateMedicationComplianceStatusForUser(
updatedAt: null,
};
}
// v1.8.7 — stale-while-revalidate: serve the last good narrative (if
// any) while the worker re-warms; only show the empty preparing
// skeleton when none was ever produced.
return {
hasProvider: true,
summary: null,
summary: outcome.lastGood?.text ?? null,
medications: [],
cached: false,
updatedAt: null,
preparing: true,
cached: outcome.lastGood !== null,
updatedAt: outcome.lastGood?.updatedAt ?? null,
preparing: outcome.lastGood === null,
};
}
+8 -5
View File
@@ -83,7 +83,7 @@ export async function generateMoodStatusForUser(
metric: "mood",
locale,
});
if (outcome === "no-provider") {
if (outcome.kind === "no-provider") {
return {
hasProvider: false,
text: getNoKeyMoodStatusText(locale),
@@ -91,12 +91,15 @@ export async function generateMoodStatusForUser(
updatedAt: null,
};
}
// v1.8.7 — stale-while-revalidate: serve the last good assessment
// (if any) instantly while the worker re-warms; only fall to the empty
// preparing skeleton when none was ever produced.
return {
hasProvider: true,
text: null,
cached: false,
updatedAt: null,
preparing: true,
text: outcome.lastGood?.text ?? null,
cached: outcome.lastGood !== null,
updatedAt: outcome.lastGood?.updatedAt ?? null,
preparing: outcome.lastGood === null,
};
}
+8 -5
View File
@@ -78,7 +78,7 @@ export async function generatePulseStatusForUser(
metric: "pulse",
locale,
});
if (outcome === "no-provider") {
if (outcome.kind === "no-provider") {
return {
hasProvider: false,
text: getNoKeyPulseStatusText(locale),
@@ -86,12 +86,15 @@ export async function generatePulseStatusForUser(
updatedAt: null,
};
}
// v1.8.7 — stale-while-revalidate: serve the last good assessment (if
// any) instantly while the worker re-warms the cache; only fall to the
// empty preparing skeleton when none was ever produced.
return {
hasProvider: true,
text: null,
cached: false,
updatedAt: null,
preparing: true,
text: outcome.lastGood?.text ?? null,
cached: outcome.lastGood !== null,
updatedAt: outcome.lastGood?.updatedAt ?? null,
preparing: outcome.lastGood === null,
};
}
+65 -6
View File
@@ -101,13 +101,62 @@ export async function readFreshStatusText(args: {
}
}
export interface LastGoodStatusHit {
text: string;
updatedAt: string;
}
/**
* v1.8.7 — read the most recent NON-stub assessment for `(userId,
* cacheAction)` regardless of which day it was generated. This is the
* stale-while-revalidate source: when today's cache is a miss the
* read-only path can still serve yesterday's (or older) good text
* instantly while a fresh generation is warmed out of band, so opening a
* category never drops to the "preparing" skeleton if an assessment was
* ever produced. Returns `null` only when there is genuinely no prior
* assessment (or every prior row is a timeout stub / malformed).
*/
export async function readLastGoodStatusText(args: {
userId: string;
cacheAction: string;
}): Promise<LastGoodStatusHit | null> {
const { userId, cacheAction } = args;
const rows = await prisma.auditLog.findMany({
where: { userId, action: cacheAction },
orderBy: { createdAt: "desc" },
take: 5,
select: { createdAt: true, details: true },
});
for (const row of rows) {
if (!row.details) continue;
try {
const parsed = JSON.parse(row.details) as ParsedStatusCache;
if (isTimeoutStub(parsed)) continue;
if (typeof parsed.text !== "string" || parsed.text.trim().length === 0) {
continue;
}
return { text: parsed.text, updatedAt: row.createdAt.toISOString() };
} catch {
// Malformed payload — skip and look further back.
continue;
}
}
return null;
}
/**
* Outcome of the read-only cache-miss resolution. The generators map this
* onto their public return shape:
* - `no-provider` → `{ hasProvider: false, text: <no-key fallback> }`
* - `preparing` → `{ hasProvider: true, text: null, preparing: true }`
* - `preparing` → `{ hasProvider: true, text: <last-good|null>, preparing: true }`
*
* v1.8.7 — `preparing` now carries the last good assessment (if any) so
* the card renders the previous text immediately (stale-while-revalidate)
* instead of a skeleton while the worker re-warms the cache.
*/
export type ReadOnlyMissOutcome = "no-provider" | "preparing";
export type ReadOnlyMissOutcome =
| { kind: "no-provider" }
| { kind: "preparing"; lastGood: LastGoodStatusHit | null };
/**
* v1.8.3 — resolve what a read-only status generation should return on a
@@ -131,10 +180,20 @@ export async function resolveReadOnlyStatusMiss(args: {
locale: "de" | "en";
}): Promise<ReadOnlyMissOutcome> {
const hasProvider = await hasUsableStatusProvider(args.userId);
if (!hasProvider) return "no-provider";
if (!hasProvider) return { kind: "no-provider" };
const cacheAction = `insights.${args.metric}-status.${args.locale}`;
// v1.8.7 — stale-while-revalidate. Surface the last good (non-stub)
// assessment for this scope so the card renders the previous text
// immediately instead of a skeleton while a refresh is warmed. Null when
// no assessment was ever produced — only then does the card show
// "preparing"/"no analysis yet".
const lastGood = await readLastGoodStatusText({
userId: args.userId,
cacheAction,
});
// v1.8.3 — honour the short-TTL negative cache. If the worker recently
// hit a provider stall it wrote a `retryAt` stub; re-enqueuing on every
// navigation while the provider is still degraded would be a storm. While
@@ -145,7 +204,7 @@ export async function resolveReadOnlyStatusMiss(args: {
action: { name: "insights.status.preparing" },
meta: { metric: args.metric, suppressed_enqueue: true },
});
return "preparing";
return { kind: "preparing", lastGood };
}
// Enqueue out of band — do NOT await an LLM here. The enqueue itself is
@@ -157,9 +216,9 @@ export async function resolveReadOnlyStatusMiss(args: {
});
annotate({
action: { name: "insights.status.preparing" },
meta: { metric: args.metric },
meta: { metric: args.metric, stale_served: lastGood !== null },
});
return "preparing";
return { kind: "preparing", lastGood };
}
/**
+8 -5
View File
@@ -132,7 +132,7 @@ export async function generateWeightStatusForUser(
metric: "weight",
locale,
});
if (outcome === "no-provider") {
if (outcome.kind === "no-provider") {
return {
hasProvider: false,
text: getNoKeyWeightStatusText(locale),
@@ -140,12 +140,15 @@ export async function generateWeightStatusForUser(
updatedAt: null,
};
}
// v1.8.7 — stale-while-revalidate: serve the last good assessment
// (if any) instantly while the worker re-warms; only fall to the empty
// preparing skeleton when none was ever produced.
return {
hasProvider: true,
text: null,
cached: false,
updatedAt: null,
preparing: true,
text: outcome.lastGood?.text ?? null,
cached: outcome.lastGood !== null,
updatedAt: outcome.lastGood?.updatedAt ?? null,
preparing: outcome.lastGood === null,
};
}