Merge branch 'fix/v1473-ai' into release/v1.47.3

# Conflicts:
#	src/__tests__/baselines/source-function-lines.json
#	src/__tests__/baselines/version-stamp-comments.json
This commit is contained in:
Marc-André Bombeck committed 2026-11-11 21:07:27 +01:00
commit 9227844f42
74 files changed
+944 -2901

No files matched your search

@@ -3,12 +3,21 @@
* phone it is the only control on the tile a thumb has to hit, so it carries
* the 44 px floor every other mobile action does (`size-11`), stepping down
* from `sm` like the rest of the app.
*
* The hint is also an invitation, so it stays away from a person who switched
* both the Coach and AI analysis off.
*/
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
const auth = vi.hoisted(() => ({
modules: {} as Record<string, boolean>,
}));
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({ user: { id: "u1" }, isAuthenticated: true }),
useAuth: () => ({
user: { id: "u1", modules: auth.modules },
isAuthenticated: true,
}),
}));
vi.mock("@/hooks/use-mounted", () => ({ useMounted: () => true }));
vi.mock("@/hooks/use-ai-capability", () => ({
@@ -22,16 +31,21 @@ vi.mock("@/hooks/use-ai-capability", () => ({
import { I18nProvider } from "@/lib/i18n/context";
import { AiSetupHint } from "../ai-setup-hint";
function dismissButton(): string {
function render(surface: "insights" | "settings" = "insights"): string {
vi.stubGlobal("window", {
localStorage: { getItem: () => null, setItem: () => undefined },
});
const html = renderToStaticMarkup(
<I18nProvider initialLocale="en">
<AiSetupHint surface="insights" />
<AiSetupHint surface={surface} />
</I18nProvider>,
);
vi.unstubAllGlobals();
return html;
}
function dismissButton(): string {
const html = render();
const match = html.match(
/<button[^>]*data-slot="ai-setup-hint-dismiss"[^>]*>/,
);
@@ -46,3 +60,22 @@ describe("the setup hint's dismiss button", () => {
expect(cls).toContain("size-11");
});
});
describe("the setup hint after an opt-out", () => {
afterEach(() => {
auth.modules = {};
});
it("is gone on both surfaces once the Coach and AI analysis are off", () => {
auth.modules = { coach: false, insights: false };
expect(render("insights")).not.toContain('data-slot="ai-setup-hint"');
expect(render("settings")).not.toContain('data-slot="ai-setup-hint"');
});
it("stays while either one is still on", () => {
auth.modules = { coach: false, insights: true };
expect(render("insights")).toContain('data-slot="ai-setup-hint"');
auth.modules = { coach: true, insights: false };
expect(render("settings")).toContain('data-slot="ai-setup-hint"');
});
});
@@ -81,18 +81,15 @@ describe("<CorrelationCard>", () => {
expect(html).toContain("High confidence");
});
it("renders the disabled experiment CTA with the Coming-soon tooltip", () => {
it("offers no placeholder action, only ones that work", () => {
const html = render(<CorrelationCard result={okResult} />);
expect(html).toMatch(/data-slot="correlation-card-cta"/);
expect(html).toContain("Try a 7-day experiment");
expect(html).toMatch(/disabled/);
expect(html).toContain("Coming soon");
expect(html).not.toMatch(/data-slot="correlation-card-cta"/);
expect(html).not.toMatch(/<button[^>]*disabled/);
});
it("renders the empty-state when status=insufficient", () => {
const html = render(<CorrelationCard result={insufficient} />);
expect(html).toContain("Need more data to see this relationship");
expect(html).not.toContain("Try a 7-day experiment");
});
it("tags the wrapper with the correlation kind", () => {
@@ -103,7 +100,7 @@ describe("<CorrelationCard>", () => {
it("renders German copy when locale=de", () => {
const html = render(<CorrelationCard result={okResult} />, "de");
expect(html).toContain("BD × Therapietreue");
expect(html).toContain("7-Tage-Experiment");
expect(html).toContain("basierend auf 28 gepaarten Messungen");
});
it("never surfaces causal language in the interpretation slot", () => {
+5 -2
View File
@@ -13,6 +13,7 @@ import { SettingsCardActions } from "@/components/settings/_card-actions";
import { useAiProviderState } from "@/hooks/use-ai-capability";
import { useAuth } from "@/hooks/use-auth";
import { useMounted } from "@/hooks/use-mounted";
import { hasOptedOutOfAi } from "@/lib/ai/capabilities/types";
import { useTranslations } from "@/lib/i18n/context";
/**
@@ -26,8 +27,9 @@ import { useTranslations } from "@/lib/i18n/context";
* It shows only while no provider is configured AND the person could set one
* up here (`provider.canConfigure`: false inside somebody else's record and
* while the operator has AI switched off, where the hint would point at a
* setting nobody on this screen can change). Dismissing it is remembered per
* viewer in this browser; the hint stays gone on both surfaces.
* setting nobody on this screen can change) AND they have not switched both
* the Coach and AI analysis off (`hasOptedOutOfAi`). Dismissing it is
* remembered per viewer in this browser; the hint stays gone on both surfaces.
*/
const AI_SETUP_HINT_STORAGE_PREFIX = "healthlog.ai-setup-hint.dismissed";
@@ -63,6 +65,7 @@ export function AiSetupHint({
const viewerId = user?.id ?? null;
if (!mounted || viewerId === null) return null;
if (provider.configured || !provider.canConfigure) return null;
if (hasOptedOutOfAi(user?.modules)) return null;
if (dismissedNow || readDismissed(viewerId)) return null;
const dismiss = () => {
+2 -23
View File
@@ -1,8 +1,7 @@
"use client";
import dynamic from "next/dynamic";
import { Activity, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Activity } from "lucide-react";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { TileHeader } from "@/components/insights/tile-header";
import { EmptyState } from "@/components/ui/empty-state";
@@ -177,27 +176,7 @@ export function CorrelationCard({ result }: CorrelationCardProps) {
})}
</p>
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
size="sm"
// Outline variant so the disabled placeholder reads as
// "this is on the roadmap" rather than "the system is
// broken right now". Flip back to default when the
// 7-day experiment feature ships in v1.5.
variant="outline"
disabled
data-slot="correlation-card-cta"
className="gap-1.5"
title={t("insights.correlationRow.experimentTooltip")}
>
<Sparkles className="h-3.5 w-3.5" aria-hidden="true" />
<span>{t("insights.correlationRow.experimentCta")}</span>
<span className="sr-only">
, {t("insights.correlationRow.experimentTooltip")}
</span>
</Button>
{/* v1.21.0 — the live Coach hand-off sits beside the
roadmap CTA: it scopes to both sources in the pair. */}
{/* The Coach hand-off scopes to both sources in the pair. */}
<AskCoachAction
question={t(COACH_QUESTION_BY_KIND[result.kind])}
scope={coachScope}
@@ -4,81 +4,46 @@ import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
/**
* The elevated done-screen AI panel must lead with value and gate nothing:
* it shows the local-first ladder and the honest "useful without AI" line,
* yet the three original exits (connect / log / dashboard) stay intact, so
* a keyless user is never stranded. The shared-key note only appears when
* the deployment's provider serves the user (`managedBy === "server"`).
* The setup flow's exit. AI gets one quiet line with a link to Settings, AI,
* and only while it could be set up here and is still wanted; the exits
* (dashboard, tour, connect, log) are there either way.
*/
const aiProviderState = vi.hoisted(() => ({
data: undefined as
| {
managedBy?: string | null;
serverProviderHealth?: string;
serverProviderOffer?: boolean;
serverProviderConsent?: boolean;
}
| undefined,
}));
/**
* The consent grant is a mutation, and this suite renders to static markup
* (the house convention — there is no jsdom in this repo), so the click
* itself cannot be dispatched. What IS worth proving is the request the
* button would send, so every `useMutation` registration is captured here
* and its `mutationFn` invoked directly.
*/
const mutations = vi.hoisted(
() =>
[] as Array<{
mutationKey?: readonly unknown[];
mutationFn?: () => Promise<unknown>;
}>,
);
vi.mock("@tanstack/react-query", () => ({
useQuery: () => ({ data: aiProviderState.data }),
useMutation: (options?: {
mutationKey?: readonly unknown[];
mutationFn?: () => Promise<unknown>;
}) => {
if (options) mutations.push(options);
return { mutate: () => {}, mutateAsync: async () => {}, isPending: false };
},
useMutation: () => ({
mutate: () => {},
mutateAsync: async () => {},
isPending: false,
}),
useQueryClient: () => ({ invalidateQueries: async () => {} }),
}));
const apiPost = vi.hoisted(() => vi.fn());
vi.mock("@/lib/api/api-fetch", async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
apiPost,
}));
const toastError = vi.hoisted(() => vi.fn());
vi.mock("sonner", () => ({ toast: { error: toastError } }));
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: () => {}, replace: () => {} }),
}));
const auth = vi.hoisted(() => ({ modules: {} as Record<string, boolean> }));
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({ user: { id: "u1" } }),
useAuth: () => ({ user: { id: "u1", modules: auth.modules } }),
}));
/**
* `ai.provider.canConfigure` from `/api/auth/me`: the panel is one optional
* offer, shown only while AI can be set up from here.
*/
const providerState = vi.hoisted(() => ({ canConfigure: true }));
/** `ai.provider` from `/api/auth/me`. */
const providerState = vi.hoisted(() => ({
configured: false,
canConfigure: true,
}));
vi.mock("@/hooks/use-ai-capability", () => ({
useAiProviderState: () => ({
configured: false,
configured: providerState.configured,
managedBy: null,
canConfigure: providerState.canConfigure,
}),
}));
vi.mock("@/components/onboarding/use-onboarding-flow", () => ({
useOnboardingAnswer: () => ({ mutate: () => {} }),
}));
vi.mock("@/hooks/use-account-switch", () => ({
useAccountSwitch: () => ({ mutate: () => {}, isPending: false }),
}));
@@ -128,34 +93,64 @@ function render(recordTarget?: OnboardingStateDto["needs"]["recordTarget"]) {
);
}
describe("<DoneScreen> AI panel", () => {
it("leads with the value-first panel and the local-first ladder", () => {
aiProviderState.data = undefined;
function withState(
next: Partial<typeof providerState>,
modules: Record<string, boolean>,
run: () => void,
) {
const before = { ...providerState };
Object.assign(providerState, next);
auth.modules = modules;
try {
run();
} finally {
Object.assign(providerState, before);
auth.modules = {};
}
}
describe("<DoneScreen> AI line", () => {
it("is one line with a link to Settings, AI, and nothing more", () => {
const html = render();
expect(html).toContain('data-slot="onboarding-ai-panel"');
// Local model is surfaced first (the calm private default).
expect(html).toContain("AI requests stay on your network");
// The honest release valve is present and prominent.
expect(html).toContain('data-slot="onboarding-ai-keyless"');
expect(html).toContain("fully useful without AI");
// Setup is a single optional deep-link, not a gate.
expect(html).toContain('href="/settings/ai"');
const line = html.match(
/<p[^>]*data-slot="onboarding-ai-line"[^>]*>([\s\S]*?)<\/p>/,
);
expect(line).not.toBeNull();
expect(line![1]).toContain("AI is optional");
expect(line![1]).toContain('href="/settings/ai"');
// No sample briefing, no provider ladder, no one-tap offer.
expect(html).not.toContain("Example");
expect(html).not.toContain("Three ways to turn it on");
expect(html).not.toMatch(/<button[^>]*>[^<]*Turn on/);
});
it("leaves the panel out when AI cannot be set up here", () => {
it("is left out when AI cannot be set up here", () => {
// The operator switched AI off, or the record belongs to somebody else.
// HealthLog is complete without AI, so the screen goes from "done"
// straight to the exits.
providerState.canConfigure = false;
aiProviderState.data = undefined;
const html = render();
expect(html).not.toContain('data-slot="onboarding-ai-panel"');
expect(html).toContain('data-slot="onboarding-open-dashboard"');
providerState.canConfigure = true;
withState({ canConfigure: false }, {}, () => {
const html = render();
expect(html).not.toContain('data-slot="onboarding-ai-line"');
expect(html).toContain('data-slot="onboarding-open-dashboard"');
});
});
it("keeps every exit so the panel is fully skippable", () => {
aiProviderState.data = undefined;
it("is left out once a provider is configured", () => {
withState({ configured: true }, {}, () => {
expect(render()).not.toContain('data-slot="onboarding-ai-line"');
});
});
it("is left out once the Coach and AI analysis are switched off", () => {
withState({}, { coach: false, insights: false }, () => {
expect(render()).not.toContain('data-slot="onboarding-ai-line"');
});
withState({}, { coach: false, insights: true }, () => {
expect(render()).toContain('data-slot="onboarding-ai-line"');
});
});
});
describe("<DoneScreen> exits", () => {
it("keeps every exit", () => {
const html = render();
expect(html).toContain('href="/settings/integrations"');
expect(html).toContain('href="/measurements"');
@@ -163,229 +158,11 @@ describe("<DoneScreen> AI panel", () => {
});
it("offers the tour rather than launching it", () => {
aiProviderState.data = undefined;
expect(render()).toContain('data-slot="onboarding-take-tour"');
});
it("offers the managed profile only to an answer that asked for it later", () => {
aiProviderState.data = undefined;
expect(render("both")).toContain('href="/settings/access"');
expect(render("me")).not.toContain('href="/settings/access"');
});
});
/**
* v1.38.19 — the shared provider, offered only when it works.
*
* The card used to read `managedBy === "server"` and promise that insights
* "work for you right now". That is a presence read: it knew a key was
* configured, never that it worked, and it said nothing about the consent
* receipt the egress actually needs — so a fresh account followed the
* promise straight into a `consent.ai.required` refusal. On 2026-09-11 the
* operator's own instance was answering HTTP 500 while the screen kept
* making that promise.
*
* Four variants now, and only one of them has a button.
*/
function grantMutation() {
return mutations.find((m) =>
(m.mutationKey ?? []).some(
(part) => typeof part === "string" && part.includes("consent"),
),
);
}
describe("<DoneScreen> shared-provider offer", () => {
it("offers one tap when the server says the provider is known to work", () => {
aiProviderState.data = {
managedBy: "server",
serverProviderHealth: "healthy",
serverProviderOffer: true,
serverProviderConsent: false,
};
const html = render();
expect(html).toContain('data-ai-state="offer"');
expect(html).toContain('data-slot="onboarding-ai-offer"');
expect(html).toContain('data-slot="onboarding-ai-offer-grant"');
// The unproven promise is gone from this branch.
expect(html).not.toContain('data-slot="onboarding-ai-shared-key"');
expect(html).not.toContain('data-slot="onboarding-ai-unavailable"');
});
it("says the provider is not answering only when a failure earned it", () => {
aiProviderState.data = {
managedBy: "server",
serverProviderHealth: "unhealthy",
serverProviderOffer: false,
serverProviderConsent: false,
};
const html = render();
expect(html).toContain('data-ai-state="unavailable"');
expect(html).toContain('data-slot="onboarding-ai-unavailable"');
expect(html).not.toContain('data-slot="onboarding-ai-offer-grant"');
expect(html).not.toContain('data-slot="onboarding-ai-shared-key"');
// The rest of the panel is untouched in every branch.
expect(html).toContain('data-slot="onboarding-ai-keyless"');
expect(html).toContain('href="/settings/ai"');
});
it("claims nothing either way when nobody has measured the provider", () => {
// `unknown` is an empty `provider_health` table — the state of every
// instance until its first AI call, and the most common way through this
// screen. Saying "not answering" there is a claim about something nobody
// measured, which is the one thing this panel exists not to do.
aiProviderState.data = {
managedBy: "server",
serverProviderHealth: "unknown",
serverProviderOffer: false,
serverProviderConsent: false,
};
const html = render();
expect(html).toContain('data-ai-state="neutral"');
expect(html).not.toContain('data-slot="onboarding-ai-unavailable"');
expect(html).not.toContain('data-slot="onboarding-ai-offer-grant"');
expect(html).not.toContain('data-slot="onboarding-ai-shared-key"');
// The neutral panel is the whole panel, minus any claim about a provider.
expect(html).toContain('data-slot="onboarding-ai-keyless"');
expect(html).toContain('href="/settings/ai"');
});
it("keeps the shared-key note for the one state it was ever true of", () => {
aiProviderState.data = {
managedBy: "server",
serverProviderHealth: "healthy",
serverProviderOffer: false,
serverProviderConsent: true,
};
const html = render();
expect(html).toContain('data-ai-state="consent"');
expect(html).toContain('data-slot="onboarding-ai-shared-key"');
expect(html).not.toContain('data-slot="onboarding-ai-offer-grant"');
expect(html).not.toContain('data-slot="onboarding-ai-unavailable"');
});
it("leaves a user with their own provider the setup link and nothing else", () => {
aiProviderState.data = {
managedBy: "user",
serverProviderHealth: "healthy",
serverProviderOffer: false,
serverProviderConsent: false,
};
const html = render();
expect(html).not.toContain('data-slot="onboarding-ai-offer"');
expect(html).not.toContain('data-slot="onboarding-ai-unavailable"');
expect(html).not.toContain('data-slot="onboarding-ai-shared-key"');
expect(html).toContain('href="/settings/ai"');
});
it("says nothing at all while the status is still in flight", () => {
aiProviderState.data = undefined;
const html = render();
// Not even the settled marker: the question is genuinely unanswered.
expect(html).not.toContain("data-ai-state");
expect(html).not.toContain('data-slot="onboarding-ai-offer"');
expect(html).not.toContain('data-slot="onboarding-ai-unavailable"');
});
/**
* The whole decision table, in one place.
*
* Three arms the screen can be in — the offer is available, the offer is
* withheld for a reason that is not health (the assistant surfaces switched
* off, a managed profile), a receipt is already on file — crossed with the
* three health states. The point of the cross is that HEALTH decides the
* claim in every arm: the consent arm used to promise "insights work for
* you right now" without reading health at all, which told somebody who had
* consented that a dead provider was working. That is the same unmeasured
* claim as the `unknown` case at the other end of the panel.
*/
const TABLE = [
{ arm: "offerable", consent: false, health: "healthy", state: "offer" },
{
arm: "offerable",
consent: false,
health: "unhealthy",
state: "unavailable",
},
{ arm: "offerable", consent: false, health: "unknown", state: "neutral" },
{ arm: "withheld", consent: false, health: "healthy", state: "neutral" },
{
arm: "withheld",
consent: false,
health: "unhealthy",
state: "unavailable",
},
{ arm: "withheld", consent: false, health: "unknown", state: "neutral" },
{ arm: "consented", consent: true, health: "healthy", state: "consent" },
{
arm: "consented",
consent: true,
health: "unhealthy",
state: "unavailable",
},
{ arm: "consented", consent: true, health: "unknown", state: "neutral" },
] as const;
it.each(TABLE)(
"settles on $state when the offer is $arm and the provider is $health",
({ arm, consent, health, state }) => {
aiProviderState.data = {
managedBy: "server",
serverProviderHealth: health,
// The server only ever offers on `healthy`, and never with a receipt
// on file; the withheld arm is the flags-off / managed-profile case.
serverProviderOffer: arm === "offerable" && health === "healthy",
serverProviderConsent: consent,
};
const html = render();
expect(html).toContain(`data-ai-state="${state}"`);
// The positive sentence appears in exactly one of the nine cells.
expect(html.includes('data-slot="onboarding-ai-shared-key"')).toBe(
state === "consent",
);
expect(html.includes('data-slot="onboarding-ai-unavailable"')).toBe(
state === "unavailable",
);
expect(html.includes('data-slot="onboarding-ai-offer-grant"')).toBe(
state === "offer",
);
// The rest of the panel is untouched in every cell.
expect(html).toContain('data-slot="onboarding-ai-keyless"');
expect(html).toContain('href="/settings/ai"');
},
);
it("grants only with the explicit confirmation the server requires", async () => {
mutations.length = 0;
apiPost.mockReset();
apiPost.mockResolvedValue({ minted: true, kind: "ai_full" });
aiProviderState.data = {
managedBy: "server",
serverProviderHealth: "healthy",
serverProviderOffer: true,
serverProviderConsent: false,
};
render();
const grant = grantMutation();
expect(grant).toBeDefined();
await grant!.mutationFn!();
expect(apiPost).toHaveBeenCalledWith("/api/consent/ai/web", {
confirm: true,
});
});
it("a refused grant throws rather than reporting a consent nobody recorded", async () => {
mutations.length = 0;
apiPost.mockReset();
apiPost.mockRejectedValue(new Error("429"));
aiProviderState.data = {
managedBy: "server",
serverProviderHealth: "healthy",
serverProviderOffer: true,
serverProviderConsent: false,
};
render();
const grant = grantMutation();
await expect(grant!.mutationFn!()).rejects.toThrow();
});
});
@@ -153,6 +153,28 @@ describe("<GettingStartedChecklist> — rows for an established account", () =>
};
});
it("leaves the AI row out once the Coach and AI analysis are switched off", () => {
// Nothing configured, so the row would be an open to-do: the person
// declined AI in Settings, Modules, and the list does not ask again.
providerState = {
configured: false,
managedBy: null,
canConfigure: true,
responseTimeoutMs: 60_000,
};
currentUser = user({ modules: { coach: false, insights: false } });
expect(render()).toContain("4 of 5 done");
// Either one still on keeps the row.
currentUser = user({ modules: { coach: false, insights: true } });
expect(render()).toContain("4 of 6 done");
providerState = {
configured: true,
managedBy: "user",
canConfigure: true,
responseTimeoutMs: 60_000,
};
});
it("keeps the supporting queries enabled while the card can render", () => {
currentUser = user();
render();
@@ -1,41 +0,0 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import { SampleBriefingCard } from "../sample-briefing-card";
/**
* The onboarding "aha" artifact must be a STATIC, clearly-labelled example
* with zero egress: no provider is configured when it renders, so it can
* never make a model call. These tests pin both properties — the "Example"
* tag is present (so it's never mistaken for real data) and nothing on the
* component touches the network.
*/
function render(node: React.ReactElement) {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">{node}</I18nProvider>,
);
}
afterEach(() => {
vi.restoreAllMocks();
});
describe("<SampleBriefingCard>", () => {
it("renders the sample briefing with an explicit Example tag", () => {
const html = render(<SampleBriefingCard />);
expect(html).toContain("Example");
// The worked-example numbers are fixed copy, never derived from a user.
expect(html).toContain("1.2 kg");
expect(html).toContain('data-slot="sample-briefing-tag"');
// The caption states plainly that this is not the user's data.
expect(html).toContain("not your own data");
});
it("makes no network call — no provider exists yet, zero egress", () => {
const fetchSpy = vi.spyOn(globalThis, "fetch");
render(<SampleBriefingCard />);
expect(fetchSpy).not.toHaveBeenCalled();
});
});
+21 -270
View File
@@ -2,10 +2,8 @@
import { useAiProviderState } from "@/hooks/use-ai-capability";
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { showErrorToast } from "@/lib/errors/error-toast";
import {
CheckCircle2,
Compass,
@@ -13,42 +11,22 @@ import {
PlusCircle,
Plug,
Settings2,
Sparkles,
UserPlus,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { MedicalDisclaimer } from "@/components/common/medical-disclaimer";
import { SampleBriefingCard } from "@/components/onboarding/sample-briefing-card";
import { StepHeading } from "@/components/onboarding/step-heading";
import { useOnboardingAnswer } from "@/components/onboarding/use-onboarding-flow";
import { useAuth } from "@/hooks/use-auth";
import { useAccountSwitch } from "@/hooks/use-account-switch";
import { setTourReferrer } from "@/components/onboarding/tour-launcher";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { useGrantAiConsent } from "@/hooks/use-grant-ai-consent";
import { hasOptedOutOfAi } from "@/lib/ai/capabilities/types";
import { useTranslations } from "@/lib/i18n/context";
import { markChecklistExpanded } from "@/lib/onboarding/checklist-storage";
import type { OnboardingStateDto } from "@/lib/onboarding/needs";
import { accountLabel } from "@/lib/sharing/account-access-view";
import { InlineAction } from "@/components/ui/inline-action";
interface AiProviderStatus {
/** Origin of the provider that would serve this user, if any. */
managedBy?: "user" | "local" | "server" | null;
/**
* v1.38.19 — the instance-wide tri-state. Fail closed for the
* offer: neither `unhealthy` nor `unknown` earns one. Only `unhealthy` is
* a verdict this screen may state out loud.
*/
serverProviderHealth?: "healthy" | "unhealthy" | "unknown";
/** Whether the shared provider may honestly be offered in one tap. */
serverProviderOffer?: boolean;
/** Whether this user already holds an active `ai_full` / `ai_coach` receipt. */
serverProviderConsent?: boolean;
}
/**
* v1.39 — the setup flow's exit.
*
@@ -68,18 +46,14 @@ interface AiProviderStatus {
* is presentational: the module map was derived on confirm, the cookie
* cleared there too.
*
* The AI panel leads with the payoff (a static, clearly-labelled SAMPLE
* briefing — no model call, no egress, no consent), then the honest
* local-first ladder and the "useful without AI" release valve. Value-first,
* never a gate: every exit below stays, and setup is a single optional
* deep-link.
* AI gets one line with a link to Settings, AI, and no more: HealthLog is
* complete without it, and the hint on Insights is where it is offered.
*/
export function DoneScreen({ state }: { state: OnboardingStateDto }) {
const { t } = useTranslations();
const router = useRouter();
const { user } = useAuth();
const [sampleOpen, setSampleOpen] = useState(false);
const answer = useOnboardingAnswer();
const accountSwitch = useAccountSwitch();
@@ -115,85 +89,15 @@ export function DoneScreen({ state }: { state: OnboardingStateDto }) {
router.push("/");
}
// ── v1.38.19 — the shared provider, offered only when it works ──
//
// This block used to be one line: `managedBy === "server"` painted a note
// reading "insights work for you right now — no setup needed". Both halves
// were wrong. `managedBy` is a PRESENCE read — it knows the operator
// configured a key, never that the key answers — and "no setup needed"
// skipped the consent receipt `consent-guard.ts` demands before any health
// data reaches `admin-openai` / `admin-codex`, so the person who believed
// the note walked into a `consent.ai.required` refusal on their first
// briefing. On 2026-09-11 the operator's own instance was answering HTTP
// 500 from its OAuth proxy while this note kept promising otherwise.
//
// The server decides now, and the four branches below only READ it. The
// rest of the panel — sample, ladder, the "fully useful without AI" line,
// the setup link — is identical in every branch; nothing here is a gate.
// The panel is one optional offer, shown only while this person could set
// AI up here: `provider.canConfigure` is false while the operator has AI
// switched off and inside a record somebody else owns. HealthLog is
// complete without it, so with nothing to offer the screen simply goes
// from "done" to the exits.
const providerState = useAiProviderState();
const showAiPanel = providerState.canConfigure;
const { data: aiProvider } = useQuery<AiProviderStatus>({
queryKey: queryKeys.userAiProvider(),
queryFn: async () => {
return apiGet("/api/user/ai-provider");
},
enabled: !!user && showAiPanel,
});
// The tap's own outcome, held locally so the line changes the moment the
// receipt is minted rather than a refetch later.
const [justGranted, setJustGranted] = useState(false);
// The tap on the offer is the consent act; the hook sends the explicit
// confirmation the server requires before it records one.
const grantConsent = useGrantAiConsent();
function agreeToSharedProvider() {
grantConsent.mutate(undefined, {
onSuccess: () => setJustGranted(true),
onError: (failure) => {
// The button stays. A failed grant is a failed grant; the screen
// must not read as though consent were on file.
showErrorToast(t("onboarding.ai.offer.error"), { cause: failure });
},
});
}
const operatorProvides = aiProvider?.managedBy === "server";
const sharedHealth = aiProvider?.serverProviderHealth;
const consentOnFile =
justGranted || aiProvider?.serverProviderConsent === true;
const offerShared =
operatorProvides &&
!consentOnFile &&
aiProvider?.serverProviderOffer === true;
// A receipt on file is a fact about the ACCOUNT; it says nothing about
// whether the provider works. This line used to promise "insights work for
// you right now" on the strength of the receipt alone, so somebody who had
// just consented was told a dead provider was serving them — the same
// unmeasured claim as the offer's, made at the other end of the panel. The
// positive sentence is now earned by health as well, and a consented
// account on a broken provider reads the same honest note as anybody else.
const sharedKeyNote =
operatorProvides && consentOnFile && sharedHealth === "healthy";
// Only a health verdict somebody EARNED paints the "not answering" card —
// `unhealthy`, which means the provider was tried and the last thing that
// happened was a failure. `unknown` is not that verdict: it is an empty
// ledger, which is the state of every instance until its first AI call and
// therefore the most common way through this screen. It falls to the
// neutral panel, as does every other non-health reason the offer is
// withheld (the assistant surfaces switched off, a managed profile whose
// provider is the operator's by definition). The neutral panel claims
// nothing either way, which is the only honest thing to say about a state
// nobody measured.
const sharedUnavailable =
operatorProvides &&
!sharedKeyNote &&
!offerShared &&
sharedHealth === "unhealthy";
// One quiet line, only while this person could set AI up here, has no
// provider yet and has not switched the Coach and AI analysis off: the same
// rule as the Insights hint, which stays the one place that invites. With
// nothing to offer the screen goes from "done" straight to the exits.
const provider = useAiProviderState();
const showAiLine =
!provider.configured &&
provider.canConfigure &&
!hasOptedOutOfAi(user?.modules);
return (
<section
@@ -218,169 +122,16 @@ export function DoneScreen({ state }: { state: OnboardingStateDto }) {
</p>
</div>
{/* v1.28 — the flagship AI value, made reachable at the one screen
every fresh user passes through. The daily briefing / Coach need
a provider the rest of onboarding never provisions, so this
leads with the payoff (a static, clearly-labelled SAMPLE
briefing — no model call, no egress, no consent), then the
honest local-first ladder and the "useful without AI" release
valve. Value-first, never a gate: the three exits below stay,
and setup is a single optional deep-link. */}
{showAiPanel ? (
<section
aria-labelledby="onboarding-ai-panel-title"
data-slot="onboarding-ai-panel"
/* Which of the four variants the panel SETTLED on, and absent until
it has settled. The panel itself is unconditional and paints
immediately, so without this an assertion that a variant is absent
passes on a status that has simply not arrived yet. The value is
the same tri-state decision made once, above. */
data-ai-state={
aiProvider === undefined
? undefined
: sharedKeyNote
? "consent"
: offerShared
? "offer"
: sharedUnavailable
? "unavailable"
: "neutral"
}
className="border-border bg-card mx-auto flex w-full max-w-md flex-col gap-4 rounded-xl border p-4 text-left md:p-6"
{showAiLine ? (
<p
data-slot="onboarding-ai-line"
className="text-muted-foreground max-w-md text-sm"
>
<header className="flex items-start gap-3">
<span
aria-hidden="true"
className="from-primary to-brand-pink flex size-9 shrink-0 items-center justify-center rounded-full bg-gradient-to-br"
>
<Sparkles className="text-background size-4" />
</span>
<div className="space-y-1">
<h2
id="onboarding-ai-panel-title"
className="text-foreground text-base font-semibold tracking-tight"
>
{t("onboarding.ai.panelTitle")}
</h2>
<p className="text-muted-foreground text-sm leading-relaxed">
{t("onboarding.ai.panelIntro")}
</p>
</div>
</header>
{sampleOpen ? (
<SampleBriefingCard />
) : (
<Button
type="button"
variant="outline"
size="sm"
className="w-full"
data-slot="onboarding-ai-show-sample"
onClick={() => setSampleOpen(true)}
>
{t("onboarding.ai.showSample")}
</Button>
)}
{sharedKeyNote ? (
<p
data-slot="onboarding-ai-shared-key"
className="text-foreground bg-primary/5 border-primary/20 rounded-lg border px-3 py-2 text-sm leading-relaxed"
>
{justGranted
? t("onboarding.ai.offer.granted")
: t("onboarding.ai.sharedKeyNote")}
</p>
) : null}
{offerShared ? (
<div
data-slot="onboarding-ai-offer"
className="border-primary/20 bg-primary/5 space-y-2.5 rounded-lg border px-3 py-3"
>
<p className="text-foreground text-sm font-medium">
{t("onboarding.ai.offer.title")}
</p>
<p className="text-muted-foreground text-sm leading-relaxed">
{t("onboarding.ai.offer.body")}
</p>
<Button
type="button"
size="sm"
className="min-h-9 w-full"
data-slot="onboarding-ai-offer-grant"
disabled={grantConsent.isPending}
onClick={agreeToSharedProvider}
>
{t("onboarding.ai.offer.cta")}
</Button>
</div>
) : null}
{sharedUnavailable ? (
<div
data-slot="onboarding-ai-unavailable"
className="border-border bg-muted/40 space-y-1 rounded-lg border px-3 py-3"
>
<p className="text-foreground text-sm font-medium">
{t("onboarding.ai.unavailable.title")}
</p>
<p className="text-muted-foreground text-sm leading-relaxed">
{t("onboarding.ai.unavailable.body")}
</p>
</div>
) : null}
<div className="space-y-2.5">
<p className="text-foreground text-sm font-medium">
{t("onboarding.ai.ladderTitle")}
</p>
<ul className="space-y-2.5">
{/* Local first — the calm, private default — then BYOK, then
the subscription/OAuth path with its training caveat. Same
ordering + vendor-blind framing as the shipped document-
provider governance. */}
<li className="space-y-0.5">
<p className="text-foreground text-sm font-medium">
{t("onboarding.ai.ladderLocalTitle")}
</p>
<p className="text-muted-foreground text-sm leading-relaxed">
{t("onboarding.ai.ladderLocalBody")}
</p>
</li>
<li className="space-y-0.5">
<p className="text-foreground text-sm font-medium">
{t("onboarding.ai.ladderByokTitle")}
</p>
<p className="text-muted-foreground text-sm leading-relaxed">
{t("onboarding.ai.ladderByokBody")}
</p>
</li>
<li className="space-y-0.5">
<p className="text-foreground text-sm font-medium">
{t("onboarding.ai.ladderOauthTitle")}
</p>
<p className="text-muted-foreground text-sm leading-relaxed">
{t("onboarding.ai.ladderOauthBody")}
</p>
</li>
</ul>
</div>
<p
data-slot="onboarding-ai-keyless"
className="text-foreground text-sm leading-relaxed"
>
{t("onboarding.ai.keylessLine")}
</p>
<MedicalDisclaimer variant="dataPosture" />
<InlineAction asChild size="sm" className="font-medium underline">
<Link href="/settings/ai">{t("onboarding.ai.setupCta")}</Link>
{t("onboarding.done.aiOptional")}{" "}
<InlineAction asChild size="sm" className="underline">
<Link href="/settings/ai">{t("onboarding.done.aiSetupCta")}</Link>
</InlineAction>
</section>
</p>
) : null}
<div className="flex w-full max-w-xs flex-col gap-2">
@@ -21,6 +21,7 @@ import type { LucideIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useAccountOnceMounted } from "@/hooks/use-auth";
import { hasOptedOutOfAi } from "@/lib/ai/capabilities/types";
import { useTranslations } from "@/lib/i18n/context";
import { useDashboardSnapshot } from "@/lib/queries/use-dashboard-snapshot";
import { queryKeys } from "@/lib/query-keys";
@@ -262,10 +263,9 @@ export function GettingStartedChecklist() {
enabled: checklistRelevant,
});
// The AI row reads the provider state `/api/auth/me` already carries:
// present only while AI can be set up from here (`canConfigure`), done once
// any provider is configured (a personal key, a local model, an OAuth
// sign-in or the operator's shared key). No request of its own.
// The AI row reads `/api/auth/me`: present while AI can be set up here and
// is still wanted (`canConfigure`, `hasOptedOutOfAi`), done once any
// provider is configured. No request of its own.
const aiProvider = useAiProviderState();
// v1.5: skip these two fetches once the card can't render at
@@ -336,7 +336,8 @@ export function GettingStartedChecklist() {
(channel) => channel?.enabled === true,
);
const insightsConfigured = aiProvider.configured;
const aiConfigurable = aiProvider.canConfigure;
const aiConfigurable =
aiProvider.canConfigure && !hasOptedOutOfAi(user?.modules);
const items = useMemo(
() =>
@@ -1,58 +0,0 @@
"use client";
import { Sparkles } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { TileHeader } from "@/components/insights/tile-header";
import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
/**
* The onboarding "aha" artifact — a static, clearly-labelled *example*
* daily briefing shown BEFORE any AI provider is connected.
*
* It exists so a fresh user feels the payoff of AI Insights with zero
* setup: no provider is configured yet, so this makes no model call, no
* fetch, no egress, and needs no consent. Every number is fixed copy
* from the `onboarding.ai.sample*` keys (the worked example the
* no-provider briefing empty state already carries) — it is never
* derived from the user's own record, and the "Example" badge plus the
* caption make that explicit so it is never mistaken for real data.
*
* Presentational only — no state, no effect, no data fetch. Reused by
* the onboarding done-screen panel; safe to drop into any surface that
* wants to show what a briefing reads like.
*/
export function SampleBriefingCard({ className }: { className?: string }) {
const { t } = useTranslations();
return (
<Card
data-slot="sample-briefing-card"
aria-label={t("onboarding.ai.sampleAriaLabel")}
density="compact"
className={cn("bg-muted/30", className)}
>
<CardHeader>
<TileHeader
icon={Sparkles}
title={t("onboarding.ai.sampleTitle")}
right={
<Badge variant="secondary" data-slot="sample-briefing-tag">
{t("onboarding.ai.sampleTag")}
</Badge>
}
/>
</CardHeader>
<CardContent className="space-y-2">
<p className="text-foreground text-sm leading-relaxed">
{t("onboarding.ai.sampleBody")}
</p>
<p className="text-muted-foreground text-xs leading-relaxed">
{t("onboarding.ai.sampleCaption")}
</p>
</CardContent>
</Card>
);
}
@@ -36,6 +36,7 @@ import { SettingsCardHeader } from "@/components/settings/_card-header";
import { ConfirmButton } from "@/components/ui/confirm-button";
import { useTranslations } from "@/lib/i18n/context";
import { useAiCapability } from "@/hooks/use-ai-capability";
import { planMetricLabel } from "@/lib/ai/coach/plan-metric";
import {
useCoachReminders,
useCoachReminderMutations,
@@ -90,7 +91,7 @@ export function CoachRemindersSection({
>
<p className="text-sm break-words">{r.note}</p>
<div className="text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
{r.metric && <span className="uppercase">{r.metric}</span>}
{r.metric && <span>{planMetricLabel(r.metric, t)}</span>}
{r.dueAt && (
<span>
{t("settings.ai.coachReminders.duePrefix", {