Merge remote-tracking branch 'origin/main' into release/v1.47.5

# 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
#	src/__tests__/sharing-surface-guard.test.ts
This commit is contained in:
Marc-André Bombeck committed 2026-11-12 14:25:05 +01:00
commit 5ac998e4f0
112 files changed
+1816 -593

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;
+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`.
@@ -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");
@@ -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) {
@@ -132,7 +132,9 @@ 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[] = [],
@@ -155,6 +157,14 @@ function wireMedicationFindFirst(
}
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(() => {
@@ -168,7 +178,6 @@ beforeEach(() => {
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);
@@ -305,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();
@@ -469,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);
@@ -487,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();
@@ -642,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,
@@ -675,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);
});
@@ -717,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,
@@ -767,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({
@@ -912,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")));
@@ -1224,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 });
});
@@ -1232,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",
@@ -1248,7 +1272,7 @@ describe("POST /api/telegram/webhook — record-only medications", () => {
* silent, so a reminder button left in the chat, the /add list and the
* "taken" keyword do nothing either.
*/
describe("POST /api/telegram/webhook — Medications module off", () => {
describe("POST /api/telegram/webhook with the Medications module off", () => {
function textUpdate(text: string) {
return {
update_id: 400,
@@ -1299,7 +1323,7 @@ describe("POST /api/telegram/webhook — Medications module off", () => {
* 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 — ended course", () => {
describe("POST /api/telegram/webhook on an ended course", () => {
const DAY_MS = 24 * 60 * 60 * 1000;
const ENDED = {
...MEDICATION,
@@ -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(
+51 -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" } });
@@ -337,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) {
+22 -1
View File
@@ -23,6 +23,7 @@ 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: () => ({
@@ -41,7 +42,10 @@ vi.mock("@tanstack/react-query", () => ({
data:
enabled === false
? undefined
: { profile: { heightCm: state.recordHeight } },
: {
targets: [{ type: "BMI", range: state.bmiRange }],
profile: { heightCm: state.recordHeight },
},
}),
}));
@@ -61,6 +65,7 @@ describe("/insights/bmi height gate", () => {
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", () => {
@@ -77,4 +82,20 @@ describe("/insights/bmi height gate", () => {
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();
});
});
+11 -5
View File
@@ -56,15 +56,21 @@ export default function InsightsBmiPage() {
const { data: targets } = useQuery({
queryKey: queryKeys.insightsTargets(),
queryFn: () =>
apiGet<{ profile?: { heightCm: number | null } }>(
"/api/insights/targets",
),
enabled: isAuthenticated && inSharedRecord,
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
@@ -140,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
@@ -12,11 +12,22 @@ describe("selectWeightBandRange", () => {
it("builds the WHO band from the record's height", () => {
const range = selectWeightBandRange({
targets: [
{ type: "WEIGHT", range: { min: 25.8, max: 34.7 }, source: "WHO BMI" },
{ type: "WEIGHT", range: { min: 59.9, max: 81 }, source: "WHO BMI" },
],
profile: { heightCm: 118 },
profile: { heightCm: 180 },
});
expect(range).toEqual(buildWeightRangeFromHeight(118));
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", () => {
+6 -4
View File
@@ -24,14 +24,16 @@ export interface WeightTargetsSlice {
* 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, and with neither there is none.
* 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 {
if (!data) return null;
const weight = data.targets.find((entry) => entry.type === "WEIGHT");
if (weight?.source === "Custom" && weight.range) {
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 },