fix(mcp): make the metric and lab deep links land on their pages

MCP `search` and `fetch` link a metric as `/insights?metric=<id>` and a lab
value as `/labs?analyte=<name>`. Neither page read its query, so every link
opened the overview or the full list.

`/insights` now resolves the id server-side, in whichever spelling the
result carries (a Coach source key such as `hrv` or `bp`, a signal or
metric-status key such as `GRIP_STRENGTH`, a measurement type, or a
sub-page slug), and redirects to the metric's page, or to its value list
when no page focuses it. An id it cannot place renders the overview as
before.

`/labs` asks for the newest reading stored under the exact analyte name
and opens its marker's page; a name with no reading keeps the list and
drops the query.
This commit is contained in:
Marc-André Bombeck committed 2026-10-08 09:40:12 +02:00
1 parent b8c7eda89c
commit 196c331068
8 files changed
+298 -3

No files matched your search

@@ -0,0 +1,44 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
/**
* MCP deep links (`/insights?metric=<id>`) used to land on the overview,
* whatever the id. The RSC now redirects a placeable id to the metric's page
* and renders the overview for anything else.
*/
const redirect = vi.hoisted(() =>
vi.fn((href: string) => {
throw new Error(`REDIRECT ${href}`);
}),
);
vi.mock("next/navigation", () => ({ redirect }));
vi.mock("@/lib/auth/acting-carrier", () => ({
getUnswitchedSession: vi.fn().mockResolvedValue(null),
}));
vi.mock("@/lib/dashboard/snapshot-read", () => ({
readDashboardSnapshotCached: vi.fn(),
}));
vi.mock("../page-client", () => ({ default: () => null }));
import InsightsPage from "../page";
beforeEach(() => {
redirect.mockClear();
});
describe("/insights?metric=", () => {
it("redirects a metric id to its page", async () => {
await expect(
InsightsPage({ searchParams: Promise.resolve({ metric: "hrv" }) }),
).rejects.toThrow("REDIRECT /insights/hrv");
});
it("renders the overview for an id it cannot place, or none", async () => {
await expect(
InsightsPage({ searchParams: Promise.resolve({ metric: "nonsense" }) }),
).resolves.toBeTruthy();
await expect(
InsightsPage({ searchParams: Promise.resolve({}) }),
).resolves.toBeTruthy();
expect(redirect).not.toHaveBeenCalled();
});
});
+16 -1
View File
@@ -4,7 +4,10 @@ import {
QueryClient,
} from "@tanstack/react-query";
import { redirect } from "next/navigation";
import { getUnswitchedSession } from "@/lib/auth/acting-carrier";
import { insightsHrefForMetric } from "@/lib/insights/metric-deep-link";
import { readDashboardSnapshotCached } from "@/lib/dashboard/snapshot-read";
import { queryKeys } from "@/lib/query-keys";
@@ -51,7 +54,19 @@ import InsightsPageClient from "./page-client";
* - Fail-soft: no session or a builder hiccup renders the page exactly as
* before this wrapper existed — the client cells own the fetch.
*/
export default async function InsightsPage() {
export default async function InsightsPage({
searchParams,
}: {
searchParams?: Promise<Record<string, string | string[] | undefined>>;
} = {}) {
// MCP deep links (`/insights?metric=<id>`) go to the metric's own page. An
// id that names no metric leaves the overview as it was.
const { metric } = (await searchParams) ?? {};
const target = insightsHrefForMetric(
typeof metric === "string" ? metric : null,
);
if (target) redirect(target);
// Global SSR-prefetch kill-switch shared with the dashboard wrapper. The e2e
// server sets `DASHBOARD_SSR_PREFETCH=false` so Playwright route mocks — which
// only see CLIENT fetches — keep governing what every prefetched page paints.
+28 -2
View File
@@ -2,8 +2,8 @@
import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
ArrowRight,
FolderOpen,
@@ -38,6 +38,12 @@ import { useRecordCapabilities } from "@/hooks/use-record-capabilities";
import { usePullToRefresh } from "@/hooks/use-pull-to-refresh";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import type { LabResultListResponse } from "@/components/labs/types";
import {
analyteFromQuery,
labHrefForAnalyteReading,
} from "@/lib/labs/analyte-deep-link";
export default function LabsPage() {
const { user, isAuthenticated, isLoading } = useAuth();
@@ -89,6 +95,26 @@ export default function LabsPage() {
disabled: dialogOpen,
});
// MCP deep links (`/labs?analyte=<name>`) open the marker's own page. The
// newest reading under that exact name says which marker it is; a name
// with no reading keeps the list and drops the query.
const searchParams = useSearchParams();
const linkedAnalyte = analyteFromQuery(searchParams.get("analyte"));
const analyteLink = useQuery({
queryKey: queryKeys.labAnalyteLink(linkedAnalyte ?? ""),
queryFn: () =>
apiGet<LabResultListResponse>(
`/api/labs?analyte=${encodeURIComponent(linkedAnalyte ?? "")}&limit=1&sortDir=desc`,
),
enabled: !!linkedAnalyte && isAuthenticated && enabled,
});
useEffect(() => {
if (!linkedAnalyte || !analyteLink.isFetched) return;
router.replace(
labHrefForAnalyteReading(analyteLink.data?.results?.[0]) ?? "/labs",
);
}, [linkedAnalyte, analyteLink.isFetched, analyteLink.data, router]);
useEffect(() => {
if (isLoading) return;
if (!isAuthenticated) {