From af09202bbca807bbdc4184676e436a421339d6fd Mon Sep 17 00:00:00 2001 From: Nebojsa Stojanovic Date: Tue, 17 Nov 2026 10:47:38 +0100 Subject: [PATCH] feat(coach): add authenticated wellbeing brief and conversational dashboard --- .env.example | 2 + COACH.md | 53 +++ app/app/coach-actions.ts | 67 ++++ components/product/dashboard-page.tsx | 4 + components/product/wellbeing-coach.tsx | 444 +++++++++++++++++++++++++ lib/coach-types.ts | 45 +++ lib/current-user.ts | 8 +- lib/loadiq-api.ts | 23 +- lib/monitoring/source-files.json | 3 + tests/auth.spec.ts | 45 +++ tests/coach.spec.ts | 184 ++++++++++ tests/fixture-server.mjs | 118 ++++++- 12 files changed, 992 insertions(+), 4 deletions(-) create mode 100644 COACH.md create mode 100644 app/app/coach-actions.ts create mode 100644 components/product/wellbeing-coach.tsx create mode 100644 lib/coach-types.ts create mode 100644 tests/auth.spec.ts create mode 100644 tests/coach.spec.ts diff --git a/.env.example b/.env.example index 8ba7b32..8a98c8a 100644 --- a/.env.example +++ b/.env.example @@ -8,4 +8,6 @@ NEXT_PUBLIC_WORKOS_REDIRECT_URI=http://localhost:3000/callback # Two separate EU Sentry projects: backend and web. Empty disables monitoring. SENTRY_DSN= NEXT_PUBLIC_SENTRY_DSN= +# Wellbeing Coach uses the existing authenticated backend connection above. +# ANTHROPIC_API_KEY and COACH_* belong only to loadiq-api; never expose them here. # E2E flags are set only by scripts/e2e-server.mjs. Never configure in deployment. diff --git a/COACH.md b/COACH.md new file mode 100644 index 0000000..cb11d0a --- /dev/null +++ b/COACH.md @@ -0,0 +1,53 @@ +# Wellbeing Coach v0 dashboard + +`WellbeingCoach` adds a daily brief and conversation to `/app` without redesigning the +existing dashboard. Its initial data is read server-side after the existing dashboard/insight +refresh, so no mount-time background server action races with navigation. A coach outage +is caught separately and cannot remove existing metrics; explicit actions can retry. +Coach reads have a five-second fetch deadline; chat has thirty seconds for the provider's +bounded request. Existing non-coach API behavior is unchanged. + +`app/app/coach-actions.ts` uses WorkOS `currentUser()` and the existing server-only API +client. No browser user ID, external-auth header or provider key is trusted or forwarded. +Next server actions retain their origin protections. Responses use no-store backend fetches. + +The UI displays the exact backend facts/trends, evidence, coverage/freshness, qualified +hypotheses, suggestions and one follow-up. Optional historical dates are bounded by the +backend. Garmin attribution accompanies derived output; manual context is not called a +measured activity. English matches the existing dashboard language. + +Chat stays in component memory (maximum six exchanges) and can be cleared. It is not +persisted in localStorage, browser recordings or a transcript table. After Anthropic consent, up to four previous user questions and assistant summaries provide conversation context to Anthropic; saved raw notes are not sent. Explicitly confirmed notes are separately saved, reviewable and removable. + +The AI transparency panel shows provider processing/retention and the absence of guaranteed +EU processing. Consent is unchecked by default, requires explicit confirmation and can be +revoked. Revocation also clears visible conversation. When provider configuration is missing, +AI enabling is unavailable and the UI honestly labels evidence-only mode. Failed requests +show a controlled retry state; no backend response payload is logged. + +Only the existing backend URL/internal key and WorkOS settings belong here. Anthropic credentials +and operator review flags are backend-only. No real-provider or production configuration is +changed by adding this UI; the backend must have the additive coach migration applied. + +Tests use fabricated Alice/Bob accounts and a local fixture server. `pnpm test:e2e` includes +brief/chat consistency, explicit AI consent/revocation, confirmed note lifecycle, stale data, +and identity-spoof rejection, plus existing dashboard/privacy tests. No real Anthropic/Garmin +calls, health recordings, traces, screenshots or video artifacts are required by CI. + +Run `pnpm typecheck`, `pnpm quality`, `pnpm test:e2e`, then `pnpm build` (sequentially with +E2E because both use `.next`). Real WorkOS + real LLM verification requires a configured +backend and explicit provider-specific consent; synthetic fixtures are not proof of that flow. + +Task 4.1: Anthropic consent explicitly covers questions, recent conversation summaries and summarized health +evidence being processed by Anthropic. Saved notes are not sent verbatim. Do not put identifiers, +locations or credentials into questions. Chat fetch deadline is thirty seconds for bounded retrieval +and synthesis. No automatic consent grant or authentication bypass is introduced. + +Real-provider status (2026-11-16): backend Haiku 5.5 passed a three-turn synthetic Croatian +conversation. The displayed coverage label describes measurement coverage, not certainty +about causes. WorkOS-to-real-Garmin-to-LLM remains unverified and disabled pending separate +owner consent. Playwright uses mocked provider responses and is not a real-provider test. + +## Task 4.3 + +Chat displays a concise conversational answer; full measurements and limitations remain expandable. Ephemeral previous assistant answers include follow-up questions for continuity. No transcript is persisted. Real WorkOS staging login is verified locally with development bypass off. UI consent remains owner-controlled and can be recorded while AI is paused. No real health questions are sent until separate explicit consent and usage approval. Backend evaluations include twenty synthetic Haiku/Sonnet pairs and Croatian multi-turn repeats. diff --git a/app/app/coach-actions.ts b/app/app/coach-actions.ts new file mode 100644 index 0000000..5a901c1 --- /dev/null +++ b/app/app/coach-actions.ts @@ -0,0 +1,67 @@ +"use server"; +import { currentUser } from "@/lib/current-user"; +import { coachApiRequest } from "@/lib/loadiq-api"; +import type { + CoachMessageInput, + CoachNote, + CoachReply, + CoachStatus, +} from "@/lib/coach-types"; + +async function safely(operation: () => Promise) { + await currentUser(); + try { + return { ok: true as const, data: await operation() }; + } catch { + return { + ok: false as const, + error: + "Coach unavailable. Please retry or reload to check the latest state.", + }; + } +} +export async function loadCoach() { + return safely(async () => { + const [status, brief, notes] = await Promise.all([ + coachApiRequest("/status"), + coachApiRequest("/brief"), + coachApiRequest("/context"), + ]); + return { status, brief, notes }; + }); +} +export async function sendCoachMessage(input: CoachMessageInput) { + return safely(() => + coachApiRequest("/chat", "POST", { + message: input.message, + previousQuestions: input.previousQuestions, + previousAnswers: input.previousAnswers, + from: input.from, + to: input.to, + }), + ); +} +export async function changeCoachConsent( + enabled: boolean, + policyVersion: string, +) { + return safely(() => + coachApiRequest("/consent", "POST", { + enabled, + policyVersion, + }), + ); +} +export async function saveCoachNote(text: string, confirmed: boolean) { + return safely(() => + coachApiRequest("/context", "POST", { text, confirmed }), + ); +} +export async function removeCoachNote(id: string) { + return safely(() => + coachApiRequest<{ removed: boolean }>( + `/context/${encodeURIComponent(id)}`, + "DELETE", + ), + ); +} diff --git a/components/product/dashboard-page.tsx b/components/product/dashboard-page.tsx index 97ae7e8..f0ebf70 100644 --- a/components/product/dashboard-page.tsx +++ b/components/product/dashboard-page.tsx @@ -33,6 +33,8 @@ import { type ImportRecord, } from "@/lib/loadiq-api"; import { TrendPanel } from "./trend-panel"; +import { WellbeingCoach } from "./wellbeing-coach"; +import { loadCoach } from "@/app/app/coach-actions"; export async function DashboardPage() { const [{ user }, summary, timeline, recentActivity, recentImports] = @@ -44,6 +46,7 @@ export async function DashboardPage() { getRecentImports(5), ]); + const coach = await loadCoach(); const greetingName = user.firstName ?? user.email.split("@")[0]; const activeStates = summary.daily.states.filter( (state) => state.status !== "RESOLVED", @@ -80,6 +83,7 @@ export async function DashboardPage() {
+
diff --git a/components/product/wellbeing-coach.tsx b/components/product/wellbeing-coach.tsx new file mode 100644 index 0000000..d32de76 --- /dev/null +++ b/components/product/wellbeing-coach.tsx @@ -0,0 +1,444 @@ +"use client"; +import { useState, type FormEvent } from "react"; +import { + changeCoachConsent, + loadCoach, + removeCoachNote, + saveCoachNote, + sendCoachMessage, +} from "@/app/app/coach-actions"; +import type { CoachNote, CoachReply, CoachStatus } from "@/lib/coach-types"; + +const button = + "rounded-xl bg-[#0F8F63] px-4 py-2 text-sm font-semibold text-white disabled:opacity-50"; +const field = + "w-full rounded-xl border border-slate-300 bg-white p-3 text-sm text-slate-900"; + +export function WellbeingCoach({ + initial, +}: { + initial: Awaited>; +}) { + const [brief, setBrief] = useState( + initial.ok ? initial.data.brief : null, + ); + const [status, setStatus] = useState( + initial.ok ? initial.data.status : null, + ); + const [notes, setNotes] = useState( + initial.ok ? initial.data.notes : [], + ); + const [messages, setMessages] = useState< + { question: string; reply: CoachReply }[] + >([]); + const [message, setMessage] = useState(""); + const [from, setFrom] = useState(""); + const [to, setTo] = useState(""); + const [note, setNote] = useState(""); + const [confirmNote, setConfirmNote] = useState(false); + const [confirmAi, setConfirmAi] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(initial.ok ? "" : initial.error); + + async function reload() { + const result = await loadCoach(); + if (!result.ok) { + setError(result.error); + return; + } + setStatus(result.data.status); + setBrief(result.data.brief); + setNotes(result.data.notes); + setError(""); + } + async function ask(event: FormEvent) { + event.preventDefault(); + if (busy || !message.trim()) return; + setBusy(true); + setError(""); + try { + const result = await sendCoachMessage({ + message, + previousQuestions: messages.slice(-4).map((m) => m.question), + previousAnswers: messages + .slice(-4) + .map((m) => m.reply.answer.slice(0, 2000)), + ...(from && to ? { from, to } : {}), + }); + if (!result.ok) { + setError(result.error); + return; + } + setMessages((previous) => [ + ...previous.slice(-5), + { question: message, reply: result.data }, + ]); + setMessage(""); + } catch { + setError("Coach unavailable. Please retry."); + } finally { + setBusy(false); + } + } + async function consent(enabled: boolean) { + if (!status) return; + setBusy(true); + try { + const result = await changeCoachConsent(enabled, status.policyVersion); + if (!result.ok) setError(result.error); + else { + setStatus(result.data); + setConfirmAi(false); + if (!enabled) setMessages([]); + } + } catch { + setError("Consent could not be updated. Please retry."); + } finally { + setBusy(false); + } + } + async function remember(event: FormEvent) { + event.preventDefault(); + if (!confirmNote || !note.trim()) return; + setBusy(true); + try { + const result = await saveCoachNote(note, confirmNote); + if (!result.ok) setError(result.error); + else { + setNote(""); + setConfirmNote(false); + await reload(); + } + } catch { + setError("Context could not be saved."); + } finally { + setBusy(false); + } + } + async function forget(id: string) { + setBusy(true); + try { + const result = await removeCoachNote(id); + if (!result.ok) setError(result.error); + else await reload(); + } catch { + setError("Context could not be removed."); + } finally { + setBusy(false); + } + } + + return ( +
+
+
+

+ Daily Wellbeing Brief +

+

+ Your wellbeing, in context +

+
+ + Discuss these signals ↓ + +
+ {!brief && !error && ( +

+ Loading your evidence… +

+ )} + {error && ( +
+ {error}{" "} + +
+ )} + {brief && } + {status && ( +
+ + AI processing & privacy —{" "} + {status.configured && status.consented + ? "enabled" + : "off; evidence-only mode"} + +

{status.notice}

+

+ + Anthropic data controls + {" "} + ·{" "} + + Provider DPA + +

+ {!status.configured && ( +

+ {(status.providerReady ?? status.configured) + ? "AI is paused. You can record consent now; questions remain evidence-only until the local operator enables AI." + : "AI provider is not configured. No data will be sent to an LLM."} +

+ )} + {status.consented ? ( + + ) : ( + <> + + + + )} +
+ )} +
+ {messages.map((entry, i) => ( +
+

You: {entry.question}

+ +
+ ))} + {busy &&

Working with your evidence…

} +
+
+ +