Merge branch 'feat/module-surfaces' into release/v1.39.0

This commit is contained in:
Marc-André Bombeck committed 2026-09-24 10:10:11 +02:00
commit ab0d1b4b71
67 files changed
+1975 -703

No files matched your search

-16
View File
@@ -4,7 +4,6 @@
* Single source of truth for which widgets show on /, what order, and
* what the default layout is for new users. Null / missing = default.
*/
import type { ModuleKey } from "@/lib/modules/registry";
import {
PRIORITY_ITEM_KINDS,
isPriorityItemKind,
@@ -513,21 +512,6 @@ export function resolveHeroRingOrder(
return out;
}
/**
* Ring id → owning toggleable module. Mirrors the derived routes'
* `DERIVED_MODULE` map for the three derived rings (READINESS rides the
* recovery module like the recovery/strain/stress trio); MED_COMPLIANCE
* belongs to the medications module. Client-safe (type-only ModuleKey
* import) so the Settings picker and the server snapshot resolver gate
* on the same map — the `WIDGET_MODULE_BY_ID` pattern.
*/
export const SCORE_RING_MODULE: Record<ScoreRingId, ModuleKey> = {
READINESS: "recovery",
RECOVERY_SCORE: "recovery",
SLEEP_SCORE: "sleep",
MED_COMPLIANCE: "medications",
};
function isScoreRingId(value: unknown): value is ScoreRingId {
return (
typeof value === "string" &&
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import { hideModuleWidgets } from "@/lib/dashboard/widget-modules";
const layout = {
version: 2,
widgets: [
{ id: "weight", visible: true, tileVisible: true, order: 0 },
{ id: "medications", visible: true, tileVisible: true, order: 1 },
{ id: "mood", visible: true, tileVisible: true, order: 2 },
{ id: "hrv", visible: true, tileVisible: true, order: 3 },
],
};
describe("hideModuleWidgets", () => {
it("hides the widgets of a switched-off module and keeps their order", () => {
const out = hideModuleWidgets(layout, { medications: false });
expect(out.widgets.map((w) => [w.id, w.visible, w.tileVisible])).toEqual([
["weight", true, true],
["medications", false, false],
["mood", true, true],
["hrv", true, true],
]);
});
it("hides the ids it is told to on top of the module mask", () => {
const out = hideModuleWidgets(layout, {}, new Set(["hrv"]));
expect(out.widgets.find((w) => w.id === "hrv")?.visible).toBe(false);
expect(out.widgets.find((w) => w.id === "mood")?.visible).toBe(true);
});
it("is a no-op before the module map is known", () => {
expect(hideModuleWidgets(layout, undefined).widgets).toEqual(
layout.widgets,
);
});
it("never writes through to the layout it was given", () => {
hideModuleWidgets(layout, { mood: false, medications: false });
expect(layout.widgets.every((w) => w.visible)).toBe(true);
});
});
+20 -12
View File
@@ -3,7 +3,8 @@
*
* The resolver is tested in isolation with the derived dispatcher
* mocked, pinning:
* - module gating (owning module + the insights gate on derived rings);
* - module gating (the owning module, from the surface map; the insights
* key, AI analysis, gates no ring);
* - the pass-through contract for derived scores (same resolvers the
* batch route calls, no recomputation, non-`ok` → no ring);
* - the dose ring: today's taken/scheduled progress off the shared
@@ -117,7 +118,11 @@ describe("buildScoreRingsBlock() — selection + module gating", () => {
);
});
it("the insights gate drops derived rings but keeps the dose ring", async () => {
it("keeps derived rings with AI analysis off: the scores are data", async () => {
computeDerivedMetric.mockResolvedValue({
status: "ok",
value: { score: 70, band: "yellow" },
});
const rings = await buildScoreRingsBlock(
fakePrisma,
"user-1",
@@ -126,16 +131,19 @@ describe("buildScoreRingsBlock() — selection + module gating", () => {
NOW,
medsToday(2, 2),
);
expect(computeDerivedMetric).not.toHaveBeenCalled();
expect(loadBaselineProfile).not.toHaveBeenCalled();
expect(rings).toEqual([
{
id: "MED_COMPLIANCE",
score: 100,
band: "green",
doses: { taken: 2, scheduled: 2 },
},
]);
expect(rings.map((r) => r.id)).toEqual(["READINESS", "MED_COMPLIANCE"]);
});
it("drops the dose ring with the medications module off", async () => {
const rings = await buildScoreRingsBlock(
fakePrisma,
"user-1",
["MED_COMPLIANCE"],
moduleMap({ medications: false }),
NOW,
medsToday(2, 2),
);
expect(rings).toEqual([]);
});
});
+7 -16
View File
@@ -25,22 +25,18 @@
* taken, `yellow` while doses remain — never `red`: pending doses in
* the morning are not an alert state.
*
* Module gating rides the client-safe `SCORE_RING_MODULE` map in
* `@/lib/dashboard-layout` (mirroring the derived routes'
* `DERIVED_MODULE`: readiness/recovery → recovery module, sleep score →
* sleep module, MED_COMPLIANCE → medications) plus the `insights` gate
* every derived read sits behind.
* Module gating reads the surface map (`score-ring:<id>` in
* `@/lib/modules/surface`): readiness/recovery → recovery, sleep score →
* sleep, MED_COMPLIANCE → medications. The derived scores are data, so the
* `insights` key (AI analysis) gates no ring.
*
* Every ring resolves fail-soft: a throwing engine drops its ring, never
* the snapshot.
*/
import type { PrismaClient } from "@/generated/prisma/client";
import type { ModuleKey } from "@/lib/modules/gate";
import {
SCORE_RING_IDS,
SCORE_RING_MODULE,
type ScoreRingId,
} from "@/lib/dashboard-layout";
import { SCORE_RING_IDS, type ScoreRingId } from "@/lib/dashboard-layout";
import { isSurfaceVisible } from "@/lib/modules/surface";
import {
computeDerivedMetric,
loadBaselineProfile,
@@ -122,12 +118,7 @@ export async function buildScoreRingsBlock(
): Promise<DashboardScoreRing[]> {
const eligible = selected.filter((id) => {
if (!(SCORE_RING_IDS as readonly string[]).includes(id)) return false;
if (modules[SCORE_RING_MODULE[id]] === false) return false;
// The derived scores are an insights-layer read everywhere else
// (`/api/insights/derived*` sits behind the insights module) — the
// snapshot honours the same gate.
if (DERIVED_RING_METRIC[id] && modules.insights === false) return false;
return true;
return isSurfaceVisible(`score-ring:${id}`, modules);
});
if (eligible.length === 0) return [];
+6 -22
View File
@@ -135,8 +135,8 @@ export {
SUMMARY_TYPE_MODULE,
} from "@/lib/dashboard/widget-modules";
import {
WIDGET_MODULE_BY_ID,
gateSummariesByModules,
hideModuleWidgets,
unavailableWidgetIds,
} from "@/lib/dashboard/widget-modules";
@@ -1079,38 +1079,22 @@ function isThickPhaseWarm(coverage: RollupCoverageMap): boolean {
}
/**
* v1.18.0 — force every widget whose module is disabled to invisible on
* the resolved layout (both `visible` and `tileVisible`). Order is
* preserved so a re-enable restores the user's saved position. Pure
* projection — the persisted `dashboardWidgetsJson` is untouched; only
* what the snapshot publishes is gated.
* The layout the snapshot publishes: widgets of a switched-off module, and
* widgets that cannot paint for this account, forced invisible. Same rule the
* Settings screen hides their toggles with, so the dashboard and the switches
* never disagree. The stored layout is untouched.
*/
function gateLayoutByModules(
layout: DashboardLayout,
modules: Record<ModuleKey, boolean>,
summaries: Record<string, DataSummary>,
): DashboardLayout {
// Widgets that cannot paint for THIS account, on the same rule the
// Settings screen hides their toggle with — so the layout the dashboard
// renders and the switches the user is offered never disagree.
const unavailable = new Set(
unavailableWidgetIds(modules, {
hasSdnn: (summaries.HEART_RATE_VARIABILITY?.count ?? 0) > 0,
}),
);
return {
...layout,
widgets: layout.widgets.map((w) => {
const moduleKey = WIDGET_MODULE_BY_ID[w.id];
if (moduleKey && modules[moduleKey] === false) {
return { ...w, visible: false, tileVisible: false };
}
if (unavailable.has(w.id)) {
return { ...w, visible: false, tileVisible: false };
}
return w;
}),
};
return hideModuleWidgets(layout, modules, unavailable);
}
/**
+53 -69
View File
@@ -13,83 +13,67 @@
* imports), so this file stays browser-bundle-safe.
*/
import type { ModuleKey } from "@/lib/modules/registry";
import { isSurfaceVisible, surfaceModulesOfKind } from "@/lib/modules/surface";
/**
* Dashboard widget id → toggleable module key. When the user disables the
* module, the matching widget is forced invisible on both the web `layout`
* and the iOS `layoutCatalogue`, so the tile/chart never paints. Only the
* toggleable surfaces appear here; CORE widgets (weight / bp / pulse /
* bodyFat / bpInTarget and the vital-derived HealthKit metrics) carry NO
* entry and are never hidden.
* Dashboard widget id → toggleable module key. A widget whose module is off
* is forced invisible on both the web `layout` and the iOS
* `layoutCatalogue`. CORE widgets carry no entry and are never hidden.
*
* v1.18.1 (D3) — `medications` graduated from CORE to a toggleable module,
* so the medication tile now gates off it like the other toggleable widgets.
* A view of the one surface map (`widget:*` in `@/lib/modules/surface`), so
* the dashboard, the Settings list and every other surface answer from the
* same declaration.
*/
export const WIDGET_MODULE_BY_ID: Partial<Record<string, ModuleKey>> = {
mood: "mood",
sleep: "sleep",
glucose: "glucose",
achievements: "achievements",
recentWorkouts: "workouts",
medications: "medications",
// v1.18.0 B1 — recovery-domain HealthKit widgets belong to the recovery
// module; the per-night breathing-disturbance widget belongs to sleep.
cardioRecovery: "recovery",
sixMinuteWalk: "recovery",
stairAscentSpeed: "recovery",
stairDescentSpeed: "recovery",
breathingDisturbances: "sleep",
// v1.29 — fluid-intake strip tile, nutrients-store-backed (see
// `SUMMARY_TYPE_MODULE.NUTRIENT_WATER` below).
waterIntake: "nutrients",
};
export const WIDGET_MODULE_BY_ID: Partial<Record<string, ModuleKey>> =
surfaceModulesOfKind("widget");
/**
* Slim-summary keys that belong to a toggleable module. When the module
* is off the key is stripped from `tiles.summaries` /
* `tiles.lastSeenByType` (so `metricStates` and the client data-floor
* gates also drop it) before the snapshot leaves the server. Core vital
* types are absent here and always pass through.
* Summary keys that belong to a toggleable module. When the module is off the
* key is stripped from `tiles.summaries` / `tiles.lastSeenByType` (so
* `metricStates` and the client data-floor gates drop it too) before the
* snapshot leaves the server. Core vital types are absent and always pass.
*
* v1.29 — widened from `Partial<Record<MeasurementType, ModuleKey>>` to
* `Partial<Record<string, ModuleKey>>` so the synthetic `NUTRIENT_WATER`
* key (a `NutrientIntakeDay`-derived summary, not a real
* `MeasurementType` — the abandoned `feat/water` branch's parallel
* `WATER_INTAKE` enum value is deliberately NOT added) can ride the same
* gate without widening the `MeasurementType` enum itself.
* Keyed by string rather than `MeasurementType` because two keys are
* synthetic (`NUTRIENT_WATER`, `MOOD_ENTRY`: day totals derived from other
* stores). A view of `summary:*` in `@/lib/modules/surface`.
*/
export const SUMMARY_TYPE_MODULE: Partial<Record<string, ModuleKey>> = {
SLEEP_DURATION: "sleep",
BLOOD_GLUCOSE: "glucose",
// v1.18.0 B1 — recovery-domain HealthKit metrics. The recovery page +
// its tiles are the recovery module's surface; when it is off these
// device-native signals must drop from the dashboard snapshot too.
CARDIO_RECOVERY: "recovery",
SIX_MINUTE_WALK_DISTANCE: "recovery",
STAIR_ASCENT_SPEED: "recovery",
STAIR_DESCENT_SPEED: "recovery",
// The HRV fallback series. `METRIC_STATUS_MODULE_OWNERS` already owns this
// type for the metric-status / MCP reads, for the reason stated there: a
// fallback path must not serve the recovery data the primary type refuses.
// The dashboard snapshot gates off THIS map instead, and the entry was
// missing — harmless only while the dashboard HRV tile read SDNN alone.
// Now that the tile falls back to RMSSD (`pickHrvSummary`), the omission
// would hand a recovery-off account a tile built from recovery-owned rows.
// `HEART_RATE_VARIABILITY` stays deliberately ungated: SDNN is a plain
// vital, and it is what the tile shows whenever the account has it.
HRV_RMSSD: "recovery",
// Per-night breathing-disturbance index is a sleep-page signal.
BREATHING_DISTURBANCES: "sleep",
// v1.29 — fluid-intake dashboard tile summary, derived server-side from
// `NutrientIntakeDay` (nutrient="water", summed across sources). Gated
// on the `nutrients` module like the rest of that store's surfaces.
NUTRIENT_WATER: "nutrients",
// Mood is a `MoodEntry`-derived summary, not a `MeasurementType`, so it
// rides the same synthetic-key route as `NUTRIENT_WATER`. Gated on the
// `mood` module: turning the module off must drop the dashboard card on
// every client, not just hide the web widget.
MOOD_ENTRY: "mood",
};
export const SUMMARY_TYPE_MODULE: Partial<Record<string, ModuleKey>> =
surfaceModulesOfKind("summary");
/**
* Force every widget whose owning module is off, and every id in `alsoHide`,
* to invisible (both `visible` and `tileVisible`). Order is kept so a
* re-enable restores the saved position.
*
* A projection for RENDERING only. The stored `dashboardWidgetsJson` is never
* written through this: `GET /api/dashboard/widgets` returns the stored
* layout as saved, because Settings edits and re-saves exactly that value,
* and a masked read saved back would switch the widget off for good. The
* dashboard snapshot applies it server-side; the dashboard's legacy (no
* snapshot) path applies it in the browser, so both feeds paint the same.
*/
export function hideModuleWidgets<
L extends {
widgets: ReadonlyArray<{
id: string;
visible: boolean;
tileVisible?: boolean;
}>;
},
>(
layout: L,
modules: Partial<Record<ModuleKey, boolean>> | null | undefined,
alsoHide: ReadonlySet<string> = new Set(),
): L {
return {
...layout,
widgets: layout.widgets.map((w) =>
isSurfaceVisible(`widget:${w.id}`, modules) && !alsoHide.has(w.id)
? w
: { ...w, visible: false, tileVisible: false },
),
};
}
/**
* The summary types a module map turns off. Lifted out of
@@ -0,0 +1,137 @@
/**
* The discovery matrix leaves out every channel whose module the record
* switched off, through the surface map, so no correlation statistic is
* computed over a switched-off module.
*/
import { describe, expect, it, vi } from "vitest";
const pts = [{ day: "2026-09-01", value: 1 }];
vi.mock("@/lib/insights/correlation-channel-series", () => ({
buildMeasurementDailySeries: vi.fn(),
fetchMeasurementWindowSeries: vi.fn(),
fetchMeasurementDailySeriesTiered: vi.fn(
async (_u: string, _tz: string, _s: Date, types: string[]) => ({
byType: new Map(types.map((t) => [t, pts])),
measurementsCapped: false,
rollupTypes: [],
}),
),
fetchMoodWindowSeries: vi.fn(async () => ({
moodDaily: pts,
moodCapped: false,
})),
fetchMoodFactorWindowSeries: vi.fn(async () => ({
moodDaily: pts,
moodCapped: false,
factorSeries: new Map([["FACTOR:work", pts]]),
})),
fetchComplianceSeries: vi.fn(async () => ({
key: "MEDICATION_COMPLIANCE",
role: "behaviour",
points: pts,
})),
fetchSymptomSeries: vi.fn(async () => ({
key: "SYMPTOM_SEVERITY",
role: "outcome",
points: pts,
})),
fetchEnvironmentSeries: vi.fn(async () => [
{ key: "ENV_TEMP_MEAN", role: "behaviour", points: pts },
]),
fetchCustomMetricBehaviourSeries: vi.fn(async () => [
{ key: "CUSTOM_METRIC:abc", role: "behaviour", points: pts },
]),
}));
vi.mock("@/lib/rollups/measurement-read", () => ({
loadUserSourcePriority: vi.fn(),
}));
import {
assembleDiscoveryMatrix,
maskSeriesByModules,
} from "@/lib/insights/discovery-matrix";
const OPTS = {
tz: "UTC",
since: new Date("2026-03-01T00:00:00Z"),
fetchMode: "tiered" as const,
includeMoodFactors: true,
};
const keysOf = (series: { key: string }[]) => [
...new Set(series.map((s) => s.key)),
];
describe("assembleDiscoveryMatrix — switched-off modules", () => {
it("keeps every channel without a module map", async () => {
const { series } = await assembleDiscoveryMatrix("u1", OPTS);
const keys = keysOf(series);
for (const key of [
"MOOD",
"FACTOR:work",
"SLEEP_DURATION",
"BLOOD_GLUCOSE",
"MEDICATION_COMPLIANCE",
"SYMPTOM_SEVERITY",
"ENV_TEMP_MEAN",
"CUSTOM_METRIC:abc",
"WEIGHT",
]) {
expect(keys).toContain(key);
}
});
it("drops each module's channels, and only those, when it is off", async () => {
const { series, byMetric } = await assembleDiscoveryMatrix("u1", {
...OPTS,
modules: {
mood: false,
sleep: false,
glucose: false,
medications: false,
illness: false,
environment: false,
},
});
const keys = keysOf(series);
for (const gone of [
"MOOD",
"FACTOR:work",
"SLEEP_DURATION",
"BLOOD_GLUCOSE",
"MEDICATION_COMPLIANCE",
"SYMPTOM_SEVERITY",
"ENV_TEMP_MEAN",
]) {
expect(keys, gone).not.toContain(gone);
expect(byMetric.has(gone), gone).toBe(false);
}
// Core vitals and custom metrics belong to no module.
expect(keys).toContain("WEIGHT");
expect(keys).toContain("BLOOD_PRESSURE_SYS");
expect(keys).toContain("CUSTOM_METRIC:abc");
});
it("drops nothing for AI analysis off", async () => {
const all = await assembleDiscoveryMatrix("u1", OPTS);
const off = await assembleDiscoveryMatrix("u1", {
...OPTS,
modules: { insights: false },
});
expect(off.series.map((s) => s.key)).toEqual(all.series.map((s) => s.key));
});
});
describe("maskSeriesByModules", () => {
it("keeps the fold order of what remains", () => {
const series = ["WEIGHT", "MOOD", "PULSE", "FACTOR:x"].map((key) => ({
key,
role: "behaviour" as const,
points: pts,
}));
expect(
maskSeriesByModules(series, { mood: false }).map((s) => s.key),
).toEqual(["WEIGHT", "PULSE"]);
});
});
@@ -1,6 +1,7 @@
import { describe, it, expect } from "vitest";
import type { DailyBriefing, DailyBriefingKeyFinding } from "@/lib/ai/schema";
import { isSurfaceVisible, surfaceModule } from "@/lib/modules/surface";
import {
selectTrendCharts,
DEFAULT_TREND_CHART_CAP,
@@ -158,23 +159,58 @@ describe("selectTrendCharts", () => {
});
});
describe("selectTrendCharts — hidden metrics", () => {
it("drops mood from the fallback triple when the mood module is off", () => {
const charts = selectTrendCharts(null, { hiddenMetrics: ["mood"] });
expect(charts.map((c) => c.metric)).not.toContain("mood");
expect(charts).toHaveLength(2);
describe("selectTrendCharts — switched-off modules", () => {
it("fills the fallback row from the next metric when mood is off", () => {
const charts = selectTrendCharts(null, { modules: { mood: false } });
expect(charts.map((c) => c.metric)).toEqual(["bp", "weight", "pulse"]);
});
it("skips a hidden metric the briefing flags", () => {
it("keeps the familiar blood pressure, weight, mood row with every module on", () => {
const charts = selectTrendCharts(null, { modules: {} });
expect(charts.map((c) => c.metric)).toEqual(["bp", "weight", "mood"]);
});
it("skips a flagged metric whose module is off and lets the next finding take the slot", () => {
const charts = selectTrendCharts(briefing(["sleep", "mood", "weight"]), {
modules: { sleep: false, mood: false },
});
expect(charts.map((c) => c.metric)).toEqual(["weight"]);
});
it("still honours an explicit hide list", () => {
const charts = selectTrendCharts(briefing(["mood", "weight"]), {
hiddenMetrics: ["mood"],
});
expect(charts.map((c) => c.metric)).not.toContain("mood");
expect(charts).toHaveLength(1);
expect(charts.map((c) => c.metric)).toEqual(["weight"]);
});
it("keeps mood when nothing is hidden", () => {
const charts = selectTrendCharts(null, { hiddenMetrics: [] });
expect(charts.map((c) => c.metric)).toContain("mood");
it("never returns a slot whose module is off, for any module map and briefing", () => {
// Exhaustive over every on/off combination of the owning modules, with
// every finding a briefing can carry, in both directions.
const owners = [
...new Set(
Object.keys(TREND_CHART_CONFIG)
.map((m) => surfaceModule(`trend:${m}`))
.filter((k): k is NonNullable<typeof k> => k !== undefined),
),
];
expect(owners.length).toBeGreaterThan(0);
const all = Object.keys(TREND_CHART_CONFIG) as Array<
keyof typeof TREND_CHART_CONFIG
>;
const briefings = [null, briefing(all), briefing([...all].reverse())];
for (let mask = 0; mask < 1 << owners.length; mask += 1) {
const modules = Object.fromEntries(
owners.map((key, i) => [key, (mask & (1 << i)) === 0]),
);
for (const b of briefings) {
for (const chart of selectTrendCharts(b, { modules })) {
expect(
isSurfaceVisible(`trend:${chart.metric}`, modules),
`${chart.metric} under ${JSON.stringify(modules)}`,
).toBe(true);
}
}
}
});
});
+34 -1
View File
@@ -57,6 +57,11 @@ import {
type MoodFactorWindowFetch,
} from "@/lib/insights/correlation-channel-series";
import { loadUserSourcePriority } from "@/lib/rollups/measurement-read";
import {
correlationChannelSurfaceId,
isSurfaceVisible,
type SurfaceModuleMap,
} from "@/lib/modules/surface";
/**
* How the measurement channels are read.
@@ -117,6 +122,14 @@ export interface DiscoveryMatrixOptions {
* measurement read instead of a second one.
*/
extraMeasurementTypes?: readonly MeasurementType[];
/**
* The record's resolved module map. A channel whose module is off
* (`correlation:<key>` in the surface map: mood and its rated factors,
* sleep, glucose, medication adherence, symptoms, weather) is left out of
* `series` and `byMetric`, so no statistic is computed over a module the
* person switched off. Omitted: every channel is kept.
*/
modules?: SurfaceModuleMap;
}
/** Per-channel reach, for the callers' wide-event annotations. */
@@ -150,6 +163,20 @@ export interface DiscoveryMatrix {
diagnostics: DiscoveryMatrixDiagnostics;
}
/**
* Leave out every channel whose owning module is off. Pure, and applied after
* the fold so the order of what remains is the order it was folded in (the
* ranking stability note on {@link assembleDiscoveryMatrix}).
*/
export function maskSeriesByModules(
series: readonly NamedSeries[],
modules: SurfaceModuleMap | null | undefined,
): NamedSeries[] {
return series.filter((s) =>
isSurfaceVisible(correlationChannelSurfaceId(s.key), modules),
);
}
/**
* The mood read, normalised to the factor-carrying shape. With factors off the
* factor map is empty, so the fold below has one code path rather than two.
@@ -302,8 +329,14 @@ export async function assembleDiscoveryMatrix(
byMetric.set(key, factorPoints);
}
for (const key of [...byMetric.keys()]) {
if (!isSurfaceVisible(correlationChannelSurfaceId(key), opts.modules)) {
byMetric.delete(key);
}
}
return {
series,
series: maskSeriesByModules(series, opts.modules),
byMetric,
diagnostics: {
measurementsCapped: measurements.measurementsCapped,
+26 -6
View File
@@ -1,4 +1,5 @@
import type { DailyBriefing, DailyBriefingKeyFinding } from "@/lib/ai/schema";
import { isSurfaceVisible, type SurfaceModuleMap } from "@/lib/modules/surface";
/**
* v1.8.5 — derive the Insights overview "Trends" chart set from the
@@ -261,6 +262,15 @@ export const DEFAULT_TREND_METRICS: ReadonlyArray<
DailyBriefingKeyFinding["sourceMetric"]
> = ["bp", "weight", "mood"];
/**
* Metrics the fallback row reaches for, in order, when a default slot is left
* out because its module is off. Pulse is a core vital, so a row without mood
* still paints three charts rather than two.
*/
const FALLBACK_FILL_METRICS: ReadonlyArray<
DailyBriefingKeyFinding["sourceMetric"]
> = ["pulse"];
/** Max charts the row renders. Three keeps the equal-height 3-up grid. */
export const DEFAULT_TREND_CHART_CAP = 3;
@@ -268,10 +278,13 @@ export interface SelectTrendChartsOptions {
/** Max number of charts to return. Defaults to {@link DEFAULT_TREND_CHART_CAP}. */
cap?: number;
/**
* Metrics whose module is switched off. They are skipped on both the
* briefing path and the fallback triple, so a disabled module never
* charts on the overview.
* The record's resolved module map (`GET /api/auth/me` `modules`). A slot
* whose module is off (`trend:<metric>` in the surface map) is skipped on
* both the briefing path and the fallback row, and the next eligible
* metric takes its place. Absent or partial: every slot is eligible.
*/
modules?: SurfaceModuleMap | null;
/** Further metrics to leave out, on top of the module map. */
hiddenMetrics?: ReadonlyArray<DailyBriefingKeyFinding["sourceMetric"]>;
}
@@ -279,12 +292,14 @@ function configsFor(
metrics: ReadonlyArray<DailyBriefingKeyFinding["sourceMetric"]>,
cap: number,
hidden: ReadonlySet<string>,
modules: SurfaceModuleMap | null | undefined,
): TrendChartConfig[] {
const seen = new Set<string>();
const out: TrendChartConfig[] = [];
for (const metric of metrics) {
if (out.length >= cap) break;
if (hidden.has(metric)) continue; // module switched off
if (hidden.has(metric)) continue;
if (!isSurfaceVisible(`trend:${metric}`, modules)) continue; // module off
const config = TREND_CHART_CONFIG[metric];
if (!config) continue; // metric has no standalone trend chart
if (seen.has(config.metric)) continue; // dedupe
@@ -313,11 +328,16 @@ export function selectTrendCharts(
const findingMetrics =
briefing?.keyFindings?.map((f) => f.sourceMetric) ?? [];
const fromBriefing = configsFor(findingMetrics, cap, hidden);
const fromBriefing = configsFor(findingMetrics, cap, hidden, options.modules);
if (fromBriefing.length > 0) {
return fromBriefing;
}
return configsFor(DEFAULT_TREND_METRICS, cap, hidden);
return configsFor(
[...DEFAULT_TREND_METRICS, ...FALLBACK_FILL_METRICS],
cap,
hidden,
options.modules,
);
}
@@ -0,0 +1,335 @@
/**
* Structural guard on the surface map (`src/lib/modules/surface.ts`).
*
* The map is the one answer to "which module owns this surface". It only
* works if two things stay true, and each half of this file holds one:
*
* 1. Every id in the map names a surface that exists. A nav href, a slug, a
* section id, a widget id that was renamed would leave an entry that
* matches nothing, and the surface it meant would silently stop hiding.
* Each family is checked against the list the app actually renders from.
*
* 2. Every surface that shows a module's data is owned by that module. This
* half cannot come from the map itself, so it is derived from a second
* source: the measurement types each surface plots, joined against the
* summary owners the dashboard already gates on. A sleep page with no
* sleep entry, or a trends slot charting a recovery-owned series with no
* owner, fails here by name. A short table of owners that no data join
* can derive (nav pages, the add menu, overview blocks) is pinned below.
*
* Plus the retirement half: the per-surface maps and guard hooks this map
* replaced must not come back, so their names are searched for in source.
*
* Limits, stated so nobody reads more into a green run: the data join only
* sees surfaces that declare the types they plot, so a surface that reads a
* module's store without declaring a type would pass. The source search
* matches names, not behaviour; a copy under a new name passes. Every match
* set asserts a non-zero count so a matcher that stopped matching fails.
*/
import { readFileSync, existsSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
// The capture picker and the Settings shell pull in forms and sections; the
// guard needs only their exported lists.
vi.mock("@/components/measurements/measurement-form", () => ({
MeasurementForm: () => null,
}));
vi.mock("@/components/mood/mood-form", () => ({ MoodForm: () => null }));
vi.mock("@/components/dashboard/medication-intake-quick-add", () => ({
MedicationIntakeQuickAdd: () => null,
}));
import {
walkSourceFiles,
stripComments,
} from "@/__tests__/helpers/source-files";
import { NAV_DESTINATIONS } from "@/components/layout/nav-model";
import { CAPTURE_KIND_ORDER } from "@/components/layout/capture-picker";
import { SETTINGS_SECTIONS } from "@/components/settings/settings-shell";
import { LAYOUT_GROUP_IDS } from "@/components/settings/layout-groups";
import {
DASHBOARD_WIDGET_CATALOGUE_IDS,
SCORE_RING_IDS,
} from "@/lib/dashboard-layout";
import { SUMMARY_TYPE_MODULE } from "@/lib/dashboard/widget-modules";
import { ENVIRONMENT_FIELDS } from "@/lib/environment/fields";
import {
DISCOVERY_BEHAVIOURS,
DISCOVERY_OUTCOMES,
FACTOR_CHANNEL_PREFIX,
} from "@/lib/insights/correlation-discovery";
import { DERIVED_METRIC_IDS } from "@/lib/insights/derived/registry";
import { INSIGHTS_SECTION_IDS } from "@/lib/insights-layout";
import {
SUB_PAGE_SLUGS,
TYPE_TO_SUB_PAGE_SLUG,
} from "@/lib/insights/sub-page-metric";
import { TREND_CHART_CONFIG } from "@/lib/insights/trend-chart-select";
import {
SURFACE_KINDS,
SURFACE_MODULE,
surfaceModule,
surfaceModulesOfKind,
type SurfaceKind,
} from "@/lib/modules/surface";
const SRC = join(process.cwd(), "src");
function localIds(kind: SurfaceKind): string[] {
const ids = Object.keys(surfaceModulesOfKind(kind));
return ids;
}
describe("every surface id names a surface that exists", () => {
it("covers every kind with at least one entry", () => {
for (const kind of SURFACE_KINDS) {
expect(localIds(kind).length, kind).toBeGreaterThan(0);
}
});
it("nav: a destination href", () => {
const hrefs = new Set(NAV_DESTINATIONS.map((d) => d.href));
for (const id of localIds("nav")) expect(hrefs.has(id), id).toBe(true);
});
it("insights-page: a routed Insights sub-page", () => {
for (const slug of localIds("insights-page")) {
expect(
existsSync(join(SRC, "app/insights", slug)),
`src/app/insights/${slug}`,
).toBe(true);
}
});
it("overview: an overview section id, or the cycle ring inside the scores strip", () => {
const ids = new Set<string>([...INSIGHTS_SECTION_IDS, "cycle-ring"]);
for (const id of localIds("overview")) expect(ids.has(id), id).toBe(true);
});
it("trend: a trends-row slot that charts something", () => {
for (const id of localIds("trend")) {
expect(
TREND_CHART_CONFIG[id as keyof typeof TREND_CHART_CONFIG],
id,
).toBeTruthy();
}
});
it("capture: an add-menu kind", () => {
const kinds = new Set<string>(CAPTURE_KIND_ORDER);
for (const id of localIds("capture")) expect(kinds.has(id), id).toBe(true);
});
it("widget: a dashboard widget id", () => {
const ids = new Set<string>(DASHBOARD_WIDGET_CATALOGUE_IDS);
for (const id of localIds("widget")) expect(ids.has(id), id).toBe(true);
});
it("derived: a derived metric id", () => {
const ids = new Set<string>(DERIVED_METRIC_IDS);
for (const id of localIds("derived")) expect(ids.has(id), id).toBe(true);
});
it("score-ring: a hero score ring id, the derived ones owned like their score", () => {
const ids = new Set<string>(SCORE_RING_IDS);
for (const id of localIds("score-ring")) {
expect(ids.has(id), id).toBe(true);
const derivedOwner = surfaceModule(`derived:${id}`);
if (derivedOwner !== undefined) {
expect(surfaceModule(`score-ring:${id}`), id).toBe(derivedOwner);
}
}
});
it("settings: a Settings section slug", () => {
const slugs = new Set<string>(SETTINGS_SECTIONS.map((s) => s.slug));
for (const id of localIds("settings")) expect(slugs.has(id), id).toBe(true);
});
it("settings-layout: a Layout group id", () => {
const ids = new Set<string>(LAYOUT_GROUP_IDS);
for (const id of localIds("settings-layout")) {
expect(ids.has(id), id).toBe(true);
}
});
it("correlation: a discovery channel, a weather field or the lab pass", () => {
const channels = new Set<string>([
...DISCOVERY_BEHAVIOURS,
...DISCOVERY_OUTCOMES,
...ENVIRONMENT_FIELDS.map((f) => f.key),
"LAB_DRAWS",
]);
for (const id of localIds("correlation")) {
expect(channels.has(id), id).toBe(true);
}
// `correlationChannelSurfaceId` folds rated factors onto mood by this
// prefix; it has to be the prefix the engine actually writes.
expect(FACTOR_CHANNEL_PREFIX).toBe("FACTOR:");
});
});
describe("every surface that shows a module's data is owned by it", () => {
/** Summary owners are the dashboard's own gate; the join source of truth. */
const ownerOfType = (type: string) => SUMMARY_TYPE_MODULE[type];
/**
* Sub-pages a module-owned type routes to but that are not that module's.
* Each carries its reason; an entry here is a decision, not a silence.
*/
const NOT_OWNED_DESPITE_TYPE: Record<string, string> = {
// The HRV page leads with SDNN, a plain vital. RMSSD is recovery-owned
// and routes here only as the multi-metric fallback.
hrv: "SDNN page; RMSSD is only its fallback series",
};
it("Insights sub-pages follow the owner of the types they plot", () => {
let joined = 0;
for (const [type, slug] of Object.entries(TYPE_TO_SUB_PAGE_SLUG)) {
const owner = ownerOfType(type);
if (!owner || slug in NOT_OWNED_DESPITE_TYPE) continue;
joined += 1;
expect(
surfaceModule(`insights-page:${slug}`),
`${slug} plots ${type}, which ${owner} owns`,
).toBe(owner);
}
expect(joined).toBeGreaterThan(0);
});
it("trends-row slots follow the owner of the series they chart", () => {
let joined = 0;
for (const [metric, config] of Object.entries(TREND_CHART_CONFIG)) {
if (!config) continue;
const owners = new Set(
config.types.map(ownerOfType).filter((o) => o !== undefined),
);
if (config.kind === "mood") owners.add("mood");
if (owners.size === 0) {
expect(surfaceModule(`trend:${metric}`), metric).toBeUndefined();
continue;
}
joined += 1;
expect(owners.size, metric).toBe(1);
expect(surfaceModule(`trend:${metric}`), metric).toBe([...owners][0]);
}
expect(joined).toBeGreaterThan(0);
});
it("correlation channels that are summary types follow the summary owner", () => {
let joined = 0;
for (const key of [...DISCOVERY_BEHAVIOURS, ...DISCOVERY_OUTCOMES]) {
const owner = ownerOfType(key);
if (!owner) continue;
joined += 1;
expect(surfaceModule(`correlation:${key}`), key).toBe(owner);
}
expect(joined).toBeGreaterThan(0);
});
it("every weather channel belongs to the environment module", () => {
for (const field of ENVIRONMENT_FIELDS) {
expect(surfaceModule(`correlation:${field.key}`), field.key).toBe(
"environment",
);
}
});
// Owners no data join can derive. Pinned by hand; each is a surface the
// audit found leaking when its module was off.
it.each([
["nav:/mood", "mood"],
["nav:/cycle", "cycle"],
["nav:/medications", "medications"],
["nav:/labs", "labs"],
["nav:/coach", "coach"],
["insights-page:mood", "mood"],
["insights-page:medications", "medications"],
["insights-page:workouts", "workouts"],
["insights-page:recovery", "recovery"],
["insights-page:nutrients", "nutrients"],
["overview:breathing", "sleep"],
["overview:labs-changes", "labs"],
["overview:cycle-summary", "cycle"],
["overview:cycle-ring", "cycle"],
["capture:mood", "mood"],
["capture:medication", "medications"],
["trend:mood", "mood"],
["widget:medications", "medications"],
["correlation:MEDICATION_COMPLIANCE", "medications"],
["correlation:SYMPTOM_SEVERITY", "illness"],
["correlation:LAB_DRAWS", "labs"],
])("%s is owned by %s", (id, owner) => {
expect(surfaceModule(id)).toBe(owner);
});
it("the insights key owns nothing (it is AI analysis, not an area)", () => {
expect(Object.values(SURFACE_MODULE)).not.toContain("insights");
});
it("the tab strip covers every sub-page slug it can render", () => {
// Every owned sub-page that is a strip slug is reachable by the strip's
// lookup; recovery is the one composite pill without a slug.
const slugs = new Set<string>(SUB_PAGE_SLUGS);
for (const id of localIds("insights-page")) {
expect(slugs.has(id) || id === "recovery", id).toBe(true);
}
});
});
describe("the replaced maps and guards stay gone", () => {
const files = walkSourceFiles(SRC, { floor: 1000 }).filter(
(rel) =>
!rel.startsWith("generated/") &&
!rel.includes("__tests__/") &&
!/\.test\.tsx?$/.test(rel),
);
const sources = files.map((rel) => ({
rel,
code: stripComments(readFileSync(join(SRC, rel), "utf8")),
}));
it.each([
["a per-destination module key", /\brequiresModule\s*[?:]/],
["a per-section module key", /\bmoduleGate\s*\?\s*:|\bmoduleGate\s*:\s*"/],
["the tab strip's own slug map", /\bSUB_PAGE_MODULE\b/],
["the redirecting page guard", /\buseModulePageGuard\b/],
])("no source declares %s", (_label, pattern) => {
const hits = sources.filter((s) => pattern.test(s.code)).map((s) => s.rel);
expect(hits).toEqual([]);
});
it("the dashboard maps are views, built from the surface map and nowhere else", () => {
const widgetModules = sources.find(
(s) => s.rel === "lib/dashboard/widget-modules.ts",
);
expect(widgetModules).toBeDefined();
expect(widgetModules!.code).toMatch(
/WIDGET_MODULE_BY_ID[^=]*=\s*surfaceModulesOfKind\(\s*"widget"\s*\)/,
);
expect(widgetModules!.code).toMatch(
/SUMMARY_TYPE_MODULE[^=]*=\s*surfaceModulesOfKind\(\s*"summary"\s*\)/,
);
});
it("the derived-score gate agrees with the surface map", () => {
// `DERIVED_MODULE` lives in the derived route, which this guard reads as
// text rather than importing (it pulls the whole server stack). Parsed
// entry by entry and compared, so a drift in either direction fails.
const route = readFileSync(
join(SRC, "app/api/insights/derived/route.ts"),
"utf8",
);
const body = /DERIVED_MODULE[^=]*=\s*\{([\s\S]*?)\}/.exec(route)?.[1];
expect(body).toBeDefined();
const entries = Object.fromEntries(
[...body!.matchAll(/([A-Z_]+)\s*:\s*"([A-Za-z]+)"/g)].map((m) => [
m[1],
m[2],
]),
);
expect(Object.keys(entries).length).toBeGreaterThan(0);
expect(entries).toEqual(surfaceModulesOfKind("derived"));
});
});
+74
View File
@@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import { MODULE_KEYS } from "@/lib/modules/registry";
import {
SURFACE_KINDS,
SURFACE_MODULE,
isSurfaceVisible,
surfaceModule,
surfaceModulesOfKind,
} from "@/lib/modules/surface";
describe("SURFACE_MODULE", () => {
it("owns every surface by a real module key", () => {
const keys = new Set<string>(MODULE_KEYS);
for (const [id, owner] of Object.entries(SURFACE_MODULE)) {
expect(keys.has(owner), `${id} → ${owner}`).toBe(true);
}
});
it("names every surface as <kind>:<local id> with a known kind", () => {
const kinds = new Set<string>(SURFACE_KINDS);
for (const id of Object.keys(SURFACE_MODULE)) {
const kind = id.slice(0, id.indexOf(":"));
expect(kinds.has(kind), id).toBe(true);
expect(id.length).toBeGreaterThan(kind.length + 1);
}
});
it("leaves the Insights area to no module (the insights key is AI analysis only)", () => {
expect(surfaceModule("nav:/insights")).toBeUndefined();
expect(Object.values(SURFACE_MODULE)).not.toContain("insights");
});
});
describe("isSurfaceVisible", () => {
it("hides an owned surface only on an explicit false", () => {
expect(isSurfaceVisible("trend:mood", { mood: false })).toBe(false);
expect(isSurfaceVisible("trend:mood", { mood: true })).toBe(true);
expect(isSurfaceVisible("trend:mood", {})).toBe(true);
expect(isSurfaceVisible("trend:mood", undefined)).toBe(true);
});
it("never hides a surface no module owns", () => {
expect(isSurfaceVisible("trend:bp", { mood: false, sleep: false })).toBe(
true,
);
expect(isSurfaceVisible("nav:/measurements", { mood: false })).toBe(true);
});
it("reads the owner's key, not the surface's name", () => {
expect(isSurfaceVisible("capture:medication", { medications: false })).toBe(
false,
);
expect(
isSurfaceVisible("insights-page:blood-glucose", { glucose: false }),
).toBe(false);
});
});
describe("surfaceModulesOfKind", () => {
it("strips the kind prefix and keeps only that kind", () => {
const widgets = surfaceModulesOfKind("widget");
expect(widgets.mood).toBe("mood");
expect(widgets.recentWorkouts).toBe("workouts");
expect(Object.keys(widgets).some((k) => k.includes(":"))).toBe(false);
expect(widgets["/mood"]).toBeUndefined();
});
it("returns an empty view for a kind with no entries rather than throwing", () => {
for (const kind of SURFACE_KINDS) {
expect(typeof surfaceModulesOfKind(kind)).toBe("object");
}
});
});
+274
View File
@@ -0,0 +1,274 @@
/**
* Which module owns which surface, in one declarative map.
*
* A module a person switches off has to disappear everywhere at once: the nav
* entry, the Insights pill, the overview card, the trends slot, the add menu,
* the dashboard tile, the Settings row, the statistics. Each of those used to
* keep its own little map (or none), and the ones with none were exactly where
* a switched-off module kept showing up. This file is the one answer. Every
* surface a toggleable module owns is listed here as `<kind>:<local id>`, and a
* surface that is absent belongs to no module and is never hidden by one.
*
* The older per-surface maps are views of this one (`surfaceModulesOfKind`),
* so they cannot drift from it. `src/lib/modules/__tests__/
* surface-module-registry.test.ts` holds every list of surfaces the app renders
* against this map.
*
* The `insights` key is deliberately absent. It means "AI analysis" (model
* written text) and owns no surface: the Insights area, its charts and its
* statistics are data and stay whatever their own module says. The AI
* capability resolver reads that key; surfaces never do.
*
* Pure data plus two pure functions, no server or React dependency, so the
* server builders and the browser read the same file. The React accessor is
* `useSurfaceVisible` in `src/hooks/use-surface-visible.ts`.
*
* Paint, not enforcement: the routes behind a module refuse on their own
* through `requireModuleEnabled`. Hiding a surface spares a click that would
* end in a refusal or an empty chart.
*/
import { ENVIRONMENT_FIELDS } from "@/lib/environment/fields";
import type { ModuleKey } from "@/lib/modules/registry";
/**
* The surface families. The part of an id before the first `:`.
*
* - `nav`: a navigation destination, by its href (sidebar, bottom bar, the
* More hub, the tour stop on that page, and the direct-URL notice).
* - `insights-page`: an Insights sub-page, by its slug (the tab-strip pill
* and the direct-URL notice under `/insights/<slug>`).
* - `overview`: a block on the Insights overview, by its section id.
* - `trend`: a trends-row chart slot, by its briefing `sourceMetric`.
* - `capture`: an entry in the add menu, by its capture kind.
* - `widget`: a dashboard widget, by its layout id.
* - `summary`: a dashboard summary key (a `MeasurementType` or a synthetic
* key such as `MOOD_ENTRY`), stripped from every summaries feed.
* - `derived`: a derived score, by its `DerivedMetricId`.
* - `settings`: a Settings section, by its slug.
* - `settings-layout`: a Settings, Layout group, by its id.
* - `correlation`: a correlation-discovery channel, by its channel key.
* - `score-ring`: a dashboard hero score ring, by its `ScoreRingId`.
*/
export const SURFACE_KINDS = [
"nav",
"insights-page",
"overview",
"trend",
"capture",
"widget",
"summary",
"derived",
"settings",
"settings-layout",
"correlation",
"score-ring",
] as const;
export type SurfaceKind = (typeof SURFACE_KINDS)[number];
const STATIC_SURFACE_MODULE = {
// ── Navigation destinations ──
// `/insights` carries no owner: the area is data, not AI analysis.
"nav:/mood": "mood",
"nav:/mental-wellbeing": "mentalHealth",
"nav:/cycle": "cycle",
"nav:/medications": "medications",
"nav:/labs": "labs",
"nav:/illness": "illness",
"nav:/vaccinations": "vaccinations",
"nav:/documents": "inboundDocuments",
"nav:/coach": "coach",
"nav:/achievements": "achievements",
// ── Insights sub-pages ──
"insights-page:mood": "mood",
"insights-page:sleep": "sleep",
// The per-night breathing-disturbance index is a sleep-page signal.
"insights-page:breathing-disturbances": "sleep",
"insights-page:blood-glucose": "glucose",
"insights-page:workouts": "workouts",
"insights-page:nutrients": "nutrients",
// Medications is surface-gated by design: its data routes stay open so an
// import or a sync keeps working, and these surfaces are what the switch
// hides.
"insights-page:medications": "medications",
// Recovery is a composite page, not a slug with a series; the four
// HealthKit recovery metrics below are the same module's, as on the
// dashboard (`widget:cardioRecovery` …).
"insights-page:recovery": "recovery",
"insights-page:cardio-recovery": "recovery",
"insights-page:six-minute-walk": "recovery",
"insights-page:stair-ascent-speed": "recovery",
"insights-page:stair-descent-speed": "recovery",
// ── Insights overview blocks ──
"overview:cycle-summary": "cycle",
// The cycle ring rides the wellness-scores strip rather than being a
// section of its own; it follows the same key as the cycle summary, so the
// two cannot disagree.
"overview:cycle-ring": "cycle",
// Breathing disturbances are measured overnight; the screening card is the
// sleep module's.
"overview:breathing": "sleep",
"overview:labs-changes": "labs",
// ── Trends row ──
"trend:mood": "mood",
"trend:sleep": "sleep",
// ── Add menu ──
"capture:mood": "mood",
"capture:medication": "medications",
// ── Dashboard widgets ──
// CORE widgets (weight, blood pressure, pulse, body fat, the vital-derived
// HealthKit metrics) carry no entry and are never hidden.
"widget:mood": "mood",
"widget:sleep": "sleep",
"widget:glucose": "glucose",
"widget:achievements": "achievements",
"widget:recentWorkouts": "workouts",
"widget:medications": "medications",
"widget:cardioRecovery": "recovery",
"widget:sixMinuteWalk": "recovery",
"widget:stairAscentSpeed": "recovery",
"widget:stairDescentSpeed": "recovery",
"widget:breathingDisturbances": "sleep",
// The fluid-intake tile reads the nutrient store.
"widget:waterIntake": "nutrients",
// ── Dashboard summary keys ──
"summary:SLEEP_DURATION": "sleep",
"summary:BLOOD_GLUCOSE": "glucose",
"summary:CARDIO_RECOVERY": "recovery",
"summary:SIX_MINUTE_WALK_DISTANCE": "recovery",
"summary:STAIR_ASCENT_SPEED": "recovery",
"summary:STAIR_DESCENT_SPEED": "recovery",
// The nightly RMSSD series is the recovery module's. The dashboard HRV tile
// falls back to it when an account has no SDNN, and a fallback must not
// serve recovery data the primary type refuses. `HEART_RATE_VARIABILITY`
// (SDNN) is a plain vital and stays unowned.
"summary:HRV_RMSSD": "recovery",
"summary:BREATHING_DISTURBANCES": "sleep",
// Synthetic keys: derived from `NutrientIntakeDay` and `MoodEntry` rather
// than a `MeasurementType`, riding the same gate.
"summary:NUTRIENT_WATER": "nutrients",
"summary:MOOD_ENTRY": "mood",
// ── Derived scores ──
// READINESS equals the computed recovery score, so it follows recovery.
// Composite baselines built on core vitals (VITALS_BASELINE, HRV_BALANCE …)
// carry no entry.
"derived:SLEEP_SCORE": "sleep",
"derived:RECOVERY_SCORE": "recovery",
"derived:STRAIN_SCORE": "recovery",
"derived:STRESS_SCORE": "recovery",
"derived:READINESS": "recovery",
// ── Dashboard hero score rings ──
// The three derived rings follow their derived score; the dose ring is
// medications'.
"score-ring:READINESS": "recovery",
"score-ring:RECOVERY_SCORE": "recovery",
"score-ring:SLEEP_SCORE": "sleep",
"score-ring:MED_COMPLIANCE": "medications",
// ── Settings sections ──
"settings:environment": "environment",
"settings:coach": "coach",
// ── Settings, Layout groups ──
"settings-layout:medications": "medications",
"settings-layout:mood": "mood",
"settings-layout:labs": "labs",
"settings-layout:illness": "illness",
// ── Correlation channels ──
// Rated mood factors (`FACTOR:<key>`) are mood's too; see
// `correlationChannelSurfaceId`.
"correlation:MOOD": "mood",
"correlation:SLEEP_DURATION": "sleep",
"correlation:BLOOD_GLUCOSE": "glucose",
"correlation:MEDICATION_COMPLIANCE": "medications",
// Symptom burden is read from the illness journal.
"correlation:SYMPTOM_SEVERITY": "illness",
// The labs ↔ outcome pass over lab draws.
"correlation:LAB_DRAWS": "labs",
} as const satisfies Record<string, ModuleKey>;
/** A surface id the map declares literally. */
export type StaticSurfaceId = keyof typeof STATIC_SURFACE_MODULE;
/**
* The map. The weather channels are spread in from the environment field
* table so a field added there is owned the moment it exists.
*/
export const SURFACE_MODULE: Readonly<Record<string, ModuleKey>> =
Object.freeze({
...STATIC_SURFACE_MODULE,
...Object.fromEntries(
ENVIRONMENT_FIELDS.map((field) => [
`correlation:${field.key}`,
"environment" as const,
]),
),
});
/**
* A partial `ModuleKey → enabled` map: the `modules` field of
* `GET /api/auth/me`, or `resolveModuleMap()` on the server. Only an explicit
* `false` hides; a missing key or a missing map reads as on, matching the
* gate's default-on contract.
*/
export type SurfaceModuleMap = Partial<Record<ModuleKey, boolean>>;
/** The module that owns a surface, or `undefined` for an unowned one. */
export function surfaceModule(surfaceId: string): ModuleKey | undefined {
return Object.prototype.hasOwnProperty.call(SURFACE_MODULE, surfaceId)
? SURFACE_MODULE[surfaceId]
: undefined;
}
/**
* Whether a surface shows under a module map. An unowned surface always
* shows; an owned one hides only when its module is explicitly `false`.
*
* Takes any string so callers can build ids from runtime values
* (`widget:${id}`); the guard test is what keeps those ids honest.
*/
export function isSurfaceVisible(
surfaceId: StaticSurfaceId | (string & {}),
modules: SurfaceModuleMap | null | undefined,
): boolean {
const owner = surfaceModule(surfaceId);
if (owner === undefined) return true;
return modules?.[owner] !== false;
}
/**
* One family of the map with the `<kind>:` prefix stripped: `{ mood: "mood",
* recentWorkouts: "workouts", … }` for `"widget"`. This is how the older
* per-surface maps (`WIDGET_MODULE_BY_ID`, `SUMMARY_TYPE_MODULE`, …) are now
* built, so they are views of this file rather than copies of it.
*/
export function surfaceModulesOfKind(
kind: SurfaceKind,
): Partial<Record<string, ModuleKey>> {
const prefix = `${kind}:`;
const out: Partial<Record<string, ModuleKey>> = {};
for (const [id, owner] of Object.entries(SURFACE_MODULE)) {
if (id.startsWith(prefix)) out[id.slice(prefix.length)] = owner;
}
return out;
}
/**
* The surface id of a correlation channel. Rated mood factors carry their own
* `FACTOR:<key>` channel names but are mood entries all the same, so they
* resolve to the mood channel.
*/
export function correlationChannelSurfaceId(channelKey: string): string {
return channelKey.startsWith("FACTOR:")
? "correlation:MOOD"
: `correlation:${channelKey}`;
}
@@ -51,6 +51,19 @@ describe("tour-state", () => {
expect(ids).toContain("wrapUp");
});
it("keeps the Insights stop with AI analysis off", () => {
const stops = buildTourStops({ modules: { insights: false } });
expect(stops.map((s) => s.id)).toContain("insights");
});
it("drops the Coach and Medications stops with their modules off", () => {
const ids = buildTourStops({
modules: { coach: false, medications: false },
}).map((s) => s.id);
expect(ids).not.toContain("coach");
expect(ids).not.toContain("medications");
});
it("keeps a module stop when its key is absent or true (fail-open)", () => {
const stops = buildTourStops({ modules: { labs: true } });
expect(stops.map((s) => s.id)).toContain("labs");
+5 -16
View File
@@ -21,6 +21,7 @@
*/
import type { ModuleKey } from "@/lib/modules/registry";
import { isSurfaceVisible } from "@/lib/modules/surface";
/** Stable IDs for every stop in the tour, in presentation order. */
export type TourStopId =
@@ -69,12 +70,6 @@ export interface TourStop {
* page.
*/
route?: string;
/**
* v1.18.6 — module gate. When set, the stop is dropped unless the
* account's resolved module map has the key enabled (default-on:
* only an explicit `false` drops it, mirroring the nav gate).
*/
requiresModule?: ModuleKey;
}
/**
@@ -111,7 +106,6 @@ const ALL_STOPS: readonly TourStop[] = [
targetId: "medications-hero",
placement: "bottom",
route: "/medications",
requiresModule: "medications",
titleKey: "onboarding.tour.steps.medications.title",
bodyKey: "onboarding.tour.steps.medications.body",
},
@@ -120,7 +114,6 @@ const ALL_STOPS: readonly TourStop[] = [
targetId: "labs-hero",
placement: "bottom",
route: "/labs",
requiresModule: "labs",
titleKey: "onboarding.tour.steps.labs.title",
bodyKey: "onboarding.tour.steps.labs.body",
},
@@ -129,7 +122,6 @@ const ALL_STOPS: readonly TourStop[] = [
targetId: "illness-hero",
placement: "bottom",
route: "/illness",
requiresModule: "illness",
titleKey: "onboarding.tour.steps.illness.title",
bodyKey: "onboarding.tour.steps.illness.body",
},
@@ -146,7 +138,6 @@ const ALL_STOPS: readonly TourStop[] = [
targetId: "cycle-hero",
placement: "bottom",
route: "/cycle",
requiresModule: "cycle",
titleKey: "onboarding.tour.steps.cycle.title",
bodyKey: "onboarding.tour.steps.cycle.body",
},
@@ -155,7 +146,6 @@ const ALL_STOPS: readonly TourStop[] = [
targetId: "mood-hero",
placement: "bottom",
route: "/mood",
requiresModule: "mood",
titleKey: "onboarding.tour.steps.mood.title",
bodyKey: "onboarding.tour.steps.mood.body",
},
@@ -164,7 +154,6 @@ const ALL_STOPS: readonly TourStop[] = [
targetId: "insights-hero",
placement: "bottom",
route: "/insights",
requiresModule: "insights",
titleKey: "onboarding.tour.steps.insights.title",
bodyKey: "onboarding.tour.steps.insights.body",
},
@@ -173,7 +162,6 @@ const ALL_STOPS: readonly TourStop[] = [
targetId: "coach-hero",
placement: "bottom",
route: "/coach",
requiresModule: "coach",
titleKey: "onboarding.tour.steps.coach.title",
bodyKey: "onboarding.tour.steps.coach.body",
},
@@ -198,7 +186,6 @@ const ALL_STOPS: readonly TourStop[] = [
targetId: "achievements-hero",
placement: "bottom",
route: "/achievements",
requiresModule: "achievements",
titleKey: "onboarding.tour.steps.achievements.title",
bodyKey: "onboarding.tour.steps.achievements.body",
},
@@ -220,7 +207,7 @@ export type TourModuleMap = Partial<Record<ModuleKey, boolean>>;
/**
* Build the resolved tour-step list for the given module map. Stops
* whose `requiresModule` resolves to `false` are dropped without
* whose page belongs to a module that is `false` are dropped without
* renumbering the rest.
*
* `filterToStop` narrows the list to a single stop — the per-module
@@ -233,8 +220,10 @@ export function buildTourStops(opts?: {
filterToStop?: TourStopId;
}): TourStop[] {
const modules = opts?.modules;
// A stop follows the page it stands on, through the same surface map the
// nav reads (`nav:<route>`), so a stop and its nav entry cannot disagree.
const gated = ALL_STOPS.filter(
(s) => !s.requiresModule || modules?.[s.requiresModule] !== false,
(s) => !s.route || isSurfaceVisible(`nav:${s.route}`, modules),
);
if (opts?.filterToStop) {
return gated.filter((s) => s.id === opts.filterToStop);