diff --git a/e2e/ai-optional-overview.spec.ts b/e2e/ai-optional-overview.spec.ts index 69c8bac60..dac4533bd 100644 --- a/e2e/ai-optional-overview.spec.ts +++ b/e2e/ai-optional-overview.spec.ts @@ -6,9 +6,9 @@ * even a hint; not one request goes to a route that calls a model or * serves model text, and no request is answered 403. * J3 — no provider, one could be set up here. Exactly one calm setup hint on - * the overview, no Coach launcher, no per-card "connect a provider" - * state. Dismissing the hint in Settings → AI keeps it gone on the - * overview. + * the overview, no Coach launcher or per-card Coach hand-off, and + * `/coach` goes back to the overview. Dismissing the hint in Settings → + * AI keeps it gone on the overview. * * Both states are served through the `ai` block of `/api/auth/me` * (`serveAiBlock`, which says why): the operator's switches are instance-wide @@ -90,12 +90,13 @@ test.describe("J1: AI switched off by the operator", () => { // Let every section's reads land before judging what painted. await page.waitForLoadState("networkidle"); - await expect( - page.locator('[data-slot="insights-overview-error"]'), - ).toHaveCount(0); + // A read refused for want of AI paints one of these on the overview: + // the section boundary, the error card, or the dense error row. await expect( page.locator('[data-slot="insights-overview-section-error"]'), ).toHaveCount(0); + await expect(page.locator('[data-slot="query-error-card"]')).toHaveCount(0); + await expect(page.locator('[data-slot="query-error-row"]')).toHaveCount(0); await expect(page.locator('[data-slot="chart-error-state"]')).toHaveCount( 0, ); @@ -138,12 +139,17 @@ test.describe("J3: no AI provider", () => { await page.waitForLoadState("networkidle"); await expect(page.locator('[data-slot="coach-fab"]')).toHaveCount(0); await expect(page.locator('[data-slot="daily-briefing"]')).toHaveCount(0); - await expect( - page.locator('[data-slot="insight-status-no-provider-cta"]'), - ).toHaveCount(0); - await expect( - page.locator('[data-slot="daily-briefing-no-provider"]'), - ).toHaveCount(0); + // The per-card Coach hand-offs paint only while the Coach is available. + await expect(page.locator('[data-slot="ask-coach-action"]')).toHaveCount(0); + await expect(page.locator('[data-slot="ask-coach-icon"]')).toHaveCount(0); + await expect(page.locator('[data-slot="coach-launch-inline"]')).toHaveCount( + 0, + ); + + // The Coach page itself answers an unavailable Coach by going back to + // the overview, rather than painting a composer that would be refused. + await page.goto("/coach"); + await expect(page).toHaveURL(/\/insights$/, { timeout: 20_000 }); // Settings → AI carries the same hint; dismissing it there is remembered. await page.goto("/settings/ai"); diff --git a/messages/de.json b/messages/de.json index 68029e2d1..3af8f13ca 100644 --- a/messages/de.json +++ b/messages/de.json @@ -5842,9 +5842,9 @@ "consent": { "title": "KI-Einwilligung", "activeSince": "Erteilt am {date}. Deine Gesundheitsdaten dürfen für die KI-Funktionen an den eingestellten Anbieter gesendet werden.", - "withdrawn": "Widerrufen. Es werden keine Gesundheitsdaten an einen KI-Anbieter gesendet; die KI-Funktionen bleiben aus.", + "withdrawn": "Widerrufen. Sofern keine andere Einwilligung sie abdeckt, nutzen Coach und Insights den KI-Zugang dieses Servers nicht mehr, und kein Online-Modell liest deine Dokumente. Mit deinem eigenen Schlüssel oder einem lokalen Modell laufen Coach und Insights weiter.", "withdraw": "Einwilligung widerrufen", - "confirmBody": "Die KI-Funktionen stoppen sofort, und die Notizen, die ein Modell für dich geschrieben hat, werden gelöscht: Statusnotizen, das tägliche Briefing, von einem Modell geschriebene Zeitraum-Zusammenfassungen, Ankunftszeilen und Trainingsnotizen. Deine Coach-Gespräche, was sich der Coach gemerkt hat, deine Pläne und deine Dokument-Zusammenfassungen bleiben, und du kannst sie selbst lesen oder löschen.", + "confirmBody": "Sofern keine andere Einwilligung sie noch abdeckt, endet sofort: der Coach und die Insights, wo sie den KI-Zugang dieses Servers nutzen, und das Lesen von Dokumenten mit einem Online-Modell. Mit deinem eigenen Schlüssel oder einem lokalen Modell laufen Coach und Insights weiter. Sofern keine andere Einwilligung die Insights noch abdeckt, werden die Notizen gelöscht, die ein Modell für dich geschrieben hat: Statusnotizen, das tägliche Briefing, von einem Modell geschriebene Zeitraum-Zusammenfassungen, Ankunftszeilen und Trainingsnotizen. Deine Coach-Gespräche, was sich der Coach gemerkt hat, deine Pläne und deine Dokument-Zusammenfassungen bleiben, und du kannst sie selbst lesen oder löschen.", "confirmWithdraw": "Widerrufen", "regrantHint": "Mit einer neuen Einwilligung dürfen die KI-Funktionen deine Gesundheitsdaten wieder an den eingestellten Anbieter senden.", "grant": "Einwilligung erteilen", @@ -5867,7 +5867,13 @@ "coachConversations": { "title": "Coach-Gespräche", "description": "Öffne ein Gespräch, um es zu lesen, oder lösche es.", - "more": "Mehr anzeigen" + "more": "Mehr anzeigen", + "openAll": "Alle Gespräche öffnen" + }, + "coachPlans": { + "title": "Coach-Pläne", + "description": "Die Pläne, die du mit dem Coach vereinbart hast, zum Lesen oder Entfernen.", + "open": "Pläne öffnen" } }, "dashboard": { diff --git a/messages/en.json b/messages/en.json index e39c7e57d..9cd82bd03 100644 --- a/messages/en.json +++ b/messages/en.json @@ -5842,9 +5842,9 @@ "consent": { "title": "AI consent", "activeSince": "Given on {date}. Your health data may be sent to the configured provider for the AI features.", - "withdrawn": "Withdrawn. No health data is sent to an AI provider; the AI features stay switched off.", + "withdrawn": "Withdrawn. Unless another consent covers them, the Coach and Insights no longer use the AI access this server provides, and no online model reads your documents. On your own key or a local model, the Coach and Insights keep working.", "withdraw": "Withdraw consent", - "confirmBody": "The AI features stop straight away, and the notes a model wrote for you are deleted: status notes, the daily briefing, model-written period summaries, arrival lines and workout notes. Your Coach conversations, what the Coach remembered, your plans and your document summaries stay, and you can read or delete them yourself.", + "confirmBody": "Unless another consent you gave still covers them, these stop straight away: the Coach and Insights where they use the AI access this server provides, and reading documents with an online model. On your own key or a local model, the Coach and Insights keep working. Unless another consent still covers Insights, the notes a model wrote for you are deleted: status notes, the daily briefing, model-written period summaries, arrival lines and workout notes. Your Coach conversations, what the Coach remembered, your plans and your document summaries stay, and you can read or delete them yourself.", "confirmWithdraw": "Withdraw", "regrantHint": "Granting again lets the AI features send your health data to the configured provider.", "grant": "Grant consent", @@ -5867,7 +5867,13 @@ "coachConversations": { "title": "Coach conversations", "description": "Open a conversation to read it, or delete it.", - "more": "Show more" + "more": "Show more", + "openAll": "Open all conversations" + }, + "coachPlans": { + "title": "Coach plans", + "description": "The plans you agreed with the Coach, to read or remove.", + "open": "Open plans" } }, "dashboard": { diff --git a/messages/es.json b/messages/es.json index 6e86d01ab..b69c2d44f 100644 --- a/messages/es.json +++ b/messages/es.json @@ -5842,9 +5842,9 @@ "consent": { "title": "Consentimiento de IA", "activeSince": "Otorgado el {date}. Tus datos de salud pueden enviarse al proveedor configurado para las funciones de IA.", - "withdrawn": "Retirado. No se envían datos de salud a ningún proveedor de IA; las funciones de IA permanecen desactivadas.", + "withdrawn": "Retirado. Salvo que otro consentimiento lo cubra, el Coach e Insights ya no usan el acceso de IA de este servidor y ningún modelo en línea lee tus documentos. Con tu propia clave o un modelo local, el Coach e Insights siguen funcionando.", "withdraw": "Retirar el consentimiento", - "confirmBody": "Las funciones de IA se detienen de inmediato y se eliminan las notas que un modelo escribió para ti: notas de estado, el resumen diario, los resúmenes de periodo escritos por un modelo, las líneas de llegada y las notas de entrenamiento. Tus conversaciones con el Coach, lo que el Coach recordaba, tus planes y los resúmenes de tus documentos se conservan, y puedes leerlos o eliminarlos tú mismo.", + "confirmBody": "Salvo que otro consentimiento tuyo los siga cubriendo, se detienen de inmediato: el Coach e Insights cuando usan el acceso de IA de este servidor, y la lectura de documentos con un modelo en línea. Con tu propia clave o un modelo local, el Coach e Insights siguen funcionando. Salvo que otro consentimiento siga cubriendo Insights, se eliminan las notas que un modelo escribió para ti: notas de estado, el resumen diario, los resúmenes de periodo escritos por un modelo, las líneas de llegada y las notas de entrenamiento. Tus conversaciones con el Coach, lo que el Coach recordaba, tus planes y los resúmenes de tus documentos se conservan, y puedes leerlos o eliminarlos tú mismo.", "confirmWithdraw": "Retirar", "regrantHint": "Si vuelves a otorgarlo, las funciones de IA podrán enviar de nuevo tus datos de salud al proveedor configurado.", "grant": "Otorgar el consentimiento", @@ -5867,7 +5867,13 @@ "coachConversations": { "title": "Conversaciones con el Coach", "description": "Abre una conversación para leerla o elimínala.", - "more": "Mostrar más" + "more": "Mostrar más", + "openAll": "Abrir todas las conversaciones" + }, + "coachPlans": { + "title": "Planes del Coach", + "description": "Los planes que acordaste con el Coach, para leerlos o eliminarlos.", + "open": "Abrir planes" } }, "dashboard": { diff --git a/messages/fr.json b/messages/fr.json index 9fe90dcb7..e832e094e 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -5842,9 +5842,9 @@ "consent": { "title": "Consentement IA", "activeSince": "Donné le {date}. Tes données de santé peuvent être transmises au fournisseur configuré pour les fonctions IA.", - "withdrawn": "Retiré. Aucune donnée de santé n'est transmise à un fournisseur IA ; les fonctions IA restent désactivées.", + "withdrawn": "Retiré. Sauf si un autre consentement le couvre, le Coach et Insights n'utilisent plus l'accès IA fourni par ce serveur, et aucun modèle en ligne ne lit vos documents. Avec votre propre clé ou un modèle local, le Coach et Insights continuent de fonctionner.", "withdraw": "Retirer le consentement", - "confirmBody": "Les fonctions d'IA s'arrêtent immédiatement et les notes qu'un modèle a écrites pour vous sont supprimées : notes d'état, briefing quotidien, résumés de période écrits par un modèle, lignes d'arrivée et notes d'entraînement. Vos conversations avec le Coach, ce que le Coach a retenu, vos plans et les résumés de vos documents sont conservés, et vous pouvez les lire ou les supprimer vous-même.", + "confirmBody": "Sauf si un autre consentement les couvre encore, ceci s'arrête immédiatement : le Coach et Insights lorsqu'ils utilisent l'accès IA fourni par ce serveur, et la lecture de documents par un modèle en ligne. Avec votre propre clé ou un modèle local, le Coach et Insights continuent de fonctionner. Sauf si un autre consentement couvre encore Insights, les notes qu'un modèle a écrites pour vous sont supprimées : notes d'état, briefing quotidien, résumés de période écrits par un modèle, lignes d'arrivée et notes d'entraînement. Vos conversations avec le Coach, ce que le Coach a retenu, vos plans et les résumés de vos documents sont conservés, et vous pouvez les lire ou les supprimer vous-même.", "confirmWithdraw": "Retirer", "regrantHint": "En le redonnant, les fonctions IA pourront à nouveau transmettre tes données de santé au fournisseur configuré.", "grant": "Donner le consentement", @@ -5867,7 +5867,13 @@ "coachConversations": { "title": "Conversations avec le Coach", "description": "Ouvrez une conversation pour la lire, ou supprimez-la.", - "more": "Afficher plus" + "more": "Afficher plus", + "openAll": "Ouvrir toutes les conversations" + }, + "coachPlans": { + "title": "Plans du Coach", + "description": "Les plans convenus avec le Coach, à lire ou à supprimer.", + "open": "Ouvrir les plans" } }, "dashboard": { diff --git a/messages/it.json b/messages/it.json index f617caf03..237f44644 100644 --- a/messages/it.json +++ b/messages/it.json @@ -5842,9 +5842,9 @@ "consent": { "title": "Consenso IA", "activeSince": "Concesso il {date}. I tuoi dati sanitari possono essere inviati al provider configurato per le funzioni IA.", - "withdrawn": "Revocato. Nessun dato sanitario viene inviato a un provider IA; le funzioni IA restano disattivate.", + "withdrawn": "Revocato. Salvo che un altro consenso lo copra, il Coach e Insights non usano più l'accesso IA fornito da questo server e nessun modello online legge i tuoi documenti. Con la tua chiave o un modello locale, il Coach e Insights continuano a funzionare.", "withdraw": "Revoca il consenso", - "confirmBody": "Le funzioni di IA si fermano subito e le note che un modello ha scritto per te vengono eliminate: note di stato, il riepilogo giornaliero, i riepiloghi di periodo scritti da un modello, le righe di arrivo e le note sugli allenamenti. Le tue conversazioni con il Coach, ciò che il Coach ricordava, i tuoi piani e i riepiloghi dei tuoi documenti restano, e puoi leggerli o eliminarli tu stesso.", + "confirmBody": "Salvo che un altro consenso li copra ancora, si fermano subito: il Coach e Insights quando usano l'accesso IA fornito da questo server, e la lettura dei documenti con un modello online. Con la tua chiave o un modello locale, il Coach e Insights continuano a funzionare. Salvo che un altro consenso copra ancora Insights, le note che un modello ha scritto per te vengono eliminate: note di stato, il riepilogo giornaliero, i riepiloghi di periodo scritti da un modello, le righe di arrivo e le note sugli allenamenti. Le tue conversazioni con il Coach, ciò che il Coach ricordava, i tuoi piani e i riepiloghi dei tuoi documenti restano, e puoi leggerli o eliminarli tu stesso.", "confirmWithdraw": "Revoca", "regrantHint": "Concedendolo di nuovo, le funzioni IA potranno inviare ancora i tuoi dati sanitari al provider configurato.", "grant": "Concedi il consenso", @@ -5867,7 +5867,13 @@ "coachConversations": { "title": "Conversazioni con il Coach", "description": "Apri una conversazione per leggerla oppure eliminala.", - "more": "Mostra altro" + "more": "Mostra altro", + "openAll": "Apri tutte le conversazioni" + }, + "coachPlans": { + "title": "Piani del Coach", + "description": "I piani concordati con il Coach, da leggere o rimuovere.", + "open": "Apri i piani" } }, "dashboard": { diff --git a/messages/ko.json b/messages/ko.json index b03990b57..91b12f477 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -5842,9 +5842,9 @@ "consent": { "title": "AI 동의", "activeSince": "{date}에 동의했어요. AI 기능을 위해 건강 데이터가 설정한 제공자에게 전송될 수 있어요.", - "withdrawn": "동의를 철회했어요. 건강 데이터를 AI 제공자에게 보내지 않고, AI 기능도 꺼진 상태로 유지돼요.", + "withdrawn": "동의를 철회했어요. 다른 동의가 적용되지 않는 한, 코치와 인사이트는 더 이상 이 서버가 제공하는 AI 연결을 사용하지 않고 온라인 모델도 문서를 읽지 않아요. 자신의 키나 로컬 모델을 사용하는 코치와 인사이트는 계속 작동해요.", "withdraw": "동의 철회", - "confirmBody": "AI 기능이 즉시 중지되고 모델이 작성한 메모가 삭제됩니다: 상태 메모, 일일 브리핑, 모델이 작성한 기간 요약, 새 측정값 알림 문장, 운동 메모. 코치 대화, 코치가 기억한 내용, 계획, 문서 요약은 그대로 남으며 직접 읽거나 삭제할 수 있습니다.", + "confirmBody": "다른 동의가 여전히 적용되지 않는 한, 다음이 즉시 중지됩니다: 이 서버가 제공하는 AI 연결을 사용하는 코치와 인사이트, 그리고 온라인 모델을 통한 문서 읽기. 자신의 키나 로컬 모델을 사용하는 코치와 인사이트는 계속 작동합니다. 인사이트에 적용되는 다른 동의가 없으면 모델이 작성한 메모가 삭제됩니다: 상태 메모, 일일 브리핑, 모델이 작성한 기간 요약, 새 측정값 알림 문장, 운동 메모. 코치 대화, 코치가 기억한 내용, 계획, 문서 요약은 그대로 남으며 직접 읽거나 삭제할 수 있습니다.", "confirmWithdraw": "철회", "regrantHint": "다시 동의하면 AI 기능이 건강 데이터를 설정한 제공자에게 보낼 수 있어요.", "grant": "동의하기", @@ -5867,7 +5867,13 @@ "coachConversations": { "title": "코치 대화", "description": "대화를 열어 읽거나 삭제하세요.", - "more": "더 보기" + "more": "더 보기", + "openAll": "모든 대화 열기" + }, + "coachPlans": { + "title": "코치 계획", + "description": "코치와 합의한 계획을 읽거나 삭제할 수 있습니다.", + "open": "계획 열기" } }, "dashboard": { diff --git a/messages/pl.json b/messages/pl.json index d041381ff..ad7f00f51 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -5842,9 +5842,9 @@ "consent": { "title": "Zgoda na AI", "activeSince": "Udzielona {date}. Twoje dane zdrowotne mogą być wysyłane do skonfigurowanego dostawcy na potrzeby funkcji AI.", - "withdrawn": "Wycofana. Żadne dane zdrowotne nie są wysyłane do dostawcy AI; funkcje AI pozostają wyłączone.", + "withdrawn": "Wycofana. Jeśli żadna inna zgoda tego nie obejmuje, Coach i Insights nie korzystają już z dostępu AI zapewnianego przez ten serwer, a żaden model online nie czyta Twoich dokumentów. Na własnym kluczu lub lokalnym modelu Coach i Insights działają dalej.", "withdraw": "Wycofaj zgodę", - "confirmBody": "Funkcje AI zatrzymują się od razu, a notatki napisane dla Ciebie przez model zostają usunięte: notatki o stanie, codzienne podsumowanie, podsumowania okresu napisane przez model, linie po nowym pomiarze i notatki o treningach. Twoje rozmowy z Coachem, to, co zapamiętał Coach, Twoje plany i podsumowania dokumentów zostają, a Ty możesz je sam przeczytać lub usunąć.", + "confirmBody": "Jeśli żadna inna Twoja zgoda ich nie obejmuje, od razu przestają działać: Coach i Insights tam, gdzie korzystają z dostępu AI zapewnianego przez ten serwer, oraz czytanie dokumentów przez model online. Na własnym kluczu lub lokalnym modelu Coach i Insights działają dalej. Jeśli żadna inna zgoda nie obejmuje już Insights, notatki napisane dla Ciebie przez model zostają usunięte: notatki o stanie, codzienne podsumowanie, podsumowania okresu napisane przez model, linie po nowym pomiarze i notatki o treningach. Twoje rozmowy z Coachem, to, co zapamiętał Coach, Twoje plany i podsumowania dokumentów zostają, a Ty możesz je sam przeczytać lub usunąć.", "confirmWithdraw": "Wycofaj", "regrantHint": "Po ponownym udzieleniu zgody funkcje AI znów będą mogły wysyłać Twoje dane zdrowotne do skonfigurowanego dostawcy.", "grant": "Udziel zgody", @@ -5867,7 +5867,13 @@ "coachConversations": { "title": "Rozmowy z Coachem", "description": "Otwórz rozmowę, aby ją przeczytać, albo ją usuń.", - "more": "Pokaż więcej" + "more": "Pokaż więcej", + "openAll": "Otwórz wszystkie rozmowy" + }, + "coachPlans": { + "title": "Plany z Coachem", + "description": "Plany uzgodnione z Coachem, do przeczytania lub usunięcia.", + "open": "Otwórz plany" } }, "dashboard": { diff --git a/src/__tests__/ai-input-invalidation-guard.test.ts b/src/__tests__/ai-input-invalidation-guard.test.ts new file mode 100644 index 000000000..6b890ceed --- /dev/null +++ b/src/__tests__/ai-input-invalidation-guard.test.ts @@ -0,0 +1,120 @@ +/** + * Structural guard: every client write that changes an input of the `ai` + * block on `GET /api/auth/me` evicts it through `aiInputDependentKeys`. + * + * Every AI surface on the web reads its capability from that block. Before + * v1.39 shipped, the provider forms, the Codex sign-in, the fallback chain and + * the central-Codex switch evicted only the provider and insights reads, so a + * freshly configured provider left every AI surface on "not set up" until a + * reload. The fix routes all of them through one bundle; this guard keeps a + * new write site from re-deciding the keys by hand. + * + * The matcher finds write calls (`apiPost/apiPut/apiPatch/apiDelete`, and + * `apiFetch`/`apiFetchRaw` with a write method) whose literal path names one + * of the endpoints below, and asserts the file calls + * `invalidateKeys(, aiInputDependentKeys)`. A tripwire, not a proof: + * it holds the file, not each mutation in it (one mutation can branch over + * two endpoints and evict once), and a path built at runtime would slip the + * matcher, which is why the matched total carries a floor and an empty sweep + * fails. + */ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { aiInputDependentKeys, queryKeys } from "@/lib/query-keys"; + +import { walkSourceFiles } from "./helpers/source-files"; + +const SRC = join(process.cwd(), "src"); + +/** + * The endpoints whose writes change an input of the capability answer. + * Starting a device sign-in changes nothing until the poll reports success, + * so the `device-start` legs are not listed. + */ +const AI_INPUT_ENDPOINTS = [ + "/api/user/ai-provider", + "/api/insights/provider-chain", + "/api/auth/codex/device-poll", + "/api/auth/codex/disconnect", + "/api/auth/me/use-central-codex", + "/api/auth/me/labs-local-ocr", + "/api/consent/ai", + "/api/auth/me/modules", + "/api/auth/me/disable-coach", + "/api/admin/ai-settings", + "/api/admin/settings/assistant-flags", + "/api/admin/settings/module-availability", + "/api/admin/central-codex/device-poll", + "/api/admin/central-codex", + // A managed record's modules / coach / profile families, written by the + // guardian from inside that record. + "/api/record-settings", +] as const; + +const HELPER_WRITE = + /\bapi(?:Post|Put|Patch|Delete)\s*(?:<[^()]*?>)?\s*\(\s*["'`](\/api\/[^"'`?]+)/g; +const RAW_WRITE = + /\bapiFetch(?:Raw)?\s*(?:<[^()]*?>)?\s*\(\s*["'`](\/api\/[^"'`?]+)[^"'`]*["'`]\s*,\s*\{[^}]*?\bmethod:\s*["'](?:POST|PUT|PATCH|DELETE)["']/g; +const BUNDLE_CALL = + /\binvalidateKeys\(\s*[A-Za-z_]\w*\s*,\s*aiInputDependentKeys\b/g; + +function isAiInputEndpoint(path: string): boolean { + if (path.endsWith("/device-start")) return false; + return AI_INPUT_ENDPOINTS.some((e) => path === e || path.startsWith(`${e}/`)); +} + +function inScope(rel: string): boolean { + if (rel.includes("__tests__") || /\.test\.tsx?$/.test(rel)) return false; + if (rel.startsWith("app/api/") || rel.startsWith("generated/")) return false; + return ( + rel.startsWith("components/") || + rel.startsWith("hooks/") || + rel.startsWith("app/") + ); +} + +function writeSites(source: string): string[] { + const out: string[] = []; + for (const re of [HELPER_WRITE, RAW_WRITE]) { + for (const m of source.matchAll(re)) { + if (isAiInputEndpoint(m[1]!)) out.push(m[1]!); + } + } + return out; +} + +const files = walkSourceFiles(SRC, { floor: 3000 }).filter(inScope); +const sites = files + .map((rel) => { + const source = readFileSync(join(SRC, rel), "utf8"); + return { + rel, + writes: writeSites(source), + bundleCalls: [...source.matchAll(BUNDLE_CALL)].length, + }; + }) + .filter((s) => s.writes.length > 0); + +describe("AI-input writes evict the capability answer", () => { + it("the bundle carries the account payload every AI surface reads", () => { + expect(aiInputDependentKeys).toContainEqual(queryKeys.authMe()); + }); + + it("finds the write sites it is meant to hold (an empty sweep is a broken matcher)", () => { + const total = sites.reduce((n, s) => n + s.writes.length, 0); + expect(sites.length).toBeGreaterThanOrEqual(21); + expect(total).toBeGreaterThanOrEqual(22); + }); + + it.each(sites.map((s) => [s.rel, s] as const))( + "%s invalidates aiInputDependentKeys", + (_rel, site) => { + expect( + site.bundleCalls, + `writes to ${site.writes.join(", ")}`, + ).toBeGreaterThanOrEqual(1); + }, + ); +}); diff --git a/src/__tests__/copy-matches-behaviour-guard.test.ts b/src/__tests__/copy-matches-behaviour-guard.test.ts index b656cda6a..13a0e554f 100644 --- a/src/__tests__/copy-matches-behaviour-guard.test.ts +++ b/src/__tests__/copy-matches-behaviour-guard.test.ts @@ -39,6 +39,8 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; +import { consentNeededForProviders } from "@/lib/ai/capabilities/resolve"; + const MESSAGES = join(__dirname, "../../messages"); const LOCALES = ["de", "en", "es", "fr", "it", "pl", "ko"] as const; @@ -417,3 +419,51 @@ describe("the MCP token copy never claims the mint is read-only", () => { }); } }); + +/** + * 5. AI CONSENT WITHDRAWAL. The confirmation said "the AI features stop + * straight away" and the withdrawn line said no health data goes to an AI + * provider any more. Neither holds: the Coach and Insights need the + * receipt only when they use the AI access the server provides (the + * operator's key or connection), so on the person's own key or a local + * model they keep working; and the deletion of model-written notes is + * skipped while another receipt still covers Insights. The copy now names + * both conditions. The behaviour half is pinned against the resolver, so a + * change to who needs the receipt fails here next to the copy it would + * falsify. + */ +describe("AI consent withdrawal copy matches what withdrawing does", () => { + it("the Coach and Insights need no receipt on an own key or a local model", () => { + for (const key of ["coach", "briefing", "statusText"] as const) { + expect(consentNeededForProviders(key, ["openai"])).toBe(false); + expect(consentNeededForProviders(key, ["local"])).toBe(false); + expect(consentNeededForProviders(key, ["admin-openai"])).toBe(true); + } + }); + + /** Per locale: a phrase naming the own key, and one naming a local model. */ + const OWN_PROVIDER: Record = { + en: ["own key", "local model"], + de: ["eigenen schlüssel", "lokalen modell"], + es: ["tu propia clave", "modelo local"], + fr: ["votre propre clé", "modèle local"], + it: ["tua chiave", "modello locale"], + pl: ["własnym kluczu", "lokalnym modelu"], + ko: ["자신의 키", "로컬 모델"], + }; + + for (const locale of LOCALES) { + it(`${locale} says what keeps working and when the notes stay`, () => { + const b = bundle(locale); + for (const path of [ + "settings.ai.consent.confirmBody", + "settings.ai.consent.withdrawn", + ]) { + const copy = resolve(b, path).toLowerCase(); + for (const phrase of OWN_PROVIDER[locale]) { + expect(copy, `${locale} ${path}`).toContain(phrase); + } + } + }); + } +}); diff --git a/src/app/insights/page-client.tsx b/src/app/insights/page-client.tsx index 78288637f..44f946c30 100644 --- a/src/app/insights/page-client.tsx +++ b/src/app/insights/page-client.tsx @@ -32,7 +32,7 @@ import { HeroStrip } from "@/components/insights/hero-strip"; import { AiSetupHint } from "@/components/insights/ai-setup-hint"; import { OverviewSectionBoundary } from "@/components/insights/overview-section-boundary"; import { isSurfaceVisible } from "@/lib/modules/surface"; -import { useCycleRingHasDial } from "@/components/cycle/use-cycle"; +import { useCycleRingDial } from "@/components/cycle/use-cycle"; import { useInsightsAdvisorQuery } from "@/components/insights/use-insights-advisor"; import { useAnalyticsQuery } from "@/lib/queries/use-analytics-query"; import { useDashboardSnapshot } from "@/lib/queries/use-dashboard-snapshot"; @@ -373,9 +373,10 @@ export default function InsightsPageClient() { "overview:cycle-ring", user?.modules, ); - const cycleRingDial = useCycleRingHasDial( - isAuthenticated && cycleRingVisible, - ); + // Until that read answers the strip keeps its skeleton, so it never paints + // Strain first and swaps it for the ring when the calendar lands. + const cycleRing = useCycleRingDial(isAuthenticated && cycleRingVisible); + const cycleRingDial = cycleRing.dial; // A failed comprehensive read no longer replaces the page. The payload only // decides the "no data yet" empty state below; every section on the page @@ -467,7 +468,7 @@ export default function InsightsPageClient() { "wellness-scores": ( { diff --git a/src/components/admin/assistant-section.tsx b/src/components/admin/assistant-section.tsx index 6181a04ed..11872bbb9 100644 --- a/src/components/admin/assistant-section.tsx +++ b/src/components/admin/assistant-section.tsx @@ -7,7 +7,11 @@ import { toast } from "sonner"; import { SettingsCard } from "@/components/settings/settings-card"; import { SettingsCardHeader } from "@/components/settings/_card-header"; import { useTranslations } from "@/lib/i18n/context"; -import { queryKeys } from "@/lib/query-keys"; +import { + aiInputDependentKeys, + invalidateKeys, + queryKeys, +} from "@/lib/query-keys"; import { SettingsToggle } from "./_shared"; import { apiGet, apiPut } from "@/lib/api/api-fetch"; @@ -74,7 +78,7 @@ function useUpdateAssistantFlags() { // Every record's resolved AI capabilities ride the account payload, // which is the only thing the web reads them from; bust it so the // operator sees the change within the session. - client.invalidateQueries({ queryKey: queryKeys.authMe() }); + void invalidateKeys(client, aiInputDependentKeys); toast.success(t("common.saved")); }, onError: (err) => { diff --git a/src/components/admin/central-codex-section.tsx b/src/components/admin/central-codex-section.tsx index 68b582074..f79daedf4 100644 --- a/src/components/admin/central-codex-section.tsx +++ b/src/components/admin/central-codex-section.tsx @@ -30,7 +30,11 @@ import { SettingsCardHeader } from "@/components/settings/_card-header"; import { apiFetchRaw, apiGet } from "@/lib/api/api-fetch"; import { formatDateTime } from "@/lib/format"; import { useTranslations } from "@/lib/i18n/context"; -import { queryKeys } from "@/lib/query-keys"; +import { + aiInputDependentKeys, + invalidateKeys, + queryKeys, +} from "@/lib/query-keys"; interface CentralCodexStatus { status: string; @@ -100,6 +104,7 @@ export function CentralCodexSection() { queryClient.invalidateQueries({ queryKey: queryKeys.adminCentralCodex(), }); + void invalidateKeys(queryClient, aiInputDependentKeys); return; } if (!cancelled) setTimeout(tick, intervalMs); @@ -135,6 +140,7 @@ export function CentralCodexSection() { queryClient.invalidateQueries({ queryKey: queryKeys.adminCentralCodex(), }); + void invalidateKeys(queryClient, aiInputDependentKeys); } catch (err) { toast.error( err instanceof Error ? err.message : t("admin.centralCodex.error"), diff --git a/src/components/admin/module-availability-section.tsx b/src/components/admin/module-availability-section.tsx index 7e1f8513a..91648eb22 100644 --- a/src/components/admin/module-availability-section.tsx +++ b/src/components/admin/module-availability-section.tsx @@ -8,7 +8,11 @@ import { toast } from "sonner"; import { SettingsCard } from "@/components/settings/settings-card"; import { SettingsCardHeader } from "@/components/settings/_card-header"; import { useTranslations } from "@/lib/i18n/context"; -import { queryKeys } from "@/lib/query-keys"; +import { + aiInputDependentKeys, + invalidateKeys, + queryKeys, +} from "@/lib/query-keys"; import { MODULE_KEYS, MODULE_REGISTRY, @@ -66,7 +70,7 @@ function useUpdateModuleAvailability() { client.setQueryData(queryKeys.adminModuleAvailability(), data); // The resolved `/api/auth/me` module map depends on this operator // layer; bust it so the operator sees the change within the session. - client.invalidateQueries({ queryKey: queryKeys.authMe() }); + void invalidateKeys(client, aiInputDependentKeys); toast.success(t("common.saved")); }, onError: (err) => { diff --git a/src/components/cycle/__tests__/use-cycle-ring-has-dial.test.tsx b/src/components/cycle/__tests__/use-cycle-ring-has-dial.test.tsx index b0b036a09..8d1e24b97 100644 --- a/src/components/cycle/__tests__/use-cycle-ring-has-dial.test.tsx +++ b/src/components/cycle/__tests__/use-cycle-ring-has-dial.test.tsx @@ -2,14 +2,20 @@ * The scores strip gives the cycle ring a cell only when the ring would draw * a dial. The ring renders nothing without an active cycle, and a cell * reserved for it (with Strain dropped to make room) sat empty in the row. + * + * The decision waits on the calendar read, so the hook also says when it is + * still pending: the strip holds its skeleton until then instead of painting + * Strain and swapping it for the ring a moment later. */ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { renderToStaticMarkup } from "react-dom/server"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { describe, expect, it } from "vitest"; import { queryKeys } from "@/lib/query-keys"; -import { localYmd, useCycleRingHasDial } from "../use-cycle"; +import { localYmd, useCycleRingDial } from "../use-cycle"; function window(): [string, string] { const from = new Date(); @@ -20,34 +26,56 @@ function window(): [string, string] { } function Probe({ enabled }: { enabled: boolean }) { - return {String(useCycleRingHasDial(enabled))}; + const { dial, pending } = useCycleRingDial(enabled); + return {`${dial}:${pending}`}; } -function hasDial(verdict: unknown, enabled = true): boolean { +function probe(verdict: unknown | undefined, enabled = true): string { const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: 0 } }, }); const [from, to] = window(); - client.setQueryData(queryKeys.cycleCalendar(from, to), { verdict }); + if (verdict !== undefined) { + client.setQueryData(queryKeys.cycleCalendar(from, to), { verdict }); + } const html = renderToStaticMarkup( , ); - return html === "true"; + return html.replace(/<\/?span>/g, ""); } -describe("useCycleRingHasDial", () => { - it("is true while a cycle is active today", () => { - expect(hasDial({ phase: "follicular", dayOfCycle: 6 })).toBe(true); +describe("useCycleRingDial", () => { + it("has a dial while a cycle is active today", () => { + expect(probe({ phase: "follicular", dayOfCycle: 6 })).toBe("true:false"); }); - it("is false without an active cycle, so no empty cell is reserved", () => { - expect(hasDial({ phase: null, dayOfCycle: null })).toBe(false); - expect(hasDial(null)).toBe(false); + it("has none without an active cycle, so no empty cell is reserved", () => { + expect(probe({ phase: null, dayOfCycle: null })).toBe("false:false"); + expect(probe(null)).toBe("false:false"); }); - it("is false while the cycle surface is hidden", () => { - expect(hasDial({ phase: "luteal", dayOfCycle: 20 }, false)).toBe(false); + it("has none, and is not pending, while the cycle surface is hidden", () => { + expect(probe({ phase: "luteal", dayOfCycle: 20 }, false)).toBe( + "false:false", + ); + expect(probe(undefined, false)).toBe("false:false"); + }); + + it("is pending until the calendar read lands", () => { + expect(probe(undefined)).toBe("false:true"); + }); +}); + +describe("the scores strip waits for the ring's decision", () => { + it("holds its skeleton while the decision is pending", () => { + const source = readFileSync( + join(process.cwd(), "src/app/insights/page-client.tsx"), + "utf8", + ); + expect(source).toMatch( + /isLoading=\{\s*dashboardDerived\.isLoading\s*\|\|\s*cycleRing\.pending\s*\}/, + ); }); }); diff --git a/src/components/cycle/use-cycle.ts b/src/components/cycle/use-cycle.ts index 39b2d0684..1377d3ffd 100644 --- a/src/components/cycle/use-cycle.ts +++ b/src/components/cycle/use-cycle.ts @@ -130,15 +130,23 @@ export function useCycleRingCalendar(enabled = true) { } /** - * Whether the cycle ring would draw a dial today. The wellness strip asks - * this before it gives the ring a cell (and takes Strain's place for it): the - * ring renders nothing without an active cycle, and a cell reserved for it - * would sit empty in the row. + * Whether the cycle ring would draw a dial today, and whether that is still + * unknown. The wellness strip asks this before it gives the ring a cell (and + * takes Strain's place for it): the ring renders nothing without an active + * cycle, and a cell reserved for it would sit empty in the row. While the + * calendar read is `pending` the strip holds its skeleton, so it never paints + * Strain and then swaps it for the ring. A failed read settles to no dial. */ -export function useCycleRingHasDial(enabled: boolean): boolean { +export function useCycleRingDial(enabled: boolean): { + dial: boolean; + pending: boolean; +} { const calendar = useCycleRingCalendar(enabled); const verdict = calendar.data?.verdict; - return enabled && verdict?.phase != null && verdict.dayOfCycle != null; + return { + dial: enabled && verdict?.phase != null && verdict.dayOfCycle != null, + pending: enabled && calendar.isPending, + }; } export function useCycleHistory(limit = 24) { diff --git a/src/components/documents/__tests__/document-record-links.test.tsx b/src/components/documents/__tests__/document-record-links.test.tsx index c93b34c62..d06b0653e 100644 --- a/src/components/documents/__tests__/document-record-links.test.tsx +++ b/src/components/documents/__tests__/document-record-links.test.tsx @@ -103,7 +103,12 @@ describe("recordOptions", () => { describe("", () => { it("lets a manager link the page to doses and visits", () => { const html = render( - undefined} />, + undefined} + />, ); expect(html).toContain('data-slot="document-vaccination-links"'); expect(html).toContain('data-slot="document-vaccination-links-add"'); @@ -124,6 +129,7 @@ describe("", () => { ], })} canManage={false} + seedFresh onChange={() => undefined} />, ); @@ -137,9 +143,26 @@ describe("", () => { undefined} />, ); expect(html).not.toContain("document-vaccination-links"); }); + + it("offers no picker until the document has been read since the sheet opened", () => { + // Each change is a replace-set write seeded from the document's links. + // Seeded from a cached copy that predates a link made on the dose's or + // the visit's own form, the first tap would silently delete that link. + const html = render( + undefined} + />, + ); + expect(html).not.toContain('data-slot="document-vaccination-links-add"'); + expect(html).not.toContain('data-slot="document-visit-links-add"'); + }); }); diff --git a/src/components/documents/document-detail-sheet.tsx b/src/components/documents/document-detail-sheet.tsx index c1b216982..780105bfa 100644 --- a/src/components/documents/document-detail-sheet.tsx +++ b/src/components/documents/document-detail-sheet.tsx @@ -353,11 +353,30 @@ export function DocumentDetailSheet({ const detail = useQuery({ queryKey: queryKeys.inboundDocument(documentId ?? "none"), enabled: open && documentId !== null, + // Always read again on open: the link pickers below write replace-sets + // seeded from this copy (see `seedFresh`). + staleTime: 0, queryFn: () => apiGet(`/api/documents/inbound/${documentId}`), }); const doc = detail.data; + // The detail's timestamp when the sheet opened on this document. A read + // that lands after it is fresh enough to seed the link pickers from; a + // cached copy from before the sheet opened is not. + const [openedOn, setOpenedOn] = useState<{ + id: string; + seenAt: number; + } | null>(null); + const openKey = open && documentId !== null ? documentId : null; + if (openKey !== (openedOn?.id ?? null)) { + setOpenedOn( + openKey === null ? null : { id: openKey, seenAt: detail.dataUpdatedAt }, + ); + } + const linkSeedFresh = + openedOn !== null && detail.dataUpdatedAt > openedOn.seenAt; + // 2026-07-17 UX/IA audit M5 / F5-5 — the document → lab-values direction // had no UI link at all: an auto-staged (PENDING) or OCR-confirmed // (APPROVED, see `linkOcrLabsToVaultDocument`) OBSERVATION fact already @@ -1111,6 +1130,9 @@ export function DocumentDetailSheet({ key={`${doc.id}:${linkResets}`} doc={doc} canManage={canManageDocuments} + seedFresh={linkSeedFresh} + seedError={!linkSeedFresh && detail.isRefetchError} + onRetrySeed={() => void detail.refetch()} onChange={(part) => patch.mutate(part)} /> diff --git a/src/components/documents/document-record-links.tsx b/src/components/documents/document-record-links.tsx index 7899443c2..cbf9e0b0a 100644 --- a/src/components/documents/document-record-links.tsx +++ b/src/components/documents/document-record-links.tsx @@ -91,10 +91,24 @@ function doseName( export function DocumentRecordLinks({ doc, canManage, + seedFresh, + seedError = false, + onRetrySeed, onChange, }: { doc: InboundDocumentDetailDto; canManage: boolean; + /** + * Whether `doc` was read from the server since the sheet opened. Every + * change is a replace-set write seeded from `doc`'s links, so a seed from a + * cached copy that predates a link made on the dose's or the visit's own + * form would delete that link on the first tap. The pickers wait for a + * fresh read instead. + */ + seedFresh: boolean; + /** That fresh read failed; the pickers show the retry row instead. */ + seedError?: boolean; + onRetrySeed?: () => void; onChange: (part: { encounterIds?: string[]; vaccinationIds?: string[]; @@ -155,10 +169,13 @@ export function DocumentRecordLinks({ icon={CalendarDays} title={t("documents.detail.visitsLabel")} slot="document-visit-links" - pending={encounters.isPending} - error={encounters.isError} + pending={encounters.isPending || !seedFresh} + error={encounters.isError || seedError} errorLabel={t("links.picker.loadError")} - onRetry={() => void encounters.refetch()} + onRetry={() => { + if (encounters.isError) void encounters.refetch(); + if (seedError) onRetrySeed?.(); + }} selected={visitIds ?? doc.encounterLinks.map((l) => l.encounterId)} onChange={(ids) => { setVisitIds(ids); @@ -199,10 +216,13 @@ export function DocumentRecordLinks({ icon={Syringe} title={t("documents.detail.vaccinationsLabel")} slot="document-vaccination-links" - pending={vaccinations.isPending} - error={vaccinations.isError} + pending={vaccinations.isPending || !seedFresh} + error={vaccinations.isError || seedError} errorLabel={t("links.picker.loadError")} - onRetry={() => void vaccinations.refetch()} + onRetry={() => { + if (vaccinations.isError) void vaccinations.refetch(); + if (seedError) onRetrySeed?.(); + }} selected={ doseIds ?? (doc.vaccinationLinks ?? []).map((link) => link.vaccinationId) diff --git a/src/components/encounters/encounter-link-pickers.tsx b/src/components/encounters/encounter-link-pickers.tsx index f215f2410..dcdbea60f 100644 --- a/src/components/encounters/encounter-link-pickers.tsx +++ b/src/components/encounters/encounter-link-pickers.tsx @@ -87,14 +87,7 @@ export function EncounterLinkPickers({ }); const labs = useQuery({ - queryKey: queryKeys.labResultsList({ - analyte: undefined, - panel: undefined, - from: undefined, - to: undefined, - page: 0, - sortDir: "desc", - }), + queryKey: queryKeys.labResultsPicker(PICKER_FETCH_LIMIT), enabled: labsOn, queryFn: () => apiGet( @@ -103,7 +96,7 @@ export function EncounterLinkPickers({ }); const episodes = useQuery({ - queryKey: queryKeys.illnessEpisodes(true), + queryKey: queryKeys.illnessEpisodesPicker(EPISODE_FETCH_LIMIT), enabled: illnessOn, queryFn: () => apiGet( diff --git a/src/components/insights/__tests__/ai-setup-hint-target.test.tsx b/src/components/insights/__tests__/ai-setup-hint-target.test.tsx new file mode 100644 index 000000000..6e06357f6 --- /dev/null +++ b/src/components/insights/__tests__/ai-setup-hint-target.test.tsx @@ -0,0 +1,48 @@ +/** + * The overview's setup hint closes with an icon button in its header. On a + * phone it is the only control on the tile a thumb has to hit, so it carries + * the 44 px floor every other mobile action does (`size-11`), stepping down + * from `sm` like the rest of the app. + */ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; + +vi.mock("@/hooks/use-auth", () => ({ + useAuth: () => ({ user: { id: "u1" }, isAuthenticated: true }), +})); +vi.mock("@/hooks/use-mounted", () => ({ useMounted: () => true })); +vi.mock("@/hooks/use-ai-capability", () => ({ + useAiProviderState: () => ({ + configured: false, + managedBy: null, + canConfigure: true, + }), +})); + +import { I18nProvider } from "@/lib/i18n/context"; +import { AiSetupHint } from "../ai-setup-hint"; + +function dismissButton(): string { + vi.stubGlobal("window", { + localStorage: { getItem: () => null, setItem: () => undefined }, + }); + const html = renderToStaticMarkup( + + + , + ); + vi.unstubAllGlobals(); + const match = html.match( + /]*data-slot="ai-setup-hint-dismiss"[^>]*>/, + ); + expect(match).not.toBeNull(); + return match![0]; +} + +describe("the setup hint's dismiss button", () => { + it("is at least 44 px on a phone", () => { + const button = dismissButton(); + const cls = button.match(/class="([^"]*)"/)![1]!.split(/\s+/); + expect(cls).toContain("size-11"); + }); +}); diff --git a/src/components/insights/ai-setup-hint.tsx b/src/components/insights/ai-setup-hint.tsx index 6e6ea316c..cf4f3e008 100644 --- a/src/components/insights/ai-setup-hint.tsx +++ b/src/components/insights/ai-setup-hint.tsx @@ -115,7 +115,9 @@ export function AiSetupHint({ aria-label={t("insights.aiSetupHint.dismiss")} title={t("insights.aiSetupHint.dismiss")} data-slot="ai-setup-hint-dismiss" - className="-my-2 shrink-0" + // 44 px on a phone like every other mobile action; the negative + // margin keeps the header row as tall as the title needs. + className="-my-2.5 size-11 shrink-0 sm:-my-2 sm:size-10" >