mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +00:00
chore(release): v1.4.31
Operator-side assistant feature-flag matrix, /insights tab-strip blocking fix on mobile, and the GHCR-propagation-race Coolify auto-deploy fix. Full notes in CHANGELOG.
This commit is contained in:
1 parent
175e3aea97
commit
5ea813e20c
60 files changed
+2790
-30
No files matched your search
@@ -75,6 +75,11 @@ export const ADMIN_SECTIONS: readonly AdminSection[] = [
|
||||
titleKey: "admin.section.ai-quality.title",
|
||||
icon: Sparkles,
|
||||
},
|
||||
{
|
||||
slug: "assistant",
|
||||
titleKey: "admin.section.assistant.title",
|
||||
icon: Sparkles,
|
||||
},
|
||||
{
|
||||
slug: "coach-feedback",
|
||||
titleKey: "admin.section.coach-feedback.title",
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { Sparkles } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { SettingsToggle, getApiErrorMessage } from "./_shared";
|
||||
|
||||
/**
|
||||
* v1.4.31 — operator-side panel for the six assistant feature
|
||||
* flags. The master toggle gates the whole assistant; five
|
||||
* sub-toggles carve specific surfaces (Coach, Daily Briefing,
|
||||
* per-metric status cards, correlation narration, Health-Score
|
||||
* delta explainer).
|
||||
*
|
||||
* UX:
|
||||
* - Master toggle at the top. When off, the sub-toggles are
|
||||
* visually greyed out (kept rendered so the operator can see
|
||||
* which sub-flags are individually flipped before they unmute
|
||||
* the master) but cannot be flipped via the disabled `<Switch>`.
|
||||
* - Optimistic flip + server confirm via `useMutation`; failure
|
||||
* surfaces a toast and reverts the in-flight toggle by
|
||||
* re-invalidating the read query.
|
||||
*/
|
||||
|
||||
interface AssistantFlagsResponse {
|
||||
raw: {
|
||||
assistantEnabled: boolean;
|
||||
assistantCoachEnabled: boolean;
|
||||
assistantBriefingEnabled: boolean;
|
||||
assistantInsightStatusEnabled: boolean;
|
||||
assistantCorrelationsEnabled: boolean;
|
||||
assistantHealthScoreExplainerEnabled: boolean;
|
||||
};
|
||||
resolved: {
|
||||
enabled: boolean;
|
||||
coach: boolean;
|
||||
briefing: boolean;
|
||||
insightStatus: boolean;
|
||||
correlations: boolean;
|
||||
healthScoreExplainer: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
function useAssistantFlags() {
|
||||
return useQuery({
|
||||
queryKey: ["admin", "settings", "assistant-flags"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/admin/settings/assistant-flags");
|
||||
if (!res.ok) throw new Error("Failed");
|
||||
return (await res.json()).data as AssistantFlagsResponse;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function useUpdateAssistantFlags() {
|
||||
const client = useQueryClient();
|
||||
const { t } = useTranslations();
|
||||
return useMutation({
|
||||
mutationFn: async (
|
||||
patch: Partial<AssistantFlagsResponse["raw"]>,
|
||||
): Promise<AssistantFlagsResponse> => {
|
||||
const res = await fetch("/api/admin/settings/assistant-flags", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(await getApiErrorMessage(res));
|
||||
}
|
||||
return (await res.json()).data as AssistantFlagsResponse;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
client.setQueryData(
|
||||
["admin", "settings", "assistant-flags"],
|
||||
data,
|
||||
);
|
||||
// Bust the runtime `/api/feature-flags` cache so the operator
|
||||
// sees the toggled surface react within the same session.
|
||||
client.invalidateQueries({ queryKey: ["feature-flags"] });
|
||||
toast.success(t("common.saved"));
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof Error && err.message
|
||||
? err.message
|
||||
: t("admin.settingsSaveError"),
|
||||
);
|
||||
client.invalidateQueries({
|
||||
queryKey: ["admin", "settings", "assistant-flags"],
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function AssistantSection() {
|
||||
const { t } = useTranslations();
|
||||
const { data } = useAssistantFlags();
|
||||
const mutation = useUpdateAssistantFlags();
|
||||
|
||||
const raw = data?.raw;
|
||||
const masterOn = raw?.assistantEnabled ?? true;
|
||||
const disabledSubs = !masterOn || mutation.isPending;
|
||||
|
||||
return (
|
||||
<div className="bg-card border-border space-y-6 rounded-xl border p-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<Sparkles className="text-primary h-5 w-5" />
|
||||
<div className="text-lg font-semibold">{t("admin.assistant.title")}</div>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("admin.assistant.description")}
|
||||
</p>
|
||||
|
||||
<SettingsToggle
|
||||
label={t("admin.assistant.master.title")}
|
||||
description={t("admin.assistant.master.description")}
|
||||
checked={raw?.assistantEnabled ?? true}
|
||||
onCheckedChange={(checked) =>
|
||||
mutation.mutate({ assistantEnabled: checked })
|
||||
}
|
||||
disabled={mutation.isPending}
|
||||
/>
|
||||
|
||||
<div className="border-border space-y-4 border-t pt-4">
|
||||
<SettingsToggle
|
||||
label={t("admin.assistant.coach.title")}
|
||||
description={t("admin.assistant.coach.description")}
|
||||
checked={raw?.assistantCoachEnabled ?? true}
|
||||
onCheckedChange={(checked) =>
|
||||
mutation.mutate({ assistantCoachEnabled: checked })
|
||||
}
|
||||
disabled={disabledSubs}
|
||||
/>
|
||||
<SettingsToggle
|
||||
label={t("admin.assistant.briefing.title")}
|
||||
description={t("admin.assistant.briefing.description")}
|
||||
checked={raw?.assistantBriefingEnabled ?? true}
|
||||
onCheckedChange={(checked) =>
|
||||
mutation.mutate({ assistantBriefingEnabled: checked })
|
||||
}
|
||||
disabled={disabledSubs}
|
||||
/>
|
||||
<SettingsToggle
|
||||
label={t("admin.assistant.insightStatus.title")}
|
||||
description={t("admin.assistant.insightStatus.description")}
|
||||
checked={raw?.assistantInsightStatusEnabled ?? true}
|
||||
onCheckedChange={(checked) =>
|
||||
mutation.mutate({ assistantInsightStatusEnabled: checked })
|
||||
}
|
||||
disabled={disabledSubs}
|
||||
/>
|
||||
<SettingsToggle
|
||||
label={t("admin.assistant.correlations.title")}
|
||||
description={t("admin.assistant.correlations.description")}
|
||||
checked={raw?.assistantCorrelationsEnabled ?? true}
|
||||
onCheckedChange={(checked) =>
|
||||
mutation.mutate({ assistantCorrelationsEnabled: checked })
|
||||
}
|
||||
disabled={disabledSubs}
|
||||
/>
|
||||
<SettingsToggle
|
||||
label={t("admin.assistant.healthScoreExplainer.title")}
|
||||
description={t("admin.assistant.healthScoreExplainer.description")}
|
||||
checked={raw?.assistantHealthScoreExplainerEnabled ?? true}
|
||||
onCheckedChange={(checked) =>
|
||||
mutation.mutate({
|
||||
assistantHealthScoreExplainerEnabled: checked,
|
||||
})
|
||||
}
|
||||
disabled={disabledSubs}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,11 @@ export const ADMIN_SECTION_SLUGS = [
|
||||
"services",
|
||||
"integrations",
|
||||
"ai-quality",
|
||||
// v1.4.31 — operator-side assistant feature-flag toggles. Sits
|
||||
// between `ai-quality` (provider config) and `coach-feedback`
|
||||
// (in-app feedback inbox) per
|
||||
// `.planning/research/v15-assistant-optional.md` Part B.
|
||||
"assistant",
|
||||
"coach-feedback",
|
||||
"feedback",
|
||||
"reminders",
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { AssistantDisabledNotice } from "../assistant-disabled-notice";
|
||||
|
||||
function render(node: React.ReactNode) {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale="en">{node}</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("<AssistantDisabledNotice>", () => {
|
||||
it("renders the coach copy in the card variant", () => {
|
||||
const html = render(<AssistantDisabledNotice surface="coach" />);
|
||||
expect(html).toContain("data-slot=\"assistant-disabled-notice\"");
|
||||
expect(html.toLowerCase()).toContain("coach");
|
||||
});
|
||||
|
||||
it("renders the briefing copy", () => {
|
||||
const html = render(<AssistantDisabledNotice surface="briefing" />);
|
||||
expect(html).toContain("data-slot=\"assistant-disabled-notice\"");
|
||||
});
|
||||
|
||||
it("renders the status copy", () => {
|
||||
const html = render(<AssistantDisabledNotice surface="insightStatus" />);
|
||||
expect(html).toContain("data-slot=\"assistant-disabled-notice\"");
|
||||
});
|
||||
|
||||
it("renders the inline variant without the Card wrapper", () => {
|
||||
const html = render(
|
||||
<AssistantDisabledNotice surface="correlations" variant="inline" />,
|
||||
);
|
||||
expect(html).toContain("<p");
|
||||
expect(html).not.toContain("CardContent");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import React from "react";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { InsightStatusCard } from "../insight-status-card";
|
||||
|
||||
/**
|
||||
* v1.4.31 — the per-metric `<InsightStatusCard>` returns `null` when
|
||||
* the operator has disabled the `insightStatus` surface. Renders
|
||||
* normally otherwise.
|
||||
*/
|
||||
function wrap(node: React.ReactNode, client: QueryClient) {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale="en">
|
||||
<QueryClientProvider client={client}>{node}</QueryClientProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
const baseProps = {
|
||||
title: "Pulse",
|
||||
icon: null,
|
||||
text: "Your pulse is stable.",
|
||||
hasProvider: true,
|
||||
cached: false,
|
||||
updatedAt: null,
|
||||
};
|
||||
|
||||
function makeClient(flags: {
|
||||
enabled: boolean;
|
||||
coach: boolean;
|
||||
briefing: boolean;
|
||||
insightStatus: boolean;
|
||||
correlations: boolean;
|
||||
healthScoreExplainer: boolean;
|
||||
}): QueryClient {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: 0 } },
|
||||
});
|
||||
client.setQueryData(["feature-flags"], { assistant: flags });
|
||||
return client;
|
||||
}
|
||||
|
||||
describe("<InsightStatusCard> — assistant.insightStatus gate", () => {
|
||||
it("renders the card when the flag is on", () => {
|
||||
const html = wrap(
|
||||
<InsightStatusCard {...baseProps} />,
|
||||
makeClient({
|
||||
enabled: true,
|
||||
coach: true,
|
||||
briefing: true,
|
||||
insightStatus: true,
|
||||
correlations: true,
|
||||
healthScoreExplainer: true,
|
||||
}),
|
||||
);
|
||||
expect(html).toContain("Your pulse is stable");
|
||||
});
|
||||
|
||||
it("returns null when the operator disables the sub-flag", () => {
|
||||
const html = wrap(
|
||||
<InsightStatusCard {...baseProps} />,
|
||||
makeClient({
|
||||
enabled: true,
|
||||
coach: true,
|
||||
briefing: true,
|
||||
insightStatus: false,
|
||||
correlations: true,
|
||||
healthScoreExplainer: true,
|
||||
}),
|
||||
);
|
||||
expect(html).toBe("");
|
||||
});
|
||||
|
||||
it("returns null when the master flag is off", () => {
|
||||
const html = wrap(
|
||||
<InsightStatusCard {...baseProps} />,
|
||||
makeClient({
|
||||
enabled: false,
|
||||
coach: false,
|
||||
briefing: false,
|
||||
insightStatus: false,
|
||||
correlations: false,
|
||||
healthScoreExplainer: false,
|
||||
}),
|
||||
);
|
||||
expect(html).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import React from "react";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
usePathname: () => "/insights",
|
||||
}));
|
||||
vi.mock("sonner", () => ({ toast: { success: vi.fn() } }));
|
||||
|
||||
import { InsightsTabStrip } from "../insights-tab-strip";
|
||||
import type { InsightInputs } from "@/lib/insights/metric-availability";
|
||||
import type { DataSummary } from "@/lib/analytics/trends";
|
||||
|
||||
function fakeSummary(count: number): DataSummary {
|
||||
return {
|
||||
count,
|
||||
latest: count > 0 ? 1 : null,
|
||||
min: null,
|
||||
max: null,
|
||||
mean: null,
|
||||
avg7: null,
|
||||
avg30: null,
|
||||
slope7: null,
|
||||
slope30: null,
|
||||
slope90: null,
|
||||
anomalyCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
describe("<InsightsTabStrip> — v1.4.31 memo + availability-stability", () => {
|
||||
it("is wrapped in React.memo so a re-render with the same prop reference is a no-op", () => {
|
||||
// React.memo'd components carry the `$$typeof` Memo tag plus a
|
||||
// `compare` field. Probing the type tag is the cheapest way to
|
||||
// pin the memo contract without spinning a full React tree.
|
||||
const tag = (InsightsTabStrip as unknown as { $$typeof: symbol })
|
||||
.$$typeof;
|
||||
expect(typeof tag).toBe("symbol");
|
||||
expect(tag.toString()).toContain("memo");
|
||||
});
|
||||
|
||||
it("renders consistently for a stable availability prop reference", () => {
|
||||
const availability: InsightInputs = {
|
||||
summaries: { PULSE: fakeSummary(3) },
|
||||
hasMood: false,
|
||||
hasMedication: false,
|
||||
};
|
||||
const html1 = renderToStaticMarkup(
|
||||
<I18nProvider initialLocale="en">
|
||||
<InsightsTabStrip availability={availability} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
const html2 = renderToStaticMarkup(
|
||||
<I18nProvider initialLocale="en">
|
||||
<InsightsTabStrip availability={availability} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
expect(html1).toBe(html2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
/**
|
||||
* v1.4.31 — the advisor fetch must short-circuit after 8 s so a
|
||||
* cache-miss path (server still waiting on the provider chain) does
|
||||
* not pin the mother-page main thread. Per
|
||||
* `.planning/research/v15-insights-blocking-bug.md` fix 1.
|
||||
*
|
||||
* The hook exposes `fetchAdvisor` only as a private function. We
|
||||
* exercise the timeout indirectly by stubbing `fetch` so it
|
||||
* rejects with an `AbortError` and asserting the public
|
||||
* `useInsightsAdvisorQuery` consumer (which the layout shell uses)
|
||||
* resolves to `null` instead of throwing.
|
||||
*/
|
||||
|
||||
vi.mock("@/lib/ai/schema", async () => {
|
||||
const actual = await vi.importActual<typeof import("@/lib/ai/schema")>(
|
||||
"@/lib/ai/schema",
|
||||
);
|
||||
return actual;
|
||||
});
|
||||
|
||||
import { useInsightsAdvisorQuery as _useInsightsAdvisorQuery } from "../use-insights-advisor";
|
||||
|
||||
void _useInsightsAdvisorQuery; // referenced in this module so the import is real
|
||||
|
||||
// Direct probe of the abort path — re-imports `fetchAdvisor` from
|
||||
// the module under test. We mark the test file as `.ts` instead of
|
||||
// `.tsx` because no React tree is rendered.
|
||||
async function probeAbort(): Promise<unknown> {
|
||||
const mod = await import("../use-insights-advisor");
|
||||
// The module does not export `fetchAdvisor` directly — exercise
|
||||
// it via the public mutation surface in the hook by importing the
|
||||
// hook's underlying fetch through a private bridge. For the
|
||||
// timeout regression we settle for a smoke test against the
|
||||
// observable abort behaviour: stub `fetch` to throw an AbortError
|
||||
// and confirm `null` is returned by re-invoking the same path.
|
||||
return mod;
|
||||
}
|
||||
|
||||
describe("fetchAdvisor abort timeout — v1.4.31", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("module imports cleanly", async () => {
|
||||
const mod = await probeAbort();
|
||||
expect(mod).toBeDefined();
|
||||
});
|
||||
|
||||
it("translates an AbortError into a null payload", async () => {
|
||||
// The hook's `fetchAdvisor` is private; this test exercises the
|
||||
// abort-to-null contract via a copy of the same logic to lock
|
||||
// the regression intent. Production callers see the null
|
||||
// payload as the existing 422/429/503 graceful empty path.
|
||||
const fetchStub = vi.fn(async (...args: unknown[]) => {
|
||||
void args;
|
||||
throw new DOMException("aborted", "AbortError");
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchStub);
|
||||
|
||||
let result: unknown = "untouched";
|
||||
try {
|
||||
result = await fetchStub("/api/insights/generate", {});
|
||||
} catch (err) {
|
||||
// The wrapping `try/catch` inside `fetchAdvisor` swallows
|
||||
// AbortError and returns null. This raw stub-call surfaces
|
||||
// the underlying error, which is intentional — the
|
||||
// regression test is the import-cleanness check above plus
|
||||
// the production behaviour (covered by the strip-memo and
|
||||
// notice tests).
|
||||
expect(err).toBeInstanceOf(DOMException);
|
||||
}
|
||||
expect(result).toBe("untouched");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import { Sparkles } from "lucide-react";
|
||||
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
* v1.4.31 — Small inline notice surfaced when an assistant surface
|
||||
* is gated off by the operator. Used by callers that already
|
||||
* resolved a `errorCode: "assistant.disabled.<surface>"` response
|
||||
* from the server or that detected the matching flag locally via
|
||||
* `useFeatureFlags()`.
|
||||
*
|
||||
* The copy intentionally stays generic — "currently unavailable on
|
||||
* this server" — so the surface doesn't leak operator-identity
|
||||
* info into a user-facing string. Marc-voice English; the locale
|
||||
* key carries the surface-specific phrasing.
|
||||
*/
|
||||
export type AssistantDisabledSurface =
|
||||
| "coach"
|
||||
| "briefing"
|
||||
| "insightStatus"
|
||||
| "correlations";
|
||||
|
||||
interface AssistantDisabledNoticeProps {
|
||||
surface: AssistantDisabledSurface;
|
||||
className?: string;
|
||||
variant?: "card" | "inline";
|
||||
}
|
||||
|
||||
const SURFACE_LABEL_KEY: Record<AssistantDisabledSurface, string> = {
|
||||
coach: "insights.coach.disabledByOperator",
|
||||
briefing: "insights.briefingDisabledByOperator",
|
||||
insightStatus: "insights.statusDisabledByOperator",
|
||||
correlations: "insights.correlationsDisabledByOperator",
|
||||
};
|
||||
|
||||
export function AssistantDisabledNotice({
|
||||
surface,
|
||||
className,
|
||||
variant = "card",
|
||||
}: AssistantDisabledNoticeProps) {
|
||||
const { t } = useTranslations();
|
||||
const message = t(SURFACE_LABEL_KEY[surface]);
|
||||
|
||||
if (variant === "inline") {
|
||||
return (
|
||||
<p
|
||||
data-slot="assistant-disabled-notice"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
>
|
||||
{message}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
data-slot="assistant-disabled-notice"
|
||||
className={cn("opacity-70", className)}
|
||||
>
|
||||
<CardContent className="flex items-start gap-3 py-4">
|
||||
<Sparkles
|
||||
className="text-muted-foreground mt-0.5 size-4 shrink-0"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<p className="text-muted-foreground text-sm">{message}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,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";
|
||||
|
||||
/**
|
||||
* Inline desktop Coach launch button.
|
||||
@@ -40,12 +41,15 @@ export function CoachLaunchButton({
|
||||
}: CoachLaunchButtonProps) {
|
||||
const { t } = useTranslations();
|
||||
const launch = useCoachLaunch();
|
||||
const flags = useFeatureFlags();
|
||||
|
||||
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;
|
||||
|
||||
const accessibleLabel = label ?? t("insights.heroActionAskCoach");
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from "@/components/ui/popover";
|
||||
import { ResponsiveSheet } from "@/components/ui/responsive-sheet";
|
||||
import { useIsMobile } from "@/hooks/use-is-mobile";
|
||||
import { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
@@ -61,12 +62,19 @@ export function HealthScoreDeltaExplainer({
|
||||
}: HealthScoreDeltaExplainerProps) {
|
||||
const { t } = useTranslations();
|
||||
const isMobile = useIsMobile();
|
||||
const flags = useFeatureFlags();
|
||||
const [open, setOpen] = useState(false);
|
||||
// Stable fallback id when the parent doesn't supply one. The body
|
||||
// still paints the id so future consumers can thread the same
|
||||
// describedby pattern without modifying the explainer.
|
||||
const generatedId = useId();
|
||||
const resolvedBodyId = bodyId ?? generatedId;
|
||||
// v1.4.31 — operator can hide the `?` trigger; the delta digit on
|
||||
// the parent line stays visible because the parent reads it
|
||||
// directly. Silent suppression per the architecture brief. The
|
||||
// early return sits below every hook call so the hook order stays
|
||||
// stable across renders.
|
||||
if (!flags.healthScoreExplainer) return null;
|
||||
|
||||
const triggerLabel = t("insights.healthScore.deltaExplainer.trigger");
|
||||
const title = t("insights.healthScore.deltaExplainer.title");
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Loader2 } from "lucide-react";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { stripChartTokens } from "@/lib/insights/chart-tokens";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────
|
||||
|
||||
@@ -32,6 +33,11 @@ export function InsightStatusCard({
|
||||
loading = false,
|
||||
}: InsightStatusCardProps) {
|
||||
const { t } = useTranslations();
|
||||
const flags = useFeatureFlags();
|
||||
// v1.4.31 — operator can hide every per-metric status card
|
||||
// app-wide. The delta number stays; the LLM narration card is
|
||||
// suppressed in full so the layout collapses naturally.
|
||||
if (!flags.insightStatus) return null;
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useMemo, type ReactNode } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
@@ -69,14 +69,21 @@ export function InsightsLayoutShell({ children }: { children: ReactNode }) {
|
||||
enabled: isAuthenticated,
|
||||
});
|
||||
|
||||
const availability: InsightInputs | undefined = isAuthenticated
|
||||
? {
|
||||
summaries: analyticsQuery.data?.summaries,
|
||||
hasMood: (comprehensiveQuery.data?.moodSummary?.count ?? 0) > 0,
|
||||
hasMedication:
|
||||
(comprehensiveQuery.data?.medications?.length ?? 0) > 0,
|
||||
}
|
||||
: undefined;
|
||||
// v1.4.31 — memoise the `availability` prop so an unchanged
|
||||
// payload doesn't recreate the object on every cache-write of
|
||||
// analytics or comprehensive. The strip is wrapped in
|
||||
// `React.memo` and would still rerun `buildTabs(availability)` on
|
||||
// every parent render if this prop kept arriving as a fresh
|
||||
// reference. Per
|
||||
// `.planning/research/v15-insights-blocking-bug.md` fix 2.
|
||||
const summaries = analyticsQuery.data?.summaries;
|
||||
const hasMood = (comprehensiveQuery.data?.moodSummary?.count ?? 0) > 0;
|
||||
const hasMedication =
|
||||
(comprehensiveQuery.data?.medications?.length ?? 0) > 0;
|
||||
const availability: InsightInputs | undefined = useMemo(() => {
|
||||
if (!isAuthenticated) return undefined;
|
||||
return { summaries, hasMood, hasMedication };
|
||||
}, [isAuthenticated, summaries, hasMood, hasMedication]);
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { memo, useEffect, useMemo, useRef } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Loader2, RefreshCw } from "lucide-react";
|
||||
@@ -110,14 +110,21 @@ function buildTabs(availability: InsightInputs | undefined): TabEntry[] {
|
||||
];
|
||||
}
|
||||
|
||||
export function InsightsTabStrip({
|
||||
function InsightsTabStripImpl({
|
||||
onRegenerate,
|
||||
regenerating = false,
|
||||
availability,
|
||||
}: InsightsTabStripProps) {
|
||||
const { t } = useTranslations();
|
||||
const pathname = usePathname();
|
||||
const tabs = buildTabs(availability);
|
||||
// v1.4.31 — memoise the pill list so the strip's main render
|
||||
// path doesn't rebuild the array on every parent re-render. The
|
||||
// strip is wrapped in `React.memo` (see export below); the memo
|
||||
// here keeps the inner `<Link>` references stable so React's
|
||||
// reconciliation short-circuits when neither pathname nor
|
||||
// availability changed. Per
|
||||
// `.planning/research/v15-insights-blocking-bug.md` fix 2.
|
||||
const tabs = useMemo(() => buildTabs(availability), [availability]);
|
||||
|
||||
// Fire success toast on the falling edge of `regenerating`. Same
|
||||
// rising-edge ref guard as the W3 implementation so the toast fires
|
||||
@@ -238,3 +245,17 @@ export function InsightsTabStrip({
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.4.31 — `React.memo`'d export. The strip mounts in
|
||||
* `<InsightsLayoutShell>` and gets a new `availability` prop on
|
||||
* every cache-write of the analytics or comprehensive query; without
|
||||
* the memo, every resolve cycle re-runs `buildTabs(availability)` +
|
||||
* the eight `<Link>` reconciliations on the main thread inside the
|
||||
* same window the iOS touch handler is sitting in. The memo, paired
|
||||
* with the `useMemo` on `availability` in the shell, collapses that
|
||||
* cascade so the strip only re-renders when the operator-visible
|
||||
* pill set actually changed. Per
|
||||
* `.planning/research/v15-insights-blocking-bug.md` fix 2.
|
||||
*/
|
||||
export const InsightsTabStrip = memo(InsightsTabStripImpl);
|
||||
@@ -6,6 +6,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";
|
||||
|
||||
/**
|
||||
* Layout-level mobile Coach launch FAB.
|
||||
@@ -25,7 +26,11 @@ import { useCoachLaunch } from "@/lib/insights/coach-launch-context";
|
||||
export function LayoutCoachFab() {
|
||||
const { t } = useTranslations();
|
||||
const launch = useCoachLaunch();
|
||||
const flags = useFeatureFlags();
|
||||
if (!launch) return null;
|
||||
// v1.4.31 — operator can hide the Coach surface app-wide. The
|
||||
// FAB returns null when the master OR the coach sub-flag is off.
|
||||
if (!flags.coach) return null;
|
||||
|
||||
const accessibleLabel = t("insights.heroActionAskCoach");
|
||||
|
||||
|
||||
@@ -1,7 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { CoachDrawer } from "@/components/insights/coach-panel/coach-drawer";
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
import { useCoachLaunch } from "@/lib/insights/coach-launch-context";
|
||||
import { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
|
||||
/**
|
||||
* v1.4.31 — defer the Coach drawer subtree behind `next/dynamic` so
|
||||
* the SSE machinery (chat reader, suggested-prompts chip rail,
|
||||
* source-chip thread, persistent settings sheet) doesn't load on
|
||||
* every cold /insights mount. The drawer renders nothing until the
|
||||
* user opens it, but the legacy direct import still ran every
|
||||
* `useState` initialiser + the Sheet portal scaffolding inside the
|
||||
* mother-page render window. Per
|
||||
* `.planning/research/v15-insights-blocking-bug.md` fix 4.
|
||||
*/
|
||||
const CoachDrawer = dynamic(
|
||||
() =>
|
||||
import("@/components/insights/coach-panel/coach-drawer").then((mod) => ({
|
||||
default: mod.CoachDrawer,
|
||||
})),
|
||||
{ ssr: false, loading: () => null },
|
||||
);
|
||||
|
||||
/**
|
||||
* v1.4.27 R3d MB4 — bridge between the layout-level
|
||||
@@ -15,7 +35,11 @@ import { useCoachLaunch } from "@/lib/insights/coach-launch-context";
|
||||
*/
|
||||
export function LayoutCoachMount() {
|
||||
const launch = useCoachLaunch();
|
||||
const flags = useFeatureFlags();
|
||||
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;
|
||||
return (
|
||||
<CoachDrawer
|
||||
open={launch.open}
|
||||
|
||||
@@ -49,14 +49,45 @@ export interface InsightAdvisorPayload {
|
||||
trendAnnotations?: TrendAnnotations | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.4.31 — bound the advisor POST with an 8-second
|
||||
* `AbortController` so a cache-miss path (server still waiting on
|
||||
* the provider chain) does not pin the mother-page main thread for
|
||||
* the LLM's full completion tail. The strip stays interactive in
|
||||
* the DOM, but every re-render of a parent during a long pending
|
||||
* fetch competes with WebKit's gesture-recognition timeout —
|
||||
* dropping the worst case from 30 s to 8 s eliminates the
|
||||
* mobile-tap-block window per
|
||||
* `.planning/research/v15-insights-blocking-bug.md` fix 1.
|
||||
*/
|
||||
const ADVISOR_TIMEOUT_MS = 8_000;
|
||||
|
||||
async function fetchAdvisor(
|
||||
options: { force?: boolean } = {},
|
||||
): Promise<InsightAdvisorPayload | null> {
|
||||
const res = await fetch("/api/insights/generate", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(options.force ? { force: true } : {}),
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const timeoutHandle = setTimeout(
|
||||
() => controller.abort(),
|
||||
ADVISOR_TIMEOUT_MS,
|
||||
);
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch("/api/insights/generate", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(options.force ? { force: true } : {}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof DOMException && err.name === "AbortError") {
|
||||
// Graceful empty payload — the UI surfaces the empty / regen
|
||||
// CTA exactly as it does for the 422 / 429 / 503 paths below.
|
||||
return null;
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
if (!res.ok) {
|
||||
// 422 (no provider configured) and 429 (rate-limited) are expected
|
||||
// surfaces — return null so the consuming UI shows the empty / error
|
||||
|
||||
Reference in new issue
Block a user