chore(release): v1.4.27

v1.4.27 — Mobile capability and maintainer-finding cleanup.

ResponsiveSheet primitive (bottom-sheet on narrow viewports, centred dialog on desktop)
applied to BD, Weight, Glucose, Mood, Activity forms. Maintainer-finding cleanups across
Coach, Insights, Reports, Privacy. GeoLite2 offline geocoding with resilience layer
(graceful fallback when EULA not yet propagated). E2E gap-fill coverage. 450-line
release notes attached to the GitHub Release.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-15 22:59:10 +02:00
1 parent d98e85cd03
commit 4f09c3f862
314 files changed
+26801 -4419

No files matched your search

@@ -0,0 +1,211 @@
/**
* Unit suite for `GET /api/workouts` — the canonical-dedup contract.
*
* v1.4.27 B7 / BL-P2-3 — wires `pickCanonicalWorkout()` into the read
* path. The test pins the contract:
* - twin workouts on the same `(sportType, ±5 min)` cluster
* collapse to a single row;
* - the source ladder picks APPLE_HEALTH over WITHINGS over MANUAL;
* - the `meta.droppedDuplicates` count reflects the diff between
* the raw fetch and the canonical subset.
*/
import { describe, expect, it, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
workout: {
findMany: vi.fn(),
},
},
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
};
function makeRequest(query = ""): NextRequest {
return new NextRequest(`http://localhost/api/workouts${query}`, {
method: "GET",
});
}
interface FakeWorkoutRow {
id: string;
source: string;
externalId: string | null;
sportType: string;
startedAt: Date;
endedAt: Date;
durationSec: number;
distanceMeters: number | null;
avgHeartRate: number | null;
maxHeartRate: number | null;
energyKcal: number | null;
createdAt: Date;
}
function makeRow(
id: string,
source: string,
startedAt: string,
sportType = "RUNNING",
): FakeWorkoutRow {
const start = new Date(startedAt);
return {
id,
source,
externalId: source === "MANUAL" ? null : `ext-${id}`,
sportType,
startedAt: start,
endedAt: new Date(start.getTime() + 30 * 60_000),
durationSec: 1800,
distanceMeters: 5000,
avgHeartRate: 145,
maxHeartRate: 170,
energyKcal: 320,
createdAt: start,
};
}
describe("GET /api/workouts — canonical dedup", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
});
it("collapses an APPLE_HEALTH + WITHINGS twin to the Apple row", async () => {
const apple = makeRow("w-apple", "APPLE_HEALTH", "2026-05-15T07:00:00Z");
const withings = makeRow("w-withings", "WITHINGS", "2026-05-15T07:01:30Z");
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
apple,
withings,
] as never);
const res = await GET(makeRequest());
const body = await res.json();
expect(res.status).toBe(200);
expect(body.data.workouts).toHaveLength(1);
expect(body.data.workouts[0].id).toBe("w-apple");
expect(body.data.meta.droppedDuplicates).toBe(1);
expect(body.data.meta.clusters).toBe(1);
});
it("keeps two workouts when they are outside the proximity window", async () => {
const morning = makeRow("w-am", "APPLE_HEALTH", "2026-05-15T07:00:00Z");
const evening = makeRow("w-pm", "APPLE_HEALTH", "2026-05-15T18:00:00Z");
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
morning,
evening,
] as never);
const res = await GET(makeRequest());
const body = await res.json();
expect(body.data.workouts).toHaveLength(2);
expect(body.data.meta.droppedDuplicates).toBe(0);
expect(body.data.meta.clusters).toBe(2);
});
it("keeps two workouts when sportType differs at the same instant", async () => {
const run = makeRow("w-run", "APPLE_HEALTH", "2026-05-15T07:00:00Z", "RUNNING");
const walk = makeRow("w-walk", "APPLE_HEALTH", "2026-05-15T07:00:00Z", "WALKING");
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce([
run,
walk,
] as never);
const res = await GET(makeRequest());
const body = await res.json();
expect(body.data.workouts).toHaveLength(2);
expect(body.data.meta.droppedDuplicates).toBe(0);
});
it("honours the limit query parameter after dedup", async () => {
const rows = Array.from({ length: 8 }, (_, i) =>
makeRow(
`w-${i}`,
"APPLE_HEALTH",
new Date(2026, 4, 15, 7 + i, 0, 0).toISOString(),
),
);
vi.mocked(prisma.workout.findMany).mockResolvedValueOnce(rows as never);
const res = await GET(makeRequest("?limit=3"));
const body = await res.json();
expect(body.data.workouts).toHaveLength(3);
expect(body.data.meta.limit).toBe(3);
});
it("paginates across cluster boundaries without double-counting deduped rows", async () => {
// Eight twin clusters: each cluster has an APPLE_HEALTH + WITHINGS
// row within the 5 min window. The picker collapses each cluster to
// its Apple row, so the canonical projection has 8 rows. Page 1
// (offset=0, limit=4) must yield Apple rows for clusters 7–4
// (descending). Page 2 (offset=4, limit=4) must yield Apple rows
// for clusters 3–0 with no overlap and no gaps. `meta.total` must
// reflect the deduped count (8), not the raw row count (16).
const rows: FakeWorkoutRow[] = [];
for (let i = 0; i < 8; i++) {
const start = new Date(2026, 4, 15, 7 + i, 0, 0).toISOString();
const start2 = new Date(2026, 4, 15, 7 + i, 1, 30).toISOString();
rows.push(makeRow(`apple-${i}`, "APPLE_HEALTH", start));
rows.push(makeRow(`withings-${i}`, "WITHINGS", start2));
}
// Mock returns the full filtered set; the route paginates after
// dedup.
vi.mocked(prisma.workout.findMany).mockResolvedValue(rows as never);
const page1 = await GET(makeRequest("?limit=4&offset=0"));
const page1Body = await page1.json();
const page2 = await GET(makeRequest("?limit=4&offset=4"));
const page2Body = await page2.json();
expect(page1Body.data.workouts).toHaveLength(4);
expect(page2Body.data.workouts).toHaveLength(4);
expect(page1Body.data.meta.total).toBe(8);
expect(page2Body.data.meta.total).toBe(8);
expect(page1Body.data.meta.droppedDuplicates).toBe(8);
expect(page2Body.data.meta.droppedDuplicates).toBe(8);
const page1Ids = page1Body.data.workouts.map((w: { id: string }) => w.id);
const page2Ids = page2Body.data.workouts.map((w: { id: string }) => w.id);
// No overlap across the page boundary.
expect(page1Ids.filter((id: string) => page2Ids.includes(id))).toEqual([]);
// All eight clusters are covered between the two pages.
expect([...page1Ids, ...page2Ids].sort()).toEqual(
Array.from({ length: 8 }, (_, i) => `apple-${i}`).sort(),
);
// Descending order is preserved within each page.
expect(page1Ids).toEqual(["apple-7", "apple-6", "apple-5", "apple-4"]);
expect(page2Ids).toEqual(["apple-3", "apple-2", "apple-1", "apple-0"]);
});
});
+42 -12
View File
@@ -356,21 +356,51 @@ async function postBatch(request: NextRequest): Promise<Response> {
// is NULL-distinct, so two manual entries on the same instant
// would both insert. We look these up by the deterministic
// (userId, source, startedAt, sportType) tuple for each row.
const manualMatches = await Promise.all(
withoutExternal.map((p) =>
tx.workout.findFirst({
where: {
userId: user.id,
//
// v1.4.27 B7 / BL-code-M3 — single batched findMany with one
// OR-row per entry instead of N serial findFirst probes. For
// a 100-row batch this cuts the per-batch round-trip count
// from 1 + N to 2; the per-entry "most-recent createdAt"
// tie-break is preserved by sorting the returned rows in
// memory and keying on the deterministic tuple.
type ManualMatch = { id: string; createdAt: Date };
const manualMatchesById = new Map<string, ManualMatch>();
if (withoutExternal.length > 0) {
const manualRows = await tx.workout.findMany({
where: {
userId: user.id,
route: null,
OR: withoutExternal.map((p) => ({
source: p.row.source,
startedAt: p.row.startedAt as Date,
sportType: p.row.sportType,
route: null,
},
select: { id: true },
orderBy: { createdAt: "desc" },
}),
),
);
})),
},
select: {
id: true,
source: true,
startedAt: true,
sportType: true,
createdAt: true,
},
orderBy: { createdAt: "desc" },
});
for (const row of manualRows) {
const key = `${row.source}::${row.startedAt.getTime()}::${row.sportType}`;
const existing = manualMatchesById.get(key);
if (!existing || existing.createdAt < row.createdAt) {
manualMatchesById.set(key, {
id: row.id,
createdAt: row.createdAt,
});
}
}
}
const manualMatches = withoutExternal.map((p) => {
const key = `${p.row.source}::${(p.row.startedAt as Date).getTime()}::${p.row.sportType}`;
const match = manualMatchesById.get(key);
return match ? { id: match.id } : null;
});
const routesToInsert: Prisma.WorkoutRouteCreateManyInput[] = [];
for (let i = 0; i < withExternal.length; i++) {
+155
View File
@@ -0,0 +1,155 @@
/**
* `GET /api/workouts` — paginated workout list with canonical-source
* deduplication.
*
* Consumers (v1.4.27+):
* 1. The /insights workouts surface (and future /workouts page) reads
* from this endpoint so duplicate twin workouts (Apple Watch
* writing a workout that Withings also published over its server-
* to-server feed) collapse to a single canonical row.
* 2. The native iOS app drains historical workouts through the same
* surface — Apple Health is the canonical ladder anchor, so an
* iOS-originated request typically returns its own rows back.
*
* Dedup contract:
* - The route reads `DEFAULT_WORKOUT_SOURCE_PRIORITY` from
* `pick-canonical-workout.ts` (APPLE_HEALTH > WITHINGS > MANUAL >
* IMPORT) with the ±5 min cluster window. A per-user workout
* ladder override is reserved for the v1.5 Settings surface; the
* server already honours it transparently through the picker's
* options bag when the field lands in `User.sourcePriorityJson`.
* - Per-cluster the picker keeps the row from the highest-priority
* source present; the others are dropped from the canonical list.
*
* Query params:
* - `limit` (default 50, max 200)
* - `offset` (default 0)
* - `since` / `until` — ISO timestamps, inclusive. Optional.
* - `sportType` — narrow to one HKWorkoutActivityType. Optional.
*
* Pagination contract:
* Dedup runs over the full filtered row set, then `offset` / `limit`
* slice the canonical projection. A naive `skip` + per-window dedup
* double-counts boundary clusters across pages because a cluster
* whose first member sits in page N-1 and whose later member sits in
* page N would be dropped on N-1 and surface again on N. Workout
* volume for HealthLog is bounded (single user, tens of workouts per
* week — single-digit MB at the table's busiest), so reading the
* full filtered set per request is well within budget. If the
* workload ever grows to where this matters, a `(startedAt, id)`
* cursor with a deterministic over-fetch window is the next step.
*
* v1.4.27 B7 / BL-P2-3 — wires `pickCanonicalWorkout()` into the read
* path. v1.4.27 R4 RC3 — corrects the pagination so `meta.total`
* reflects the deduped count and cluster boundaries no longer leak
* across pages.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { apiSuccess } from "@/lib/api-response";
import {
pickCanonicalWorkout,
DEFAULT_WORKOUT_SOURCE_PRIORITY,
DEFAULT_WORKOUT_PROXIMITY_MINUTES,
type WorkoutPickerRow,
} from "@/lib/sources/pick-canonical-workout";
const DEFAULT_LIMIT = 50;
const MAX_LIMIT = 200;
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
annotate({ action: { name: "workouts.list" } });
const { searchParams } = new URL(request.url);
const limit = Math.min(
Math.max(
1,
parseInt(searchParams.get("limit") ?? String(DEFAULT_LIMIT), 10) ||
DEFAULT_LIMIT,
),
MAX_LIMIT,
);
const offset = Math.max(
0,
parseInt(searchParams.get("offset") ?? "0", 10) || 0,
);
const since = searchParams.get("since");
const until = searchParams.get("until");
const sportType = searchParams.get("sportType");
const where: Record<string, unknown> = { userId: user.id };
if (since || until) {
const range: Record<string, Date> = {};
if (since) {
const d = new Date(since);
if (!Number.isNaN(d.getTime())) range.gte = d;
}
if (until) {
const d = new Date(until);
if (!Number.isNaN(d.getTime())) range.lte = d;
}
if (Object.keys(range).length > 0) {
where.startedAt = range;
}
}
if (sportType) {
where.sportType = sportType;
}
// Read the full filtered set then dedupe once. See the file-level
// "Pagination contract" note for the reason this is preferred over
// a per-page over-fetch + slice. The picker is O(n) on cluster
// building plus O(k) per cluster (k = open clusters of the same
// sport type) and the workout table is bounded.
const rows = await prisma.workout.findMany({
where,
orderBy: { startedAt: "desc" },
select: {
id: true,
source: true,
externalId: true,
sportType: true,
startedAt: true,
endedAt: true,
durationSec: true,
distanceMeters: true,
avgHeartRate: true,
maxHeartRate: true,
energyKcal: true,
createdAt: true,
},
});
// The picker only inspects `source`, `startedAt`, `sportType`, and
// `id`. The rest of the selected columns ride through untouched on
// the returned subset.
const pickerRows = rows as Array<(typeof rows)[number] & WorkoutPickerRow>;
const { canonical, clusters } = pickCanonicalWorkout(pickerRows, {
sourcePriority: DEFAULT_WORKOUT_SOURCE_PRIORITY,
proximityMinutes: DEFAULT_WORKOUT_PROXIMITY_MINUTES,
});
// The picker sorts ascending for deterministic cluster building.
// Restore descending order on the canonical projection so the API
// matches the orderBy contract above.
const canonicalDesc = [...canonical].sort(
(a, b) => b.startedAt.getTime() - a.startedAt.getTime(),
);
const page = canonicalDesc.slice(offset, offset + limit);
return apiSuccess({
workouts: page,
meta: {
total: canonicalDesc.length,
limit,
offset,
droppedDuplicates: rows.length - canonicalDesc.length,
clusters: clusters.length,
},
});
});