mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 07:42:23 +00:00
refactor(web): retire the feature-flag reader for the capability map
The web no longer reads GET /api/feature-flags: useFeatureFlags and its query key are gone, and use-ai-capability gains the two readers the Coach pages and the operator notice need. A structural guard fails when web code reads the retired projection, and when a module requests an AI route without being registered with the capability that gates it. Adds the copy for every new state in all seven locales and drops the per-card no-provider strings.
This commit is contained in:
1 parent
3d85445e50
commit
5f6a0e42b4
14 files changed
+621
-286
No files matched your search
@@ -1,88 +0,0 @@
|
||||
import React from "react";
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
import { DEFAULT_ASSISTANT_FLAGS, useFeatureFlags } from "../use-feature-flags";
|
||||
|
||||
function Probe() {
|
||||
const flags = useFeatureFlags();
|
||||
return <pre data-testid="flags">{JSON.stringify(flags)}</pre>;
|
||||
}
|
||||
|
||||
function htmlEscape(s: string): string {
|
||||
return s.replace(/"/g, """);
|
||||
}
|
||||
|
||||
describe("useFeatureFlags", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("returns the all-on default when no QueryClient is mounted", () => {
|
||||
const html = renderToStaticMarkup(<Probe />);
|
||||
expect(html).toContain(htmlEscape(JSON.stringify(DEFAULT_ASSISTANT_FLAGS)));
|
||||
});
|
||||
|
||||
it("returns the all-on default while the query is still loading", () => {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: 0 } },
|
||||
});
|
||||
const html = renderToStaticMarkup(
|
||||
<QueryClientProvider client={client}>
|
||||
<Probe />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
expect(html).toContain(htmlEscape(JSON.stringify(DEFAULT_ASSISTANT_FLAGS)));
|
||||
});
|
||||
|
||||
it("returns the resolved matrix when the endpoint responds", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(
|
||||
async () =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
assistant: {
|
||||
enabled: true,
|
||||
coach: false,
|
||||
briefing: true,
|
||||
insightStatus: false,
|
||||
documentAi: true,
|
||||
},
|
||||
},
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: 0 } },
|
||||
});
|
||||
// Pre-populate so the SSR pass surfaces the cached payload
|
||||
// synchronously without a fetch round-trip.
|
||||
client.setQueryData(["feature-flags"], {
|
||||
assistant: {
|
||||
enabled: true,
|
||||
coach: false,
|
||||
briefing: true,
|
||||
insightStatus: false,
|
||||
documentAi: true,
|
||||
},
|
||||
});
|
||||
|
||||
const html = renderToStaticMarkup(
|
||||
<QueryClientProvider client={client}>
|
||||
<Probe />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
expect(html).toContain(""coach":false");
|
||||
expect(html).toContain(""insightStatus":false");
|
||||
});
|
||||
});
|
||||
@@ -63,3 +63,48 @@ function useAiProviderStateInner(): AiProviderState {
|
||||
const { user } = useAuth();
|
||||
return user?.ai?.provider ?? NO_PROVIDER_STATE;
|
||||
}
|
||||
|
||||
/**
|
||||
* The server's answer for one capability, or `null` while there is none yet
|
||||
* (`/me` loading, no signed-in account, no query client). For the few places
|
||||
* that act on an unavailable capability rather than just hiding: a Coach page
|
||||
* that sends its visitor elsewhere must not do so on the loading frame, when
|
||||
* `useAiCapability` already reads unavailable.
|
||||
*/
|
||||
export function useAiCapabilityAnswer(
|
||||
key: AiCapabilityKey,
|
||||
): AiCapabilityState | null {
|
||||
const hasClient = useQueryClientMounted();
|
||||
if (!hasClient) return null;
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
return useAiCapabilityAnswerInner(key);
|
||||
}
|
||||
|
||||
function useAiCapabilityAnswerInner(
|
||||
key: AiCapabilityKey,
|
||||
): AiCapabilityState | null {
|
||||
const { user, isLoading } = useAuth();
|
||||
if (isLoading || !user) return null;
|
||||
return user.ai?.capabilities?.[key] ?? UNKNOWN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every capability at once, or `null` until `/me` has answered. For the one
|
||||
* surface that explains the whole set (the operator notice in Settings → AI);
|
||||
* a surface that shows or hides one feature reads `useAiCapability`.
|
||||
*/
|
||||
export function useAiCapabilityMap(): Partial<
|
||||
Record<AiCapabilityKey, AiCapabilityState>
|
||||
> | null {
|
||||
const hasClient = useQueryClientMounted();
|
||||
if (!hasClient) return null;
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
return useAiCapabilityMapInner();
|
||||
}
|
||||
|
||||
function useAiCapabilityMapInner(): Partial<
|
||||
Record<AiCapabilityKey, AiCapabilityState>
|
||||
> | null {
|
||||
const { user } = useAuth();
|
||||
return user?.ai?.capabilities ?? null;
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { apiFetchRaw } from "@/lib/api/api-fetch";
|
||||
import { useQueryClientMounted } from "@/hooks/_internal/use-query-client-safe";
|
||||
|
||||
/**
|
||||
* v1.4.31 — Client-side accessor for the operator's assistant
|
||||
* feature-flag matrix. Mirrors `GET /api/feature-flags`'s response
|
||||
* shape directly so callers can rely on a typed structure.
|
||||
*
|
||||
* The matrix gates every assistant-driven surface on the web —
|
||||
* Coach + chat, Daily Briefing, per-metric status notes, reading
|
||||
* documents. Deprecated: `ai` on `GET /api/auth/me` (read through
|
||||
* `useAiCapability`) is the resolved answer per capability. iOS reads the same
|
||||
* endpoint and uses the same matrix; the contract is locked per
|
||||
* `.planning/RESPONSE-TO-IOS-TEAM-2026-05-16.md` §3 R5.
|
||||
*/
|
||||
|
||||
export interface AssistantFlagSet {
|
||||
/** Master kill-switch — when false, every sub-flag is forced false. */
|
||||
enabled: boolean;
|
||||
/** Coach drawer, chat SSE, history rail, FAB. */
|
||||
coach: boolean;
|
||||
/** Daily Briefing card + advisor recommendations + regen icon. */
|
||||
briefing: boolean;
|
||||
/** Per-metric status cards on every `/insights/<metric>` sub-page. */
|
||||
insightStatus: boolean;
|
||||
/** Document vault reads, lab report scans, medication text extraction. */
|
||||
documentAi: boolean;
|
||||
}
|
||||
|
||||
interface FeatureFlagsPayload {
|
||||
assistant: AssistantFlagSet;
|
||||
}
|
||||
|
||||
/** All-on default — matches the v1.4.30 behaviour for fresh installs. */
|
||||
export const DEFAULT_ASSISTANT_FLAGS: AssistantFlagSet = Object.freeze({
|
||||
enabled: true,
|
||||
coach: true,
|
||||
briefing: true,
|
||||
insightStatus: true,
|
||||
documentAi: true,
|
||||
});
|
||||
|
||||
async function fetchFeatureFlags(): Promise<FeatureFlagsPayload> {
|
||||
// `apiFetchRaw` (no .ok throw) — this read soft-fails to the all-on
|
||||
// default below instead of surfacing an error state.
|
||||
const res = await apiFetchRaw("/api/feature-flags");
|
||||
if (!res.ok) {
|
||||
// Soft-fail: any HTTP error returns the all-on default so the
|
||||
// surface continues to render. The endpoint is a non-critical
|
||||
// metadata read; a 5xx must not turn into a "Coach hidden"
|
||||
// false negative for the user.
|
||||
return { assistant: { ...DEFAULT_ASSISTANT_FLAGS } };
|
||||
}
|
||||
const json = (await res.json()) as { data: FeatureFlagsPayload };
|
||||
return json.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the operator's assistant feature-flag matrix.
|
||||
*
|
||||
* `staleTime: 60_000` matches the server-side cache header so the
|
||||
* hot /insights mount path doesn't re-fetch the matrix on every
|
||||
* remount within a minute. The hook fails open — any network error
|
||||
* returns the all-on default so the user keeps seeing the surface.
|
||||
*
|
||||
* The hook is referenced from presentational components such as
|
||||
* `<InsightStatusCard>` whose unit tests render without a
|
||||
* `<QueryClientProvider>`. To keep those tests valid we delegate
|
||||
* the React-Query call to a child hook that's only invoked when a
|
||||
* client is mounted. The branch is stable across the component's
|
||||
* lifetime — `QueryClientProvider` placement never flips between
|
||||
* renders — so the conditional hook call is safe per the Rules of
|
||||
* Hooks (same posture the React docs document for "different
|
||||
* environments where the same component renders").
|
||||
*
|
||||
* v1.4.48 M4 — the SSR-mount probe is shared with `useDisableCoach`
|
||||
* via `_internal/use-query-client-safe` so the eslint-disable line
|
||||
* stays in exactly one place per consumer.
|
||||
*/
|
||||
export function useFeatureFlags(): AssistantFlagSet {
|
||||
const hasClient = useQueryClientMounted();
|
||||
if (!hasClient) return DEFAULT_ASSISTANT_FLAGS;
|
||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
||||
return useFeatureFlagsQuery();
|
||||
}
|
||||
|
||||
function useFeatureFlagsQuery(): AssistantFlagSet {
|
||||
const query = useQuery({
|
||||
queryKey: queryKeys.featureFlags(),
|
||||
queryFn: fetchFeatureFlags,
|
||||
staleTime: 60_000,
|
||||
gcTime: 300_000,
|
||||
retry: 0,
|
||||
});
|
||||
|
||||
// While loading or on error, default to all-on so the assistant
|
||||
// surfaces don't flicker out and back in.
|
||||
return query.data?.assistant ?? DEFAULT_ASSISTANT_FLAGS;
|
||||
}
|
||||
Reference in new issue
Block a user