Merge branch 'release/v1.47.3' into release/v1.47.4

# Conflicts:
#	src/__tests__/baselines/source-file-lines.json
#	src/__tests__/baselines/source-function-lines.json
#	src/__tests__/baselines/test-as-never.json
#	src/__tests__/baselines/version-stamp-comments.json
This commit is contained in:
Marc-André Bombeck committed 2026-11-12 13:27:52 +01:00
commit 031379d966
384 files changed
+7908 -5710

No files matched your search

+7 -1
View File
@@ -37,6 +37,8 @@ import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { generateTotpSecret, buildOtpauthUri } from "@/lib/auth/mfa/totp";
import { checkCookieEnrollmentProof } from "@/lib/auth/existing-factor-proof";
const TOTP_ALREADY_ACTIVE_CODE = "auth.mfa.already_active";
export const dynamic = "force-dynamic";
const SETUP_RATE_LIMIT = 5;
@@ -64,7 +66,11 @@ export const POST = apiHandler(async (req: Request) => {
// live secret out from under the user's authenticator.
if (user.totpConfirmedAt) {
annotate({ action: { name: "auth.mfa.totp.setup.already_active" } });
throw new HttpError(409, "A second factor is already active");
throw new HttpError(
409,
"A second factor is already active",
TOTP_ALREADY_ACTIVE_CODE,
);
}
if (auth.transport === "cookie") {
@@ -6,6 +6,7 @@ import {
import { createMfaAuthenticationOptions } from "@/lib/auth/mfa/webauthn";
import {
RECENT_PROOF_MAX_AGE_MS,
REPROOF_FAILED_CODE,
REPROOF_REQUIRED_CODE,
isSecondFactorProof,
recordReproofFailure,
@@ -29,8 +30,12 @@ import { apiHandler, requireCookieAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { stepUpMintSchema } from "@/lib/validations/step-up";
// A wrong or missing proof, not an ended session: the code keeps the web from
// reading the bare 401 as "sign in again".
const proofRequired = () =>
apiError("Fresh existing-factor proof required", 401);
apiError("Fresh existing-factor proof required", 401, {
errorCode: REPROOF_FAILED_CODE,
});
export const POST = apiHandler(async (request: NextRequest) => {
const { user, session } = await requireCookieAuth();
@@ -13,6 +13,7 @@ import {
import { NextRequest } from "next/server";
import { apiHandler, requireCookieAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { REPROOF_FAILED_CODE } from "@/lib/auth/existing-factor-proof";
export const POST = apiHandler(async (request: NextRequest) => {
const { user, session } = await requireCookieAuth();
@@ -40,7 +41,9 @@ export const POST = apiHandler(async (request: NextRequest) => {
(freshSession.mfaVerifiedAt &&
freshSession.mfaVerifiedAt.getTime() < Date.now() - 5 * 60 * 1000)
) {
return apiError("Fresh reauthentication proof required", 401);
return apiError("Fresh reauthentication proof required", 401, {
errorCode: REPROOF_FAILED_CODE,
});
}
const claim = await consumeRegistrationChallenge({
@@ -49,12 +52,11 @@ export const POST = apiHandler(async (request: NextRequest) => {
sessionId: session.id,
});
if (!claim.ok) {
return apiError(
claim.reason === "wrong_context"
? "Fresh reauthentication proof required"
: "Registration challenge invalid or expired",
claim.reason === "wrong_context" ? 401 : 400,
);
return claim.reason === "wrong_context"
? apiError("Fresh reauthentication proof required", 401, {
errorCode: REPROOF_FAILED_CODE,
})
: apiError("Registration challenge invalid or expired", 400);
}
let verification;
+1
View File
@@ -126,6 +126,7 @@ export const DELETE = apiHandler(
return apiError(
"Cannot delete. At least one authentication method must remain",
400,
{ errorCode: "auth.passkey.last_method" },
);
}
+4 -1
View File
@@ -40,6 +40,7 @@ import {
rateLimitHeaders,
} from "@/lib/rate-limit";
import {
REPROOF_FAILED_CODE,
REPROOF_LIMIT,
REPROOF_WINDOW_MS,
reproofBucket,
@@ -132,7 +133,9 @@ export const POST = apiHandler(async (request: NextRequest) => {
action: { name: "auth.stepup.mint.failed" },
meta: { method: parsed.data.method, reason: failure },
});
return apiError("Verification failed", 401);
return apiError("Verification failed", 401, {
errorCode: REPROOF_FAILED_CODE,
});
}
const { token, expiresAt } = await mintStepUpElevation({
@@ -225,6 +225,7 @@ describe("PATCH /api/custom-metrics/[id]", () => {
const res = await PATCH(patchReq({ name: "Other" }), params("cm-1"));
expect(res.status).toBe(409);
expect((await res.json()).meta.errorCode).toBe("customMetric.name_taken");
expect(prisma.customMetric.update).not.toHaveBeenCalled();
});
});
+3 -1
View File
@@ -111,7 +111,9 @@ export const PATCH = apiHandler(
select: { id: true },
});
if (clash) {
return apiError("A custom metric with this name already exists", 409);
return apiError("A custom metric with this name already exists", 409, {
errorCode: "customMetric.name_taken",
});
}
}
@@ -134,6 +134,9 @@ describe("POST /api/custom-metrics", () => {
const res = await POST(postReq({ name: "Grip strength", unit: "kg" }));
expect(res.status).toBe(409);
// The form names the clash by this code: a 409 without it can be the
// first save still running under the same key.
expect((await res.json()).meta.errorCode).toBe("customMetric.name_taken");
expect(prisma.customMetric.create).not.toHaveBeenCalled();
});
+3 -1
View File
@@ -100,7 +100,9 @@ async function postCustomMetric(request: NextRequest) {
select: { id: true, deletedAt: true },
});
if (existing && existing.deletedAt === null) {
return apiError("A custom metric with this name already exists", 409);
return apiError("A custom metric with this name already exists", 409, {
errorCode: "customMetric.name_taken",
});
}
// Field-by-field assignment — never spread `parsed.data`.
+16 -5
View File
@@ -19,7 +19,7 @@ import { prisma } from "@/lib/db";
import { summarize, type DataPoint } from "@/lib/analytics/trends";
import { probeRollupCoverage } from "@/lib/rollups/measurement-coverage";
import { readDayMeanSeries } from "@/lib/insights/derived/baseline";
import { getBpTargets } from "@/lib/analytics/bp-targets";
import { resolveEffectiveBpTargets } from "@/lib/analytics/effective-range";
import { isBpReadingInTarget } from "@/lib/analytics/bp-in-target";
import {
generateAlerts,
@@ -72,6 +72,17 @@ interface InsightCard {
export const dynamic = "force-dynamic";
/**
* The profile fields BMI and the BP band read: the person's own BP target
* where one is set, the age default otherwise.
*/
const PROFILE_SELECT = {
heightCm: true,
dateOfBirth: true,
gender: true,
thresholdsJson: true,
} as const;
export const GET = apiHandler(async () => {
// v1.37.0 — MANAGE-level read: computed over the whole record, with no
// provider anywhere on the path.
@@ -85,7 +96,7 @@ export const GET = apiHandler(async () => {
await Promise.all([
prisma.user.findUnique({
where: { id: user.id },
select: { heightCm: true, dateOfBirth: true },
select: PROFILE_SELECT,
}),
// WEIGHT + BP are manual entries (low volume, and BP needs exact-
// timestamp pairing below for `bpPctInTarget`), so a bounded raw read
@@ -168,14 +179,14 @@ export const GET = apiHandler(async () => {
}
let bpPctInTarget: number | null = null;
const bpTargets = getBpTargets(dbUser?.dateOfBirth ?? null);
const bpTargets =
dbUser && resolveEffectiveBpTargets(dbUser, dbUser.thresholdsJson);
if (bpTargets) {
const sysData = byType("BLOOD_PRESSURE_SYS");
const diaData = byType("BLOOD_PRESSURE_DIA");
const pairs = pairByTimestamp(sysData, diaData, 5 * 60_000);
if (pairs.length > 0) {
// v1.4.16 — one-sided ceiling semantics with hypotension
// floor. See lib/analytics/bp-in-target.ts.
// One-sided ceiling with a hypotension floor (`bp-in-target.ts`).
const inTarget = pairs.filter((p) =>
isBpReadingInTarget(p.a, p.b, bpTargets),
).length;
@@ -4715,7 +4715,7 @@ exports[`coach chat golden transcripts > 15 an unknown learn link is scrubbed, a
}
`;
exports[`coach chat golden transcripts > 16a coach.provider.none via an empty chain and no legacy provider 1`] = `
exports[`coach chat golden transcripts > 16a coach.provider.none via an empty chain 1`] = `
{
"body": null,
"calls": [
@@ -4757,342 +4757,6 @@ exports[`coach chat golden transcripts > 16a coach.provider.none via an empty ch
}
`;
exports[`coach chat golden transcripts > 16b an empty chain served by the legacy provider 1`] = `
{
"body": null,
"calls": [
{
"call": "createConversation",
},
{
"call": "appendMessage",
"content": "How is my blood pressure?",
"metricSource": null,
"model": null,
"providerType": null,
"role": "user",
"tokensUsed": null,
},
{
"call": "storeDeterministicFacts",
},
{
"call": "enqueueCoachMemoryRefresh",
},
{
"call": "assertConsentForChain",
"chain": [
"admin-openai",
],
},
{
"amount": 600,
"call": "reserveBudget",
"cap": 2000000,
"dateKey": "2026-09-26",
"owner": "user",
"surface": "coach",
},
{
"call": "runStreamingRawCompletionWithFallback",
"maxTokens": 600,
"messages": [
"user:70927bca288b:747",
],
"providers": [
"admin-openai",
],
"signal": true,
"surface": "coach",
"system": "af01480eff5e:1404",
"temperature": 0.4,
"timeoutMs": 180000,
},
{
"call": "annotate",
"metaKeys": [
"deltas",
],
"name": "coach.stream.deltas",
},
{
"actual": 42,
"attribution": {
"reservedOwner": "user",
"servedBy": "local",
},
"cached": 5,
"call": "reconcileSpend",
"dateKey": "2026-09-26",
"reserved": 600,
},
{
"call": "appendMessage",
"content": "Your systolic averaged 128 mmHg over the window.",
"metricSource": {
"activity": [
{
"count": 1,
"durationMs": 0,
"id": "a1",
"label": "Reading your record summary",
"labelKey": "coach.step.snapshot",
"phase": "fetch",
"round": 1,
"status": "done",
"stepRef": "s1",
},
{
"durationMs": 0,
"id": "a2",
"label": "Thinking…",
"labelKey": "insights.coach.activity.thinking",
"phase": "thinking",
"round": 1,
"status": "done",
},
{
"id": "a3",
"label": "Writing the answer…",
"labelKey": "insights.coach.activity.answer",
"phase": "answer",
"round": 1,
"status": "done",
},
],
"groundedFigures": [
128,
82,
46,
105,
35.9375,
56.09756097560976,
],
"metrics": [
"bp",
],
"steps": [
{
"count": 1,
"domain": "snapshot",
"id": "s1",
"label": "Reading your record summary",
"labelKey": "coach.step.snapshot",
"status": "done",
"tool": "snapshot",
},
],
"windows": [
"last30days",
],
},
"model": "m-local",
"providerType": "local",
"role": "assistant",
"tokensUsed": 42,
},
{
"call": "annotate",
"metaKeys": [
"activityEntries",
"clusterCount",
"conversationId",
"historyTurns",
"promptChars",
"promptVersion",
"provider",
"snapshotSent",
"stop",
"tokens",
"toolMode",
"toolsCalled",
"trailStored",
],
"name": "insights.coach.replied",
},
],
"contentType": "text/event-stream; charset=utf-8",
"frames": [
{
"step": {
"count": 1,
"domain": "snapshot",
"id": "s1",
"label": "Reading your record summary",
"labelKey": "coach.step.snapshot",
"status": "done",
"tool": "snapshot",
},
"type": "step",
},
{
"activity": {
"count": 1,
"id": "a1",
"label": "Reading your record summary",
"labelKey": "coach.step.snapshot",
"phase": "fetch",
"round": 1,
"status": "running",
"stepRef": "s1",
},
"type": "activity",
},
{
"activity": {
"count": 1,
"durationMs": 0,
"id": "a1",
"label": "Reading your record summary",
"labelKey": "coach.step.snapshot",
"phase": "fetch",
"round": 1,
"status": "done",
"stepRef": "s1",
},
"type": "activity",
},
{
"activity": {
"id": "a2",
"label": "Thinking…",
"labelKey": "insights.coach.activity.thinking",
"phase": "thinking",
"round": 1,
"status": "running",
},
"type": "activity",
},
{
"activity": {
"durationMs": 0,
"id": "a2",
"label": "Thinking…",
"labelKey": "insights.coach.activity.thinking",
"phase": "thinking",
"round": 1,
"status": "done",
},
"type": "activity",
},
{
"activity": {
"id": "a3",
"label": "Writing the answer…",
"labelKey": "insights.coach.activity.answer",
"phase": "answer",
"round": 1,
"status": "running",
},
"type": "activity",
},
{
"token": "Your ",
"type": "token",
},
{
"token": "systolic ",
"type": "token",
},
{
"token": "averaged ",
"type": "token",
},
{
"token": "128 ",
"type": "token",
},
{
"token": "mmHg ",
"type": "token",
},
{
"token": "over ",
"type": "token",
},
{
"token": "the ",
"type": "token",
},
{
"token": "window.",
"type": "token",
},
{
"metricSource": {
"activity": [
{
"count": 1,
"durationMs": 0,
"id": "a1",
"label": "Reading your record summary",
"labelKey": "coach.step.snapshot",
"phase": "fetch",
"round": 1,
"status": "done",
"stepRef": "s1",
},
{
"durationMs": 0,
"id": "a2",
"label": "Thinking…",
"labelKey": "insights.coach.activity.thinking",
"phase": "thinking",
"round": 1,
"status": "done",
},
{
"id": "a3",
"label": "Writing the answer…",
"labelKey": "insights.coach.activity.answer",
"phase": "answer",
"round": 1,
"status": "done",
},
],
"groundedFigures": [
128,
82,
46,
105,
35.9375,
56.09756097560976,
],
"metrics": [
"bp",
],
"steps": [
{
"count": 1,
"domain": "snapshot",
"id": "s1",
"label": "Reading your record summary",
"labelKey": "coach.step.snapshot",
"status": "done",
"tool": "snapshot",
},
],
"windows": [
"last30days",
],
},
"type": "provenance",
},
{
"conversationId": "c-new",
"messageId": "m2",
"type": "done",
"usage": {
"model": "m-local",
"totalTokens": 42,
},
},
],
"status": 200,
"thrown": null,
}
`;
exports[`coach chat golden transcripts > 16c coach.provider.none from the capability gate 1`] = `
{
"body": null,
@@ -119,7 +119,6 @@ export const m = {
resolveServerLocale: vi.fn(),
runStreamingRawCompletionWithFallback: vi.fn(),
resolveProviderChain: vi.fn(),
resolveProvider: vi.fn(),
assertConsentForChain: vi.fn(),
appendMessage: vi.fn(),
createConversation: vi.fn(),
@@ -201,7 +200,6 @@ export function resetGolden(): void {
m.resolveProviderChain.mockResolvedValue([
{ providerType: "anthropic", instance: {} },
]);
m.resolveProvider.mockResolvedValue({ type: "none" });
m.assertConsentForChain.mockImplementation(
async (args: { chain: Array<{ providerType: string }> }) => {
record("assertConsentForChain", {
@@ -81,7 +81,6 @@ vi.mock("@/lib/ai/provider-runner", () => ({
}));
vi.mock("@/lib/ai/provider", () => ({
resolveProviderChain: h.m.resolveProviderChain,
resolveProvider: h.m.resolveProvider,
}));
vi.mock("@/lib/ai/consent-guard", () => ({
assertConsentForChain: h.m.assertConsentForChain,
@@ -416,21 +415,8 @@ describe("coach chat golden transcripts", () => {
});
// 16 ── no provider ──────────────────────────────────────────────────────
it("16a coach.provider.none via an empty chain and no legacy provider", async () => {
it("16a coach.provider.none via an empty chain", async () => {
m.resolveProviderChain.mockResolvedValue([]);
m.resolveProvider.mockResolvedValue({ type: "none" });
await golden({ message: "How is my blood pressure?" });
});
it("16b an empty chain served by the legacy provider", async () => {
m.resolveProviderChain.mockResolvedValue([]);
m.resolveProvider.mockResolvedValue({
type: "openai",
supportsTools: false,
});
m.runStreamingRawCompletionWithFallback.mockImplementation(
streamingResult("Your systolic averaged 128 mmHg over the window."),
);
await golden({ message: "How is my blood pressure?" });
});
@@ -93,11 +93,7 @@ vi.mock("@/lib/ai/provider", async () => {
);
return {
...actual,
resolveProvider: vi.fn(),
// v1.4.16: the route consults the multi-provider chain
// first; the existing single-provider mocks return an empty chain
// so the route falls through to `resolveProvider()` and the legacy
// test fixtures keep behaving exactly as before.
// Empty unless a test hands the route a provider (`serveFrom`).
resolveProviderChain: vi.fn(async () => []),
};
});
@@ -167,7 +163,7 @@ import { NextRequest } from "next/server";
import { GET, POST, resolveInsightsRateLimit } from "../route";
import { enqueueStatusRefillForUser } from "@/lib/insights/comprehensive-generate";
import { resolveProvider } from "@/lib/ai/provider";
import { resolveProviderChain } from "@/lib/ai/provider";
import { checkRateLimit } from "@/lib/rate-limit";
import { prisma } from "@/lib/db";
import { hasUsableStatusProvider } from "@/lib/insights/status-provider";
@@ -214,8 +210,17 @@ beforeEach(() => {
});
});
type ChainEntries = Awaited<ReturnType<typeof resolveProviderChain>>;
/** The chain the route resolves: one operator-key entry serving `instance`. */
function serveFrom(instance: unknown) {
vi.mocked(resolveProviderChain).mockResolvedValue([
{ providerType: "admin-openai", instance },
] as unknown as ChainEntries);
}
function makeWorkingProvider() {
vi.mocked(resolveProvider).mockResolvedValue({
serveFrom({
type: "openai",
generateCompletion: vi.fn(async () => ({
content: JSON.stringify({
@@ -230,7 +235,7 @@ function makeWorkingProvider() {
providerType: "openai",
model: "gpt-4",
})),
} as unknown as Awaited<ReturnType<typeof resolveProvider>>);
});
}
interface ApiErrorEnvelope {
@@ -253,13 +258,12 @@ function jsonRequest(body: unknown = {}): Request {
function makeProviderThatThrows(
err: Error & { httpStatus?: number; bodyExcerpt?: string },
) {
vi.mocked(resolveProvider).mockResolvedValue({
serveFrom({
type: "openai",
generateCompletion: vi.fn(async () => {
throw err;
}),
// The route only calls generateCompletion; pad the type for TS.
} as unknown as Awaited<ReturnType<typeof resolveProvider>>);
});
}
describe("POST /api/insights/generate — daily token ceiling", () => {
@@ -314,7 +318,8 @@ describe("POST /api/insights/generate — a provider the health ledger benched",
httpStatus: 401,
});
makeProviderThatThrows(err);
const provider = await vi.mocked(resolveProvider)("u-1");
const [{ instance: provider }] =
await vi.mocked(resolveProviderChain)("u-1");
const body = JSON.stringify({ force: true });
const request = new NextRequest("http://localhost/api/insights/generate", {
method: "POST",
@@ -894,7 +899,7 @@ describe("GET /api/insights/generate — read-only advisor read", () => {
expect(body.data.cached).toBe(true);
expect(body.data.insights).toEqual(cached);
// No completion is ever run on the read path.
expect(resolveProvider).not.toHaveBeenCalled();
expect(resolveProviderChain).not.toHaveBeenCalled();
// A fresh cache (just now) does not trigger a warm — and the payload
// says so, so the client never starts a convergence poll.
expect(enqueueForceWarm).not.toHaveBeenCalled();
@@ -919,7 +924,7 @@ describe("GET /api/insights/generate — read-only advisor read", () => {
userId: "u-1",
locale: "en",
});
expect(resolveProvider).not.toHaveBeenCalled();
expect(resolveProviderChain).not.toHaveBeenCalled();
// The stale serve is honest: `revalidating: true` rides on the
// payload so the client polls (bounded) until the warm lands.
const body = (await res.json()) as { data: { revalidating: boolean } };
@@ -953,7 +958,7 @@ describe("GET /api/insights/generate — read-only advisor read", () => {
userId: "u-1",
locale: "en",
});
expect(resolveProvider).not.toHaveBeenCalled();
expect(resolveProviderChain).not.toHaveBeenCalled();
});
it("serves a fresh cache whose tag matches the reader's language", async () => {
@@ -48,6 +48,7 @@ export const GET = apiHandler(async () => {
biomarkerId: true,
unit: true,
value: true,
sourceValue: true,
referenceLow: true,
referenceHigh: true,
sourceReferenceLow: true,
@@ -65,6 +66,7 @@ export const GET = apiHandler(async () => {
biomarkerId: r.biomarkerId,
unit: r.unit,
value: r.value as number,
sourceValue: r.sourceValue,
referenceLow: r.referenceLow,
referenceHigh: r.referenceHigh,
sourceReferenceLow: r.sourceReferenceLow,
@@ -238,6 +238,48 @@ describe("PUT /api/insights/provider-chain", () => {
]);
});
it("drops the effort of a gateway the person switches off", async () => {
// A disabled gateway entry with an effort is the gateway form's holder,
// which the picked gateway still serves behind; a switch-off is not.
storedChain([
{
providerType: "openai-compatible",
priority: 1,
enabled: true,
reasoningEffort: "low",
},
]);
await put([{ providerType: "openai-compatible", enabled: false }]);
expect(persisted()).toEqual([
{ providerType: "openai-compatible", priority: 1, enabled: false },
]);
});
it("keeps the holder's effort when the chain is saved around it", async () => {
storedChain([
{ providerType: "local", priority: 1, enabled: true },
{
providerType: "openai-compatible",
priority: 2,
enabled: false,
reasoningEffort: "low",
},
]);
await put([
{ providerType: "openai-compatible", enabled: false },
{ providerType: "local", enabled: true },
]);
expect(persisted()).toEqual([
{
providerType: "openai-compatible",
priority: 1,
enabled: false,
reasoningEffort: "low",
},
{ providerType: "local", priority: 2, enabled: true },
]);
});
it("clears it on null", async () => {
storedChain([
{
+19 -9
View File
@@ -118,18 +118,28 @@ export const PUT = apiHandler(async (request: NextRequest) => {
where: { id: user.id },
select: { aiProviderChain: true },
});
const storedChain = parseProviderChain(stored?.aiProviderChain ?? null);
const storedEffort = new Map(
parseProviderChain(stored?.aiProviderChain ?? null).map((e) => [
e.providerType,
e.reasoningEffort ?? null,
]),
storedChain.map((e) => [e.providerType, e.reasoningEffort ?? null]),
);
// A disabled gateway entry with an effort is the holder the gateway form
// writes, which the picked gateway still serves behind
// (`servesPickedGateway`). Switching the gateway off here is the person's
// word, so its effort goes with the switch.
const gatewayWasOn =
storedChain.find((e) => e.providerType === "openai-compatible")?.enabled !==
false;
const normalised = parsed.data.chain.map((entry, idx) => {
const reasoningEffort = isReasoningProviderType(entry.providerType)
? entry.reasoningEffort === undefined
? (storedEffort.get(entry.providerType) ?? null)
: entry.reasoningEffort
: null;
const switchedOff =
entry.providerType === "openai-compatible" &&
!entry.enabled &&
gatewayWasOn;
const reasoningEffort =
!isReasoningProviderType(entry.providerType) || switchedOff
? null
: entry.reasoningEffort === undefined
? (storedEffort.get(entry.providerType) ?? null)
: entry.reasoningEffort;
return {
providerType: entry.providerType,
priority: idx + 1,
+4 -3
View File
@@ -15,9 +15,10 @@ import { buildTargetsResponse } from "@/lib/targets/build-response";
export const dynamic = "force-dynamic";
export const GET = apiHandler(async () => {
// v1.37.0 — MANAGE-level read: computed over the whole record, with no
// provider anywhere on the path.
const { user } = await requireRecordAuth("manage", "record");
// A read of the whole record, with no provider anywhere on the path, at the
// level the dashboard snapshot answers: the weight band and the BMI chart
// read it inside a shared record, and a read or write grant got a 403.
const { user } = await requireRecordAuth("read", "record");
// v1.16.8 — stale-while-revalidate read. The cold build is the multi-query
// walk in `buildTargetsResponse`; past the 60 s fresh TTL the prior body
// serves immediately while ONE background rebuild warms the cell. Writes
@@ -156,6 +156,18 @@ describe("POST /api/measurements/bulk-delete", () => {
});
});
it("leaves a computed score out of the selection it deletes", async () => {
// The read is scoped like the write, so a computed row never reaches it.
vi.mocked(prisma.measurement.findMany).mockResolvedValue([]);
vi.mocked(prisma.measurement.updateMany).mockResolvedValue({ count: 0 });
await POST(postReq({ ids: ["score-1"] }));
expect(
vi.mocked(prisma.measurement.findMany).mock.calls[0][0]?.where,
).toMatchObject({ source: { not: "COMPUTED" } });
});
it("collapses the rollup recompute to the unique (type, day) set, not per-row", async () => {
// 4 deleted rows: 2× WEIGHT on the same UTC day, 1× WEIGHT next day,
// 1× PULSE same day as the first → 3 distinct (type, day) keys.
@@ -81,9 +81,17 @@ async function postBulkDelete(request: NextRequest): Promise<Response> {
// other half and the cuff's pulse, `bloodPressureSiblings`) into the same
// statement, so the shared `deletedAt` lets the restore route bring the
// reading back whole.
//
// A computed score (recovery, strain, stress) is skipped: the server
// rewrites it from its inputs, and a tombstone kept the recompute out.
const { affected, count } = await prisma.$transaction(async (tx) => {
const selected = await tx.measurement.findMany({
where: { id: { in: ids }, userId: user.id, deletedAt: null },
where: {
id: { in: ids },
userId: user.id,
deletedAt: null,
source: { not: "COMPUTED" },
},
select: { id: true, type: true, source: true, measuredAt: true },
});
const siblings = await bloodPressureSiblings(tx, user.id, selected, "live");
@@ -51,7 +51,6 @@ vi.mock("@/lib/ai/coach/budget", () => ({
}));
vi.mock("@/lib/ai/provider", () => ({
resolveProvider: vi.fn(async () => ({ type: "none" })),
resolveProviderChain: vi.fn(async () => []),
}));
@@ -82,7 +81,7 @@ import {
reconcileSpend,
resolveDailyCap,
} from "@/lib/ai/coach/budget";
import { resolveProvider, resolveProviderChain } from "@/lib/ai/provider";
import { resolveProviderChain } from "@/lib/ai/provider";
import {
runRawCompletionWithFallback,
AllProvidersFailedError,
@@ -382,9 +381,6 @@ describe("POST /api/medications/extract — validation + provider errors", () =>
it("returns 503 when no provider is configured for the user", async () => {
vi.mocked(requireAuth).mockResolvedValue(AUTH_OK as never);
vi.mocked(resolveProviderChain).mockResolvedValueOnce([]);
vi.mocked(resolveProvider).mockResolvedValueOnce({
type: "none",
} as never);
// The status stays 503 (a shipped client may branch on it) and gains the
// code that says what it means.
+8 -12
View File
@@ -72,7 +72,7 @@ import {
runRawCompletionWithFallback,
} from "@/lib/ai/provider-runner";
import { spentOnFailure } from "@/lib/ai/reasoning/answerless";
import { resolveProvider, resolveProviderChain } from "@/lib/ai/provider";
import { resolveProviderChain } from "@/lib/ai/provider";
import { singleUserTurn } from "@/lib/ai/types";
import {
@@ -198,17 +198,13 @@ async function handleExtract(request: NextRequest): Promise<Response> {
// surface a structured 503 — the wizard hides the overlay.
const chain = await resolveProviderChain(userId);
if (chain.length === 0) {
const legacy = await resolveProvider(userId);
if (legacy.type === "none") {
annotate({ action: { name: "medications.extract.no-provider" } });
throw new AiUnavailableError(
"medicationExtract",
"no_provider",
null,
MEDICATION_EXTRACT_NO_PROVIDER,
);
}
chain.push({ providerType: "admin-openai", instance: legacy });
annotate({ action: { name: "medications.extract.no-provider" } });
throw new AiUnavailableError(
"medicationExtract",
"no_provider",
null,
MEDICATION_EXTRACT_NO_PROVIDER,
);
}
// The wire. The runner may cascade through every entry, so each one is
+13 -8
View File
@@ -84,20 +84,25 @@ export const GET = apiHandler(async () => {
globallyEnabled: globalToggles[ch.type] ?? true,
}));
// Admin-only events (backup health) are listed for admins only, and an
// event nothing sends is listed for nobody: a switch for either would
// switch nothing. A stored row for an unlisted event stays in the table and
// is not served.
const eventTypes: string[] = eventTypesForRole(user.role);
const preferences = channels.flatMap((ch) =>
ch.preferences.map((p) => ({
channelId: p.channelId,
eventType: p.eventType,
enabled: p.enabled,
})),
ch.preferences
.filter((p) => eventTypes.includes(p.eventType))
.map((p) => ({
channelId: p.channelId,
eventType: p.eventType,
enabled: p.enabled,
})),
);
return apiSuccess({
channels: channelData,
preferences,
// Admin-only events (backup health) are listed for admins only: nobody
// else is ever sent one, so a switch for it would switch nothing.
eventTypes: eventTypesForRole(user.role),
eventTypes,
// What an event does on a channel with no stored row, resolved for this
// account by the same function the dispatcher asks. A client renders a
// switch without a row from this map, never from its own copy of the
@@ -90,6 +90,20 @@ describe("POST /api/onboarding/complete", () => {
);
});
it("stores a date of birth from the iOS app as its day in the owner's zone", async () => {
vi.mocked(getSession).mockResolvedValue({
...SESSION_OK,
user: { ...SESSION_OK.user, timezone: "Europe/Berlin" },
} as unknown as Awaited<ReturnType<typeof getSession>>);
// 14 May picked at 00:30 in Berlin.
const res = await POST(req({ dateOfBirth: "1960-05-13T23:30:00Z" }));
expect(res.status).toBe(200);
const data = vi.mocked(prisma.user.update).mock.calls[0]![0]!.data as {
dateOfBirth: Date;
};
expect(data.dateOfBirth.toISOString()).toBe("1960-05-14T12:00:00.000Z");
});
it("still refuses an unsupported gender", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await POST(req({ gender: "diverse" }));
+8 -4
View File
@@ -29,6 +29,8 @@ import { readManagedProfileForGuardian } from "@/lib/managed-profiles/lifecycle"
import { writeRecordModulePreferences } from "@/lib/record-settings/modules";
import { NextRequest } from "next/server";
import { onboardingCompleteSchema } from "@/lib/validations/onboarding";
import { dateOfBirthForStorage } from "@/lib/tz/date-only";
import { resolveStoredTimezone } from "@/lib/tz/resolver";
/**
* Complete the onboarding flow. Saves optional profile data and marks
@@ -84,10 +86,12 @@ export const POST = apiHandler(async (request: NextRequest) => {
}
if (result.data.dateOfBirth) {
const dob = new Date(result.data.dateOfBirth);
if (!isNaN(dob.getTime())) {
data.dateOfBirth = dob;
}
// The calendar day in the owner's zone: the iOS app sends an instant.
const dob = dateOfBirthForStorage(
result.data.dateOfBirth,
await resolveStoredTimezone(user.timezone),
);
if (dob) data.dateOfBirth = dob;
}
if (result.data.gender) {
@@ -97,6 +97,8 @@ vi.mock("@/lib/medications/dose-day-refresh", () => ({
refreshDoseSlot: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/modules/gate", () => ({ isModuleEnabled: vi.fn() }));
import { POST, GET } from "../route";
import { prisma } from "@/lib/db";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
@@ -112,6 +114,7 @@ import {
} from "@/lib/mood/create-from-telegram";
import { scheduleTelegramAutoDelete } from "@/lib/telegram-cleanup";
import { satisfyReminder } from "@/lib/measurement-reminders/satisfy";
import { isModuleEnabled } from "@/lib/modules/gate";
const ORIGINAL_SECRET = process.env.TELEGRAM_WEBHOOK_SECRET;
@@ -129,11 +132,14 @@ const MEDICATION = { id: "med-1", name: "Ramipril" };
* schedule projection (distinguishable by `select.schedules`); every other
* `medication.findFirst` in the webhook wants the bare id/name shape. The
* default projection carries no schedules, so the generic dispatch tests
* exercise the ad-hoc (standalone create) path unchanged.
* exercise the ad-hoc (standalone create) path unchanged. The dose lookup
* (`findTelegramDoseMedication`) reads every match by id or name through
* `findMany`; a list read (no id, no name) finds nothing unless a test says.
*/
function wireMedicationFindFirst(
schedules: unknown[] = [],
scheduleRevisions: unknown[] = [],
medication: Record<string, unknown> = MEDICATION,
) {
vi.mocked(prisma.medication.findFirst).mockImplementation(((args: {
select?: Record<string, unknown>;
@@ -149,8 +155,16 @@ function wireMedicationFindFirst(
scheduleRevisions,
});
}
return Promise.resolve(MEDICATION);
return Promise.resolve(medication);
}) as never);
vi.mocked(prisma.medication.findMany).mockImplementation(((args: {
where?: Record<string, unknown>;
}) =>
Promise.resolve(
args?.where && ("id" in args.where || "name" in args.where)
? [medication]
: [],
)) as never);
}
beforeEach(() => {
@@ -162,8 +176,8 @@ beforeEach(() => {
resetAt: Date.now() + 60_000,
} as never);
vi.mocked(prisma.user.findFirst).mockResolvedValue(TG_USER as never);
vi.mocked(isModuleEnabled).mockResolvedValue(true);
wireMedicationFindFirst();
vi.mocked(prisma.medication.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.medication.update).mockResolvedValue({} as never);
vi.mocked(prisma.medicationIntakeEvent.findFirst).mockResolvedValue(null);
vi.mocked(prisma.medicationIntakeEvent.create).mockResolvedValue({} as never);
@@ -300,6 +314,7 @@ describe("Telegram webhook — callback dispatch", () => {
expect(res.status).toBe(200);
expect(prisma.medication.findFirst).not.toHaveBeenCalled();
expect(prisma.medication.findMany).not.toHaveBeenCalled();
expect(prisma.medicationIntakeEvent.create).not.toHaveBeenCalled();
expect(prisma.medication.update).not.toHaveBeenCalled();
expect(deleteMessage).not.toHaveBeenCalled();
@@ -464,7 +479,7 @@ describe("Telegram webhook — callback dispatch", () => {
});
it("rejects 'taken' for an inactive medication and acks with the localised error", async () => {
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(null);
vi.mocked(prisma.medication.findMany).mockResolvedValueOnce([]);
const res = await POST(tgRequest(callbackUpdate("taken:med-1")));
expect(res.status).toBe(200);
@@ -482,7 +497,7 @@ describe("Telegram webhook — callback dispatch", () => {
});
it("'snooze' for a missing medication acks with medicationNotFound (no update)", async () => {
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(null);
vi.mocked(prisma.medication.findMany).mockResolvedValueOnce([]);
const res = await POST(tgRequest(callbackUpdate("snooze:med-X:60")));
expect(res.status).toBe(200);
expect(prisma.medication.update).not.toHaveBeenCalled();
@@ -637,7 +652,7 @@ describe("Telegram webhook — text-message dispatch", () => {
});
it("/add with no active medications replies with the 'no active' message", async () => {
vi.mocked(prisma.medication.findMany).mockResolvedValueOnce([] as never);
vi.mocked(prisma.medication.findMany).mockResolvedValueOnce([]);
const res = await POST(
tgRequest({
update_id: 203,
@@ -670,8 +685,8 @@ describe("Telegram webhook — text-message dispatch", () => {
}),
);
expect(res.status).toBe(200);
// markMedicationTaken → findFirst on active medication
expect(prisma.medication.findFirst).toHaveBeenCalled();
// The list, then markMedicationTaken's lookup of the one it found.
expect(prisma.medication.findMany).toHaveBeenCalledTimes(2);
expect(prisma.medicationIntakeEvent.create).toHaveBeenCalledTimes(1);
});
@@ -712,15 +727,6 @@ describe("Telegram webhook — text-message dispatch", () => {
});
it("'taken Ramipril' (text command) creates an intake event for the matched medication", async () => {
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce({
id: "med-1",
} as never);
// Second findFirst inside markMedicationTaken
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce({
id: "med-1",
name: "Ramipril",
} as never);
const res = await POST(
tgRequest({
update_id: 206,
@@ -762,8 +768,8 @@ describe("Telegram webhook — text-message dispatch", () => {
});
it("'taken UnknownMed' replies with the medication-not-found message and writes nothing", async () => {
// First findFirst (lookup by name) returns null
vi.mocked(prisma.medication.findFirst).mockResolvedValueOnce(null);
// The lookup by name finds nothing.
vi.mocked(prisma.medication.findMany).mockResolvedValueOnce([]);
const res = await POST(
tgRequest({
@@ -907,6 +913,29 @@ describe("Telegram webhook — slot convergence (v1.16.9)", () => {
});
});
it("books the reminder's own dose on the last day of a course after it ended", async () => {
// The course ran through 9 June; yesterday's 09:00 reminder is confirmed
// the next morning. The dose belongs to a day the course covered.
wireMedicationFindFirst([scheduleRow], [], {
...MEDICATION,
dose: "5 mg",
startsOn: null,
endsOn: new Date("2026-06-09T00:00:00.000Z"),
endedAt: null,
});
vi.mocked(prisma.telegramReminderMessage.findFirst).mockResolvedValue({
date: "2026-06-09",
timeOfDay: "09:00",
} as never);
await POST(tgRequest(callbackUpdate("taken:med-1")));
expect(prisma.$transaction).toHaveBeenCalled();
expect(vi.mocked(answerTelegramCallbackQuery).mock.calls[0][2]).not.toMatch(
/not found or inactive/i,
);
});
it("a take converges via band attribution when no reminder row matches", async () => {
vi.mocked(prisma.telegramReminderMessage.findFirst).mockResolvedValue(null);
const res = await POST(tgRequest(callbackUpdate("taken:med-1")));
@@ -1219,7 +1248,7 @@ describe("POST /api/telegram/webhook — record-only medications", () => {
it("the 'taken' keyword resolves tracked medications only", async () => {
await POST(tgRequest(textUpdate("taken Ramipril")));
const where = whereOf(vi.mocked(prisma.medication.findFirst).mock.calls[0]);
const where = whereOf(vi.mocked(prisma.medication.findMany).mock.calls[0]);
expect(where).toMatchObject({ active: true, trackIntake: true });
});
@@ -1227,7 +1256,7 @@ describe("POST /api/telegram/webhook — record-only medications", () => {
await POST(tgRequest(callbackUpdate("taken:med-1")));
// The gate lookup: a record-only medication resolves to nothing here,
// so no dose is written (later lookups only bind an admitted dose).
const calls = vi.mocked(prisma.medication.findFirst).mock.calls;
const calls = vi.mocked(prisma.medication.findMany).mock.calls;
expect(calls.length).toBeGreaterThan(0);
expect(whereOf(calls[0])).toMatchObject({
id: "med-1",
@@ -1236,3 +1265,86 @@ describe("POST /api/telegram/webhook — record-only medications", () => {
});
});
});
/**
* With the Medications module switched off the bot offers no dose and books
* none: the web shows no medication surface and the reminder jobs are
* silent, so a reminder button left in the chat, the /add list and the
* "taken" keyword do nothing either.
*/
describe("POST /api/telegram/webhook with the Medications module off", () => {
function textUpdate(text: string) {
return {
update_id: 400,
message: { message_id: 40, text, chat: { id: 7777 }, from: { id: 7777 } },
};
}
beforeEach(() => {
vi.mocked(isModuleEnabled).mockResolvedValue(false);
});
it.each(["taken:med-1", "skip:med-1", "add:med-1"])(
"the %s button books nothing",
async (data) => {
const res = await POST(tgRequest(callbackUpdate(data)));
expect(res.status).toBe(200);
expect(isModuleEnabled).toHaveBeenCalledWith("user-1", "medications");
expect(prisma.medicationIntakeEvent.create).not.toHaveBeenCalled();
expect(prisma.$transaction).not.toHaveBeenCalled();
},
);
it("the snooze button snoozes nothing", async () => {
await POST(tgRequest(callbackUpdate("snooze:med-1:60")));
expect(prisma.medication.update).not.toHaveBeenCalled();
expect(vi.mocked(answerTelegramCallbackQuery).mock.calls[0][2]).toMatch(
/not found/i,
);
});
it("/add offers nothing", async () => {
await POST(tgRequest(textUpdate("/add")));
expect(prisma.medication.findMany).not.toHaveBeenCalled();
expect(vi.mocked(sendTelegramMessage).mock.calls[0][2]).toMatch(
/no active medications/i,
);
});
it("the 'taken' keyword records nothing", async () => {
await POST(tgRequest(textUpdate("taken Ramipril")));
expect(prisma.medicationIntakeEvent.create).not.toHaveBeenCalled();
expect(prisma.$transaction).not.toHaveBeenCalled();
});
});
/**
* A reminder button left in the chat takes no dose for a course that has
* since ended, which would also take a unit off the stock. The list side is
* pinned in `src/lib/__tests__/telegram-dose-medications.test.ts`.
*/
describe("POST /api/telegram/webhook on an ended course", () => {
const DAY_MS = 24 * 60 * 60 * 1000;
const ENDED = {
...MEDICATION,
dose: "5 mg",
startsOn: new Date(Date.now() - 20 * DAY_MS),
endsOn: new Date(Date.now() - 3 * DAY_MS),
endedAt: null,
};
it("the taken button on an ended course books nothing", async () => {
wireMedicationFindFirst([], [], ENDED);
await POST(tgRequest(callbackUpdate("taken:med-1")));
expect(prisma.medicationIntakeEvent.create).not.toHaveBeenCalled();
expect(prisma.$transaction).not.toHaveBeenCalled();
expect(vi.mocked(answerTelegramCallbackQuery).mock.calls[0][2]).toMatch(
/not found or inactive/i,
);
});
it("the skip button on an ended course books nothing", async () => {
wireMedicationFindFirst([], [], ENDED);
await POST(tgRequest(callbackUpdate("skip:med-1")));
expect(prisma.$transaction).not.toHaveBeenCalled();
});
});
@@ -751,6 +751,24 @@ describe("PATCH /api/user/ai-provider — reasoning setting (#1126)", () => {
]);
});
it("switches the gateway's entry on when the gateway form saves it as the pick", async () => {
// The disabled holder above, written for a picked gateway, read as the
// person switching off the provider they had just picked.
storedChain(null);
await patch(
patchRequest({
provider: "OPENAI_COMPATIBLE",
compatReasoningEffort: "low",
}),
);
const chain = written()?.aiProviderChain as Array<{
providerType: string;
}>;
expect(
chain.find((e) => e.providerType === "openai-compatible"),
).toMatchObject({ enabled: true, reasoningEffort: "low" });
});
it("does not touch the chain when Default is restated on a default chain", async () => {
storedChain(null);
await patch(
+53 -31
View File
@@ -16,6 +16,7 @@ import {
providerWorkAuthorityForRecord,
} from "@/lib/sharing/provider-work-authority";
import { annotate } from "@/lib/logging/context";
import type { z } from "zod/v4";
import { aiProviderPatchSchema } from "@/lib/validations/ai-provider";
import {
chainWithReasoningEffort,
@@ -191,6 +192,51 @@ export const GET = apiHandler(async () => {
});
});
/**
* #1126 — the chain to write after the Local or gateway form set its entry's
* reasoning effort, or undefined when nothing changed. Stored on the entry in
* `aiProviderChain` rather than in a column of their own, so the setting is
* per entry and a chain can mix a thinking model with one that does not know
* the field. See `chainWithReasoningEffort` for how a default chain, or a
* provider absent from the chain, holds the value.
*/
async function chainAfterReasoningSave(
userId: string,
body: Pick<
z.infer<typeof aiProviderPatchSchema>,
"localReasoningEffort" | "compatReasoningEffort"
>,
pickedNow: unknown,
): Promise<unknown> {
const current = await prisma.user.findUnique({
where: { id: userId },
select: { aiProviderChain: true, aiProvider: true },
});
let chain: unknown = current?.aiProviderChain ?? null;
if (body.localReasoningEffort !== undefined) {
chain = chainWithReasoningEffort(chain, "local", body.localReasoningEffort);
}
if (body.compatReasoningEffort !== undefined) {
// Saving the gateway form picks the gateway, so its entry is on: a
// disabled one read as the person switching off what they had just picked.
const picked = pickedNow !== undefined ? pickedNow : current?.aiProvider;
chain = chainWithReasoningEffort(
chain,
"openai-compatible",
body.compatReasoningEffort,
String(picked ?? "").toUpperCase() === "OPENAI_COMPATIBLE",
);
}
// Written only when it changed: restating Default on a chain that was
// never customised must not freeze today's default chain into the row.
const before = serializeProviderChain(
parseProviderChain(current?.aiProviderChain ?? null),
);
return serializeProviderChain(parseProviderChain(chain)) !== before
? chain
: undefined;
}
export const PATCH = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
annotate({ action: { name: "user.ai-provider.update" } });
@@ -265,6 +311,7 @@ export const PATCH = apiHandler(async (request: NextRequest) => {
return apiError(
"Base URL points to an internal/private host. The operator must allow its exact origin on this instance via AI_PRIVATE_ORIGINS (e.g. http://ollama.lan:11434) for a self-hosted Ollama / LM Studio.",
422,
{ errorCode: "ai_provider.private_host" },
);
}
updates.aiBaseUrl = trimmed;
@@ -289,6 +336,7 @@ export const PATCH = apiHandler(async (request: NextRequest) => {
return apiError(
"Base URL points to an internal/private host. The operator must allow its exact origin on this instance via AI_PRIVATE_ORIGINS (e.g. http://litellm.lan:4000) for a self-hosted gateway.",
422,
{ errorCode: "ai_provider.private_host" },
);
}
updates.aiCompatBaseUrl = trimmed;
@@ -335,42 +383,16 @@ export const PATCH = apiHandler(async (request: NextRequest) => {
updates.aiResponseTimeoutSeconds = body.responseTimeoutSeconds;
}
// ── #1126 — reasoning settings of the Local and gateway entries ──
// Stored on the entry in `aiProviderChain` rather than in a column of their
// own, so the setting is per entry and a chain can mix a thinking model with
// one that does not know the field. See `chainWithReasoningEffort` for how a
// default chain, or a provider absent from the chain, holds the value.
const reasoningTouched =
body.localReasoningEffort !== undefined ||
body.compatReasoningEffort !== undefined;
if (reasoningTouched) {
const current = await prisma.user.findUnique({
where: { id: user.id },
select: { aiProviderChain: true },
});
let chain: unknown = current?.aiProviderChain ?? null;
if (body.localReasoningEffort !== undefined) {
chain = chainWithReasoningEffort(
chain,
"local",
body.localReasoningEffort,
);
}
if (body.compatReasoningEffort !== undefined) {
chain = chainWithReasoningEffort(
chain,
"openai-compatible",
body.compatReasoningEffort,
);
}
// Written only when it changed: restating Default on a chain that was
// never customised must not freeze today's default chain into the row.
const before = serializeProviderChain(
parseProviderChain(current?.aiProviderChain ?? null),
const chain = await chainAfterReasoningSave(
user.id,
body,
updates.aiProvider,
);
if (serializeProviderChain(parseProviderChain(chain)) !== before) {
updates.aiProviderChain = chain;
}
if (chain !== undefined) updates.aiProviderChain = chain;
}
if (Object.keys(updates).length === 0 && !reasoningTouched) {
@@ -96,7 +96,7 @@ beforeEach(() => {
describe("PUT /api/user/thresholds — 422 multi-issue (v1.4.43 W6)", () => {
it("surfaces TWO simultaneous validation errors", async () => {
// WEIGHT bounds are min=30, max=300. Sending min > max + a value
// WEIGHT bounds are min=1, max=300. Sending min > max + a value
// out of bounds on PULSE forces two range errors.
const res = await PUT(
putReq({
@@ -97,7 +97,7 @@ function report(): DoctorReportData {
end: "2026-01-31T00:00:00.000Z",
},
patient: {
username: null,
name: null,
dateOfBirth: null,
gender: null,
heightCm: null,
@@ -18,9 +18,9 @@ vi.mock("@/hooks/use-ai-capability", () => ({
useAiCapabilityAnswer: () => capability.answer,
}));
const plan = (id: string, status: string) => ({
const plan = (id: string, status: string, metric = "WEIGHT") => ({
id,
metric: "WEIGHT",
metric,
ifCue: `cue ${id}`,
thenAction: `action ${id}`,
target: null,
@@ -35,7 +35,7 @@ vi.mock("@/hooks/use-coach-plans", () => ({
data: [
plan("p-proposed", "proposed"),
plan("p-active", "active"),
plan("p-met", "met"),
plan("p-met", "met", "mood vibes"),
],
isError: false,
isLoading: false,
@@ -48,12 +48,16 @@ vi.mock("@/hooks/use-coach-plans", () => ({
}));
import { I18nProvider } from "@/lib/i18n/context";
import { primeMessages } from "@/lib/i18n/load-locale";
import deMessages from "../../../../../messages/de.json";
import CoachPlansPage from "../page";
function render(): string {
primeMessages("de", deMessages);
function render(locale: "en" | "de" = "en"): string {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<I18nProvider initialLocale={locale}>
<CoachPlansPage />
</I18nProvider>,
);
@@ -90,4 +94,12 @@ describe("/coach/plans", () => {
expect(count(html, "coach-plan-delete")).toBe(1);
expect(html).not.toContain("you can still read and delete your plans");
});
it("names the metric in the reader's language, and an unknown key as written", () => {
capability.answer = { available: true };
const html = render("de");
expect(html.split("<span>Gewicht</span>").length - 1).toBe(2);
expect(html).toContain("<span>mood vibes</span>");
expect(html).not.toContain("WEIGHT");
});
});
+2 -1
View File
@@ -23,6 +23,7 @@ import {
type CoachPlanDTO,
} from "@/hooks/use-coach-plans";
import { useAiCapabilityAnswer } from "@/hooks/use-ai-capability";
import { planMetricLabel } from "@/lib/ai/coach/plan-metric";
import { useTranslations } from "@/lib/i18n/context";
import { formatDateOrRelative } from "@/lib/format";
import { cn } from "@/lib/utils";
@@ -109,7 +110,7 @@ function CoachPlansBody({ readOnly }: { readOnly: boolean }) {
</p>
) : null}
<div className="text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
<span className="uppercase">{plan.metric}</span>
<span>{planMetricLabel(plan.metric, t)}</span>
<span>{t(`coach.plans.status.${plan.status}`)}</span>
<span>{formatDateOrRelative(plan.updatedAt, t)}</span>
{plan.reviewDate ? (
@@ -0,0 +1,101 @@
/**
* `/insights/bmi` decides from a height whether it can show anything. It used
* the height of the person at the keyboard, so inside somebody else's record
* a viewer without a height of their own was asked to set it, and a viewer
* with one hid that the record has none.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
const shellProps = vi.fn();
vi.mock("@/components/insights/sub-page-shell", () => ({
SubPageShell: (props: Record<string, unknown>) => {
shellProps(props);
return null;
},
}));
vi.mock("@/lib/i18n/context", () => ({
useTranslations: () => ({ t: (key: string) => key, locale: "en" }),
}));
const state = {
viewerHeight: null as number | null,
inSharedRecord: true,
recordHeight: 118 as number | null,
bmiRange: { min: 18.5, max: 24.9 } as { min: number; max: number } | null,
};
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
isAuthenticated: true,
user: { heightCm: state.viewerHeight, timezone: "UTC" },
}),
}));
vi.mock("@/hooks/use-record-capabilities", () => ({
useRecordCapabilities: () => ({ inSharedRecord: state.inSharedRecord }),
}));
vi.mock("@/hooks/use-insights-analytics", () => ({
useInsightsAnalytics: () => ({ isEmpty: false }),
}));
vi.mock("@tanstack/react-query", () => ({
useQuery: ({ enabled }: { enabled?: boolean }) => ({
data:
enabled === false
? undefined
: {
targets: [{ type: "BMI", range: state.bmiRange }],
profile: { heightCm: state.recordHeight },
},
}),
}));
import InsightsBmiPage from "../page";
/** True when the page rendered its "set your height" state. */
function asksForHeight(): boolean {
renderToStaticMarkup(<InsightsBmiPage />);
const props = shellProps.mock.calls.at(-1)![0] as { coachLaunch?: boolean };
// The chart branch launches the Coach from the shell; the empty states do not.
return props.coachLaunch !== true;
}
describe("/insights/bmi height gate", () => {
beforeEach(() => {
shellProps.mockClear();
state.viewerHeight = null;
state.inSharedRecord = true;
state.recordHeight = 118;
state.bmiRange = { min: 18.5, max: 24.9 };
});
it("reads the record's height inside somebody else's record", () => {
expect(asksForHeight()).toBe(false);
state.viewerHeight = 180;
state.recordHeight = null;
expect(asksForHeight()).toBe(true);
});
it("reads the account's own height in one's own record", () => {
state.inSharedRecord = false;
state.viewerHeight = 180;
expect(asksForHeight()).toBe(false);
state.viewerHeight = null;
expect(asksForHeight()).toBe(true);
});
it("draws the adult bands only where the record's BMI range is named", () => {
const chartBands = () => {
renderToStaticMarkup(<InsightsBmiPage />);
const { children } = shellProps.mock.calls.at(-1)![0] as {
children: Array<{ props?: { valueBands?: unknown } }>;
};
return children.find(
(child) => child?.props && "valueBands" in child.props,
)?.props?.valueBands;
};
expect(chartBands()).toBeDefined();
// A child's record: the server names no BMI range.
state.bmiRange = null;
expect(chartBands()).toBeUndefined();
});
});
+29 -2
View File
@@ -1,9 +1,13 @@
"use client";
import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { Ruler } from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { useRecordCapabilities } from "@/hooks/use-record-capabilities";
import { apiGet } from "@/lib/api/api-fetch";
import { queryKeys } from "@/lib/query-keys";
import { useInsightsAnalytics } from "@/hooks/use-insights-analytics";
import { useTranslations } from "@/lib/i18n/context";
import { useInsightsLayoutPrefs } from "@/hooks/use-insights-layout-prefs";
@@ -45,6 +49,29 @@ export default function InsightsBmiPage() {
const { isEmpty } = useInsightsAnalytics("BMI");
// `useAuth()` is the person at the keyboard. Inside somebody else's record
// the height that decides is the record's, from the route that knows which
// record is on screen (the reference panel below reads the same cell).
const { inSharedRecord } = useRecordCapabilities();
const { data: targets } = useQuery({
queryKey: queryKeys.insightsTargets(),
queryFn: () =>
apiGet<{
targets: ReadonlyArray<{ type: string; range: unknown }>;
profile?: { heightCm: number | null };
}>("/api/insights/targets"),
enabled: isAuthenticated,
});
const heightCm = inSharedRecord
? (targets?.profile?.heightCm ?? null)
: (user?.heightCm ?? null);
const heightKnown = !inSharedRecord || targets !== undefined;
// The adult bands only where the server names the BMI range: it names none
// for a child's record, which they do not describe.
const bmiBands = targets?.targets.find((entry) => entry.type === "BMI")?.range
? BMI_BANDS
: undefined;
// v1.4.27 — BMI is derived from WEIGHT. When no weight readings
// exist yet, the existing "set your height" branch can never compute
// anything useful either; surface the empty-state CTA pointing at
@@ -75,7 +102,7 @@ export default function InsightsBmiPage() {
);
}
if (!user?.heightCm) {
if (heightKnown && !heightCm) {
return (
<SubPageShell
title={t("insights.bmiSectionTitle")}
@@ -119,7 +146,7 @@ export default function InsightsBmiPage() {
colors={["var(--chart-5)"]}
unit="kg/m²"
valueMode="bmi"
valueBands={BMI_BANDS}
valueBands={bmiBands}
compareBaseline={compareBaseline}
userTimezone={user?.timezone}
showDataTable
@@ -0,0 +1,105 @@
/**
* `/insights/weight` shades the band of the record on screen. It used to take
* the height of the person at the keyboard (`useAuth()`) and their own target
* (`/api/user/thresholds`, refused under a switch), so a parent of 180 cm on
* a child's record saw the parent's healthy band behind the child's weights.
*
* `SubPageShell` is stubbed to a probe so the test reads the band the page
* hands the chart, not rendered pixels.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
const shellProps = vi.fn();
vi.mock("@/components/insights/sub-page-shell", () => ({
SubPageShell: (props: Record<string, unknown>) => {
shellProps(props);
return null;
},
}));
vi.mock("@/lib/i18n/context", () => ({
useTranslations: () => ({ t: (key: string) => key, locale: "en" }),
}));
// The viewer: 180 cm, signed in, looking at somebody else's record.
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
isAuthenticated: true,
user: { heightCm: 180, timezone: "UTC", unitPreference: "metric" },
}),
useAccountOnceMounted: () => null,
}));
vi.mock("@/hooks/use-insights-analytics", () => ({
useInsightsAnalytics: () => ({
data: { summaries: { WEIGHT: { count: 10 } } },
isLoading: false,
isEmpty: false,
}),
}));
// The record on screen: 118 cm, no target of its own.
const targets = {
current: {
targets: [
{ type: "WEIGHT", range: { min: 25.8, max: 34.7 }, source: "WHO BMI" },
],
profile: { heightCm: 118 },
} as unknown,
};
vi.mock("@tanstack/react-query", () => ({
useQuery: ({ queryKey }: { queryKey: readonly unknown[] }) => ({
data: JSON.stringify(queryKey).includes("targets")
? targets.current
: undefined,
isLoading: false,
error: null,
}),
}));
import InsightsGewichtPage from "../page";
import { buildWeightRangeFromHeight } from "@/lib/analytics/value-bands";
function chartBands(): Array<{ min: number; max: number }> | undefined {
renderToStaticMarkup(<InsightsGewichtPage />);
const props = shellProps.mock.calls.at(-1)![0] as { children: unknown };
const children = Array.isArray(props.children)
? props.children
: [props.children];
const chart = children.find(
(el) =>
el &&
typeof el === "object" &&
Array.isArray((el as { props?: { types?: unknown } }).props?.types),
) as { props: { valueBands?: Array<{ min: number; max: number }> } };
return chart.props.valueBands;
}
describe("/insights/weight band", () => {
beforeEach(() => shellProps.mockClear());
it("shades the WHO band for the record's height, not the viewer's", () => {
const bands = chartBands();
const record = buildWeightRangeFromHeight(118);
const viewer = buildWeightRangeFromHeight(180);
expect(bands).toContainEqual(
expect.objectContaining({ min: record.greenMin, max: record.greenMax }),
);
expect(bands).not.toContainEqual(
expect.objectContaining({ min: viewer.greenMin, max: viewer.greenMax }),
);
});
it("shades no band when the record's targets are not readable", () => {
targets.current = undefined;
try {
expect(chartBands()).toBeUndefined();
} finally {
targets.current = {
targets: [],
profile: { heightCm: 118 },
};
}
});
});
@@ -0,0 +1,57 @@
/**
* The weight band belongs to the record on screen. It used to be built from
* the signed-in person's height, so a parent of 180 cm looking at a child's
* record saw a healthy band of about 60 to 81 kg behind the child's weights.
*/
import { describe, expect, it } from "vitest";
import { buildWeightRangeFromHeight } from "@/lib/analytics/value-bands";
import { selectWeightBandRange } from "../weight-band";
describe("selectWeightBandRange", () => {
it("builds the WHO band from the record's height", () => {
const range = selectWeightBandRange({
targets: [
{ type: "WEIGHT", range: { min: 59.9, max: 81 }, source: "WHO BMI" },
],
profile: { heightCm: 180 },
});
expect(range).toEqual(buildWeightRangeFromHeight(180));
});
it("paints no adult band behind a child's weights", () => {
// A 118 cm child: the server names no WHO range for a record under 18,
// where the adult band read a normal 21 kg as underweight.
expect(
selectWeightBandRange({
targets: [{ type: "WEIGHT", range: null, source: "WHO BMI" }],
profile: { heightCm: 118 },
}),
).toBeNull();
});
it("paints the record's own target with the override wings", () => {
const range = selectWeightBandRange({
targets: [
{ type: "WEIGHT", range: { min: 70, max: 80 }, source: "Custom" },
],
profile: { heightCm: 180 },
});
expect(range).toEqual({
greenMin: 70,
greenMax: 80,
orangeMin: 68.5,
orangeMax: 81.5,
});
});
it("paints nothing without a target or a height, or before the read lands", () => {
expect(
selectWeightBandRange({
targets: [{ type: "WEIGHT", range: null, source: "WHO BMI" }],
profile: { heightCm: null },
}),
).toBeNull();
expect(selectWeightBandRange(null)).toBeNull();
});
});
+18 -39
View File
@@ -23,11 +23,9 @@ import { MetricCorrelationCard } from "@/components/insights/metric-correlation-
import { MeasurementDiversityNudge } from "@/components/insights/measurement-diversity-nudge";
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
import { SubPageShell } from "@/components/insights/sub-page-shell";
import {
buildBandsFromTrafficRange,
buildWeightBandsFromHeight,
type TrafficRange,
} from "@/lib/analytics/value-bands";
import { METRIC_BOUNDS } from "@/lib/analytics/effective-range";
import { buildBandsFromTrafficRange } from "@/lib/analytics/value-bands";
import { selectWeightBandRange, type WeightTargetsSlice } from "./weight-band";
/**
* v1.4.25 — `/insights/weight`.
@@ -37,8 +35,8 @@ import {
* (`chartKey="weight"`) lets the user toggle trend lines + comparison
* overlay independently from the dashboard weight card.
*
* v1.34 — the bands follow the user's own weight target when one is set,
* and fall back to the height-derived WHO band only when it is not.
* The bands follow the record's own weight target when one is set, and fall
* back to the WHO band for the record's height only when it is not.
*
* v1.4.28 — analytics fetch + empty-state
* branch now consume `useInsightsAnalytics()` + `<MetricEmptyState>`.
@@ -56,19 +54,13 @@ export default function InsightsGewichtPage() {
} = useInsightsAnalytics("WEIGHT");
const weightSummary = analytics?.summaries?.WEIGHT ?? null;
// v1.34 — the user's own weight target, read through the shared
// `queryKeys.userThresholds()` cell the targets editor also subscribes to, so
// editing the target repaints this chart's band without a reload.
const { data: thresholds } = useQuery({
queryKey: queryKeys.userThresholds(),
queryFn: async () => {
return apiGet<{
effective: Record<
string,
{ range: TrafficRange | null; isOverride: boolean }
>;
}>("/api/user/thresholds");
},
// The record's own target and height, from the route that knows which
// record is on screen (see `selectWeightBandRange`). Shares the
// `insightsTargets()` cell with the reference panel below; the targets
// editor invalidates it on save, so the band repaints without a reload.
const { data: targets } = useQuery({
queryKey: queryKeys.insightsTargets(),
queryFn: () => apiGet<WeightTargetsSlice>("/api/insights/targets"),
enabled: isAuthenticated,
});
@@ -136,27 +128,14 @@ export default function InsightsGewichtPage() {
);
}
// v1.34 — the shaded zone follows the user's OWN target when they set one.
// The page used to shade the height-derived WHO band unconditionally, so
// someone who had entered a target on `/targets` kept reading a chart that
// ignored the answer. `/api/user/thresholds` already resolves the override
// (with its orange wings) through `getEffectiveRange`, so the page reads the
// resolved band rather than re-deriving one. No target and no height → no
// bands, unchanged.
const overrideRange = thresholds?.effective?.WEIGHT?.isOverride
? (thresholds.effective.WEIGHT.range ?? null)
: null;
const weightBands = overrideRange
? buildBandsFromTrafficRange(overrideRange, {
lowerBound: 30,
// No target and no height → no bands.
const weightRange = selectWeightBandRange(targets ?? null);
const weightBands = weightRange
? buildBandsFromTrafficRange(weightRange, {
lowerBound: METRIC_BOUNDS.WEIGHT.min,
upperBound: 250,
})
: user?.heightCm
? buildWeightBandsFromHeight(user.heightCm, {
lowerBound: 30,
upperBound: 250,
})
: undefined;
: undefined;
// The bands are kg bounds → scale into the display unit so the shaded zone
// tracks the converted line (factor-only; weight carries no offset).
const displayBands =
+45
View File
@@ -0,0 +1,45 @@
import { getEffectiveRange } from "@/lib/analytics/effective-range";
import {
buildWeightRangeFromHeight,
type TrafficRange,
} from "@/lib/analytics/value-bands";
/** The slice of `GET /api/insights/targets` the weight band needs. */
export interface WeightTargetsSlice {
targets: ReadonlyArray<{
type: string;
range: { min: number; max: number } | null;
source: string;
}>;
profile?: { heightCm: number | null };
}
/**
* The weight band for the record on screen, as the server resolved it.
*
* The page used to read the person at the keyboard: their height from
* `useAuth()` and their own target from `/api/user/thresholds`, which
* refuses inside somebody else's record. A parent on a child's record saw a
* band built from the parent's height. `/api/insights/targets` resolves the
* record's own target and height, and the reference panel under the chart
* reads the same payload. The record's own target (`source: "Custom"`) gets
* the wings `getEffectiveRange` gives every override; otherwise the band is
* the height-derived WHO one. Where the server names no range there is none:
* no target and no height, or a child's record, which the adult WHO band does
* not describe.
*/
export function selectWeightBandRange(
data: WeightTargetsSlice | null,
): TrafficRange | null {
const weight = data?.targets.find((entry) => entry.type === "WEIGHT");
if (!data || !weight?.range) return null;
if (weight.source === "Custom") {
return getEffectiveRange(
"WEIGHT",
{ heightCm: null, dateOfBirth: null, gender: null },
{ WEIGHT: weight.range },
).range;
}
const heightCm = data.profile?.heightCm ?? null;
return heightCm ? buildWeightRangeFromHeight(heightCm) : null;
}
+3 -15
View File
@@ -37,7 +37,7 @@ import { useMounted } from "@/hooks/use-mounted";
import { useRecordCapabilities } from "@/hooks/use-record-capabilities";
import { usePullToRefresh } from "@/hooks/use-pull-to-refresh";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { invalidateKeys, labDependentKeys, queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import type { LabResultListResponse } from "@/components/labs/types";
import {
@@ -231,18 +231,14 @@ export default function LabsPage() {
footerSlot={addFooterEl}
onSuccess={() => {
setDialogOpen(false);
queryClient.invalidateQueries({
queryKey: queryKeys.labResults(),
});
void invalidateKeys(queryClient, labDependentKeys);
}}
// v1.30.1 — "Save & add another" keeps the sheet open; the
// form clears the reading itself, this callback just refreshes
// the list underneath so the just-saved row is there once the
// user is done and closes the sheet.
onSavedKeepOpen={() => {
queryClient.invalidateQueries({
queryKey: queryKeys.labResults(),
});
void invalidateKeys(queryClient, labDependentKeys);
}}
onCancel={() => setDialogOpen(false)}
/>
@@ -255,14 +251,6 @@ export default function LabsPage() {
mode={ocrCapability.data.mode}
pdfSupported={ocrCapability.data.pdfSupported}
consentRequired={labsOcr.reason === "consent_required"}
onCommitted={() => {
queryClient.invalidateQueries({
queryKey: queryKeys.labResults(),
});
queryClient.invalidateQueries({
queryKey: queryKeys.biomarkers(),
});
}}
/>
) : null}
@@ -143,8 +143,8 @@ describe("NotificationsPage", () => {
},
],
preferences: [],
eventTypes: ["MOOD_REMINDER", "PERSONAL_RECORD"],
eventDefaults: { MOOD_REMINDER: true, PERSONAL_RECORD: false },
eventTypes: ["MOOD_REMINDER", "DAILY_BRIEFING"],
eventDefaults: { MOOD_REMINDER: true, DAILY_BRIEFING: false },
};
const html = render();
const state = (label: string) =>
@@ -152,10 +152,10 @@ describe("NotificationsPage", () => {
`aria-label="${label} - Telegram"[^>]*data-state="(checked|unchecked)"|data-state="(checked|unchecked)"[^>]*aria-label="${label} - Telegram"`,
).exec(html);
const mood = state("Mood reminder");
const record = state("Personal record");
const briefing = state("Daily briefing");
expect(mood, "mood switch rendered").not.toBeNull();
expect(mood?.[1] ?? mood?.[2]).toBe("checked");
expect(record?.[1] ?? record?.[2]).toBe("unchecked");
expect(briefing?.[1] ?? briefing?.[2]).toBe("unchecked");
});
it("a stored row still wins over the default", () => {