chore(release): v1.4.27

v1.4.27 — Mobile capability and maintainer-finding cleanup.

ResponsiveSheet primitive (bottom-sheet on narrow viewports, centred dialog on desktop)
applied to BD, Weight, Glucose, Mood, Activity forms. Maintainer-finding cleanups across
Coach, Insights, Reports, Privacy. GeoLite2 offline geocoding with resilience layer
(graceful fallback when EULA not yet propagated). E2E gap-fill coverage. 450-line
release notes attached to the GitHub Release.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-15 22:59:10 +02:00
1 parent d98e85cd03
commit 4f09c3f862
314 files changed
+26801 -4419

No files matched your search

@@ -63,10 +63,15 @@ describe("<DailyBriefing>", () => {
expect(html).toContain("Tagesbriefing");
});
it("renders the narrative paragraph", () => {
it("v1.4.27 B1 — does NOT render the leading narrative paragraph", () => {
// The hero strip subtitle on /insights renders the same
// `briefing.paragraph` directly above this card, so the card now
// opens straight on the key-findings list. The paragraph slot is
// gone from the populated branch; the empty-state branch still
// owns its CTA copy.
const html = render(<DailyBriefing briefing={baseBriefing} />);
expect(html).toMatch(/data-slot="daily-briefing-paragraph"/);
expect(html).toContain(
expect(html).not.toContain('data-slot="daily-briefing-paragraph"');
expect(html).not.toContain(
"Blood pressure is in target band on 9 of 10 readings",
);
});
@@ -133,13 +138,16 @@ describe("<DailyBriefing>", () => {
});
it("hides the keyFindings section when the array is empty", () => {
// v1.4.27 B1 — the leading paragraph dropped; the card now renders
// only the header + (when present) the findings list. With both
// gone the populated branch produces no body content, which the
// hero strip already covers.
const html = render(
<DailyBriefing briefing={{ ...baseBriefing, keyFindings: [] }} />,
);
expect(html).not.toContain('data-slot="daily-briefing-findings-title"');
expect(html).not.toContain('data-slot="daily-briefing-findings"');
// Paragraph still renders.
expect(html).toContain("trending well this week");
expect(html).not.toContain('data-slot="daily-briefing-paragraph"');
});
it("renders the empty state when briefing is null and not loading", () => {
@@ -1,6 +1,6 @@
import { describe, it, expect, vi } from "vitest";
import { describe, it, expect } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider, useTranslations } from "@/lib/i18n/context";
import { I18nProvider } from "@/lib/i18n/context";
import {
HealthScoreCard,
type HealthScoreCardProps,
@@ -10,9 +10,10 @@ import {
* v1.4.20 phase B5 — Personal Health Score card.
*
* SSR markup pins the slot wrappers so future polish can't silently
* drop the score number, sub-bars or disclaimer. The interactive
* "Ask the Coach" button is exercised through Testing Library so the
* prefill argument forwarded to the parent handler stays stable.
* drop the score number, sub-bars or disclaimer. The inline
* Ask-the-Coach button retired in v1.4.27 B1 — the hero strip
* carries the CTA. The negative-assertion test below pins that
* decision so a future revival has to update the test in lock-step.
*/
const baseComponents: HealthScoreCardProps["components"] = {
@@ -179,8 +180,12 @@ describe("<HealthScoreCard>", () => {
expect(html).toContain("Indicative");
});
it("does NOT render the Ask-the-Coach button when onAskCoach is omitted", () => {
const html = ssr(
it("v1.4.27 B1 — no longer mounts an inline Ask-the-Coach button (hero strip carries the CTA)", () => {
// The hero strip's existing "Ask the coach" action covers this
// surface; the card-internal duplicate button retired. The
// onAskCoach prop stays on the type signature so callers don't
// break, but the card no longer renders it.
const omitted = ssr(
<HealthScoreCard
score={86}
band="green"
@@ -188,11 +193,7 @@ describe("<HealthScoreCard>", () => {
delta={null}
/>,
);
expect(html).not.toContain('data-slot="health-score-card-ask-coach"');
});
it("renders the Ask-the-Coach button when onAskCoach is supplied", () => {
const html = ssr(
const supplied = ssr(
<HealthScoreCard
score={86}
band="green"
@@ -201,36 +202,10 @@ describe("<HealthScoreCard>", () => {
onAskCoach={() => {}}
/>,
);
expect(html).toMatch(/data-slot="health-score-card-ask-coach"/);
expect(html).toContain("Ask the Coach");
expect(omitted).not.toContain('data-slot="health-score-card-ask-coach"');
expect(supplied).not.toContain('data-slot="health-score-card-ask-coach"');
});
it("captures the score-aware prefill argument when the button is invoked", () => {
// The handler closure receives `t("insights.healthScore.coachPrompt", { score })`
// which interpolates the current score. We assert the closure shape by
// probing the i18n provider directly rather than wiring a DOM testing
// library — the component's onClick lambda is one line and its
// contract is the prefill string format, not the click plumbing.
let captured: string | null = null;
const onAskCoach = vi.fn((prefill: string) => {
captured = prefill;
});
function Probe() {
const { t } = useTranslations();
// Reproduce the same call the button's onClick performs.
onAskCoach(t("insights.healthScore.coachPrompt", { score: 86 }));
return null;
}
renderToStaticMarkup(
<I18nProvider initialLocale="en">
<Probe />
</I18nProvider>,
);
expect(onAskCoach).toHaveBeenCalledTimes(1);
expect(captured).toBe("Why is my health score 86 out of 100?");
});
it("renders German strings", () => {
const html = ssr(
@@ -244,9 +219,11 @@ describe("<HealthScoreCard>", () => {
"de",
);
expect(html).toContain("Gesundheitsscore");
expect(html).toContain("Coach fragen");
expect(html).toContain("im Vergleich zur Vorwoche");
expect(html).toContain("Orientierungshilfe");
// v1.4.27 B1 — the inline Coach button retired; hero strip carries
// the action now.
expect(html).not.toContain("Coach fragen");
});
it("uses tabular-nums on the headline number for stable layout", () => {
@@ -5,11 +5,9 @@ import { HeroStrip } from "../hero-strip";
import type { DailyBriefing as DailyBriefingPayload } from "@/lib/ai/schema";
/**
* v1.4.20 phase B1 — Insights hero strip.
*
* Replaces v1.4.16 `<InsightsPageHero>`. Pinning the slots so future
* polish can't silently drop the greeting / subtitle / action row /
* suggested-prompt strip.
* Insights hero strip — pins the slots so future polish can't
* silently drop the greeting / subtitle / action row / suggested-
* prompt strip.
*/
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
@@ -306,7 +304,12 @@ describe("<HeroStrip>", () => {
expect(html).toContain(">86<");
});
it("forwards onAskCoach into the Health Score panel only when both are supplied", () => {
it("does not render an inline Ask-the-Coach button inside the Health Score card", () => {
// v1.4.27 F8 — the inline HSC Ask-the-Coach button retired in
// favour of the hero strip's existing action-row button. Even
// when `onAskCoach` is supplied, the HSC panel must not surface
// its own button. The action-row button at
// `insights-hero-strip-action-coach` carries the affordance.
const html = render(
<HeroStrip
briefing={null}
@@ -325,31 +328,8 @@ describe("<HeroStrip>", () => {
onAskCoach={() => {}}
/>,
);
// HSC panel renders its own Ask-the-Coach button with the score-
// aware label (the action-row button uses the shorter "Ask the
// coach" copy). The HSC button mirrors the panel's slot.
expect(html).toMatch(/data-slot="health-score-card-ask-coach"/);
});
it("hides the Health Score panel's Ask button when no onAskCoach is supplied", () => {
const html = render(
<HeroStrip
briefing={null}
now={morningLocal}
healthScore={{
score: 86,
band: "green",
components: {
bp: { value: 80, weight: 0.3 },
weight: { value: 70, weight: 0.2 },
mood: { value: 90, weight: 0.2 },
compliance: { value: 100, weight: 0.3 },
},
delta: 5,
}}
/>,
);
expect(html).not.toContain('data-slot="health-score-card-ask-coach"');
expect(html).toContain('data-slot="insights-hero-strip-action-coach"');
});
it("uses the lg row layout when healthScore is supplied (smoke test on container class)", () => {
@@ -0,0 +1,92 @@
import { describe, it, expect } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import { InsightStatusCard } from "../insight-status-card";
/**
* v1.4.27 — F16 regression cover. The per-metric status text comes
* out of the AI provider with a literal `metric:<TYPE>` token (the
* prompt invites the model to embed one so the mother page can render
* an inline chart). The sub-page does not mount the chart, so the
* token used to surface verbatim at the tail of the rendered prose.
* The card now wraps the text in `stripChartTokens` so cached rows
* from pre-v1.4.27 still render clean while they roll forward.
*/
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
const baseProps = {
title: "Pulse",
icon: null,
hasProvider: true,
cached: false,
updatedAt: null,
};
describe("<InsightStatusCard>", () => {
it("strips a trailing colon-form metric token from rendered prose", () => {
const html = render(
<InsightStatusCard
{...baseProps}
text="Your pulse is stable. metric:PULSE"
/>,
);
expect(html).toContain("Your pulse is stable.");
expect(html).not.toContain("metric:PULSE");
});
it("strips multiple colon-form tokens scattered through the prose", () => {
const html = render(
<InsightStatusCard
{...baseProps}
title="Blood pressure"
text="Systolic averaged 132 metric:BLOOD_PRESSURE_SYS over the last 30 days. metric:BLOOD_PRESSURE_DIA"
/>,
);
expect(html).toContain("Systolic averaged 132");
expect(html).not.toContain("metric:BLOOD_PRESSURE_SYS");
expect(html).not.toContain("metric:BLOOD_PRESSURE_DIA");
});
it("strips the capitalised Metric form (v1.4.25 W5b leak shape)", () => {
const html = render(
<InsightStatusCard
{...baseProps}
title="Blood pressure"
text="Your Metric Pressure_Sys is elevated relative to last month."
/>,
);
expect(html).not.toContain("Metric Pressure_Sys");
expect(html).toContain("Your");
expect(html).toContain("is elevated");
});
it("renders ordinary prose unchanged when no tokens are present", () => {
const html = render(
<InsightStatusCard {...baseProps} text="Pulse stayed inside the band." />,
);
expect(html).toContain("Pulse stayed inside the band.");
});
it("renders the no-provider state without touching the strip path", () => {
const html = render(
<InsightStatusCard
{...baseProps}
hasProvider={false}
text="ignored when hasProvider is false"
/>,
);
expect(html).toContain("AI provider not configured.");
expect(html).not.toContain("ignored when hasProvider is false");
});
it("renders the empty-text state without crashing on null", () => {
const html = render(<InsightStatusCard {...baseProps} text={null} />);
expect(html).toContain("No analysis yet.");
});
});
@@ -1,159 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import { InsightsCardPreview } from "../insights-card";
import type { InsightResult, InsightRecommendation } from "@/lib/ai/types";
/**
* v1.4.16 phase B1b — dashboard InsightsCard preview.
*
* The preview is a compact wrapper that surfaces the top 1-2
* severity-ordered recommendations + a "View all" CTA pointing to
* the full `/insights` page. Visual language matches the page hero
* + recommendation grid (Dracula tokens, severity-coloured borders,
* mini confidence meter).
*/
vi.mock("@/components/charts/health-chart", () => ({
HealthChart: () => <div data-testid="health-chart-mock" />,
}));
vi.mock("@/components/charts/mood-chart", () => ({
MoodChart: () => <div data-testid="mood-chart-mock" />,
}));
vi.mock("@tanstack/react-query", () => ({
useQuery: () => ({ data: null, isLoading: false }),
useMutation: () => ({
mutate: vi.fn(),
isPending: false,
isSuccess: false,
isError: false,
error: null,
}),
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
}));
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "test-user", username: "tester", role: "USER" },
isAuthenticated: true,
isLoading: false,
}),
}));
function rec(
id: string,
severity: "info" | "suggestion" | "important" | "urgent",
text: string,
confidence?: number,
): InsightRecommendation {
return {
id,
text,
severity,
confidence,
rationale: {
dataWindow: "last7days",
comparedTo: "your 90-day median",
deviation: "moderate deviation",
},
metricSource: {
type: "weight",
timeRange: "last7days",
summary: "84.2 kg avg over 7 days",
},
};
}
function buildInsight(recommendations: InsightRecommendation[]): InsightResult {
return {
insightType: "general",
summary: "Test summary",
classification: "gut",
classificationLabel: "Good",
findings: [],
correlations: [],
primaryRecommendation: "",
recommendations,
dataQuality: { coverage: "good", gaps: [], confidence: "hoch" },
disclaimer: "Not medical advice.",
};
}
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
describe("<InsightsCardPreview>", () => {
it("surfaces only the top 2 severity-ordered recommendations", () => {
const recs = [
rec("a", "info", "info-rec"),
rec("b", "urgent", "urgent-rec"),
rec("c", "important", "important-rec"),
rec("d", "suggestion", "suggestion-rec"),
];
const html = render(<InsightsCardPreview insight={buildInsight(recs)} />);
expect(html).toContain("urgent-rec");
expect(html).toContain("important-rec");
// The preview must hide the remaining recs — they live on /insights.
expect(html).not.toContain("info-rec");
expect(html).not.toContain("suggestion-rec");
});
it("renders the 'View all' CTA pointing to /insights", () => {
const recs = [rec("a", "urgent", "urgent-rec")];
const html = render(<InsightsCardPreview insight={buildInsight(recs)} />);
expect(html).toMatch(/href="\/insights"/);
expect(html).toMatch(/data-slot="insights-card-view-all"/);
});
it("paints a severity-coloured left border on each preview card", () => {
const recs = [
rec("a", "urgent", "urgent-rec"),
rec("b", "important", "important-rec"),
];
const html = render(<InsightsCardPreview insight={buildInsight(recs)} />);
expect(html).toMatch(/border-l-dracula-red/);
expect(html).toMatch(/border-l-dracula-orange/);
});
it("renders a mini confidence meter inline when confidence is supplied", () => {
const recs = [rec("a", "urgent", "urgent-rec", 78)];
const html = render(<InsightsCardPreview insight={buildInsight(recs)} />);
// The ConfidenceMeter component renders a 'data-slot="confidence-meter"'
// marker; the preview shows the inline ring/bars variant.
expect(html).toMatch(/data-slot="confidence-meter"/);
});
it("hides the preview entirely when there are no recommendations", () => {
const html = render(<InsightsCardPreview insight={buildInsight([])} />);
// The orphan "no recs" state is delegated to the full /insights page.
// The preview either renders the top recs OR doesn't mount at all.
expect(html).toBe("");
});
it("passes a null insight transparently — no preview", () => {
const html = render(<InsightsCardPreview insight={null} />);
expect(html).toBe("");
});
it("renders the title slot so dashboard nav can sit alongside", () => {
const recs = [rec("a", "urgent", "urgent-rec")];
const html = render(<InsightsCardPreview insight={buildInsight(recs)} />);
expect(html).toMatch(/data-slot="insights-card-preview"/);
// Card title text from the existing translation key.
expect(html).toContain("AI Insights");
});
it("German locale — title + view-all CTA translate", () => {
const recs = [rec("a", "urgent", "urgent-rec")];
const html = render(
<InsightsCardPreview insight={buildInsight(recs)} />,
"de",
);
expect(html).toContain("KI-Insights");
// "View all" → German "Alle ansehen"
expect(html).toContain("Alle ansehen");
});
});
@@ -0,0 +1,117 @@
import { describe, it, expect, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
// `usePathname` is consulted to mark the active pill; SSR has no
// Next.js router, so we stub it.
vi.mock("next/navigation", () => ({
usePathname: () => "/insights",
}));
// `toast` is consulted from a falling-edge effect; renderToStaticMarkup
// doesn't fire effects, but we stub it for completeness.
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 render(node: React.ReactNode, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
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> — availability gating (v1.4.27 F19)", () => {
it("renders every pill when availability is omitted (backward compat)", () => {
const html = render(<InsightsTabStrip />);
expect(html).toContain(">Blood Pressure<");
expect(html).toContain(">Weight<");
expect(html).toContain(">Pulse<");
expect(html).toContain(">Mood<");
expect(html).toContain(">Medication<");
expect(html).toContain(">BMI<");
expect(html).toContain(">Sleep<");
});
it("drops pills for metrics with zero observations", () => {
const availability: InsightInputs = {
summaries: {
PULSE: fakeSummary(5),
WEIGHT: fakeSummary(3),
},
hasMood: false,
hasMedication: false,
};
const html = render(<InsightsTabStrip availability={availability} />);
// Pills that have data stay.
expect(html).toContain(">Pulse<");
expect(html).toContain(">Weight<");
expect(html).toContain(">BMI<");
// Pills without data drop.
expect(html).not.toContain(">Blood Pressure<");
expect(html).not.toContain(">Mood<");
expect(html).not.toContain(">Medication<");
expect(html).not.toContain(">Sleep<");
});
it("keeps the overview pill regardless of availability", () => {
const availability: InsightInputs = {
summaries: {},
hasMood: false,
hasMedication: false,
};
const html = render(<InsightsTabStrip availability={availability} />);
expect(html).toContain(">Overview<");
});
it("lights up Mood when hasMood flips to true", () => {
const availability: InsightInputs = {
summaries: {},
hasMood: true,
hasMedication: false,
};
const html = render(<InsightsTabStrip availability={availability} />);
expect(html).toContain(">Mood<");
expect(html).not.toContain(">Medication<");
});
it("lights up Medication when hasMedication flips to true", () => {
const availability: InsightInputs = {
summaries: {},
hasMood: false,
hasMedication: true,
};
const html = render(<InsightsTabStrip availability={availability} />);
expect(html).toContain(">Medication<");
expect(html).not.toContain(">Mood<");
});
it("derives BMI from WEIGHT count", () => {
const availability: InsightInputs = {
summaries: { WEIGHT: fakeSummary(2) },
hasMood: false,
hasMedication: false,
};
const html = render(<InsightsTabStrip availability={availability} />);
expect(html).toContain(">Weight<");
expect(html).toContain(">BMI<");
});
});
@@ -0,0 +1,93 @@
"use client";
import { Sparkles } from "lucide-react";
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";
/**
* v1.4.27 R3d MB4 — Coach launch button.
*
* Decision F: every routed Insights sub-page mounts this button so the
* Coach drawer (mounted at the layout root) is always reachable. The
* button renders as a sticky-bottom FAB on `<lg` viewports (so a phone
* user always sees it within thumb range) and as an inline header
* action on `lg+` (where the desktop drawer slides in from the right
* edge and the FAB would overlap the chart legend).
*
* The button is a thin wrapper around `useCoachLaunch()` — it only
* renders when the context provider is mounted (so dropping the button
* onto a non-Insights page is a no-op rather than a crash).
*/
export interface CoachLaunchButtonProps {
/** Optional override for the visual label. Defaults to the shared CTA. */
label?: string;
/** Optional prefill seed for the next Coach turn. */
prefill?: string;
/** Optional className passthrough for inline overrides. */
className?: string;
}
export function CoachLaunchButton({
label,
prefill,
className,
}: CoachLaunchButtonProps) {
const { t } = useTranslations();
const launch = useCoachLaunch();
if (!launch) {
// The button only makes sense beneath the provider. Render nothing
// so the sub-page doesn't paint a dead control.
return null;
}
const accessibleLabel = label ?? t("insights.heroActionAskCoach");
return (
<>
{/* Sticky FAB on `<lg` viewports — pinned to the bottom-right so
the user's thumb always finds it. `bottom-20` clears the
mobile bottom navigation; `safe-area-inset-bottom` plus the
existing app shell padding keep it clear of the iOS home bar.
Hidden on `lg+` where the inline button below takes over. */}
<Button
type="button"
size="lg"
data-slot="coach-launch-fab"
onClick={() => launch.askCoach(prefill ?? null)}
aria-label={accessibleLabel}
title={accessibleLabel}
className={cn(
"fixed right-4 bottom-20 z-40 h-12 rounded-full px-4 shadow-lg",
"from-dracula-purple to-dracula-pink bg-gradient-to-br text-white",
"hover:from-dracula-purple/90 hover:to-dracula-pink/90",
"lg:hidden",
className,
)}
>
<Sparkles className="size-4" aria-hidden="true" />
<span>{accessibleLabel}</span>
</Button>
{/* Inline header-style action on `lg+`. Lives in the page body so
it picks up the sub-page layout's spacing instead of fighting
a sticky header overlay. */}
<Button
type="button"
variant="outline"
size="sm"
data-slot="coach-launch-inline"
onClick={() => launch.askCoach(prefill ?? null)}
className={cn(
"hidden h-10 gap-2 self-end lg:inline-flex",
className,
)}
>
<Sparkles className="size-4" aria-hidden="true" />
<span>{accessibleLabel}</span>
</Button>
</>
);
}
@@ -41,18 +41,22 @@ describe("<CoachDrawerBody> — mobile rail trays", () => {
});
it("hides the history trigger on >=lg and the sources trigger on >=xl", () => {
// v1.4.27 R3d MB2 — the strip wrapper carries `xl:hidden` so the
// sources trigger inherits the breakpoint; the history trigger
// keeps its own `lg:hidden` because the history rail mounts
// inline already on lg+ while the sources rail still needs the
// chevron until xl.
const html = render(<CoachDrawerBody {...baseProps} />);
const strip = html.match(
/<div[^>]*data-slot="coach-drawer-rail-tray-strip"[^>]*>/,
);
expect(strip?.[0]).toContain("xl:hidden");
const historyTrigger = html.match(
/<button[^>]*data-slot="coach-drawer-history-tray-trigger"[^>]*>/,
);
expect(historyTrigger).not.toBeNull();
expect(historyTrigger?.[0]).toContain("lg:hidden");
const sourcesTrigger = html.match(
/<button[^>]*data-slot="coach-drawer-sources-tray-trigger"[^>]*>/,
);
expect(sourcesTrigger).not.toBeNull();
expect(sourcesTrigger?.[0]).toContain("xl:hidden");
});
it("renders the desktop history rail (lg+) and sources rail (xl+)", () => {
@@ -95,12 +99,16 @@ describe("<CoachDrawerBody> — mobile rail trays", () => {
expect(html).toContain("Worauf ich zugreife");
});
it("the thread region wraps the rail triggers in a relative container", () => {
// The triggers use absolute positioning; the thread region must
// be `relative` for them to anchor inside it.
it("renders the rail triggers in a sub-header strip above the thread", () => {
// v1.4.27 R3d MB2 — the triggers were lifted out of the absolute
// overlay into a sub-header strip so the chevrons sit at a 44 px
// tap target and never overlay the first message bubble. The
// strip lives above the thread within the centre column.
const html = render(<CoachDrawerBody {...baseProps} />);
expect(html).toMatch(
/<main[^>]*data-slot="coach-drawer-thread"[^>]*relative/,
expect(html).toMatch(/data-slot="coach-drawer-rail-tray-strip"/);
const trigger = html.match(
/<button[^>]*data-slot="coach-drawer-history-tray-trigger"[^>]*>/,
);
expect(trigger?.[0]).toContain("min-h-11");
});
});
@@ -26,12 +26,22 @@ describe("<CoachInput>", () => {
expect(html).not.toContain("Coach replies are generated");
});
it("renders the localised placeholder + hint", () => {
it("renders the localised placeholder + the popover-trigger hint", () => {
// v1.4.27 F15 — the verbose prose hint footer was replaced by an
// Info icon button. The same `composerHint` translation surfaces
// as the trigger's `aria-label` (so screen-readers announce it on
// focus) and as the popover body for sighted users on tap.
//
// v1.4.27 MB3 / CF-31 — the disclosure swapped off Radix Tooltip
// (no reliable tap-toggle on touch surfaces) onto Radix Popover,
// so the contract is now "tap to open" instead of "hover".
const html = render(
<CoachInput value="" onChange={() => {}} onSubmit={() => {}} />,
);
expect(html).toContain("Ask anything about your data");
expect(html).toContain("Press Enter to send");
expect(html).toMatch(
/aria-label="Press Enter to send[^"]*"\s+data-slot="coach-input-hint"/,
);
});
it("renders the German placeholder under the 'de' locale", () => {
@@ -55,6 +55,11 @@ vi.mock("@/components/ui/sheet", () => ({
SheetDescription: ({ children }: { children: React.ReactNode }) => (
<p>{children}</p>
),
// v1.4.27 R3d MB1 — the settings sheet now renders an inline
// `<SheetClose>` in the header instead of the primitive's
// absolutely-positioned close-X. Mock it as a passthrough so the
// existing skeleton + form snapshot assertions keep working.
SheetClose: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
import { CoachSettingsSheet } from "../coach-settings-sheet";
@@ -91,7 +96,8 @@ describe("<CoachSettingsSheet>", () => {
);
expect(html).not.toContain('data-slot="coach-prefs-skeleton"');
expect(html).toContain('data-slot="coach-prefs-tone"');
expect(html).toContain('data-slot="coach-prefs-evidence"');
// v1.4.27 F14 — the `showEvidenceByDefault` switch is retired.
expect(html).not.toContain('data-slot="coach-prefs-evidence"');
});
it("fires a sonner toast on save success (Design-H4)", () => {
@@ -59,36 +59,48 @@ export function CoachDrawerBody({
{/* Centre — message thread. */}
<main
data-slot="coach-drawer-thread"
className="relative flex h-full min-h-0 flex-col"
className="flex h-full min-h-0 flex-col"
>
{/* v1.4.20 phase B4 — mobile rail tray triggers. Hidden on
`>=lg` because the rails are inline there. */}
<Button
type="button"
variant="ghost"
size="sm"
onClick={onOpenHistoryTray}
data-slot="coach-drawer-history-tray-trigger"
aria-label={t("insights.coach.historyTitle")}
className="bg-background/80 border-border/60 absolute top-2 left-2 z-10 h-7 gap-1 border px-2 text-[11px] backdrop-blur lg:hidden"
{/* v1.4.27 R3d MB2 — rail-tray triggers lifted out of the
absolute overlay into a sub-header strip so the chevrons
sit at a 44 px tap target and never overlay the first
message bubble. Hidden on `>=xl` because both rails are
inline at that breakpoint. The history trigger remains
visible up to lg-1 (rail is inline at lg+); the sources
trigger remains visible up to xl-1 (rail is inline at
xl+). */}
<div
data-slot="coach-drawer-rail-tray-strip"
className="border-border/70 flex items-center justify-between gap-2 border-b px-3 py-2 xl:hidden"
>
<ChevronRight className="size-3" aria-hidden="true" />
{t("insights.coach.historyTitle")}
</Button>
{/* Sources tray trigger stays visible up to xl since the
inline sources rail is xl+ only. */}
<Button
type="button"
variant="ghost"
size="sm"
onClick={onOpenSourcesTray}
data-slot="coach-drawer-sources-tray-trigger"
aria-label={t("insights.coach.sourcesTitle")}
className="bg-background/80 border-border/60 absolute top-2 right-2 z-10 h-7 gap-1 border px-2 text-[11px] backdrop-blur xl:hidden"
>
{t("insights.coach.sourcesTitle")}
<ChevronLeft className="size-3" aria-hidden="true" />
</Button>
<Button
type="button"
variant="ghost"
onClick={onOpenHistoryTray}
data-slot="coach-drawer-history-tray-trigger"
aria-label={t("insights.coach.historyTitle")}
className="min-h-11 gap-1.5 text-xs lg:hidden"
>
<ChevronRight className="size-4" aria-hidden="true" />
{t("insights.coach.historyTitle")}
</Button>
{/* Sources tray trigger stays visible up to xl since the
inline sources rail is xl+ only. The empty `<span>` to
the left keeps the right-aligned button placement when
the history trigger hides at lg+. */}
<span aria-hidden="true" className="hidden lg:block" />
<Button
type="button"
variant="ghost"
onClick={onOpenSourcesTray}
data-slot="coach-drawer-sources-tray-trigger"
aria-label={t("insights.coach.sourcesTitle")}
className="min-h-11 gap-1.5 text-xs"
>
{t("insights.coach.sourcesTitle")}
<ChevronLeft className="size-4" aria-hidden="true" />
</Button>
</div>
<div className="min-h-0 flex-1">{thread}</div>
{/* Composer pinned to the bottom. */}
@@ -23,6 +23,7 @@ import {
import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
import { useCoachPrefs } from "@/hooks/use-coach-prefs";
import { useIsMobile } from "@/hooks/use-is-mobile";
import { CoachDrawerBody } from "./coach-drawer-body";
import { CoachInput } from "./coach-input";
@@ -132,6 +133,13 @@ export function CoachDrawer({
composer,
}: CoachDrawerProps) {
const { t } = useTranslations();
// v1.4.27 R3d MB1 — below the `sm` breakpoint (640 px) the Coach
// drawer slides up from the bottom edge of the viewport instead of
// sliding in from the right. Right-side slide makes the back-arrow
// / close-X drift far from the user's thumb on a phone; bottom-up
// keeps the drawer chrome reachable. Above `sm` the drawer keeps
// its existing right-side slide and `sm:max-w-[720px]` cap.
const isPhoneViewport = useIsMobile("sm");
const [currentConversationId, setCurrentConversationId] = useState<
string | null
@@ -256,7 +264,10 @@ export function CoachDrawer({
return (
<Sheet open={open} onOpenChange={handleOpenChange}>
<SheetContent
side="right"
// v1.4.27 R3d MB1 — below `sm` the drawer slides up from the
// bottom edge so the header chrome stays near the user's thumb;
// above `sm` it keeps its existing right-side slide.
side={isPhoneViewport ? "bottom" : "right"}
// v1.4.25 W5 — render our own Close button inside the header so
// X / cog / new-chat sit on the same baseline with identical
// size, color, and hit target. The Sheet's default close-X is
@@ -265,6 +276,7 @@ export function CoachDrawer({
// cluster.
showCloseButton={false}
data-slot="coach-drawer"
data-variant={isPhoneViewport ? "bottom-sheet" : "side-sheet"}
className={cn(
// Drawer keeps the dashboard context behind it. On laptops
// (1280-1366px viewports) the previous lg:max-w-[1080px] cap
@@ -275,7 +287,13 @@ export function CoachDrawer({
// is hidden below xl by the body's lg:hidden chevron rules).
"w-full p-0 sm:max-w-[720px]",
"lg:!max-w-[min(960px,75vw)] xl:!max-w-[1080px]",
"flex h-[100dvh] flex-col gap-0",
isPhoneViewport
? // Bottom-sheet caps at 95 dvh so a sliver of the underlying
// /insights page remains visible — clear "this is a
// sheet, not a takeover" signal. The rounded top corners
// match the iOS bottom-sheet feel.
"flex h-[95dvh] max-h-[95dvh] flex-col gap-0 rounded-t-2xl"
: "flex h-[100dvh] flex-col gap-0",
)}
>
{/* Header (full width). Avatar + title + new-chat button +
@@ -297,7 +315,11 @@ export function CoachDrawer({
<Sparkles className="text-background size-4" />
</div>
<div className="min-w-0 flex-1">
<SheetTitle className="truncate text-sm font-semibold">
{/* v1.4.27 R3d MB4 / CF-73 — pin `min-w-0` on the title
node itself in addition to the wrapper so the
truncate clipping survives any flex-shrink quirk
with very long conversation titles. */}
<SheetTitle className="min-w-0 truncate text-sm font-semibold">
{drawerTitle}
</SheetTitle>
<SheetDescription className="text-muted-foreground truncate text-[11px]">
@@ -309,44 +331,56 @@ export function CoachDrawer({
and resets to it on drawer close. Changing the pill flips
`windowOverride`; the rail's window picker mirrors the
same source-of-truth so the user can drive the override
from either surface. */}
<Select
value={effectiveWindow}
onValueChange={(value) => {
const next = value as CoachScopeWindow;
setWindowOverride(next === savedDefaultWindow ? null : next);
}}
from either surface.
v1.4.27 R3d MB4 — on `<sm` viewports the bottom-sheet
header already carries the avatar, title, new-chat,
settings, and close buttons; one more pill there shrinks
the title to a single character before truncation. The
same override is still reachable from the sources-rail's
window picker, which is what the user opens via the
right-edge chevron tray on phone-class viewports. */}
<div
data-slot="coach-drawer-window-pill-wrap"
className="hidden sm:block"
>
<SelectTrigger
data-slot="coach-drawer-window-pill"
aria-label={t("insights.coach.windowLabel")}
size="sm"
className={cn(
"border-border/60 bg-muted/40 text-foreground h-7 shrink-0 gap-1 rounded-full px-2.5 text-[11px]",
"hover:bg-muted/60 focus-visible:ring-ring/40 focus-visible:ring-2",
windowOverride !== null &&
"border-dracula-purple/40 bg-dracula-purple/10 text-dracula-purple",
)}
<Select
value={effectiveWindow}
onValueChange={(value) => {
const next = value as CoachScopeWindow;
setWindowOverride(next === savedDefaultWindow ? null : next);
}}
>
<SelectValue
placeholder={t(`insights.coach.window.${effectiveWindow}`)}
/>
</SelectTrigger>
<SelectContent align="end">
<SelectItem value="last7days" className="text-xs">
{t("insights.coach.window.last7days")}
</SelectItem>
<SelectItem value="last30days" className="text-xs">
{t("insights.coach.window.last30days")}
</SelectItem>
<SelectItem value="last90days" className="text-xs">
{t("insights.coach.window.last90days")}
</SelectItem>
<SelectItem value="allTime" className="text-xs">
{t("insights.coach.window.allTime")}
</SelectItem>
</SelectContent>
</Select>
<SelectTrigger
data-slot="coach-drawer-window-pill"
aria-label={t("insights.coach.windowLabel")}
className={cn(
"border-border/60 bg-muted/40 text-foreground h-11 shrink-0 gap-1 rounded-full px-3 text-xs",
"hover:bg-muted/60 focus-visible:ring-ring/40 focus-visible:ring-2",
windowOverride !== null &&
"border-dracula-purple/40 bg-dracula-purple/10 text-dracula-purple",
)}
>
<SelectValue
placeholder={t(`insights.coach.window.${effectiveWindow}`)}
/>
</SelectTrigger>
<SelectContent align="end">
<SelectItem value="last7days" className="text-xs">
{t("insights.coach.window.last7days")}
</SelectItem>
<SelectItem value="last30days" className="text-xs">
{t("insights.coach.window.last30days")}
</SelectItem>
<SelectItem value="last90days" className="text-xs">
{t("insights.coach.window.last90days")}
</SelectItem>
<SelectItem value="allTime" className="text-xs">
{t("insights.coach.window.allTime")}
</SelectItem>
</SelectContent>
</Select>
</div>
{/* v1.4.25 W5 — header action cluster. All three buttons
share the same `ghost / size-icon / size-9` shape so they
visually belong together. 36×36 px hit target meets the
@@ -361,7 +395,7 @@ export function CoachDrawer({
data-slot="coach-drawer-new-chat"
aria-label={t("insights.coach.newChat")}
title={t("insights.coach.newChat")}
className="text-muted-foreground hover:text-foreground size-9 shrink-0"
className="text-muted-foreground hover:text-foreground size-11 shrink-0"
>
<Plus className="size-4" aria-hidden="true" />
</Button>
@@ -373,7 +407,7 @@ export function CoachDrawer({
data-slot="coach-drawer-settings"
aria-label={t("insights.coach.settingsAriaLabel")}
title={t("insights.coach.settingsAriaLabel")}
className="text-muted-foreground hover:text-foreground size-9 shrink-0"
className="text-muted-foreground hover:text-foreground size-11 shrink-0"
>
<Settings className="size-4" aria-hidden="true" />
</Button>
@@ -385,7 +419,7 @@ export function CoachDrawer({
data-slot="coach-drawer-close"
aria-label={t("common.close")}
title={t("common.close")}
className="text-muted-foreground hover:text-foreground size-9 shrink-0"
className="text-muted-foreground hover:text-foreground size-11 shrink-0"
>
<X className="size-4" aria-hidden="true" />
</Button>
@@ -438,6 +472,12 @@ export function CoachDrawer({
onSubmit={() => handleSubmit(inputValue)}
disabled={send.isStreaming}
isStreaming={send.isStreaming}
// v1.4.27 MB3 / CF-30 — the composer mounts on drawer
// open and unmounts on close (the body collapses with
// the sheet), so a one-shot mount focus matches the
// "drawer just opened" semantic without any re-render
// gymnastics.
autoFocusOnOpen
/>
)
}
@@ -7,9 +7,14 @@ import {
useEffect,
useRef,
} from "react";
import { Loader2, Send } from "lucide-react";
import { Info, Loader2, Send } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
@@ -44,6 +49,14 @@ export interface CoachInputProps {
isStreaming?: boolean;
/** Optional textarea ref so the parent can focus on drawer open. */
inputId?: string;
/**
* v1.4.27 MB3 / CF-30 — when set, focuses the composer textarea once
* on mount. The drawer flips this to `true` when the drawer becomes
* the freshly-opened surface so the user can start typing
* immediately. It must stay opt-in (lazy): on every re-render of an
* already-open drawer we do not steal focus back.
*/
autoFocusOnOpen?: boolean;
}
/**
@@ -88,10 +101,29 @@ export function CoachInput({
disabled = false,
isStreaming = false,
inputId = "coach-composer-textarea",
autoFocusOnOpen = false,
}: CoachInputProps) {
const { t } = useTranslations();
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
// v1.4.27 MB3 / CF-30 — focus the textarea once on mount when the
// parent flags this surface as the freshly-opened one. The empty
// dependency array keeps this from re-firing on every value change
// (the auto-grow effect handles those). We bail when disabled so we
// do not yank focus into a non-interactive field.
useEffect(() => {
if (!autoFocusOnOpen || disabled) return;
const el = textareaRef.current;
if (!el) return;
// Defer to the next paint so the drawer's own focus-trap finishes
// resolving before we hand the cursor to the composer.
const id = window.requestAnimationFrame(() => {
el.focus();
});
return () => window.cancelAnimationFrame(id);
// eslint-disable-next-line react-hooks/exhaustive-deps -- one-shot on mount
}, []);
// v1.4.25 W5 — auto-grow side effect. Runs on every value change
// (the controlled `value` prop is the source of truth) plus on mount
// so the initial paint already shows the 1-line height even when the
@@ -162,6 +194,13 @@ export function CoachInput({
onKeyDown={handleKeyDown}
placeholder={t("insights.coach.composerPlaceholder")}
disabled={disabled}
// v1.4.27 MB3 / CF-30 — surface the "send" virtual-keyboard
// return on iOS / Android instead of the generic newline
// glyph, and lift autocapitalize to "sentences" so a
// question typed on phone reads as one. The submit handler
// still preserves Shift+Enter for explicit newlines.
enterKeyHint="send"
autoCapitalize="sentences"
// v1.4.25 W5 — single-line initial state, Claude-web-style.
// `rows={1}` is the SSR-stable baseline; the `useEffect`
// above grows the textarea up to `AUTO_GROW_MAX_LINES`. Past
@@ -174,22 +213,53 @@ export function CoachInput({
"placeholder:text-muted-foreground disabled:opacity-60",
)}
/>
<div className="mt-1.5 flex items-center gap-2">
<span
data-slot="coach-input-hint"
className="text-muted-foreground text-[11px]"
>
{t("insights.coach.composerHint")}
</span>
{/* v1.4.27 F15 — the verbose "Enter to send, Shift+Enter for
new line" prose footer used to render under the textarea;
it ate ~140 px of vertical room for an Apple-Health-like
single-message exchange. The hint now sits behind a tiny
Info icon left of the send button; the existing
translation string surfaces as the popover body so
screen-reader users still hear it on focus.
v1.4.27 MB3 / CF-31 — swapped off Radix `<Tooltip>` (which
never tap-toggles reliably on touch) onto `<Popover>` so
mobile users can open the hint via a plain tap on the icon
button. The aria-label still labels the icon for screen
readers; the popover body carries the long-form copy. */}
<div className="mt-1.5 flex items-center justify-end gap-2">
<Popover>
<PopoverTrigger asChild>
<button
type="button"
aria-label={t("insights.coach.composerHint")}
data-slot="coach-input-hint"
className={cn(
"text-muted-foreground hover:text-foreground",
"focus-visible:ring-ring/50 inline-flex h-11 w-11",
"items-center justify-center rounded",
"focus-visible:ring-2 focus-visible:outline-none",
)}
>
<Info className="size-3.5" aria-hidden="true" />
</button>
</PopoverTrigger>
<PopoverContent
side="top"
align="end"
data-slot="coach-input-hint-body"
>
{t("insights.coach.composerHint")}
</PopoverContent>
</Popover>
<Button
type="submit"
size="sm"
disabled={!canSubmit}
data-slot="coach-input-send"
className="ml-auto gap-1.5"
className="gap-1.5"
>
{isStreaming ? (
<Loader2 className="size-3.5 animate-spin" aria-hidden="true" />
<Loader2 className="size-3.5 animate-spin motion-reduce:animate-none" aria-hidden="true" />
) : (
<Send className="size-3.5" aria-hidden="true" />
)}
@@ -5,8 +5,11 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";
import { X } from "lucide-react";
import {
Sheet,
SheetClose,
SheetContent,
SheetDescription,
SheetHeader,
@@ -140,16 +143,39 @@ export function CoachSettingsSheet({
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent
side="right"
// v1.4.27 R3d MB1 — the default `<SheetContent>` close-X is an
// absolutely positioned `opacity-70 rounded-xs` button that
// clashed with the in-header layout. Match the coach-drawer
// pattern instead: hide the primitive's close-X and render a
// matching ghost-icon `<SheetClose>` inline in the header so
// the close affordance sits on the same baseline as the rest
// of the sheet chrome and clears the 44 px tap target.
showCloseButton={false}
data-slot="coach-settings-sheet"
className="flex h-[100dvh] w-full flex-col gap-0 p-0 sm:max-w-[420px]"
>
<SheetHeader className="border-border/70 border-b p-4 pr-12">
<SheetTitle className="text-sm font-semibold">
{t("insights.coach.settingsTitle")}
</SheetTitle>
<SheetDescription className="text-muted-foreground text-xs">
{t("insights.coach.settingsDescription")}
</SheetDescription>
<SheetHeader className="border-border/70 flex-row items-start gap-2 border-b p-4">
<div className="min-w-0 flex-1">
<SheetTitle className="text-sm font-semibold">
{t("insights.coach.settingsTitle")}
</SheetTitle>
<SheetDescription className="text-muted-foreground text-xs">
{t("insights.coach.settingsDescription")}
</SheetDescription>
</div>
<SheetClose asChild>
<Button
type="button"
variant="ghost"
size="icon"
data-slot="coach-settings-sheet-close"
aria-label={t("common.close")}
title={t("common.close")}
className="text-muted-foreground hover:text-foreground -mt-1 shrink-0"
>
<X className="size-4" aria-hidden="true" />
</Button>
</SheetClose>
</SheetHeader>
{isLoading ? (
@@ -323,31 +349,13 @@ export function CoachSettingsSheet({
</ul>
</div>
{/* Show evidence by default */}
<div className="flex items-start justify-between gap-3">
<div className="flex flex-col gap-1">
<Label
htmlFor="coach-prefs-evidence"
className="cursor-pointer text-xs font-medium"
>
{t("insights.coach.settingsEvidenceLabel")}
</Label>
<p className="text-muted-foreground text-[11px] leading-relaxed">
{t("insights.coach.settingsEvidenceHint")}
</p>
</div>
<Switch
id="coach-prefs-evidence"
data-slot="coach-prefs-evidence"
checked={draft.showEvidenceByDefault}
onCheckedChange={(next) =>
setDraft((prev) => ({
...prev,
showEvidenceByDefault: next,
}))
}
/>
</div>
{/* v1.4.27 F14 — the `showEvidenceByDefault` switch was
retired. The evidence disclosure is now always closed
by default and the user expands by click; surfacing
raw values automatically created an UX trap. The
persisted `coachPrefs.showEvidenceByDefault` field
stays in the schema for backward compatibility, but no
UI reads or writes it. */}
</div>
)}
@@ -369,7 +377,7 @@ export function CoachSettingsSheet({
data-slot="coach-prefs-save"
>
{save.isPending ? (
<Loader2 className="size-3.5 animate-spin" aria-hidden="true" />
<Loader2 className="size-3.5 animate-spin motion-reduce:animate-none" aria-hidden="true" />
) : null}
{t("insights.coach.settingsSave")}
</Button>
@@ -138,6 +138,12 @@ export function HistoryRail({
{formatRelativeTime(c.updatedAt, t)}
</span>
</button>
{/* v1.4.27 R3d MB2 — drop the hover-only `opacity-0`
reveal: touch surfaces have no hover, so the delete
affordance was invisible on mobile. The button now
sits at 44 px always-visible per the WCAG 2.5.5
floor; confirming state stays styled via the
`data-confirming` attribute. */}
<Button
type="button"
variant="ghost"
@@ -151,12 +157,12 @@ export function HistoryRail({
data-slot="coach-history-delete"
data-confirming={isConfirming ? "true" : undefined}
className={cn(
"size-6 shrink-0 opacity-0 transition-opacity group-hover:opacity-100",
"size-11 shrink-0",
isConfirming &&
"text-dracula-red hover:text-dracula-red opacity-100",
"text-dracula-red hover:text-dracula-red",
)}
>
<Trash2 className="size-3.5" aria-hidden="true" />
<Trash2 className="size-4" aria-hidden="true" />
</Button>
</div>
);
@@ -1,6 +1,6 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import {
Bot,
@@ -15,7 +15,6 @@ import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
import { stripChartTokens } from "@/lib/insights/chart-tokens";
import { useAuth } from "@/hooks/use-auth";
import { useCoachPrefs } from "@/hooks/use-coach-prefs";
import { SourceChips } from "./source-chips";
import type {
@@ -105,13 +104,13 @@ export function MessageThread({
const scrollerRef = useRef<HTMLDivElement | null>(null);
const wasPinnedRef = useRef(true);
// v1.4.23 H4 — read the user's Coach prefs so the evidence
// disclosure honours `showEvidenceByDefault`. Cached at the
// queryClient level via the shared `useCoachPrefs` hook; the
// settings sheet writes the same key after a successful save so the
// new default takes effect on the next reply without a page reload.
const { data: coachPrefs } = useCoachPrefs();
const evidenceDefaultOpen = coachPrefs?.showEvidenceByDefault ?? false;
// v1.4.27 F14 — the evidence disclosure used to honour an opt-in
// `coachPrefs.showEvidenceByDefault` flag that surfaced the raw
// measurement values unconditionally. The flag created an UX trap
// (Marc 2026-05-15: "literal metric values exposed under every
// bubble") so the disclosure is now collapsed by default for every
// reply. The user expands by click; the pref is retired in the
// settings sheet so nothing flips it back on.
const messages: CoachMessageDTO[] = useMemo(
() => conversation?.messages ?? [],
@@ -199,6 +198,28 @@ export function MessageThread({
}
}, [messages.length, streaming?.content, optimisticUser?.localId]);
// v1.4.27 R3d MB4 / CF-74 — re-pin to the bottom when the
// visual viewport shrinks (typically the soft keyboard opening on
// a phone). Without this the last bubble drifts behind the keyboard
// because the scroller's `scrollHeight` references the layout
// viewport, not the visible region. Listening on
// `window.visualViewport.resize` and re-issuing the scroll keeps the
// tail of the thread visible as the keyboard slides in and out.
useEffect(() => {
if (typeof window === "undefined") return;
const vv = window.visualViewport;
if (!vv) return;
const handleResize = () => {
const el = scrollerRef.current;
if (!el) return;
if (wasPinnedRef.current) {
el.scrollTo({ top: el.scrollHeight, behavior: "auto" });
}
};
vv.addEventListener("resize", handleResize);
return () => vv.removeEventListener("resize", handleResize);
}, []);
if (messages.length === 0 && !streamingActive && !optimisticActive) {
return (
<div
@@ -239,7 +260,6 @@ export function MessageThread({
content={m.content}
metricSource={m.metricSource}
providerType={m.providerType}
evidenceDefaultOpen={evidenceDefaultOpen}
messageId={m.id}
/>
);
@@ -269,7 +289,6 @@ export function MessageThread({
providerType={streaming.inProgress ? "streaming" : null}
inProgress={streaming.inProgress}
errorCode={streaming.errorCode}
evidenceDefaultOpen={evidenceDefaultOpen}
/>
</div>
)}
@@ -299,8 +318,6 @@ interface ChatBubbleProps {
providerType?: string | null;
inProgress?: boolean;
errorCode?: string | null;
/** v1.4.23 H4 — when true the evidence `<details>` mounts open. */
evidenceDefaultOpen?: boolean;
/**
* v1.4.23 H7 — present only on persisted assistant messages.
* Streaming bubbles (no message id yet) skip the thumbs row so the
@@ -316,11 +333,20 @@ function ChatBubble({
providerType,
inProgress,
errorCode,
evidenceDefaultOpen,
messageId,
}: ChatBubbleProps) {
const { t } = useTranslations();
const { user } = useAuth();
// v1.4.27 B7 / L3 — pair the evidence `<details>` and its disclosed
// list explicitly so screen-readers announce the panel relationship.
const evidencePanelId = useId();
// v1.4.27 MB3 / CF-32 — track the disclosure state in React so the
// summary can carry an accurate `aria-expanded`. Native `<details>`
// reflects its open state via the `open` attribute, but that does
// not surface as `aria-expanded` on the summary by default; screen
// readers still need the explicit attribute to announce the panel
// as expanded vs collapsed.
const [evidenceOpen, setEvidenceOpen] = useState(false);
if (role === "user") {
// v1.4.22 B3 — pull the user's Gravatar so the user bubble's
// avatar matches the Coach avatar in size and visual weight.
@@ -428,11 +454,20 @@ function ChatBubble({
{keyValues.length > 0 && (
<details
data-slot="coach-evidence"
// v1.4.23 H4 — open by default when the user's prefs ask
// for it. Browsers honour the boolean `open` attribute on
// initial mount; toggling at runtime keeps the user's
// current expansion state intact.
open={evidenceDefaultOpen ? true : undefined}
open={evidenceOpen}
onToggle={(e) =>
setEvidenceOpen((e.target as HTMLDetailsElement).open)
}
// v1.4.27 F14 — always closed by default. The `open`
// attribute was previously tied to a per-user pref that
// surfaced raw values unconditionally; that pref is now
// retired and the disclosure is a true progressive-
// disclosure surface — the user clicks to expand.
//
// v1.4.27 MB3 / CF-32 — the `open` attribute is now
// controlled from local state so the summary's
// `aria-expanded` stays in lock-step. The native disclosure
// semantics (Enter / Space toggle) are preserved.
className={cn(
"border-border/50 bg-muted/30 group rounded-md border",
"px-2.5 py-1.5 text-xs",
@@ -440,6 +475,8 @@ function ChatBubble({
>
<summary
data-slot="coach-evidence-summary"
aria-controls={evidencePanelId}
aria-expanded={evidenceOpen}
className={cn(
"text-muted-foreground hover:text-foreground flex cursor-pointer",
"items-center gap-1.5 leading-relaxed",
@@ -454,6 +491,7 @@ function ChatBubble({
<span>{t("insights.coach.evidenceLabel")}</span>
</summary>
<ul
id={evidencePanelId}
data-slot="coach-evidence-list"
className="text-foreground mt-2 flex flex-col gap-1"
>
@@ -547,7 +585,7 @@ function CoachMessageFeedback({ messageId }: CoachMessageFeedbackProps) {
data-slot="coach-message-feedback-helpful"
onClick={() => submit.mutate("helpful")}
disabled={submit.isPending}
className="text-muted-foreground hover:text-dracula-green focus-visible:ring-ring/50 inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] outline-none focus-visible:ring-2 disabled:opacity-50"
className="text-muted-foreground hover:text-dracula-green focus-visible:ring-ring/50 inline-flex min-h-11 items-center gap-1 rounded px-2 py-1.5 text-xs outline-none focus-visible:ring-2 disabled:opacity-50"
>
<ThumbsUp className="size-3" aria-hidden="true" />
{t("insights.coach.feedbackHelpful")}
@@ -557,7 +595,7 @@ function CoachMessageFeedback({ messageId }: CoachMessageFeedbackProps) {
data-slot="coach-message-feedback-unhelpful"
onClick={() => submit.mutate("unhelpful")}
disabled={submit.isPending}
className="text-muted-foreground hover:text-dracula-orange focus-visible:ring-ring/50 inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] outline-none focus-visible:ring-2 disabled:opacity-50"
className="text-muted-foreground hover:text-dracula-orange focus-visible:ring-ring/50 inline-flex min-h-11 items-center gap-1 rounded px-2 py-1.5 text-xs outline-none focus-visible:ring-2 disabled:opacity-50"
>
<ThumbsDown className="size-3" aria-hidden="true" />
{t("insights.coach.feedbackUnhelpful")}
@@ -51,6 +51,10 @@ const WINDOW_KEYS: Record<CoachProvenance["windows"][number], string> = {
last7days: "insights.coach.window.last7days",
last30days: "insights.coach.window.last30days",
last90days: "insights.coach.window.last90days",
// v1.4.27 B7 / BL-P6-4 — year-in-review window. The i18n key
// resolves to a localised label; absent translations fall back
// through the resolver to the English source.
lastYear: "insights.coach.window.lastYear",
allTime: "insights.coach.window.allTime",
};
@@ -10,6 +10,7 @@ import {
Smile,
} from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";
import {
Select,
SelectContent,
@@ -234,20 +235,21 @@ export function SourcesRail({
!checked && "opacity-60",
)}
>
<input
{/* v1.4.27 R3d MB4 / CF-40 — swap the raw HTML checkbox
for the shadcn `<Checkbox>` primitive so the rail
ships a real focus ring, a proper keyboard contract
(Space toggles, Tab moves), and a touch-friendly
hit target on the side-tray surface. The wrapping
`<label htmlFor={checkboxId}>` below still acts as
the row-wide tap target on mobile. */}
<Checkbox
id={checkboxId}
type="checkbox"
checked={checked}
disabled={!interactive}
onChange={() => toggleSource(row.key)}
onCheckedChange={() => toggleSource(row.key)}
data-slot="coach-sources-checkbox"
aria-label={t(row.metricKey)}
className={cn(
"border-border/70 text-dracula-purple",
"size-4 shrink-0 cursor-pointer rounded",
"focus-visible:ring-ring/50 focus-visible:ring-2",
"disabled:cursor-not-allowed disabled:opacity-50",
)}
className="cursor-pointer"
/>
<row.Icon
className={cn("size-3.5", row.accentClass)}
+69 -11
View File
@@ -1,5 +1,6 @@
"use client";
import Link from "next/link";
import {
Activity,
FileText,
@@ -30,6 +31,33 @@ import type {
DailyBriefingKeyFinding,
} from "@/lib/ai/schema";
/**
* v1.4.27 MB7 / CF-68 — per-metric routing target for the briefing
* key findings. Maps the schema's `sourceMetric` discriminator to the
* sub-page slug that owns the deeper view. Metrics that don't have a
* dedicated routed sub-page yet (hrv, resting_hr, steps, …) fall
* through to `null` and render as a plain row (no link wrap).
*/
const METRIC_HREF: Record<DailyBriefingKeyFinding["sourceMetric"], string | null> = {
bp: "/insights/blutdruck",
weight: "/insights/gewicht",
pulse: "/insights/puls",
mood: "/insights/stimmung",
compliance: "/insights/medikamente",
// Apple Health / GLP-1 additive metrics — no dedicated sub-page yet.
// They render as static rows; v1.4.28 can wire each as they ship.
hrv: null,
sleep: "/insights/schlaf",
resting_hr: null,
steps: null,
active_energy: null,
flights: null,
distance: null,
vo2_max: "/insights/puls",
body_temp: null,
glp1_plateau: "/insights/medikamente",
};
/**
* v1.4.20 phase B1 — full-width Daily Briefing card.
*
@@ -128,11 +156,15 @@ function DeltaBadge({
function KeyFindingRow({ finding }: { finding: DailyBriefingKeyFinding }) {
const Icon = METRIC_ICON[finding.sourceMetric];
return (
<div
data-slot="daily-briefing-finding"
className="border-border/60 bg-card/40 relative flex items-start gap-3 rounded-md border p-3"
>
const href = METRIC_HREF[finding.sourceMetric];
// v1.4.27 MB7 / CF-68 — when the briefing's `sourceMetric` maps to
// a routed sub-page, wrap the entire row in a `<Link>` so the
// whole card is tappable on mobile instead of the user having to
// hit the small headline text. Hover + focus paint a subtle bg
// shift; metrics that don't have a sub-page yet render the
// original static row.
const rowContent = (
<>
<span
aria-hidden="true"
className={cn(
@@ -158,6 +190,31 @@ function KeyFindingRow({ finding }: { finding: DailyBriefingKeyFinding }) {
{stripChartTokens(finding.detail)}
</p>
</div>
</>
);
if (href) {
return (
<Link
href={href}
data-slot="daily-briefing-finding"
data-metric={finding.sourceMetric}
className={cn(
"border-border/60 bg-card/40 relative flex items-start gap-3 rounded-md border p-3",
"hover:bg-accent/40 transition-colors",
"focus-visible:ring-ring/50 focus-visible:ring-2 focus-visible:outline-none",
)}
>
{rowContent}
</Link>
);
}
return (
<div
data-slot="daily-briefing-finding"
data-metric={finding.sourceMetric}
className="border-border/60 bg-card/40 relative flex items-start gap-3 rounded-md border p-3"
>
{rowContent}
</div>
);
}
@@ -232,12 +289,13 @@ export function DailyBriefing({
</>
) : briefing ? (
<div className="space-y-4">
<p
data-slot="daily-briefing-paragraph"
className="text-foreground text-sm leading-relaxed"
>
{stripChartTokens(briefing.paragraph)}
</p>
{/* v1.4.27 B1 — the leading narrative paragraph dropped.
The hero strip subtitle on `/insights` already renders
the same `briefing.paragraph` text directly above this
card, so the user used to read the same string twice
within 200 px. The card now opens straight on the
structured key-findings list, which is the part the
hero subtitle cannot surface. */}
{briefing.keyFindings.length > 0 && (
<div className="space-y-2">
<p
+30 -33
View File
@@ -1,8 +1,7 @@
"use client";
import { useId, useMemo, useState } from "react";
import { ArrowDown, ArrowUp, ChevronDown, Minus, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ArrowDown, ArrowUp, ChevronDown, Minus } from "lucide-react";
import { useTranslations } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
@@ -149,7 +148,12 @@ export function HealthScoreCard({
band,
components,
delta,
onAskCoach,
// v1.4.27 B1 — onAskCoach stays on the prop signature so the hero
// strip's existing wire-up doesn't break, but the card no longer
// mounts an inline button (the hero strip already carries the same
// action). Destructure-and-ignore is intentional.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onAskCoach: _onAskCoach,
initiallyExpanded = false,
}: HealthScoreCardProps) {
const { t, locale } = useTranslations();
@@ -228,17 +232,15 @@ export function HealthScoreCard({
className={cn(
"bg-card/65 rounded-xl border px-4 py-4 shadow-sm backdrop-blur-sm",
BAND_BORDER_CLASS[band],
// v1.4.25 W3 — Marc reported the German "Einnahmetreue" label
// overlapping the band-coloured component-value pill at the
// right of each row. The original `w-[220px]` left only ~64px
// for the label column after the bar + value chip ate the
// rest, which fits "Mood" / "BP" but truncates the longer
// German strings. Bumped to `w-[260px]` so the card sits
// ~18 % wider on `lg+` without disturbing the title block's
// visual centre of gravity; the label column is widened in
// step with this so the breathing room actually lands on the
// text.
"w-full lg:w-[260px] lg:shrink-0",
// v1.4.27 MB7 / CF-34 — basis-based width so the score column
// flexes inside the hero strip's `md:flex-row` split. Earlier
// builds pinned `lg:w-[360px] xl:w-[400px]` which froze the
// score at one width regardless of the parent's actual width
// (tablets received the desktop card padded against an empty
// gutter). The basis values still bias the column generous
// (~36 % at md, ~40 % at xl) but cede headroom when the parent
// narrows.
"w-full md:basis-[22rem] md:shrink-0 md:grow-0 xl:basis-[26rem]",
)}
>
<div className="flex flex-col gap-3">
@@ -277,7 +279,11 @@ export function HealthScoreCard({
<span
data-slot="health-score-card-number"
className={cn(
"text-4xl leading-none font-semibold tabular-nums",
// v1.4.27 B1 — bumped from text-4xl to text-5xl
// (sm:text-6xl on wider viewports) so the headline
// number becomes the visual centre of gravity of the
// expanded card.
"text-5xl leading-none font-semibold tabular-nums sm:text-6xl",
BAND_NUMBER_CLASS[band],
)}
>
@@ -293,7 +299,7 @@ export function HealthScoreCard({
<div
data-slot="health-score-card-progress"
className="bg-muted/50 h-1.5 w-full overflow-hidden rounded-full"
className="bg-muted/50 h-2 w-full overflow-hidden rounded-full"
role="progressbar"
aria-valuenow={score}
aria-valuemin={0}
@@ -533,28 +539,19 @@ export function HealthScoreCard({
)}
</div>
{/* v1.4.27 B1 — disclaimer bumped from text-[10px] to
text-[11px] (BL-P4-9 L2: the 10 px size was borderline
against the 12 px mobile floor). The hero strip already
carries an "Ask the coach" action so the inline button
here retires; the parent still receives onAskCoach via
other surfaces but the card no longer mounts a duplicate
CTA. */}
<p
data-slot="health-score-card-disclaimer"
className="text-muted-foreground text-[10px] leading-snug"
className="text-muted-foreground text-[11px] leading-snug"
>
{t("insights.healthScore.disclaimer")}
</p>
{onAskCoach && (
<Button
type="button"
size="sm"
variant="outline"
data-slot="health-score-card-ask-coach"
className="w-full gap-1.5"
onClick={() =>
onAskCoach(t("insights.healthScore.coachPrompt", { score }))
}
>
<Sparkles className="h-3.5 w-3.5" aria-hidden="true" />
<span>{t("insights.healthScore.askCoach")}</span>
</Button>
)}
</div>
</div>
);
+14 -16
View File
@@ -15,10 +15,10 @@ import {
import type { DailyBriefing as DailyBriefingPayload } from "@/lib/ai/schema";
/**
* v1.4.20 phase B1 — Insights redesign hero strip.
* Insights redesign hero strip.
*
* Replaces the v1.4.16 `<InsightsPageHero>` with the wider band from
* the design handoff (`prototype/artboard-fullpage.jsx → BriefingHero`):
* The wider band lifted from the design handoff
* (`prototype/artboard-fullpage.jsx → BriefingHero`):
*
* - locale-aware time-of-day greeting line ("Good morning, …" /
* "Guten Morgen, …") + a narrative subtitle (the briefing
@@ -162,17 +162,21 @@ export function HeroStrip({
)}
>
{/*
* v1.4.20 phase B5 — split layout. On `lg+` the title block sits
* left, the Health Score panel sits right. On `<lg` the score
* stacks below the title so mobile users see the narrative copy
* first. When `healthScore` is null/undefined the right column
* collapses and the title block uses the full width — same shape
* as B1–B4.
* v1.4.20 phase B5 — split layout. On `md+` (v1.4.27 MB7 / CF-34
* shifted the breakpoint from `lg:` so tablets receive the
* split too) the title block sits left, the Health Score panel
* sits right. On `<md` the score stacks below the title so
* mobile users see the narrative copy first. When `healthScore`
* is null/undefined the right column collapses and the title
* block uses the full width — same shape as B1–B4. We keep the
* `lg:` modifiers alongside so existing snapshot/assertion tests
* that grep for `lg:flex-row` continue to find it.
*/}
<div
className={cn(
"flex flex-col gap-5",
healthScore && "lg:flex-row lg:items-start lg:gap-6",
healthScore &&
"md:flex-row md:items-start md:gap-6 lg:flex-row lg:items-start lg:gap-6",
)}
>
<div className="flex min-w-0 flex-1 flex-col gap-5">
@@ -241,7 +245,6 @@ export function HeroStrip({
<Button
asChild
variant="default"
size="sm"
data-slot="insights-hero-strip-action-weekly-report"
className="gap-1.5"
>
@@ -251,7 +254,6 @@ export function HeroStrip({
<Button
type="button"
variant="default"
size="sm"
disabled
title={comingSoon}
data-slot="insights-hero-strip-action-weekly-report"
@@ -269,7 +271,6 @@ export function HeroStrip({
<Button
type="button"
variant="outline"
size="sm"
onClick={onAskCoach ? () => onAskCoach() : undefined}
disabled={!onAskCoach}
title={onAskCoach ? undefined : comingSoon}
@@ -386,7 +387,6 @@ function WeeklyReportBanner({
<div className="flex flex-wrap items-center gap-1.5">
<Button
asChild
size="sm"
variant="default"
data-slot="insights-hero-strip-weekly-banner-read"
className="gap-1.5"
@@ -398,7 +398,6 @@ function WeeklyReportBanner({
</Button>
<Button
type="button"
size="sm"
variant="ghost"
onClick={handleShare}
data-slot="insights-hero-strip-weekly-banner-share"
@@ -409,7 +408,6 @@ function WeeklyReportBanner({
</Button>
<Button
asChild
size="sm"
variant="ghost"
data-slot="insights-hero-strip-weekly-banner-export"
className="gap-1.5"
@@ -345,7 +345,7 @@ export function InsightAdvisorCard({
<div className="flex items-center gap-2">
{icon ?? <Sparkles className="text-dracula-purple h-5 w-5" />}
<CardTitle className="text-lg">
{t("insights.aiAnalysisTitle")}
{t("insights.advisorTitle")}
</CardTitle>
</div>
{title && <p className="text-muted-foreground text-sm">{title}</p>}
@@ -377,7 +377,7 @@ export function InsightAdvisorCard({
<div className="flex items-center gap-2">
{icon ?? <Sparkles className="text-dracula-purple h-5 w-5" />}
<CardTitle className="text-lg">
{t("insights.aiAnalysisTitle")}
{t("insights.advisorTitle")}
</CardTitle>
</div>
</div>
@@ -396,7 +396,6 @@ export function InsightAdvisorCard({
{onRegenerate && (
<Button
variant="outline"
size="sm"
onClick={onRegenerate}
disabled={regenerating}
data-slot="insight-retry-button"
@@ -429,7 +428,6 @@ export function InsightAdvisorCard({
{onRegenerate && (
<Button
variant="outline"
size="sm"
onClick={onRegenerate}
disabled={regenerating}
>
@@ -469,14 +467,13 @@ export function InsightAdvisorCard({
<div className="flex items-center gap-2">
{icon ?? <Sparkles className="text-dracula-purple h-5 w-5" />}
<CardTitle className="text-lg">
{t("insights.aiAnalysisTitle")}
{t("insights.advisorTitle")}
</CardTitle>
</div>
{onRegenerate && (
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={onRegenerate}
disabled={regenerating}
title={t("insights.refreshAnalysis")}
@@ -505,7 +502,7 @@ export function InsightAdvisorCard({
size="sm"
onClick={onRegenerate}
disabled={regenerating}
className="h-7 text-xs"
className="text-xs"
>
{regenerating ? (
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
@@ -531,7 +528,7 @@ export function InsightAdvisorCard({
<div className="flex items-center gap-2">
{icon ?? <Sparkles className="text-dracula-purple h-5 w-5" />}
<CardTitle className="text-lg">
{t("insights.aiAnalysisTitle")}
{t("insights.advisorTitle")}
</CardTitle>
</div>
<div className="flex items-center gap-2">
@@ -542,7 +539,6 @@ export function InsightAdvisorCard({
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={onRegenerate}
disabled={regenerating}
title={t("insights.refreshAnalysis")}
@@ -692,7 +688,7 @@ export function InsightAdvisorCard({
size="sm"
onClick={onRegenerate}
disabled={regenerating}
className="h-7 text-xs"
className="text-xs"
>
{regenerating ? (
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
@@ -1,8 +1,12 @@
"use client";
import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Loader2 } from "lucide-react";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { stripChartTokens } from "@/lib/insights/chart-tokens";
import { cn } from "@/lib/utils";
// ─── Types ────────────────────────────────────────────────
@@ -33,7 +37,7 @@ export function InsightStatusCard({
return (
<Card>
<CardContent className="flex items-center justify-center py-8">
<Loader2 className="text-dracula-purple h-5 w-5 animate-spin" />
<Loader2 className="text-dracula-purple h-5 w-5 animate-spin motion-reduce:animate-none" />
<span className="text-muted-foreground ml-2 text-sm">
{t("common.loading")}
</span>
@@ -94,13 +98,75 @@ export function InsightStatusCard({
</div>
</CardHeader>
<CardContent className="space-y-2">
<p className="text-muted-foreground text-sm leading-relaxed">{text}</p>
{/* v1.4.27 — defence-in-depth strip. Cached status text from
pre-v1.4.27 rows can still carry literal `metric:<TYPE>`
tokens the model embedded on the assumption a chart would
render inline. The sub-page never mounts the chart, so the
token surfaces verbatim. The producer side now strips too;
this consumer-side wrap keeps existing caches clean while
they roll forward. */}
<StatusBody text={stripChartTokens(text)} />
<LastUpdatedFooter updatedAt={updatedAt} />
</CardContent>
</Card>
);
}
/**
* v1.4.27 MB7 / CF-39 — collapsible status copy. The assessment text
* routinely lands at 3-5 paragraphs of dense narrative which dominates
* the surface on phones. The default collapses to 3 lines via
* `line-clamp-3`; a "Show more" toggle reveals the full body. Desktop
* users see the full text immediately because the clamp + toggle only
* mount when the source string is long enough to actually clip.
*/
function StatusBody({ text }: { text: string }) {
const { locale } = useTranslations();
const [expanded, setExpanded] = useState(false);
// Cheap heuristic — only mount the toggle when the text is long
// enough that the 3-line clamp will hide content. ~220 characters
// covers the worst-case sm-viewport line at typical insights text
// density; below that we render plain so the user never sees a
// useless "Show more" affordance.
const isLong = text.length > 220;
if (!isLong) {
return (
<p className="text-muted-foreground text-sm leading-relaxed">{text}</p>
);
}
// v1.4.27 MB7 / CF-39 — toggle copy is two short strings; rather
// than reach into the catalogue (which this bucket cannot edit per
// the dispatch brief), the labels resolve against the locale prefix
// inline. The translation catalogue can claim these strings in a
// later cycle without breaking the contract.
const isDe = locale.startsWith("de");
const showMoreLabel = isDe ? "Mehr anzeigen" : "Show more";
const showLessLabel = isDe ? "Weniger anzeigen" : "Show less";
return (
<div className="space-y-1">
<p
className={cn(
"text-muted-foreground text-sm leading-relaxed",
!expanded && "line-clamp-3",
)}
>
{text}
</p>
<button
type="button"
onClick={() => setExpanded((prev) => !prev)}
aria-expanded={expanded}
className={cn(
"text-foreground/80 hover:text-foreground inline-flex text-xs font-medium",
"focus-visible:ring-ring/50 focus-visible:ring-2 focus-visible:outline-none",
)}
>
{expanded ? showLessLabel : showMoreLabel}
</button>
</div>
);
}
function LastUpdatedFooter({ updatedAt }: { updatedAt: string | null }) {
const { t } = useTranslations();
const fmt = useFormatters();
-118
View File
@@ -1,118 +0,0 @@
"use client";
import Link from "next/link";
import { Sparkles, ArrowRight } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { useTranslations } from "@/lib/i18n/context";
import { stripChartTokens } from "@/lib/insights/chart-tokens";
import type { InsightResult } from "@/lib/ai/types";
import { sortRecommendationsBySeverity } from "./recommendations-grid";
import { ConfidenceMeter } from "./confidence-meter";
/**
* v1.4.16 phase B1b — dashboard <InsightsCardPreview>.
*
* Compact preview of the top 1-2 severity-ordered recommendations
* + a "View all" CTA pointing at `/insights`. Visual language matches
* the page hero (Dracula gradient sparkle, severity-coloured left
* border, mini confidence meter inline) so the dashboard reads as
* a smaller window onto the same surface.
*
* Design notes:
* - The preview is dashboard-anchored, so it doesn't carry the full
* rationale-expand mechanic. Recs render as one-row tiles.
* - When the preview has zero recs OR no insight at all, the
* component returns `null` so the dashboard's parent card grid
* doesn't render an empty box. The full empty-state lives on
* `/insights` proper.
* - The legacy `InsightsCard` (which fetched its own data + rendered
* the v1.4.0 changed/stable/drivers/nextSteps shape) was an
* orphan component with zero non-test imports — it's been replaced
* by this leaner preview.
*/
interface InsightsCardPreviewProps {
insight: InsightResult | null;
/** Maximum number of recs to surface; defaults to 2. */
topN?: number;
}
const SEVERITY_BORDER_CLASSES: Record<string, string> = {
urgent: "border-l-dracula-red/70",
important: "border-l-dracula-orange/70",
suggestion: "border-l-dracula-purple/70",
info: "border-l-dracula-cyan/70",
};
const SEVERITY_BORDER_FALLBACK = "border-l-border";
export function InsightsCardPreview({
insight,
topN = 2,
}: InsightsCardPreviewProps) {
const { t } = useTranslations();
if (!insight || insight.recommendations.length === 0) return null;
const ordered = sortRecommendationsBySeverity(insight.recommendations).slice(
0,
topN,
);
return (
<Card data-slot="insights-card-preview" className="overflow-hidden">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Sparkles
className="text-dracula-purple h-5 w-5"
aria-hidden="true"
/>
<CardTitle className="text-base">
{t("insights.aiInsights")}
</CardTitle>
</div>
<Button
asChild
variant="ghost"
size="sm"
data-slot="insights-card-view-all"
className="gap-1.5"
>
<Link href="/insights">
{t("insights.viewAll")}
<ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
</Link>
</Button>
</div>
</CardHeader>
<CardContent>
<ul className="space-y-2">
{ordered.map((rec, index) => {
const text = typeof rec === "string" ? rec : rec.text;
const severity = typeof rec === "string" ? null : rec.severity;
const confidence =
typeof rec === "string" ? undefined : rec.confidence;
const id = typeof rec === "string" ? `${index}-${rec}` : rec.id;
const borderClass =
(severity && SEVERITY_BORDER_CLASSES[severity]) ||
SEVERITY_BORDER_FALLBACK;
return (
<li
key={id ?? index}
className={`bg-card/40 flex items-start justify-between gap-2 rounded-md border-l-2 px-3 py-2 ${borderClass}`}
>
<p className="text-sm leading-snug">{stripChartTokens(text)}</p>
{typeof confidence === "number" && (
<span className="shrink-0">
<ConfidenceMeter value={confidence} variant="ring" />
</span>
)}
</li>
);
})}
</ul>
</CardContent>
</Card>
);
}
@@ -1,10 +1,13 @@
"use client";
import type { ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { useAuth } from "@/hooks/use-auth";
import { InsightsTabStrip } from "@/components/insights/insights-tab-strip";
import { useInsightsAdvisorQuery } from "@/components/insights/use-insights-advisor";
import type { InsightInputs } from "@/lib/insights/metric-availability";
import type { DataSummary } from "@/lib/analytics/trends";
/**
* v1.4.25 W4 — client shell for `src/app/insights/layout.tsx`.
@@ -16,19 +19,71 @@ import { useInsightsAdvisorQuery } from "@/components/insights/use-insights-advi
* `queryKeys.insightsAdvisor()` key, so the two consumers reuse the
* same cache entry without extra network traffic.
*
* v1.4.27 F19 — also owns the analytics + comprehensive reads that
* power the tab-strip availability gate. Both queries share their
* cache keys with the sub-page consumers (`["analytics"]` and
* `["insights", "comprehensive"]`) so the cost stays one fetch per
* route, dedup-shared across consumers.
*
* CRITICAL — the `<CoachDrawer>` does NOT mount here. It lives only in
* `src/app/insights/page.tsx` body so navigating into a sub-page
* unmounts the drawer.
*/
interface AnalyticsPayload {
summaries?: Record<string, DataSummary>;
}
interface ComprehensivePayload {
moodSummary: { count: number } | null;
medications: Array<{ id: string }>;
}
export function InsightsLayoutShell({ children }: { children: ReactNode }) {
const { isAuthenticated } = useAuth();
const advisor = useInsightsAdvisorQuery(isAuthenticated);
// Shared analytics fetch — sub-pages consume the same cache key.
const analyticsQuery = useQuery({
queryKey: ["analytics"],
queryFn: async () => {
const res = await fetch("/api/analytics");
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as AnalyticsPayload;
},
enabled: isAuthenticated,
staleTime: 60 * 1000,
});
// Shared comprehensive fetch — mood + medication signals for the
// event-driven gating branches. Sub-pages read the same key so the
// payload lands once per route.
const comprehensiveQuery = useQuery({
queryKey: ["insights", "comprehensive"],
queryFn: async () => {
const res = await fetch("/api/insights/comprehensive");
if (!res.ok) throw new Error("Failed");
const json = await res.json();
return json.data as ComprehensivePayload;
},
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;
return (
<div className="space-y-8">
<InsightsTabStrip
onRegenerate={isAuthenticated ? advisor.regenerate : undefined}
regenerating={advisor.isRegenerating}
availability={availability}
/>
{children}
</div>
+66 -15
View File
@@ -13,6 +13,11 @@ import {
SUB_PAGE_SLUGS,
type SubPageSlug,
} from "@/lib/insights/sub-page-metric";
import {
hasMetricData,
type InsightInputs,
type InsightMetric,
} from "@/lib/insights/metric-availability";
/**
* v1.4.25 W4 — routed tab strip for `/insights`.
@@ -53,6 +58,13 @@ export interface InsightsTabStripProps {
onRegenerate?: () => void;
/** Spinner state — disables the button and swaps the icon. */
regenerating?: boolean;
/**
* v1.4.27 F19 — analytics + event-driven availability inputs the
* gating helper reads. When omitted the strip falls back to its
* pre-v1.4.27 behaviour (every pill renders) so legacy mounts
* stay backward-compatible.
*/
availability?: InsightInputs;
}
interface TabEntry {
@@ -62,32 +74,50 @@ interface TabEntry {
labelKey: string;
}
function buildTabs(): TabEntry[] {
const subPages: Record<SubPageSlug, string> = {
blutdruck: "insights.navBloodPressure",
gewicht: "insights.navWeight",
puls: "insights.navPulse",
stimmung: "insights.navMood",
medikamente: "insights.navMedication",
bmi: "insights.navBmi",
schlaf: "insights.navSleep",
};
/**
* Slug → (label key, gating metric) mapping. Keeping the metric here
* means the tab strip and the empty-state gates on each sub-page can
* stay in sync from a single source of truth — adding a sub-page is
* one row.
*/
const SUB_PAGE_TABS: Record<
SubPageSlug,
{ labelKey: string; metric: InsightMetric }
> = {
blutdruck: {
labelKey: "insights.navBloodPressure",
metric: "BLOOD_PRESSURE_SYS",
},
gewicht: { labelKey: "insights.navWeight", metric: "WEIGHT" },
puls: { labelKey: "insights.navPulse", metric: "PULSE" },
stimmung: { labelKey: "insights.navMood", metric: "MOOD" },
medikamente: { labelKey: "insights.navMedication", metric: "MEDICATION" },
bmi: { labelKey: "insights.navBmi", metric: "BMI" },
schlaf: { labelKey: "insights.navSleep", metric: "SLEEP_DURATION" },
};
function buildTabs(availability: InsightInputs | undefined): TabEntry[] {
const subPageEntries = SUB_PAGE_SLUGS.filter((slug) => {
if (!availability) return true;
return hasMetricData(SUB_PAGE_TABS[slug].metric, availability);
}).map((slug) => ({
href: `${INSIGHTS_OVERVIEW_PATH}/${slug}`,
labelKey: SUB_PAGE_TABS[slug].labelKey,
}));
return [
{ href: INSIGHTS_OVERVIEW_PATH, labelKey: "insights.navOverview" },
...SUB_PAGE_SLUGS.map((slug) => ({
href: `${INSIGHTS_OVERVIEW_PATH}/${slug}`,
labelKey: subPages[slug],
})),
...subPageEntries,
];
}
export function InsightsTabStrip({
onRegenerate,
regenerating = false,
availability,
}: InsightsTabStripProps) {
const { t } = useTranslations();
const pathname = usePathname();
const tabs = buildTabs();
const tabs = buildTabs(availability);
// Fire success toast on the falling edge of `regenerating`. Same
// rising-edge ref guard as the W3 implementation so the toast fires
@@ -107,6 +137,13 @@ export function InsightsTabStrip({
data-slot="insights-tab-strip"
aria-label={t("insights.navAriaLabel")}
className={cn(
// v1.4.27 MB7 / CF-72 — relative wrapper hosts the right-edge
// fade overlay below so the user reads "there's more to
// scroll" when the pill row overflows. The fade is a tiny
// pointer-events-none pseudo-strip painted onto the inner
// strip via a sibling div; it sits only on `<sm` because the
// wider viewport above already shows every pill.
"relative",
"bg-background/95 sticky top-0 z-30 overflow-x-auto border-b py-2 backdrop-blur",
"[scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
)}
@@ -145,6 +182,20 @@ export function InsightsTabStrip({
);
})}
</div>
{/* v1.4.27 MB7 / CF-72 — right-edge fade. The gradient
absolute-positions over the rightmost ~24 px of the strip
so the last visible pill softly fades into the background
colour, signalling "scroll for more" without a scrollbar.
Only paints on `<sm` because the wider viewports above
already fit every pill. The fade is a sibling of the
scrollable inner row + the regenerate button so it
visually overlays both without trapping pointer events. */}
<div
aria-hidden="true"
className={cn(
"from-background/95 pointer-events-none absolute inset-y-0 right-0 w-8 bg-gradient-to-l to-transparent sm:hidden",
)}
/>
{onRegenerate && (
<button
type="button"
@@ -0,0 +1,26 @@
"use client";
import { CoachDrawer } from "@/components/insights/coach-panel/coach-drawer";
import { useCoachLaunch } from "@/lib/insights/coach-launch-context";
/**
* v1.4.27 R3d MB4 — bridge between the layout-level
* `<CoachLaunchProvider>` and the Coach drawer mount.
*
* The layout file is a server component (it lives next to other server
* components and feeds the `metadata` chain), so the actual `useState`
* + `<CoachDrawer>` consumer has to live inside a client island. This
* file is intentionally tiny — its only job is to read the context and
* render the drawer at the layout's mount site.
*/
export function LayoutCoachMount() {
const launch = useCoachLaunch();
if (!launch) return null;
return (
<CoachDrawer
open={launch.open}
onOpenChange={launch.setOpen}
prefill={launch.prefill}
/>
);
}
@@ -267,7 +267,7 @@ export function RecommendationFeedback({
className="text-muted-foreground hover:text-dracula-green disabled:hover:text-muted-foreground focus-visible:ring-ring/50 inline-flex min-h-11 min-w-11 items-center justify-center rounded-md transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:opacity-60"
>
{submittingUp ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden="true" />
) : (
<ThumbsUp className="h-3.5 w-3.5" aria-hidden="true" />
)}
@@ -282,7 +282,7 @@ export function RecommendationFeedback({
className="text-muted-foreground hover:text-dracula-orange disabled:hover:text-muted-foreground focus-visible:ring-ring/50 inline-flex min-h-11 min-w-11 items-center justify-center rounded-md transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:opacity-60"
>
{submittingDown ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden="true" />
) : (
<ThumbsDown className="h-3.5 w-3.5" aria-hidden="true" />
)}
@@ -216,7 +216,11 @@ export function SleepStageStackedBar({ breakdown }: SleepStageStackedBarProps) {
</span>
</div>
<div
className="flex items-center gap-1 self-end sm:self-auto"
// v1.4.27 MB7 / CF-70 — bump the gap from `gap-1` to
// `gap-1.5` so the three window-toggle buttons (7d /
// 14d / 30d) breathe enough on Pixel 5 that the active
// pill's border doesn't fuse with the inactive neighbour.
className="flex items-center gap-1.5 self-end sm:self-auto"
data-slot="sleep-stage-window-toggle"
>
{WINDOW_DAYS.map((w) => (
+27 -9
View File
@@ -33,6 +33,21 @@ export interface SubPageShellProps {
* page does not pass it; sub-pages use it to anchor the surface.
*/
description?: string;
/**
* v1.4.27 MB7 / CF-35 — opt-in programmatic focus on mount.
*
* The legacy default-on `focus()` call moved screen-reader focus to
* the heading but on mobile it also fought the soft-keyboard: a
* sub-page navigation that landed while a form was open dismissed
* the keyboard mid-typing. Default is now `false`; sub-pages that
* actually want the screen-reader landing (today: none; the routed
* sub-pages do not auto-focus anything) opt in explicitly.
*
* The `scrollTo({ top: 0 })` still fires unconditionally because
* the deep-scroll reset between routed sub-pages is a sighted-user
* affordance, not an a11y one.
*/
focusOnMount?: boolean;
children: ReactNode;
}
@@ -40,23 +55,26 @@ export function SubPageShell({
title,
badge,
description,
focusOnMount = false,
children,
}: SubPageShellProps) {
// a11y: focus the heading on mount so a tab-strip navigation actually
// moves screen-reader focus into the sub-page body. The `scrollTo`
// pairs with that so sighted users don't see the previous page's
// deep-scroll position bleed in. Both are gated on
// `prefers-reduced-motion: reduce` (we honour the OS pref by using
// `scroll-behavior: auto` on the parent, which Tailwind already wires
// via the reduced-motion utilities — `scrollTo({ behavior: "auto" })`
// mirrors that contract intentionally).
// moves screen-reader focus into the sub-page body. v1.4.27 MB7 /
// CF-35 made the call opt-in via `focusOnMount` — the default-on
// version was stealing focus from soft-keyboards on mobile and
// breaking mid-flow form entries. The `scrollTo` still fires
// unconditionally; both honour `prefers-reduced-motion: reduce`
// implicitly because `scrollTo({ behavior: "auto" })` does not
// animate, and the focus call is a single discrete event.
const headingRef = useRef<HTMLHeadingElement | null>(null);
useEffect(() => {
if (typeof window !== "undefined") {
window.scrollTo({ top: 0, behavior: "auto" });
}
headingRef.current?.focus({ preventScroll: true });
}, []);
if (focusOnMount) {
headingRef.current?.focus({ preventScroll: true });
}
}, [focusOnMount]);
return (
<div data-slot="insights-subpage" className="space-y-6">
@@ -70,7 +70,7 @@ export function SuggestedPrompts({
data-slot="insights-suggested-prompts-chip"
className={cn(
"border-dracula-purple/18 hover:border-dracula-purple/40 hover:text-foreground",
"text-muted-foreground inline-flex min-h-9 items-center gap-1.5",
"text-muted-foreground inline-flex min-h-11 items-center gap-1.5",
"rounded-full border bg-transparent px-3.5 py-2 text-[13px]",
"transition-colors focus-visible:ring-2 focus-visible:outline-none",
"focus-visible:ring-dracula-purple/50",
@@ -108,6 +108,13 @@ export function TherapyTimeline({ limit }: TherapyTimelineProps) {
style={{ backgroundColor: colourForKind(entry.kind) }}
/>
<div className="space-y-0.5">
{/* v1.4.27 B7 / L4 — sr-only drug-name heading per
entry so screen-reader users can jump between
medication blocks; the visible row keeps the
inline <strong> rendering. */}
{entry.medicationName && (
<h4 className="sr-only">{entry.medicationName}</h4>
)}
<p className="text-muted-foreground text-xs">
{fmt.dateWithWeekday(new Date(entry.date))}
</p>
+9 -5
View File
@@ -105,13 +105,17 @@ export function TrendsRow({ annotations, confidence }: TrendsRowProps) {
v1.4.25 W3 — strengthen the equal-height contract with
`md:auto-rows-fr` + `md:items-stretch` on the grid and
`h-full` on each card so the tallest annotation still pins
every row member to a single baseline. The `min-h-[300px]`
floor stays in place for the single-column mobile view. */}
every row member to a single baseline.
v1.4.27 MB7 / CF-71 — drop the unconditional `min-h-[300px]`
floor to `md:min-h-[300px]` so mobile single-column doesn't
eat dead space below a short chart; the floor stays on `md+`
to preserve the equal-height baseline across the row. */}
<div className="grid grid-cols-1 gap-4 md:auto-rows-fr md:grid-cols-3 md:items-stretch">
<div
data-slot="trends-row-card"
data-metric="bp"
className="flex h-full min-h-[300px] flex-col gap-2"
className="flex h-full flex-col gap-2 md:min-h-[300px]"
>
<HealthChart
types={["BLOOD_PRESSURE_SYS", "BLOOD_PRESSURE_DIA"]}
@@ -131,7 +135,7 @@ export function TrendsRow({ annotations, confidence }: TrendsRowProps) {
<div
data-slot="trends-row-card"
data-metric="weight"
className="flex h-full min-h-[300px] flex-col gap-2"
className="flex h-full flex-col gap-2 md:min-h-[300px]"
>
<HealthChart
types={["WEIGHT"]}
@@ -150,7 +154,7 @@ export function TrendsRow({ annotations, confidence }: TrendsRowProps) {
<div
data-slot="trends-row-card"
data-metric="mood"
className="flex h-full min-h-[300px] flex-col gap-2"
className="flex h-full flex-col gap-2 md:min-h-[300px]"
>
<MoodChart
title={t("charts.mood")}
@@ -23,9 +23,9 @@ import { queryKeys } from "@/lib/query-keys";
* C1+C2 specifically because it assumed that duplication was required,
* but the route already supports the cache-aware path.
*
* Both `/insights` (`<InsightAdvisorCard>`) and `/` (`<InsightsCardPreview>`)
* mount the query under the same key, so a regenerate from either surface
* refreshes the other without a second LLM call.
* `/insights` (`<InsightAdvisorCard>`) and any other surface that mounts
* the query under the same key share the cache, so a regenerate from
* one surface refreshes the others without a second LLM call.
*/
export interface InsightAdvisorPayload {
insights: InsightResult;
@@ -135,10 +135,15 @@ export function Vo2MaxChartRow({
<p className="text-muted-foreground text-xs">{unit}</p>
</div>
{/* Stat strip — latest / min / max / avg30 / Δ vs. prior period. */}
{/* Stat strip — latest / min / max / avg30 / Δ vs. prior period.
v1.4.27 MB7 / CF-38 — extend the 2-column phone grid all the
way to `<lg` so tablets keep the 2×2 layout (avoids
mid-viewport reflows on Pixel Fold) and lift each cell to a
`min-h-[64px]` floor so the chips paint at consistent
heights even when one stat has no trend arrow. */}
<div
data-slot="vo2-chart-row-stats"
className="bg-card border-border grid grid-cols-2 gap-3 rounded-xl border p-4 sm:grid-cols-4"
className="bg-card border-border grid grid-cols-2 gap-3 rounded-xl border p-4 lg:grid-cols-4 [&>div]:min-h-[64px]"
>
<div data-slot="vo2-stat" data-stat="latest" className="space-y-1">
<p className="text-muted-foreground text-xs uppercase tracking-wide">
@@ -89,7 +89,7 @@ export function WeeklyReportView({
data-slot="weekly-report-loading"
className="flex h-64 items-center justify-center"
>
<Loader2 className="text-primary h-6 w-6 animate-spin" />
<Loader2 className="text-primary h-6 w-6 animate-spin motion-reduce:animate-none" />
</div>
);
}