v1.4.33 — polish and reliability

Quality-leap release between two HealthKit milestones. The headline is a P0 hotfix for the `/api/analytics` 500 that broke the Insights mother page for any account with more than a few thousand measurements: the six per-metric status helpers were spreading the entire numeric history into `Math.min` / `Math.max`, which trips a stack overflow once a single argument list exceeds the V8 spread cap. Both the surfaced symptom and the latent risk in five sibling helpers were folded onto a reduce-based min/max path.

Around that hotfix landed a deep polish pass: the Insights mother page now defers three below-the-fold blocks behind `next/dynamic` to trim the cold mount cost, the analytics endpoint gained a `?slice=summaries` slim slice that the per-metric sub-pages now ride, the Coach snapshot builder picked up a 60 s LRU keyed on `(userId, scope)`, the Settings shell consolidated three duplicate copies of the about / notifications / about-dropdown surfaces, the navigation strip dropped a redundant "Home" group label and a colliding "Notifications" sibling, every icon-only button on the medications and admin surfaces gained an accessible name, every Progress bar gained one too, three pages had their heading hierarchy repaired to a sequential h1 → h2 → h3, the mobile Coach FAB now hides while a chart tooltip is open so it cannot occlude the read-out, and the auth shell normalised every authenticated route to a single `max-w-screen-xl` container.

Also lands the Apple App Site Association handler at `/.well-known/apple-app-site-association` on every host that fronts the app, advertising the iOS bundle's App ID prefix (S8WDX4W5KX.dev.healthlog.app) under `webcredentials.apps` so the passkey ceremony shares cleanly between the web origin and the iOS app.

The release closes nineteen issues from a five-surface audit + a runtime bug-hunt pass, plus six follow-up tracks of polish across the affected surfaces.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-16 19:46:43 +02:00
1 parent c7a0ff214b
commit 7bef199039
186 files changed
+9358 -946

No files matched your search

+12
View File
@@ -22,6 +22,18 @@ describe("queryKeys factory", () => {
"en",
]);
});
// v1.4.33 IW2 — slice param routes the slim consumer onto its own
// cache slot but leaves `["analytics"]` (the root) as a prefix so
// mutation invalidations sweep both shapes.
it("threads the slim slice through queryKeys.analytics", () => {
expect(queryKeys.analytics("summaries")).toEqual(["analytics", "summaries"]);
});
it("keeps the no-arg call byte-identical to the legacy literal", () => {
expect(queryKeys.analytics()).toEqual(["analytics"]);
expect(queryKeys.analytics(undefined)).toEqual(["analytics"]);
});
});
describe("dependent-key bundles", () => {
@@ -1,6 +1,9 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { buildCoachSnapshot } from "../snapshot";
import {
__resetCoachSnapshotCacheForTests,
buildCoachSnapshot,
} from "../snapshot";
vi.mock("@/lib/db", () => ({
prisma: {
@@ -50,6 +53,9 @@ function daysAgo(
describe("buildCoachSnapshot — Apple Health additive metrics (v1.4.23)", () => {
beforeEach(() => {
vi.clearAllMocks();
// v1.4.33 — `buildCoachSnapshot` now memoises results in-process
// for 60 s; reset between tests so each fixture is read fresh.
__resetCoachSnapshotCacheForTests();
prismaMock.moodEntry.findMany.mockResolvedValue([]);
prismaMock.medicationIntakeEvent.findMany.mockResolvedValue([]);
// v1.4.23 H4 — snapshot now reads `User.coachPrefsJson`. Default
+54 -1
View File
@@ -1,6 +1,9 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { buildCoachSnapshot } from "../snapshot";
import {
__resetCoachSnapshotCacheForTests,
buildCoachSnapshot,
} from "../snapshot";
vi.mock("@/lib/db", () => ({
prisma: {
@@ -47,6 +50,10 @@ function daysAgo(
describe("buildCoachSnapshot", () => {
beforeEach(() => {
vi.clearAllMocks();
// v1.4.33 — `buildCoachSnapshot` now memoises results in-process
// for 60 s. Reset the cache between tests so each test sees its
// own freshly-mocked Prisma fixture.
__resetCoachSnapshotCacheForTests();
prismaMock.measurement.findMany.mockResolvedValue([]);
prismaMock.moodEntry.findMany.mockResolvedValue([]);
prismaMock.medicationIntakeEvent.findMany.mockResolvedValue([]);
@@ -182,4 +189,50 @@ describe("buildCoachSnapshot", () => {
const parsed = JSON.parse(out.snapshotJson);
expect(parsed.mood.timeline.recent.length).toBe(1);
});
// v1.4.33 — 60 s in-process snapshot cache. A chat conversation
// sends 2-4 turns within a minute and rebuilding the snapshot from
// ~10 measurement reads on every turn is wasteful. Cache hits skip
// every persistent read; cache misses on a different scope (window
// or sources) compute fresh.
it("memoises the result for repeated (userId, scope) within the 60 s window", async () => {
featuresMock.mockResolvedValue({
weight: { avg30: 82.1, coverage: { count: 5 } },
});
prismaMock.measurement.findMany.mockResolvedValue([
daysAgo(2, 82.0, "WEIGHT"),
daysAgo(5, 82.4, "WEIGHT"),
]);
const first = await buildCoachSnapshot("user-1", { sources: ["weight"] });
const second = await buildCoachSnapshot("user-1", { sources: ["weight"] });
// Same JSON shape on both calls.
expect(second.snapshotJson).toBe(first.snapshotJson);
// Prisma reads ran once for the first call; the second call short-
// circuits on the cache so the count is still 1.
expect(prismaMock.measurement.findMany).toHaveBeenCalledTimes(1);
expect(prismaMock.user.findUnique).toHaveBeenCalledTimes(1);
});
it("recomputes when the scope window or sources change", async () => {
featuresMock.mockResolvedValue({
weight: { avg30: 82.1, coverage: { count: 5 } },
});
prismaMock.measurement.findMany.mockResolvedValue([
daysAgo(3, 82.0, "WEIGHT"),
]);
await buildCoachSnapshot("user-1", {
window: "last7days",
sources: ["weight"],
});
await buildCoachSnapshot("user-1", {
window: "last30days",
sources: ["weight"],
});
// Two distinct window keys → two cache slots → two Prisma reads.
expect(prismaMock.measurement.findMany).toHaveBeenCalledTimes(2);
});
});
+78
View File
@@ -274,6 +274,67 @@ function resolveScope(scope?: CoachScope): {
};
}
/**
* v1.4.33 — 60-second in-memory cache for `buildCoachSnapshot()`. The
* snapshot reads only persisted data; a single chat conversation sends
* 2-4 turns within a minute and the snapshot would otherwise rebuild
* from the same rows each turn. Caching the result for 60s shaves the
* ~10 measurement reads + the GLP-1 / mood / intake side-fetches off
* every turn after the first, which `.planning/round-v1433-audit-perf.md`
* §3.3 estimates at 200-800 ms of server-side tail.
*
* Scope is part of the cache key so a switch from `last30days` to
* `last7days` (or a different `sources` set) computes fresh. The map
* is bounded at 64 entries — a multi-tenant deployment with a few
* active power users sits well inside that ceiling even if each cycles
* through several scopes per minute.
*/
const SNAPSHOT_TTL_MS = 60_000;
const SNAPSHOT_LRU_MAX = 64;
const snapshotCache = new Map<
string,
{ expiresAt: number; result: CoachSnapshotResult }
>();
function snapshotCacheKey(userId: string, scope: CoachScope | undefined): string {
const { sources, window } = resolveScope(scope);
const sourceList = Array.from(sources).sort().join(",");
return `${userId}|${window}|${sourceList}`;
}
function readSnapshotCache(key: string): CoachSnapshotResult | null {
const entry = snapshotCache.get(key);
if (!entry) return null;
if (entry.expiresAt <= Date.now()) {
snapshotCache.delete(key);
return null;
}
// Touch for LRU — re-insert moves to the end of the Map's iteration order.
snapshotCache.delete(key);
snapshotCache.set(key, entry);
return entry.result;
}
function writeSnapshotCache(key: string, result: CoachSnapshotResult): void {
if (snapshotCache.size >= SNAPSHOT_LRU_MAX) {
// Evict the oldest entry — JS Map iteration order is insertion order,
// so the first key is the least-recently inserted/touched.
const oldest = snapshotCache.keys().next().value;
if (oldest !== undefined) {
snapshotCache.delete(oldest);
}
}
snapshotCache.set(key, {
expiresAt: Date.now() + SNAPSHOT_TTL_MS,
result,
});
}
/** Clear the snapshot cache. Test-only escape hatch. */
export function __resetCoachSnapshotCacheForTests(): void {
snapshotCache.clear();
}
/**
* Build the Coach prompt snapshot for `userId`. Always uses
* `includeRaw=false` because the Coach replies are conversational and
@@ -293,10 +354,27 @@ function resolveScope(scope?: CoachScope): {
* user's display timezone (read from `User.timezone`). Falls back to
* Europe/Berlin when the column is missing so the legacy snapshot
* stays byte-identical for the only path the v1.4.24 suite tested.
*
* v1.4.33 — wraps the previous `buildCoachSnapshotImpl` with a 60s
* in-memory LRU keyed on `(userId, window, sources)`. The Coach's
* chat handler calls this once per turn; within the same conversation
* the second+ turn lands a cache hit and skips the row-level reads.
*/
export async function buildCoachSnapshot(
userId: string,
scope?: CoachScope,
): Promise<CoachSnapshotResult> {
const key = snapshotCacheKey(userId, scope);
const cached = readSnapshotCache(key);
if (cached) return cached;
const result = await buildCoachSnapshotImpl(userId, scope);
writeSnapshotCache(key, result);
return result;
}
async function buildCoachSnapshotImpl(
userId: string,
scope?: CoachScope,
): Promise<CoachSnapshotResult> {
const { sources: scopedSources, window } = resolveScope(scope);
@@ -0,0 +1,163 @@
/**
* v1.4.33 C1 — unit-level pin for the slim summaries slice. Heavier
* integration coverage lives in `tests/integration/analytics-summaries-slice.test.ts`
* (real Postgres, real `regr_slope`); this file mocks `$queryRaw` so
* the slope/round/empty contracts are pinned without a container.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
$queryRaw: vi.fn(),
},
}));
vi.mock("@/lib/logging/context", () => ({
annotate: vi.fn(),
}));
import { prisma } from "@/lib/db";
import { computeSummariesSlice } from "../summaries-slice";
const RAW = prisma.$queryRaw as unknown as ReturnType<typeof vi.fn>;
beforeEach(() => {
RAW.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("computeSummariesSlice", () => {
it("returns the empty-summary skeleton when the user has no rows", async () => {
// Pass 1 (aggregates) returns empty, pass 2 (latest) returns empty.
RAW.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
const result = await computeSummariesSlice("user-1");
// Every enum option is seeded so consumers can read
// `summaries.WEIGHT` and get a stable empty shape.
expect(result.summaries.WEIGHT).toEqual({
count: 0,
latest: null,
min: null,
max: null,
mean: null,
avg7: null,
avg30: null,
slope7: null,
slope30: null,
slope90: null,
anomalyCount: 0,
avg30LastMonth: null,
avg30LastYear: null,
});
expect(result.bmi).toBeNull();
// Both SQL passes fired.
expect(RAW).toHaveBeenCalledTimes(2);
});
it("maps a populated aggregate row into the DataSummary shape", async () => {
RAW.mockResolvedValueOnce([
{
type: "WEIGHT",
count: BigInt(42),
min_value: 79.2,
max_value: 84.1,
mean_value: 82.05,
avg7: 81.9,
avg30: 82.1,
slope7: -0.014,
r2_7: 0.65,
slope30: -0.005,
r2_30: 0.42,
slope90: 0.001,
r2_90: 0.12,
},
]).mockResolvedValueOnce([{ type: "WEIGHT", value: 81.4 }]);
const result = await computeSummariesSlice("user-1");
const weight = result.summaries.WEIGHT;
expect(weight.count).toBe(42);
expect(weight.latest).toBe(81.4);
expect(weight.min).toBe(79.2);
expect(weight.max).toBe(84.1);
expect(weight.mean).toBe(82.05);
expect(weight.avg7).toBe(81.9);
expect(weight.avg30).toBe(82.1);
expect(weight.anomalyCount).toBe(0);
expect(weight.avg30LastMonth).toBeNull();
expect(weight.avg30LastYear).toBeNull();
// Slope direction respects the 0.01-units-per-day "stable"
// threshold the JS helper uses. -0.014 → "down", -0.005 →
// "stable", 0.001 → "stable".
expect(weight.slope7).toEqual({
slope: -0.014,
direction: "down",
confidence: 0.65,
});
expect(weight.slope30).toEqual({
slope: -0.005,
direction: "stable",
confidence: 0.42,
});
expect(weight.slope90).toEqual({
slope: 0.001,
direction: "stable",
confidence: 0.12,
});
});
it("returns a null slope tuple when the SQL slope is null (insufficient rows)", async () => {
RAW.mockResolvedValueOnce([
{
type: "PULSE",
count: BigInt(1),
min_value: 72,
max_value: 72,
mean_value: 72,
avg7: 72,
avg30: 72,
// regr_slope returns NULL when n < 2.
slope7: null,
r2_7: null,
slope30: null,
r2_30: null,
slope90: null,
r2_90: null,
},
]).mockResolvedValueOnce([{ type: "PULSE", value: 72 }]);
const result = await computeSummariesSlice("user-1");
expect(result.summaries.PULSE.slope7).toBeNull();
expect(result.summaries.PULSE.slope30).toBeNull();
expect(result.summaries.PULSE.slope90).toBeNull();
});
it("seeds the latest value from the DISTINCT ON pass per type", async () => {
RAW.mockResolvedValueOnce([
{
type: "PULSE",
count: BigInt(3),
min_value: 60,
max_value: 95,
mean_value: 77,
avg7: 77,
avg30: 77,
slope7: 0,
r2_7: 0,
slope30: 0,
r2_30: 0,
slope90: 0,
r2_90: 0,
},
]).mockResolvedValueOnce([{ type: "PULSE", value: 88 }]);
const result = await computeSummariesSlice("user-1");
// Latest is NOT max — comes from the row at MAX(measured_at).
expect(result.summaries.PULSE.latest).toBe(88);
expect(result.summaries.PULSE.max).toBe(95);
});
});
@@ -131,4 +131,36 @@ describe("summarize", () => {
expect(summary.slope7).toBeNull(); // window snaps to `now`, no points
expect(summary.slope30).toBeNull(); // same
});
// v1.4.33 P0 regression — production stacktrace
// `RangeError: Maximum call stack size exceeded` at index 3 of the
// analytics route's per-type `Promise.all` (PULSE).
//
// Root cause: `Math.min(...values)` / `Math.max(...values)` spread the
// whole series as function arguments. V8 caps function arity at
// ~125 000-130 000; an Apple-Health-synced PULSE series easily
// exceeds that for a multi-year power user. The fix folds min/max via
// a single pass instead, keeping the working set bounded.
it("survives a multi-hundred-thousand-row series without blowing the stack", () => {
// 250 000 points — well above V8's spread-arg ceiling. The
// unrolled values give us deterministic min/max so we can assert
// both the safety contract AND the correctness contract in one go.
const N = 250_000;
const now = Date.now();
const data: DataPoint[] = new Array(N);
for (let i = 0; i < N; i++) {
data[i] = {
date: new Date(now - (N - i) * 1000),
// Wave between 40 and 199; min=40, max=199.
value: 40 + (i % 160),
};
}
// Must not throw — before the fix this raised
// `RangeError: Maximum call stack size exceeded`.
const summary = summarize(data);
expect(summary.count).toBe(N);
expect(summary.min).toBe(40);
expect(summary.max).toBe(199);
expect(summary.latest).toBe(data[N - 1].value);
});
});
+236
View File
@@ -0,0 +1,236 @@
/**
* v1.4.33 C1 — slim `summaries` slice for `/api/analytics?slice=summaries`.
*
* The default `/api/analytics` path fans out 30+ `Promise.all`-wrapped
* chunked findMany reads (one per `MeasurementType`) so it can hand
* each series to `summarize()` for slope7/30/90 + anomaly detection +
* lastMonth/lastYear means. The dashboard tile strip only consumes
* `count`, `latest`, `avg7`, `avg30`, `min`, `max`, `mean`, and the
* three slope tuples — every other field gets `null`-coalesced before
* it ever paints — yet the user waits on the full chunked walk.
*
* This helper resolves the same `DataSummary` shape (per-type) with
* two SQL passes:
*
* 1. **`groupBy` + windowed aggregates** — one `$queryRaw` carrying
* `COUNT`/`MIN`/`MAX`/`AVG`, the 7-day and 30-day `AVG` slices
* via `FILTER`, plus `regr_slope` + `regr_r2` for the slope
* tuples at 7d / 30d / 90d windows. Postgres folds all of this
* into one index scan over `measurements WHERE user_id = …`.
*
* 2. **`DISTINCT ON (type)` latest read** — one `$queryRaw`
* returning the most-recent `(type, value)` pair per type so the
* slim shape can populate `latest`. `MAX(value)` would not do —
* we need the value of the row at `MAX(measured_at)`, not the
* largest value ever recorded.
*
* Fields the slim shape intentionally omits (the dashboard never
* reads them on first paint):
* - `anomalyCount`: would require an extra per-type read for the
* z-score loop. The Coach / insights paths still get it via the
* default slice.
* - `avg30LastMonth` / `avg30LastYear`: the dashboard tile delta
* callout uses them, but only when the comparison-baseline
* widget is enabled — that path already pre-fetches the default
* slice via the explicit comparison opt-in.
*
* Slope `confidence` is the SQL `regr_r2` value (R²) which matches
* the existing `trendSlope()` helper's `Math.round(rSquared * 100) /
* 100`. Slope `direction` is derived from `slope`'s sign with the
* same 0.01-units-per-day "stable" threshold the JS helper uses.
*/
import { prisma } from "@/lib/db";
import type { DataSummary } from "@/lib/analytics/trends";
import { measurementTypeEnum } from "@/lib/validations/measurement";
import { annotate } from "@/lib/logging/context";
interface AggregateRow {
type: string;
count: bigint;
min_value: number | null;
max_value: number | null;
mean_value: number | null;
avg7: number | null;
avg30: number | null;
slope7: number | null;
r2_7: number | null;
slope30: number | null;
r2_30: number | null;
slope90: number | null;
r2_90: number | null;
}
interface LatestRow {
type: string;
value: number;
}
/** Same threshold/rounding contract as `trendSlope()` in `trends.ts`. */
function buildSlope(
slope: number | null,
rSquared: number | null,
): DataSummary["slope7"] {
if (slope === null) return null;
const threshold = 0.01;
const direction: "up" | "down" | "stable" =
Math.abs(slope) < threshold ? "stable" : slope > 0 ? "up" : "down";
return {
slope: Math.round(slope * 1000) / 1000,
direction,
confidence: rSquared === null ? 0 : Math.round(rSquared * 100) / 100,
};
}
function round2(value: number | null): number | null {
if (value === null || !Number.isFinite(value)) return null;
return Math.round(value * 100) / 100;
}
function emptySummary(): DataSummary {
return {
count: 0,
latest: null,
min: null,
max: null,
mean: null,
avg7: null,
avg30: null,
slope7: null,
slope30: null,
slope90: null,
anomalyCount: 0,
avg30LastMonth: null,
avg30LastYear: null,
};
}
export interface SummariesSlice {
summaries: Record<string, DataSummary>;
/**
* `null` on the slim slice. The default route computes BMI from
* `summaries.WEIGHT.latest` + `user.heightCm`; consumers of the
* slim slice that need BMI re-derive client-side or fetch the
* default slice.
*/
bmi: null;
}
export async function computeSummariesSlice(
userId: string,
): Promise<SummariesSlice> {
// The two passes run in parallel — they target the same index path
// (`measurements (user_id, type, measured_at)`) but Postgres can
// serve them off the buffer cache concurrently.
const [aggregates, latests] = await Promise.all([
prisma.$queryRaw<AggregateRow[]>`
SELECT
m."type"::text AS type,
COUNT(*) AS count,
MIN(m."value")::double precision AS min_value,
MAX(m."value")::double precision AS max_value,
AVG(m."value")::double precision AS mean_value,
AVG(m."value") FILTER (
WHERE m."measured_at" >= NOW() - INTERVAL '7 days'
)::double precision AS avg7,
AVG(m."value") FILTER (
WHERE m."measured_at" >= NOW() - INTERVAL '30 days'
)::double precision AS avg30,
REGR_SLOPE(
m."value",
EXTRACT(EPOCH FROM m."measured_at") / 86400.0
) FILTER (
WHERE m."measured_at" >= NOW() - INTERVAL '7 days'
)::double precision AS slope7,
REGR_R2(
m."value",
EXTRACT(EPOCH FROM m."measured_at") / 86400.0
) FILTER (
WHERE m."measured_at" >= NOW() - INTERVAL '7 days'
)::double precision AS r2_7,
REGR_SLOPE(
m."value",
EXTRACT(EPOCH FROM m."measured_at") / 86400.0
) FILTER (
WHERE m."measured_at" >= NOW() - INTERVAL '30 days'
)::double precision AS slope30,
REGR_R2(
m."value",
EXTRACT(EPOCH FROM m."measured_at") / 86400.0
) FILTER (
WHERE m."measured_at" >= NOW() - INTERVAL '30 days'
)::double precision AS r2_30,
REGR_SLOPE(
m."value",
EXTRACT(EPOCH FROM m."measured_at") / 86400.0
) FILTER (
WHERE m."measured_at" >= NOW() - INTERVAL '90 days'
)::double precision AS slope90,
REGR_R2(
m."value",
EXTRACT(EPOCH FROM m."measured_at") / 86400.0
) FILTER (
WHERE m."measured_at" >= NOW() - INTERVAL '90 days'
)::double precision AS r2_90
FROM measurements m
WHERE m."user_id" = ${userId}
GROUP BY m."type"
`,
prisma.$queryRaw<LatestRow[]>`
SELECT DISTINCT ON (m."type")
m."type"::text AS type,
m."value"::double precision AS value
FROM measurements m
WHERE m."user_id" = ${userId}
ORDER BY m."type", m."measured_at" DESC
`,
]);
const latestByType = new Map<string, number>();
for (const row of latests) {
latestByType.set(row.type, Number(row.value));
}
// Seed every enum option so consumers can read `summaries.PULSE` and
// get a deterministic empty shape rather than `undefined`. Mirrors
// the default route which iterates `measurementTypeEnum.options`.
const summaries: Record<string, DataSummary> = {};
for (const type of measurementTypeEnum.options) {
summaries[type] = emptySummary();
}
let totalRows = 0;
for (const row of aggregates) {
const count = Number(row.count);
totalRows += count;
const latest = latestByType.get(row.type) ?? null;
summaries[row.type] = {
count,
latest,
min: round2(row.min_value),
max: round2(row.max_value),
mean: round2(row.mean_value),
avg7: round2(row.avg7),
avg30: round2(row.avg30),
slope7: buildSlope(row.slope7, row.r2_7),
slope30: buildSlope(row.slope30, row.r2_30),
slope90: buildSlope(row.slope90, row.r2_90),
anomalyCount: 0,
avg30LastMonth: null,
avg30LastYear: null,
};
}
annotate({
action: { name: "analytics.get.slim" },
meta: {
analytics: {
slim_summaries: {
row_count: totalRows,
type_count: aggregates.length,
},
},
},
});
return { summaries, bmi: null };
}
+20 -3
View File
@@ -192,7 +192,24 @@ export function summarize(data: DataPoint[]): DataSummary {
const sorted = [...data].sort((a, b) => a.date.getTime() - b.date.getTime());
const values = sorted.map((p) => p.value);
const mean = values.reduce((s, v) => s + v, 0) / values.length;
// v1.4.33 P0 — single-pass fold for sum/min/max replaces the previous
// `Math.min(...values)` / `Math.max(...values)` spread. V8 caps
// function arity at ~125k-130k; Apple-Health-synced PULSE series for
// a multi-year power user routinely exceed that, and the spread
// surfaced as `RangeError: Maximum call stack size exceeded` from the
// `/api/analytics` route's per-type `Promise.all` aggregator. Folding
// the three reductions into one walk keeps the working set bounded
// (no transient argument array) and is also cheaper than three
// separate passes.
let sum = 0;
let minVal = values[0];
let maxVal = values[0];
for (const v of values) {
sum += v;
if (v < minVal) minVal = v;
if (v > maxVal) maxVal = v;
}
const mean = sum / values.length;
const now = Date.now();
const DAY = 24 * 60 * 60 * 1000;
@@ -222,8 +239,8 @@ export function summarize(data: DataPoint[]): DataSummary {
return {
count: data.length,
latest: sorted[sorted.length - 1].value,
min: Math.min(...values),
max: Math.max(...values),
min: minVal,
max: maxVal,
mean: Math.round(mean * 100) / 100,
avg7:
last7.length > 0
+2 -2
View File
@@ -169,8 +169,8 @@ export function apiHandler<T extends (...args: any[]) => Promise<Response>>(
// envelope is locked per
// `.planning/RESPONSE-TO-IOS-TEAM-2026-05-16.md` §3 R5.
// Older iOS clients that don't know the errorCode surface
// this as a generic 403; v1.4.31+ clients render the
// `<AssistantDisabledNotice>` empty state.
// this as a generic 403; v1.4.31+ clients can branch on the
// errorCode to render an inline operator-disabled notice.
evt.setError(error);
response = NextResponse.json(
{
+57 -1
View File
@@ -8,8 +8,15 @@ vi.mock("@/lib/db", () => ({
},
}));
// v1.4.33 — `mockEvent` lets the dedicated memoisation describe-block
// below pin a stable WideEventBuilder stub so the per-request cache
// keys on the same reference across multiple `getAssistantFlags()`
// calls. The legacy describe-blocks leave `mockEvent` null so every
// call gets a fresh `{}` and the memo never collapses — preserves the
// pre-v1.4.33 assertion semantics.
let mockEvent: object | null = null;
vi.mock("@/lib/logging/context", () => ({
getEvent: () => ({ addWarning: vi.fn() }),
getEvent: () => mockEvent ?? { addWarning: vi.fn() },
}));
import { prisma } from "@/lib/db";
@@ -25,6 +32,7 @@ const FIND = prisma.appSettings.findUnique as ReturnType<typeof vi.fn>;
beforeEach(() => {
FIND.mockReset();
mockEvent = null;
});
describe("resolveAssistantFlags", () => {
@@ -162,3 +170,51 @@ describe("requireAssistantSurface", () => {
expect(err.errorCode).toBe("assistant.disabled.correlations");
});
});
describe("per-request memoisation", () => {
// v1.4.33 — When the same request opens the Coach drawer, five gated
// routes (`/api/insights/chat`, the rail list, each `<metric>-status`
// call, etc.) all funnel through `getAssistantFlags()` → `AppSettings`
// read. The memo on the active WideEventBuilder collapses those to
// one DB hit.
it("collapses repeated reads inside the same request to one DB call", async () => {
FIND.mockResolvedValue({
assistantEnabled: true,
assistantCoachEnabled: true,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: true,
assistantCorrelationsEnabled: true,
assistantHealthScoreExplainerEnabled: true,
});
// Pin a stable stub object so every `getEvent()` inside this test
// returns the same reference — the memo keys on identity, so a
// shared reference == shared cache.
mockEvent = { addWarning: vi.fn() };
const a = await getAssistantFlags();
const b = await getAssistantFlags();
const c = await getAssistantFlags();
expect(a).toBe(b);
expect(b).toBe(c);
expect(FIND).toHaveBeenCalledTimes(1);
});
it("issues independent reads when the request context changes", async () => {
FIND.mockResolvedValue({
assistantEnabled: true,
assistantCoachEnabled: true,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: true,
assistantCorrelationsEnabled: true,
assistantHealthScoreExplainerEnabled: true,
});
mockEvent = { addWarning: vi.fn(), id: "req-1" };
await getAssistantFlags();
mockEvent = { addWarning: vi.fn(), id: "req-2" };
await getAssistantFlags();
expect(FIND).toHaveBeenCalledTimes(2);
});
});
+41 -30
View File
@@ -1,5 +1,6 @@
import { prisma } from "@/lib/db";
import { getEvent } from "@/lib/logging/context";
import { memoizePerRequest } from "@/lib/request-cache";
/**
* v1.4.31 — Assistant-surface operator feature flags.
@@ -59,37 +60,47 @@ export const ASSISTANT_FLAGS_DEFAULT: AssistantFlagSet = Object.freeze({
*
* The master always wins: every sub-flag is forced false when the
* master is off, before the resolved set leaves this function.
*
* v1.4.33 — memoised per-request so a single Coach-drawer open that
* fires five gated fetches in parallel (`/api/insights/chat`,
* `/api/insights/comprehensive`, six `/api/insights/<metric>-status`
* routes, the rail list) reads `AppSettings.singleton` once instead of
* five times. The cache lives on the active `WideEventBuilder` so it
* goes away with the request; behaviour outside an event context (unit
* tests, background jobs) stays unchanged.
*/
export async function getAssistantFlags(): Promise<AssistantFlagSet> {
try {
const settings = await prisma.appSettings.findUnique({
where: { id: "singleton" },
select: {
assistantEnabled: true,
assistantCoachEnabled: true,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: true,
assistantCorrelationsEnabled: true,
assistantHealthScoreExplainerEnabled: true,
},
});
return memoizePerRequest("assistant-flags", async () => {
try {
const settings = await prisma.appSettings.findUnique({
where: { id: "singleton" },
select: {
assistantEnabled: true,
assistantCoachEnabled: true,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: true,
assistantCorrelationsEnabled: true,
assistantHealthScoreExplainerEnabled: true,
},
});
const master = settings?.assistantEnabled ?? true;
return resolveAssistantFlags({
enabled: master,
coach: settings?.assistantCoachEnabled ?? true,
briefing: settings?.assistantBriefingEnabled ?? true,
insightStatus: settings?.assistantInsightStatusEnabled ?? true,
correlations: settings?.assistantCorrelationsEnabled ?? true,
healthScoreExplainer:
settings?.assistantHealthScoreExplainerEnabled ?? true,
});
} catch {
getEvent()?.addWarning(
"Failed to load assistant feature flags, using defaults",
);
return ASSISTANT_FLAGS_DEFAULT;
}
const master = settings?.assistantEnabled ?? true;
return resolveAssistantFlags({
enabled: master,
coach: settings?.assistantCoachEnabled ?? true,
briefing: settings?.assistantBriefingEnabled ?? true,
insightStatus: settings?.assistantInsightStatusEnabled ?? true,
correlations: settings?.assistantCorrelationsEnabled ?? true,
healthScoreExplainer:
settings?.assistantHealthScoreExplainerEnabled ?? true,
});
} catch {
getEvent()?.addWarning(
"Failed to load assistant feature flags, using defaults",
);
return ASSISTANT_FLAGS_DEFAULT;
}
});
}
/**
@@ -120,8 +131,8 @@ export function resolveAssistantFlags(raw: AssistantFlagSet): AssistantFlagSet {
*
* Older iOS clients that predate the v1.4.31 contract surface this as
* a generic 403 (their existing 403-handler covers the case); v1.4.31+
* clients read the `errorCode` to render the `AssistantDisabledNotice`
* empty-state.
* clients read the `errorCode` to render an inline operator-disabled
* notice.
*/
export class AssistantDisabledError extends Error {
readonly surface: AssistantSurface;
+18 -8
View File
@@ -57,11 +57,6 @@ function round(value: number, digits = 1): number {
return Math.round(value * factor) / factor;
}
function average(values: number[]): number {
if (values.length === 0) return 0;
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function normalizeSummaryText(value: string): string {
return stripChartTokens(value).replace(/\s+/g, " ").trim();
}
@@ -74,14 +69,29 @@ function summarizeSeries(series: Array<{ value: number }>) {
if (series.length === 0) return null;
const first = series[0].value;
const last = series[series.length - 1].value;
// v1.4.33 — fold sum/min/max into a single walk. The previous
// `Math.min(...series.map(...))` / `Math.max(...series.map(...))`
// spread tripped V8's ~125 000-arg ceiling on the bound /api/analytics
// path; see `.planning/round-v1433-analytics-500-report.md` §"Carry-
// over". These helpers are fed bounded windows today so the crash
// never reached them, but the spread allocates a transient args array
// on every call — the fold is both stack-safe and cheaper.
let sum = 0;
let minVal = series[0].value;
let maxVal = series[0].value;
for (const entry of series) {
sum += entry.value;
if (entry.value < minVal) minVal = entry.value;
if (entry.value > maxVal) maxVal = entry.value;
}
return {
points: series.length,
start: round(first, 2),
end: round(last, 2),
delta: round(last - first, 2),
mean: round(average(series.map((entry) => entry.value)), 2),
min: round(Math.min(...series.map((entry) => entry.value)), 2),
max: round(Math.max(...series.map((entry) => entry.value)), 2),
mean: round(sum / series.length, 2),
min: round(minVal, 2),
max: round(maxVal, 2),
};
}
+19 -8
View File
@@ -42,11 +42,6 @@ function round(value: number, digits = 1): number {
return Math.round(value * factor) / factor;
}
function average(values: number[]): number {
if (values.length === 0) return 0;
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function normalizeSummaryText(value: string): string {
return stripChartTokens(value).replace(/\s+/g, " ").trim();
}
@@ -59,14 +54,30 @@ function summarizeSeries(series: Array<{ value: number }>) {
if (series.length === 0) return null;
const first = series[0].value;
const last = series[series.length - 1].value;
// v1.4.33 — fold sum/min/max into a single walk. The previous
// `Math.min(...series.map(...))` / `Math.max(...series.map(...))`
// spread tripped V8's ~125 000-arg ceiling on the bound /api/analytics
// path and is the same anti-pattern fixed in `summarize()` (see
// `.planning/round-v1433-analytics-500-report.md` §"Carry-over").
// These helpers feed off bounded windows today so they did not crash,
// but the spread allocates a transient args array on every call;
// folding once is both stack-safe and cheaper.
let sum = 0;
let minVal = series[0].value;
let maxVal = series[0].value;
for (const entry of series) {
sum += entry.value;
if (entry.value < minVal) minVal = entry.value;
if (entry.value > maxVal) maxVal = entry.value;
}
return {
points: series.length,
start: round(first, 2),
end: round(last, 2),
delta: round(last - first, 2),
mean: round(average(series.map((entry) => entry.value)), 2),
min: round(Math.min(...series.map((entry) => entry.value)), 2),
max: round(Math.max(...series.map((entry) => entry.value)), 2),
mean: round(sum / series.length, 2),
min: round(minVal, 2),
max: round(maxVal, 2),
};
}
+18 -7
View File
@@ -51,10 +51,6 @@ function round(value: number, digits = 1): number {
return Math.round(value * factor) / factor;
}
function average(values: number[]): number {
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function normalizeSummaryText(value: string): string {
return stripChartTokens(value).replace(/\s+/g, " ").trim();
}
@@ -63,14 +59,29 @@ function summarizeSeries(series: Array<{ value: number }>) {
if (series.length === 0) return null;
const first = series[0].value;
const last = series[series.length - 1].value;
// v1.4.33 — fold sum/min/max into a single walk. The previous
// `Math.min(...series.map(...))` / `Math.max(...series.map(...))`
// spread tripped V8's ~125 000-arg ceiling on the bound /api/analytics
// path; see `.planning/round-v1433-analytics-500-report.md` §"Carry-
// over". These helpers are fed bounded windows today so the crash
// never reached them, but the spread allocates a transient args array
// on every call — the fold is both stack-safe and cheaper.
let sum = 0;
let minVal = series[0].value;
let maxVal = series[0].value;
for (const entry of series) {
sum += entry.value;
if (entry.value < minVal) minVal = entry.value;
if (entry.value > maxVal) maxVal = entry.value;
}
return {
points: series.length,
start: round(first, 2),
end: round(last, 2),
delta: round(last - first, 2),
mean: round(average(series.map((entry) => entry.value)), 2),
min: round(Math.min(...series.map((entry) => entry.value)), 2),
max: round(Math.max(...series.map((entry) => entry.value)), 2),
mean: round(sum / series.length, 2),
min: round(minVal, 2),
max: round(maxVal, 2),
};
}
+18 -8
View File
@@ -49,11 +49,6 @@ function round(value: number, digits = 1): number {
return Math.round(value * factor) / factor;
}
function average(values: number[]): number {
if (values.length === 0) return 0;
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function normalizeSummaryText(value: string): string {
return stripChartTokens(value).replace(/\s+/g, " ").trim();
}
@@ -66,14 +61,29 @@ function summarizeSeries(series: Array<{ value: number }>) {
if (series.length === 0) return null;
const first = series[0].value;
const last = series[series.length - 1].value;
// v1.4.33 — fold sum/min/max into a single walk. The previous
// `Math.min(...series.map(...))` / `Math.max(...series.map(...))`
// spread tripped V8's ~125 000-arg ceiling on the bound /api/analytics
// path; see `.planning/round-v1433-analytics-500-report.md` §"Carry-
// over". These helpers are fed bounded windows today so the crash
// never reached them, but the spread allocates a transient args array
// on every call — the fold is both stack-safe and cheaper.
let sum = 0;
let minVal = series[0].value;
let maxVal = series[0].value;
for (const entry of series) {
sum += entry.value;
if (entry.value < minVal) minVal = entry.value;
if (entry.value > maxVal) maxVal = entry.value;
}
return {
points: series.length,
start: round(first, 2),
end: round(last, 2),
delta: round(last - first, 2),
mean: round(average(series.map((entry) => entry.value)), 2),
min: round(Math.min(...series.map((entry) => entry.value)), 2),
max: round(Math.max(...series.map((entry) => entry.value)), 2),
mean: round(sum / series.length, 2),
min: round(minVal, 2),
max: round(maxVal, 2),
};
}
+18 -8
View File
@@ -48,11 +48,6 @@ function round(value: number, digits = 1): number {
return Math.round(value * factor) / factor;
}
function average(values: number[]): number {
if (values.length === 0) return 0;
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function normalizeSummaryText(value: string): string {
return stripChartTokens(value).replace(/\s+/g, " ").trim();
}
@@ -65,14 +60,29 @@ function summarizeSeries(series: Array<{ value: number }>) {
if (series.length === 0) return null;
const first = series[0].value;
const last = series[series.length - 1].value;
// v1.4.33 — fold sum/min/max into a single walk. The previous
// `Math.min(...series.map(...))` / `Math.max(...series.map(...))`
// spread tripped V8's ~125 000-arg ceiling on the bound /api/analytics
// path; see `.planning/round-v1433-analytics-500-report.md` §"Carry-
// over". These helpers are fed bounded windows today so the crash
// never reached them, but the spread allocates a transient args array
// on every call — the fold is both stack-safe and cheaper.
let sum = 0;
let minVal = series[0].value;
let maxVal = series[0].value;
for (const entry of series) {
sum += entry.value;
if (entry.value < minVal) minVal = entry.value;
if (entry.value > maxVal) maxVal = entry.value;
}
return {
points: series.length,
start: round(first, 2),
end: round(last, 2),
delta: round(last - first, 2),
mean: round(average(series.map((entry) => entry.value)), 2),
min: round(Math.min(...series.map((entry) => entry.value)), 2),
max: round(Math.max(...series.map((entry) => entry.value)), 2),
mean: round(sum / series.length, 2),
min: round(minVal, 2),
max: round(maxVal, 2),
};
}
+29 -11
View File
@@ -24,27 +24,45 @@
* enum, the slug array, and the per-slug metric list all derive from
* the keys of this record — adding a sub-page is a one-place change.
*/
// v1.4.33 F9 — order follows the MeasurementCategory overlay
// (`src/lib/measurements/categories.ts`):
//
// vitals → body → activity → sleep → cardiovascular → mood → events
//
// The wave-A HealthKit entries added in v1.4.32 (HRV, resting HR, SpO2,
// body temperature, active energy) used to stack at the end of the
// strip in insertion order; the regrouping below interleaves them into
// their categorical neighbours so a user reading left-to-right scans
// each metric domain as a block. Heavier regrouping (collapse five
// wave-A pills under a single "Apple Health" pill, fold BMI into
// Gewicht, fold Sauerstoff/Körpertemperatur into a single Vitals pill)
// is deferred to v1.4.34 — that needs a screenshot review per
// .planning/round-v1433-audit-menu.md §7.
export const SUB_PAGE_METRIC = {
// ── vitals ──
blutdruck: ["BLOOD_PRESSURE_SYS", "BLOOD_PRESSURE_DIA", "PULSE"],
gewicht: ["WEIGHT"],
puls: ["PULSE"],
stimmung: ["MOOD"],
// medication adherence is event-driven; no measurement series.
medikamente: [],
sauerstoff: ["OXYGEN_SATURATION"],
koerpertemperatur: ["BODY_TEMPERATURE"],
// ── body composition ──
gewicht: ["WEIGHT"],
// BMI is derived from WEIGHT + profile height (no separate series).
bmi: ["WEIGHT"],
schlaf: ["SLEEP_DURATION"],
// ── activity ──
"aktive-energie": ["ACTIVE_ENERGY_BURNED"],
// v1.4.32 — workouts surface; the page reads `Workout` rows directly
// through `useWorkouts()` rather than the `summaries` map, so the
// metric list stays empty.
workouts: [],
// v1.4.32 — five new HealthKit wave-A sub-pages. Each one reads its
// own MeasurementType series via the standard analytics path.
hrv: ["HEART_RATE_VARIABILITY"],
// ── sleep ──
schlaf: ["SLEEP_DURATION"],
// ── cardiovascular ──
ruhepuls: ["RESTING_HEART_RATE"],
sauerstoff: ["OXYGEN_SATURATION"],
koerpertemperatur: ["BODY_TEMPERATURE"],
"aktive-energie": ["ACTIVE_ENERGY_BURNED"],
hrv: ["HEART_RATE_VARIABILITY"],
// ── mood ──
stimmung: ["MOOD"],
// ── events (medication adherence is event-driven; no measurement series) ──
medikamente: [],
} as const satisfies Record<string, readonly string[]>;
export type SubPageSlug = keyof typeof SUB_PAGE_METRIC;
+18 -8
View File
@@ -52,11 +52,6 @@ function round(value: number, digits = 1): number {
return Math.round(value * factor) / factor;
}
function average(values: number[]): number {
if (values.length === 0) return 0;
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function normalizeSummaryText(value: string): string {
return stripChartTokens(value).replace(/\s+/g, " ").trim();
}
@@ -69,14 +64,29 @@ function summarizeSeries(series: Array<{ value: number }>) {
if (series.length === 0) return null;
const first = series[0].value;
const last = series[series.length - 1].value;
// v1.4.33 — fold sum/min/max into a single walk. The previous
// `Math.min(...series.map(...))` / `Math.max(...series.map(...))`
// spread tripped V8's ~125 000-arg ceiling on the bound /api/analytics
// path; see `.planning/round-v1433-analytics-500-report.md` §"Carry-
// over". These helpers are fed bounded windows today so the crash
// never reached them, but the spread allocates a transient args array
// on every call — the fold is both stack-safe and cheaper.
let sum = 0;
let minVal = series[0].value;
let maxVal = series[0].value;
for (const entry of series) {
sum += entry.value;
if (entry.value < minVal) minVal = entry.value;
if (entry.value > maxVal) maxVal = entry.value;
}
return {
points: series.length,
start: round(first, 2),
end: round(last, 2),
delta: round(last - first, 2),
mean: round(average(series.map((entry) => entry.value)), 2),
min: round(Math.min(...series.map((entry) => entry.value)), 2),
max: round(Math.max(...series.map((entry) => entry.value)), 2),
mean: round(sum / series.length, 2),
min: round(minVal, 2),
max: round(maxVal, 2),
};
}
+133
View File
@@ -0,0 +1,133 @@
"use client";
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { queryKeys } from "@/lib/query-keys";
import type { DataSummary } from "@/lib/analytics/trends";
import type { SubPageAnalyticsData } from "@/types/analytics";
/**
* v1.4.33 IW2 — single TanStack-Query wrapper for `/api/analytics`.
*
* Pre-fix, seven mount sites each declared `useQuery({ queryKey:
* ["analytics"], … })` with inconsistent `staleTime` / `enabled` /
* `refetchOnMount` options. TanStack treats the first-mount wins → the
* earliest consumer's options govern the shared cache cell, but every
* route-change re-mount still spins up a fresh subscription tree and
* any consumer without an `enabled: isAuthenticated` short-circuit
* re-issues the network on a back-forward swing. The audit
* (`.planning/round-v1433-audit-perf.md` §1) ranks this as the top-1
* ROI win.
*
* The shared hook:
* - centralises the queryKey via `queryKeys.analytics(slice)`,
* - sets `staleTime: 60_000` so a route swing within a minute is a
* free cache hit,
* - sets `refetchOnMount: false` + `refetchOnWindowFocus: false` so
* route transitions never trigger a refetch storm,
* - defaults to `enabled: isAuthenticated` so the unauthenticated
* surfaces (registration, sign-in) don't spin up a 401-bound
* request,
* - lets the caller opt into the slim `?slice=summaries` server
* branch shipped in IW1 / C1 when the consumer only needs the
* per-type DataSummary headlines (sub-pages, gating helpers,
* onboarding checklist).
*
* The dashboard's mother query keeps the default slice because it also
* reads `bpInTargetPct*` and `glucoseByContext` — those slots stay
* stubbed on the slim path per the IW1 follow-up.
*/
/**
* Strict structural subset shared between the slim slice and the thick
* default payload. Consumers that only read `summaries` should type
* the hook return as `AnalyticsSlicePayload` (or import
* `SubPageAnalyticsData` directly — same shape, kept aliased for
* call-site clarity).
*/
export type AnalyticsSlicePayload = SubPageAnalyticsData;
/**
* Discriminator for the server-side slice. `undefined` (the default)
* routes onto the thick payload; `"summaries"` routes onto IW1's
* `?slice=summaries` branch.
*/
export type AnalyticsSlice = "summaries" | undefined;
/**
* The unwrapped `data` field returned by the API. Typed as a wide
* shape so the dashboard's `bpInTargetPct*` / `glucoseByContext`
* consumers can narrow without a runtime cast. The slim slice fills
* the optional thick fields with `null` / empty so call-site reads
* remain undefined-safe.
*/
export interface AnalyticsRawPayload {
summaries: Record<string, DataSummary>;
// Thick-only fields — present on the default slice, stubbed on the
// slim branch. Optional so the type covers both shapes.
bpInTargetPct?: number | null;
bpInTargetPct7d?: number | null;
bpInTargetPct30d?: number | null;
bpInTargetPctAllTime?: number | null;
bpInTargetPctPriorMonth?: number | null;
bpInTargetPctPriorYear?: number | null;
glucoseByContext?: Record<string, unknown>;
correlations?: unknown;
healthScore?: unknown;
sleepStages?: unknown;
// Keep the contract open — additive server fields don't need a
// type bump every release.
[key: string]: unknown;
}
export interface UseAnalyticsQueryOptions {
/**
* `"summaries"` — hit IW1's slim slice (2 SQL passes, no
* correlations / health-score / bp-in-target / sleep-stages).
* Omit (or pass `undefined`) for the thick default payload.
*/
slice?: AnalyticsSlice;
/**
* Optional override for the auth gate. Defaults to
* `isAuthenticated`. The Insights mother page can pass extra
* disabled-flag composition without losing the auth gate.
*/
enabled?: boolean;
}
async function fetchAnalytics(
slice: AnalyticsSlice,
): Promise<AnalyticsRawPayload> {
const url =
slice === "summaries" ? "/api/analytics?slice=summaries" : "/api/analytics";
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Failed to load analytics (${res.status})`);
}
const json = (await res.json()) as { data: AnalyticsRawPayload };
return json.data;
}
/**
* Shared hook. Returns the raw `data` payload typed as
* `AnalyticsRawPayload`. Consumers can narrow at the call site (e.g.
* `const summaries = query.data?.summaries;`).
*/
export function useAnalyticsQuery(
options: UseAnalyticsQueryOptions = {},
): UseQueryResult<AnalyticsRawPayload, Error> {
const { isAuthenticated } = useAuth();
const slice = options.slice;
const enabled =
options.enabled !== undefined ? options.enabled : isAuthenticated;
return useQuery({
queryKey: queryKeys.analytics(slice),
queryFn: () => fetchAnalytics(slice),
enabled,
staleTime: 60_000,
refetchOnMount: false,
refetchOnWindowFocus: false,
});
}
+11 -1
View File
@@ -16,7 +16,17 @@ export const queryKeys = {
measurements: () => ["measurements"] as const,
moodEntries: () => ["mood-entries"] as const,
analytics: () => ["analytics"] as const,
/**
* v1.4.33 IW2 — the analytics queryKey now optionally carries a
* `slice` discriminator so the dashboard tile-strip can subscribe to
* the slim `?slice=summaries` server slice (IW1 / C1) without
* colliding with the thick-payload consumers on the Insights tree.
* Calling `queryKeys.analytics()` without a slice keeps the legacy
* shape `["analytics"]` so mutation invalidations and the bulk-key
* lists below stay byte-identical.
*/
analytics: (slice?: "summaries") =>
(slice ? (["analytics", slice] as const) : (["analytics"] as const)),
moodAnalytics: () => ["mood-analytics"] as const,
insightsRoot: () => ["insights"] as const,
+73
View File
@@ -0,0 +1,73 @@
/**
* v1.4.33 — per-request memoisation carrier.
*
* Multiple gated routes share the same in-process request lifecycle
* (api-handler wraps every handler in `eventStorage.run(builder, …)`),
* yet the gate helpers and snapshot builders re-read the same row on
* every call. The Coach drawer opening fires five fetches in parallel,
* each of which lands a `requireAssistantSurface("coach")` call —
* five separate `SELECT` against `AppSettings.singleton` for the same
* value within the same wall-clock millisecond.
*
* This helper attaches a request-scoped `Map<string, Promise<unknown>>`
* to the active `WideEventBuilder` from `@/lib/logging/context`. Same
* key inside one request = one compute; different requests get
* independent caches; outside any request (e.g. tests with no event
* context) the factory runs every time so behaviour is unchanged.
*
* The cache is keyed by string. Callers compose composite keys (e.g.
* `"assistant-flags"` or `"coach-snapshot:${userId}:${windowKey}"`).
* The cache is intentionally weak: it lives on the event builder
* itself via a `WeakMap`, so it goes away as soon as the request
* finishes and the builder is collected.
*/
import { getEvent } from "@/lib/logging/context";
import type { WideEventBuilder } from "@/lib/logging/event-builder";
const REQUEST_CACHES = new WeakMap<WideEventBuilder, Map<string, unknown>>();
function getCache(builder: WideEventBuilder): Map<string, unknown> {
let cache = REQUEST_CACHES.get(builder);
if (!cache) {
cache = new Map<string, unknown>();
REQUEST_CACHES.set(builder, cache);
}
return cache;
}
/**
* Memoise `factory()` for the lifetime of the current request. Returns
* the factory's result directly when no event context is active so
* unit tests and background jobs that don't enter `eventStorage.run()`
* keep their existing semantics.
*
* The cached value is the Promise itself, so concurrent callers within
* the same request await one outstanding compute instead of starting
* their own — important for the gate-cascade pattern where five
* mounts fire `requireAssistantSurface()` in parallel.
*/
export function memoizePerRequest<T>(
key: string,
factory: () => Promise<T>,
): Promise<T> {
const event = getEvent();
if (!event) {
return factory();
}
const cache = getCache(event);
const existing = cache.get(key);
if (existing !== undefined) {
return existing as Promise<T>;
}
const promise = factory();
cache.set(key, promise);
// If the factory rejects, evict so a retry on the same key inside
// this request gets a fresh attempt. Cached failures inside a single
// request would mask real recovery (e.g. transient DB hiccup).
promise.catch(() => {
if (cache.get(key) === promise) {
cache.delete(key);
}
});
return promise;
}