"use client"; /** * v1.16.1 — Settings → AI "Coach preferences" card. * * The prompt-tuning form moved out of the in-chat sheet * (`coach-settings-sheet.tsx`, retired) into the AI settings section so * model + behaviour live in one place; the chat header keeps a gear * that deep-links here. Reads + writes `/api/auth/me/coach-prefs` * through the shared `useCoachPrefs` / `useSaveCoachPrefs` pair — the * same persisted row the chat's "What I draw on" rail edits. * * One source of truth for data scope: `excludeMetrics`. The optional * context group (sleep / medications / profile) used to render its own * switches with the same checked-polarity as the exclude list, so * "exclude sleep" and "send sleep context" could read as both ON at * once. The context switches now DERIVE from the exclusion list * (checked = not excluded = sent), so the two groups can never * contradict each other. */ import { useState } from "react"; import Link from "next/link"; import { Loader2, SlidersHorizontal } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { SettingsCardActions } from "@/components/settings/_card-actions"; import { Label } from "@/components/ui/label"; import { Switch } from "@/components/ui/switch"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Skeleton } from "@/components/ui/skeleton"; import { SettingsCard } from "@/components/settings/settings-card"; import { SettingsCardHeader } from "@/components/settings/_card-header"; import { useTranslations } from "@/lib/i18n/context"; import { useCoachPrefs, useSaveCoachPrefs } from "@/hooks/use-coach-prefs"; import { useAiCapability } from "@/hooks/use-ai-capability"; import { COACH_FOLLOW_UP_UI_KEYS } from "@/lib/ai/coach/dialog-keys"; import { DEFAULT_COACH_PREFS, type CoachExcludeMetric, type CoachPrefs, type CoachTone, type CoachVerbosity, } from "@/lib/validations/coach-prefs"; const EXCLUDE_OPTIONS: CoachExcludeMetric[] = [ "bp", "weight", "pulse", "mood", "compliance", "hrv", "sleep", "resting_hr", "steps", ]; // Optional context blocks. Derived from `excludeMetrics` (see header // comment): a switch here reads "send this block" and is simply the // inverse of the exclusion entry. const CONTEXT_OPTIONS: CoachExcludeMetric[] = [ "sleep", "medications", "anthropometrics", ]; export interface CoachPrefsSectionProps { isAuthenticated: boolean; } export function CoachPrefsSection({ isAuthenticated }: CoachPrefsSectionProps) { const { t } = useTranslations(); const coach = useAiCapability("coach"); const { data: persisted } = useCoachPrefs({ enabled: isAuthenticated }); // Local working copy edited by the form; re-syncs to the persisted // shape on every fetch via the in-render setState pattern (the // `react-hooks/set-state-in-effect` rule rejects setState inside an // effect when the source is a query result). const [draft, setDraft] = useState(DEFAULT_COACH_PREFS); const [lastSeenPersisted, setLastSeenPersisted] = useState( null, ); if (persisted && persisted !== lastSeenPersisted) { setLastSeenPersisted(persisted); setDraft(persisted); } const save = useSaveCoachPrefs({ onSuccess: () => { toast.success(t("insights.coach.settingsSaved")); }, // v1.32.22 (R5b) — a concurrent write advanced the row since this edit was // based. The hook already refetched (so the form re-syncs to server truth // and the token advances); nudge the user to re-apply and save again. onConflict: () => { toast.message(t("common.conflictReloaded")); }, }); function setExcluded(metric: CoachExcludeMetric, excluded: boolean) { setDraft((prev) => ({ ...prev, excludeMetrics: excluded ? Array.from(new Set([...prev.excludeMetrics, metric])) : prev.excludeMetrics.filter((m) => m !== metric), })); } const isLoading = isAuthenticated && !persisted; return ( {isLoading ? (
) : (
{/* Tone */}
{/* Verbosity. The concise tone forces "brief" server-side (system-prompt.ts, buildPrefsPrefix), so the picker is disabled there — showing "brief" — with a hint instead of a live control that silently does nothing. */}
{draft.tone === "concise" && (

{t("insights.coach.settingsVerbosityConciseHint")}

)}
{/* Data clusters + analysis window live on ONE owner: the sources rail inside the chat ("What I draw on"). This card used to render its own copies of both controls; two writable surfaces for the same persisted fields is exactly the redundancy the rail was built to end. A pointer replaces them. Only while the Coach can open: without it the link would bounce back to Insights and the rail is out of reach. */} {coach.available ? (

{t("insights.coach.settingsSourcesPointer")}{" "} {t("insights.coach.settingsSourcesPointerLink")}

) : null} {/* Exclude metrics — checked = excluded. */}

{t("insights.coach.settingsExcludeHint")}

    {EXCLUDE_OPTIONS.map((metric) => { const id = `coach-prefs-exclude-${metric}`; const checked = draft.excludeMetrics.includes(metric); return (
  • setExcluded(metric, next)} />
  • ); })}
{/* Optional context blocks — checked = sent, derived as the inverse of the exclusion list so the two groups can never contradict each other. */}

{t("insights.coach.settingsContextHint")}

    {CONTEXT_OPTIONS.map((metric) => { const id = `coach-prefs-context-${metric}`; const sent = !draft.excludeMetrics.includes(metric); return (
  • setExcluded(metric, !next)} />
  • ); })}
{/* v1.18.1 (Workstream C) — cadence-suggestion opt-out. The Coach offers an occasional, evidence-based reminder to measure a metric more regularly; this is the master switch for that surface. Off ⇒ no suggestion cards ever surface. */}

{t("coach.settings.reminderSuggestionsDescription")}

setDraft((prev) => ({ ...prev, reminderSuggestions: { enabled: next, stopped: prev.reminderSuggestions?.stopped ?? false, dismissedCadences: prev.reminderSuggestions?.dismissedCadences ?? [], lastSuggestedAt: prev.reminderSuggestions?.lastSuggestedAt ?? null, }, })) } />
{/* v1.39.4 — follow-up chips under the Coach's latest answer. Absent in the saved prefs means on. */}

{t(COACH_FOLLOW_UP_UI_KEYS.settingHint)}

setDraft((prev) => ({ ...prev, followUpChips: next })) } />
)}
); }