mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
feat(coach): follow the coach capability at every entry point
The floating button, the drawer, the launch pills, the nav entry and the Coach pages read the coach capability from /api/auth/me instead of combining the operator switch with Hide Coach on their own. A missing provider or consent now hides the Coach too, instead of opening one that can only answer with an error. Stored conversations stay reachable: while the Coach is unavailable the conversation list turns read-only, opens a transcript in place and keeps delete. Refusals before the stream opens are read by meta.errorCode and each code has its own copy.
This commit is contained in:
1 parent
c2005fd8f1
commit
61d912627d
22 files changed
+371
-986
No files matched your search
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Every Coach entry point follows one answer: the `coach` capability on
|
||||
* `/api/auth/me`.
|
||||
*
|
||||
* The launchers used to AND the operator's switch with the person's Hide
|
||||
* Coach, each on its own, and none of them knew about a missing provider or
|
||||
* a missing consent, so the floating button and the "Ask the Coach" pills
|
||||
* stayed on screen and opened a Coach that could only answer with an error.
|
||||
* Now each surface paints only while the capability is available, and is
|
||||
* gone (no DOM trace, no inert control) for every reason it is not.
|
||||
*/
|
||||
import type { ReactNode } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { CoachLaunchProvider } from "@/lib/insights/coach-launch-context";
|
||||
import {
|
||||
AI_UNAVAILABLE_REASONS,
|
||||
type AiCapabilityKey,
|
||||
type AiCapabilityState,
|
||||
} from "@/lib/ai/capabilities/types";
|
||||
import {
|
||||
AI_AVAILABLE,
|
||||
aiUnavailable,
|
||||
} from "@/__tests__/helpers/ai-capability-fixtures";
|
||||
|
||||
const coachState = vi.hoisted(() => ({
|
||||
current: null as AiCapabilityState | null,
|
||||
asked: [] as string[],
|
||||
}));
|
||||
vi.mock("@/hooks/use-ai-capability", () => ({
|
||||
useAiCapability: (key: AiCapabilityKey) => {
|
||||
coachState.asked.push(key);
|
||||
return coachState.current;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||
usePathname: () => "/insights",
|
||||
}));
|
||||
|
||||
import { AskCoachAction } from "../ask-coach-action";
|
||||
import { CoachLaunchButton } from "../coach-launch-button";
|
||||
import { LayoutCoachFab } from "../layout-coach-fab";
|
||||
import { LayoutCoachMount } from "../layout-coach-mount";
|
||||
|
||||
function render(node: ReactNode): string {
|
||||
return renderToStaticMarkup(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<I18nProvider initialLocale="en">
|
||||
<CoachLaunchProvider>{node}</CoachLaunchProvider>
|
||||
</I18nProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
interface Surface {
|
||||
name: string;
|
||||
mount: () => ReactNode;
|
||||
/** What proves it painted; empty for surfaces that SSR to nothing. */
|
||||
proof: string;
|
||||
}
|
||||
|
||||
const SURFACES: Surface[] = [
|
||||
{
|
||||
name: "CoachLaunchButton",
|
||||
mount: () => <CoachLaunchButton />,
|
||||
proof: 'data-slot="coach-launch-inline"',
|
||||
},
|
||||
{
|
||||
name: "AskCoachAction",
|
||||
mount: () => <AskCoachAction question="Why?" />,
|
||||
proof: 'data-slot="ask-coach-action"',
|
||||
},
|
||||
{
|
||||
name: "LayoutCoachFab",
|
||||
mount: () => <LayoutCoachFab />,
|
||||
proof: 'data-slot="coach-fab"',
|
||||
},
|
||||
// The drawer is lazy (next/dynamic) and SSRs to nothing either way; the
|
||||
// capability read is what the test pins for it.
|
||||
{ name: "LayoutCoachMount", mount: () => <LayoutCoachMount />, proof: "" },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
coachState.current = AI_AVAILABLE;
|
||||
coachState.asked = [];
|
||||
vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
describe("Coach entry points follow the coach capability", () => {
|
||||
for (const surface of SURFACES) {
|
||||
it(`${surface.name} paints while the Coach is available`, () => {
|
||||
const html = render(surface.mount());
|
||||
if (surface.proof) expect(html).toContain(surface.proof);
|
||||
expect(coachState.asked).toContain("coach");
|
||||
});
|
||||
|
||||
for (const reason of AI_UNAVAILABLE_REASONS) {
|
||||
it(`${surface.name} is gone when the Coach is unavailable (${reason})`, () => {
|
||||
coachState.current = aiUnavailable(reason);
|
||||
const html = render(surface.mount());
|
||||
if (surface.proof) expect(html).not.toContain(surface.proof);
|
||||
expect(html).not.toMatch(/data-slot="(coach-|ask-coach)/);
|
||||
expect(coachState.asked).toContain("coach");
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -5,6 +5,15 @@ import { renderToStaticMarkup } from "react-dom/server";
|
||||
// navigation hooks the FAB uses. The pathname is mutable so the
|
||||
// hide-on-coach-page branch can be exercised.
|
||||
let mockPathname = "/insights";
|
||||
// AI surfaces paint only while their capability is available; these tests
|
||||
// cover the painted surface, so every capability reads available here.
|
||||
vi.mock("@/hooks/use-ai-capability", () => ({
|
||||
useAiCapability: () => ({
|
||||
available: true,
|
||||
reason: null,
|
||||
onDeviceAllowed: true,
|
||||
}),
|
||||
}));
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||
usePathname: () => mockPathname,
|
||||
|
||||
@@ -15,8 +15,7 @@ import {
|
||||
useCoachLaunch,
|
||||
type CoachLaunchScope,
|
||||
} from "@/lib/insights/coach-launch-context";
|
||||
import { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
import { useDisableCoach } from "@/hooks/use-disable-coach";
|
||||
import { useAiCapability } from "@/hooks/use-ai-capability";
|
||||
|
||||
/**
|
||||
* v1.21.0 (C4 H2) — discreet "Ask the Coach about this" affordance for
|
||||
@@ -71,15 +70,13 @@ export function AskCoachAction({
|
||||
}: AskCoachActionProps) {
|
||||
const { t } = useTranslations();
|
||||
const launch = useCoachLaunch();
|
||||
const flags = useFeatureFlags();
|
||||
const disableCoach = useDisableCoach();
|
||||
const coach = useAiCapability("coach");
|
||||
|
||||
// Same gate posture as <CoachLaunchButton> / <LayoutCoachFab>: render
|
||||
// nothing unless the provider is mounted, the operator flag is on, and
|
||||
// the user has not opted out.
|
||||
// nothing unless the launch provider is mounted and the `coach`
|
||||
// capability is available.
|
||||
if (!launch) return null;
|
||||
if (!flags.coach) return null;
|
||||
if (disableCoach) return null;
|
||||
if (!coach.available) return null;
|
||||
|
||||
const accessibleLabel = label ?? t("insights.coach.askAboutThis");
|
||||
|
||||
@@ -125,12 +122,10 @@ export function AskCoachIconButton({
|
||||
}: AskCoachActionProps) {
|
||||
const { t } = useTranslations();
|
||||
const launch = useCoachLaunch();
|
||||
const flags = useFeatureFlags();
|
||||
const disableCoach = useDisableCoach();
|
||||
const coach = useAiCapability("coach");
|
||||
|
||||
if (!launch) return null;
|
||||
if (!flags.coach) return null;
|
||||
if (disableCoach) return null;
|
||||
if (!coach.available) return null;
|
||||
|
||||
const accessibleLabel = label ?? t("insights.coach.askAboutThis");
|
||||
|
||||
|
||||
@@ -7,8 +7,7 @@ import { cn } from "@/lib/utils";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import type { CoachLaunchScope } from "@/lib/insights/coach-launch-context";
|
||||
import { useCoachLaunch } from "@/lib/insights/coach-launch-context";
|
||||
import { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
import { useDisableCoach } from "@/hooks/use-disable-coach";
|
||||
import { useAiCapability } from "@/hooks/use-ai-capability";
|
||||
|
||||
/**
|
||||
* Inline desktop Coach launch button.
|
||||
@@ -78,20 +77,16 @@ export function CoachLaunchButton({
|
||||
}: CoachLaunchButtonProps) {
|
||||
const { t } = useTranslations();
|
||||
const launch = useCoachLaunch();
|
||||
const flags = useFeatureFlags();
|
||||
const disableCoach = useDisableCoach();
|
||||
const coach = useAiCapability("coach");
|
||||
|
||||
if (!launch) {
|
||||
// The button only makes sense beneath the provider. Render nothing
|
||||
// so the sub-page doesn't paint a dead control.
|
||||
return null;
|
||||
}
|
||||
// v1.4.31 — operator can hide the Coach surface app-wide.
|
||||
if (!flags.coach) return null;
|
||||
// v1.4.47 W3 — per-user opt-out is a peer gate to the operator's
|
||||
// flag; either being off hides the pill entirely. See
|
||||
// Hidden while the `coach` capability is unavailable for any reason. See
|
||||
// `<LayoutCoachFab>` for the matching FAB gate.
|
||||
if (disableCoach) return null;
|
||||
if (!coach.available) return null;
|
||||
|
||||
const accessibleLabel = label ?? t("insights.heroActionAskCoach");
|
||||
|
||||
|
||||
@@ -734,6 +734,33 @@ describe("errorCodeToI18nKey", () => {
|
||||
);
|
||||
});
|
||||
|
||||
// v1.39 — a refused turn names its reason. The capability refusals carry
|
||||
// their code in `meta.errorCode`; each maps to copy that says what is off
|
||||
// and who can change it, never the generic "provider unavailable".
|
||||
it("maps each AI capability refusal to its own copy", () => {
|
||||
expect(errorCodeToI18nKey("consent.ai.required")).toBe(
|
||||
"insights.coach.errorConsent",
|
||||
);
|
||||
expect(errorCodeToI18nKey("ai.record.notPermitted")).toBe(
|
||||
"insights.coach.errorNotPermitted",
|
||||
);
|
||||
expect(errorCodeToI18nKey("ai.unavailable")).toBe(
|
||||
"insights.coach.errorUnavailable",
|
||||
);
|
||||
expect(errorCodeToI18nKey("ai.provider.none")).toBe(
|
||||
"insights.coach.errorNoProvider",
|
||||
);
|
||||
expect(errorCodeToI18nKey("assistant.disabled.coach")).toBe(
|
||||
"insights.coach.errorOperatorOff",
|
||||
);
|
||||
expect(errorCodeToI18nKey("assistant.disabled.enabled")).toBe(
|
||||
"insights.coach.errorOperatorOff",
|
||||
);
|
||||
expect(errorCodeToI18nKey("module.disabled")).toBe(
|
||||
"insights.coach.errorCoachOff",
|
||||
);
|
||||
});
|
||||
|
||||
it("forward-compats unknown codes with the namespaced key", () => {
|
||||
expect(errorCodeToI18nKey("errorProvider")).toBe(
|
||||
"insights.coach.errorProvider",
|
||||
|
||||
@@ -99,7 +99,23 @@ export function errorCodeToI18nKey(code: string): string {
|
||||
case "coach.provider.empty":
|
||||
case "coach.stream":
|
||||
return "insights.coach.errorProvider";
|
||||
// v1.39 — the capability refusals (`meta.errorCode` on a 403/422/503
|
||||
// before the stream opens). Each says what is off and who can change it.
|
||||
case "consent.ai.required":
|
||||
return "insights.coach.errorConsent";
|
||||
case "ai.record.notPermitted":
|
||||
return "insights.coach.errorNotPermitted";
|
||||
case "ai.unavailable":
|
||||
return "insights.coach.errorUnavailable";
|
||||
case "ai.provider.none":
|
||||
return "insights.coach.errorNoProvider";
|
||||
case "module.disabled":
|
||||
return "insights.coach.errorCoachOff";
|
||||
default:
|
||||
// The operator switched the Coach (or all AI) off on this server.
|
||||
if (code.startsWith("assistant.disabled.")) {
|
||||
return "insights.coach.errorOperatorOff";
|
||||
}
|
||||
// Forward-compat: try `insights.coach.<code>` for codes that
|
||||
// ship their own translation (e.g. legacy `errorProvider`).
|
||||
return `insights.coach.${code}`;
|
||||
@@ -756,7 +772,8 @@ function ChatBubbleImpl({
|
||||
setup gap, not a transient failure: surface a direct link to
|
||||
Settings → AI so the Coach guides the user into BYOK / local
|
||||
setup instead of inviting an endless retry. */}
|
||||
{errorCode === "coach.provider.none" && (
|
||||
{(errorCode === "coach.provider.none" ||
|
||||
errorCode === "ai.provider.none") && (
|
||||
<Link
|
||||
href="/settings/ai"
|
||||
data-slot="coach-no-provider-cta"
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import { QueryErrorRow } from "@/components/ui/query-error-row";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
import { useCoachConversation } from "./use-coach";
|
||||
|
||||
/**
|
||||
* One stored conversation, read back as plain text while the Coach itself is
|
||||
* unavailable. The messages render as React text children, like every other
|
||||
* Coach surface.
|
||||
*/
|
||||
export function ConversationTranscript({ id }: { id: string }) {
|
||||
const { t } = useTranslations();
|
||||
const { data, isLoading, isError, refetch } = useCoachConversation(id);
|
||||
if (isLoading) {
|
||||
return (
|
||||
<p className="text-muted-foreground px-3 pb-3 text-xs">
|
||||
{t("common.loading")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (isError || !data) {
|
||||
return (
|
||||
<QueryErrorRow
|
||||
className="mx-3 mb-3"
|
||||
onRetry={() => void refetch()}
|
||||
slot="coach-conversations-transcript-error"
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ol
|
||||
data-slot="coach-conversations-transcript"
|
||||
className="flex flex-col gap-3 px-3 pb-3"
|
||||
>
|
||||
{data.messages.map((message) => (
|
||||
<li key={message.id} className="flex flex-col gap-1">
|
||||
<span className="text-muted-foreground text-xs font-medium">
|
||||
{message.role === "user"
|
||||
? t("insights.coach.transcriptYou")
|
||||
: t("insights.coach.transcriptCoach")}
|
||||
</span>
|
||||
<p className="text-foreground text-sm whitespace-pre-wrap">
|
||||
{message.content}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
@@ -950,8 +950,13 @@ export function useSendCoachMessage(opts: UseSendCoachMessageOptions = {}) {
|
||||
try {
|
||||
const envelope = (await response.clone().json()) as {
|
||||
error?: unknown;
|
||||
meta?: { errorCode?: unknown } | null;
|
||||
};
|
||||
if (typeof envelope?.error === "string") {
|
||||
// v1.39 — a capability refusal carries its code in
|
||||
// `meta.errorCode` and a sentence in `error`; the code wins.
|
||||
if (typeof envelope?.meta?.errorCode === "string") {
|
||||
structured = envelope.meta.errorCode;
|
||||
} else if (typeof envelope?.error === "string") {
|
||||
structured = envelope.error;
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -9,8 +9,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { useCoachLaunch } from "@/lib/insights/coach-launch-context";
|
||||
import { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
import { useDisableCoach } from "@/hooks/use-disable-coach";
|
||||
import { useAiCapability } from "@/hooks/use-ai-capability";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
import { apiGet, apiPost } from "@/lib/api/api-fetch";
|
||||
@@ -78,8 +77,9 @@ export function LayoutCoachFab() {
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const launch = useCoachLaunch();
|
||||
const flags = useFeatureFlags();
|
||||
const disableCoach = useDisableCoach();
|
||||
// One answer for every Coach entry point: the `coach` capability on
|
||||
// `/api/auth/me` (operator switch, Hide Coach, provider, consent).
|
||||
const coach = useAiCapability("coach");
|
||||
|
||||
// Local "seen on this device" stamp — the nudge timestamp the user
|
||||
// last dismissed by opening the chat. Lazy initialiser per the
|
||||
@@ -93,7 +93,7 @@ export function LayoutCoachFab() {
|
||||
}
|
||||
});
|
||||
|
||||
const coachAvailable = !!launch && flags.coach && !disableCoach;
|
||||
const coachAvailable = !!launch && coach.available;
|
||||
const onCoachPage = pathname?.startsWith("/coach") ?? false;
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
import { useCoachLaunch } from "@/lib/insights/coach-launch-context";
|
||||
import { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
import { useDisableCoach } from "@/hooks/use-disable-coach";
|
||||
import { useAiCapability } from "@/hooks/use-ai-capability";
|
||||
|
||||
/**
|
||||
* v1.4.31 — defer the Coach drawer subtree behind `next/dynamic` so
|
||||
@@ -36,17 +35,13 @@ const CoachDrawer = dynamic(
|
||||
*/
|
||||
export function LayoutCoachMount() {
|
||||
const launch = useCoachLaunch();
|
||||
const flags = useFeatureFlags();
|
||||
const disableCoach = useDisableCoach();
|
||||
const coach = useAiCapability("coach");
|
||||
if (!launch) return null;
|
||||
// v1.4.31 — operator can hide the Coach drawer app-wide; suppress
|
||||
// the entire SSE mount when the flag is off.
|
||||
if (!flags.coach) return null;
|
||||
// v1.4.47 W3 — per-user opt-out short-circuits the drawer subtree
|
||||
// the same way the operator's master flag does. Keeps the SSE
|
||||
// chat reader + portal scaffolding out of the bundle for users
|
||||
// who never want the Coach mounted.
|
||||
if (disableCoach) return null;
|
||||
// The drawer subtree (SSE chat reader, portal scaffolding) mounts only
|
||||
// while the `coach` capability is available: the operator's switch, the
|
||||
// person's Hide Coach, a missing provider and missing consent all keep it
|
||||
// out, so nothing offers a Coach that cannot answer.
|
||||
if (!coach.available) return null;
|
||||
return (
|
||||
<CoachDrawer
|
||||
open={launch.open}
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
import { isSurfaceVisible } from "@/lib/modules/surface";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useNavModules } from "@/hooks/use-nav-modules";
|
||||
import { useMounted } from "@/hooks/use-mounted";
|
||||
import { useRecordCapabilities } from "@/hooks/use-record-capabilities";
|
||||
import {
|
||||
@@ -107,15 +108,18 @@ export function BottomNav() {
|
||||
// feature destination that isn't a primary slot, plus the shared utility
|
||||
// tail. Cycle is gated by the same flag the sidebar uses, so the two
|
||||
// surfaces gate identically and cannot drift.
|
||||
// The Coach entry follows the `coach` AI capability (a Coach that cannot
|
||||
// answer is not offered); the sidebar reads the same map.
|
||||
const navModules = useNavModules();
|
||||
const moreHub = useMemo<ReadonlyArray<NavLink>>(
|
||||
() =>
|
||||
mobileMoreHubDestinations({
|
||||
modules: user?.modules,
|
||||
modules: navModules,
|
||||
mounted,
|
||||
sharedRecord,
|
||||
sections,
|
||||
}),
|
||||
[user?.modules, mounted, sharedRecord, sections],
|
||||
[navModules, mounted, sharedRecord, sections],
|
||||
);
|
||||
|
||||
// Every slot but Home asks two things: does sharing cover it, and does its
|
||||
@@ -133,10 +137,10 @@ export function BottomNav() {
|
||||
// Insights drops out under a switch.
|
||||
(!sharedRecord || isDestinationInSharedRecord(item.href, sections)) &&
|
||||
mounted &&
|
||||
isSurfaceVisible(`nav:${item.href}`, user?.modules)
|
||||
isSurfaceVisible(`nav:${item.href}`, navModules)
|
||||
);
|
||||
},
|
||||
[user?.modules, mounted, sharedRecord, sections],
|
||||
[navModules, mounted, sharedRecord, sections],
|
||||
);
|
||||
|
||||
// Both fixed flanks run through the ONE slot filter, so a module-gated
|
||||
|
||||
@@ -29,6 +29,7 @@ import { cn } from "@/lib/utils";
|
||||
import { Logo } from "@/components/ui/logo";
|
||||
import { useAuth, useLogout } from "@/hooks/use-auth";
|
||||
import { useIsMobile } from "@/hooks/use-is-mobile";
|
||||
import { useNavModules } from "@/hooks/use-nav-modules";
|
||||
import { useMounted } from "@/hooks/use-mounted";
|
||||
import { useRecordCapabilities } from "@/hooks/use-record-capabilities";
|
||||
import { useTheme } from "@/components/providers";
|
||||
@@ -320,10 +321,12 @@ export function SidebarNav() {
|
||||
// The Settings entry needs them: a record-content page is offered only when
|
||||
// the grant manages the section its forms write.
|
||||
const manageableDomains = user?.accountAccess?.active?.manageableDomains;
|
||||
// The Coach entry follows the `coach` AI capability, like every other
|
||||
// Coach entry point; the rest of the map is `modules` unchanged.
|
||||
const navModules = useNavModules();
|
||||
const visibleNavItems = useMemo(
|
||||
() =>
|
||||
visibleNavDestinations(user?.modules, mounted, sharedRecord, sections),
|
||||
[user?.modules, mounted, sharedRecord, sections],
|
||||
() => visibleNavDestinations(navModules, mounted, sharedRecord, sections),
|
||||
[navModules, mounted, sharedRecord, sections],
|
||||
);
|
||||
// Collapsed = the user's stored choice, or — with no stored choice — a
|
||||
// viewport default: tablet widths (md–lg, e.g. an iPad held upright)
|
||||
|
||||
Reference in new issue
Block a user