mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +00:00
feat(coach): document chats live in the Coach view and history
Asking the Coach about a document opened a separate, half-finished chat panel that never appeared in Coach history. The bespoke drawer is gone; a document conversation now opens the real Coach view, appears in the Coach list with a document badge and a "Chatting about: <title>" note, and is read back through the same history rail as any other thread. The prompt-injection fence is unchanged and stays server-side. A document turn is still sent through the hardened fenced endpoint (no tools, no health snapshot, grounded in the document text only); the coach tool route continues to fetch with documentId null, so a document-scoped conversation can never be continued through the tool loop even from a hostile client. Only the surface moved into the Coach; the boundary did not. The relaxed conversation-list and detail filters drop only the documentId predicate — userId scoping is unchanged, so a document thread is still visible only to its owner. CoachConversationDTO gains documentId + documentTitle (server-derived, title/filename only); no schema change (documentId exists since 0230). OpenAPI regenerated.
This commit is contained in:
1 parent
57539283c8
commit
5b24ca0fa1
28 files changed
+605
-1112
No files matched your search
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import { resolveCoachSendTarget } from "../use-coach";
|
||||
|
||||
/**
|
||||
* v1.28.51 (Documents R3, Design A) — the prompt-injection fence rests on ONE
|
||||
* decision: a document-scoped turn must go to the hardened fenced document
|
||||
* endpoint and NEVER to the full Coach tool route (`/api/insights/chat`, which
|
||||
* injects the health snapshot + runs the write-tool loop). These tests pin that
|
||||
* branch so a regression that routes untrusted document text through the tool
|
||||
* loop fails loudly here.
|
||||
*/
|
||||
describe("resolveCoachSendTarget", () => {
|
||||
it("routes a doc-scoped turn to the fenced document endpoint, never the tool route", () => {
|
||||
const target = resolveCoachSendTarget({
|
||||
conversationId: "conv-1",
|
||||
message: "What does this lab say?",
|
||||
documentId: "doc-abc",
|
||||
// Coach-only fields that MUST NOT influence the fenced path.
|
||||
scope: { sources: ["bp"] },
|
||||
guidedQuestion: "how are you sleeping?",
|
||||
prefill: "seed",
|
||||
});
|
||||
|
||||
expect(target.url).toBe("/api/documents/inbound/doc-abc/chat");
|
||||
// The acceptance criterion above all others: a doc turn never hits the
|
||||
// coach tool route.
|
||||
expect(target.url).not.toBe("/api/insights/chat");
|
||||
expect(target.url).not.toContain("/api/insights/chat");
|
||||
|
||||
const body = JSON.parse(target.body);
|
||||
expect(body).toEqual({
|
||||
conversationId: "conv-1",
|
||||
message: "What does this lab say?",
|
||||
locale: undefined,
|
||||
});
|
||||
// The tool-driving fields are stripped — the fenced endpoint has no tools,
|
||||
// no snapshot, no guided flow.
|
||||
expect(body).not.toHaveProperty("scope");
|
||||
expect(body).not.toHaveProperty("guidedQuestion");
|
||||
expect(body).not.toHaveProperty("prefill");
|
||||
});
|
||||
|
||||
it("URL-encodes the document id in the fenced path", () => {
|
||||
const target = resolveCoachSendTarget({
|
||||
message: "hi",
|
||||
documentId: "doc/../etc",
|
||||
});
|
||||
expect(target.url).toBe("/api/documents/inbound/doc%2F..%2Fetc/chat");
|
||||
});
|
||||
|
||||
it("routes a normal health turn to the Coach tool route", () => {
|
||||
const target = resolveCoachSendTarget({
|
||||
conversationId: "conv-2",
|
||||
message: "How is my BP trending?",
|
||||
scope: { sources: ["bp"] },
|
||||
guidedQuestion: "q",
|
||||
});
|
||||
expect(target.url).toBe("/api/insights/chat");
|
||||
const body = JSON.parse(target.body);
|
||||
expect(body.message).toBe("How is my BP trending?");
|
||||
expect(body.scope).toEqual({ sources: ["bp"] });
|
||||
expect(body.guidedQuestion).toBe("q");
|
||||
});
|
||||
|
||||
it.each([undefined, null, ""])(
|
||||
"treats %p documentId as a normal health turn (tool route)",
|
||||
(documentId) => {
|
||||
const target = resolveCoachSendTarget({
|
||||
message: "hello",
|
||||
documentId: documentId as string | null | undefined,
|
||||
});
|
||||
expect(target.url).toBe("/api/insights/chat");
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { useEffect, useReducer, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Plus, Settings, Sparkles } from "lucide-react";
|
||||
import { FileText, Plus, Settings, Sparkles } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -15,6 +15,7 @@ import { apiDelete, apiGet } from "@/lib/api/api-fetch";
|
||||
import type { CoachScope } from "@/lib/ai/coach/types";
|
||||
import type { CoachLaunchScope } from "@/lib/insights/coach-launch-context";
|
||||
import type { CoachSeededQuestionDTO } from "@/app/api/insights/coach/seeded-question/route";
|
||||
import type { InboundDocumentDetailDto } from "@/lib/validations/inbound-documents";
|
||||
import {
|
||||
metricScopeLabelFallback,
|
||||
scopeSourceMetricLabelKey,
|
||||
@@ -191,6 +192,15 @@ export interface CoachConversationProps {
|
||||
* "new chat" or thread switch is never overridden.
|
||||
*/
|
||||
autoOpenMostRecent?: boolean;
|
||||
/**
|
||||
* v1.28.51 (Documents R3, Design A) — seed a fresh chat SCOPED to a stored
|
||||
* document. The `/coach?doc=<id>` deep-link (the detail sheet's "Ask the
|
||||
* Coach" action) passes it so the first turn is created + sent through the
|
||||
* HARDENED fenced document endpoint, and the scope badge + not-indexed hint
|
||||
* render before anything is typed. Once a thread exists the scope is read
|
||||
* authoritatively from the loaded conversation's `documentId` instead.
|
||||
*/
|
||||
initialDocumentId?: string | null;
|
||||
}
|
||||
|
||||
export function CoachConversation({
|
||||
@@ -208,6 +218,7 @@ export function CoachConversation({
|
||||
surface,
|
||||
initialConversationId,
|
||||
autoOpenMostRecent = false,
|
||||
initialDocumentId,
|
||||
}: CoachConversationProps) {
|
||||
const { t } = useTranslations();
|
||||
const router = useRouter();
|
||||
@@ -259,12 +270,48 @@ export function CoachConversation({
|
||||
});
|
||||
|
||||
const { data: conversation } = useCoachConversation(currentConversationId);
|
||||
|
||||
// v1.28.51 (Documents R3, Design A) — document scope. `pendingDocumentId`
|
||||
// seeds a fresh, not-yet-created chat from the `?doc=<id>` deep-link; once a
|
||||
// thread exists the loaded conversation's own `documentId` is authoritative.
|
||||
// `activeDocumentId` is what drives the send-path branch (fenced document
|
||||
// endpoint vs. Coach tool route) and the scope badge. Cleared whenever the
|
||||
// user starts a new chat or switches threads, so a stale doc scope can never
|
||||
// leak onto a health thread.
|
||||
const [pendingDocumentId, setPendingDocumentId] = useState<string | null>(
|
||||
initialDocumentId ?? null,
|
||||
);
|
||||
const activeDocumentId =
|
||||
conversation?.documentId ?? pendingDocumentId ?? null;
|
||||
|
||||
const send = useSendCoachMessage({
|
||||
onDone: (resolvedId) => {
|
||||
setCurrentConversationId(resolvedId);
|
||||
},
|
||||
});
|
||||
|
||||
// Resolve the document's badge title + indexed status. `documentTitle` on the
|
||||
// loaded conversation covers a persisted thread; the detail fetch covers the
|
||||
// fresh `?doc=` case (no thread yet) AND supplies `hasContentIndex` for the
|
||||
// "read it with AI first" hint (the conversation DTO does not carry it).
|
||||
const { data: docDetail } = useQuery({
|
||||
queryKey: queryKeys.inboundDocument(activeDocumentId ?? "none"),
|
||||
enabled: activeDocumentId !== null,
|
||||
staleTime: 60_000,
|
||||
queryFn: async () =>
|
||||
apiGet<InboundDocumentDetailDto>(
|
||||
`/api/documents/inbound/${activeDocumentId}`,
|
||||
),
|
||||
});
|
||||
const docScopeTitle =
|
||||
conversation?.documentTitle ??
|
||||
docDetail?.title ??
|
||||
docDetail?.filename ??
|
||||
t("documents.card.untitled");
|
||||
// Only warn when we positively know the document is NOT indexed. While the
|
||||
// detail is still loading we say nothing rather than flash a false hint.
|
||||
const docScopeNotIndexed = docDetail ? !docDetail.hasContentIndex : false;
|
||||
|
||||
// v1.18.11 (W11, #67) — auto-open the most-recent conversation when the
|
||||
// surface mounts with no explicit selection. Only fetches the rail list
|
||||
// when the behaviour is requested AND no deep-linked id was supplied, so
|
||||
@@ -325,11 +372,14 @@ export function CoachConversation({
|
||||
: undefined;
|
||||
// v1.16.6 — hand the question to the turn so the Coach reaction is
|
||||
// contextual (the question bubble itself is never persisted).
|
||||
// v1.28.51 — `documentId` routes a doc-scoped turn through the hardened
|
||||
// fenced endpoint (see `resolveCoachSendTarget`); undefined on health chats.
|
||||
const resolvedId = await send.send({
|
||||
conversationId: currentConversationId ?? undefined,
|
||||
message: trimmed,
|
||||
guidedQuestion: guidedQuestion ?? undefined,
|
||||
scope,
|
||||
documentId: activeDocumentId ?? undefined,
|
||||
});
|
||||
if (guidedQuestion !== null && guidedIndex !== null) {
|
||||
setPendingAdopt({
|
||||
@@ -392,6 +442,7 @@ export function CoachConversation({
|
||||
conversationId: currentConversationId ?? undefined,
|
||||
message: trimmed,
|
||||
scope,
|
||||
documentId: activeDocumentId ?? undefined,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -399,6 +450,8 @@ export function CoachConversation({
|
||||
setCurrentConversationId(null);
|
||||
setInputValue("");
|
||||
setPendingAdopt(null);
|
||||
// v1.28.51 — a new chat is always a health thread; drop any document scope.
|
||||
setPendingDocumentId(null);
|
||||
dispatchGuided({ type: "RESET" });
|
||||
send.reset();
|
||||
}
|
||||
@@ -657,6 +710,33 @@ export function CoachConversation({
|
||||
</div>
|
||||
);
|
||||
|
||||
// v1.28.51 (Documents R3, Design A) — the scope banner for a doc-scoped
|
||||
// thread: a small "Document" badge + "Chatting about: <title>", plus the
|
||||
// "read it with AI first" hint when the document is not yet indexed. Rendered
|
||||
// in BOTH surfaces (page + drawer) above the thread so the fenced scope is
|
||||
// always visible. Null on a normal health thread.
|
||||
const docScopeBanner = activeDocumentId ? (
|
||||
<div
|
||||
data-slot="coach-doc-scope"
|
||||
className="border-border/70 bg-muted/20 flex shrink-0 flex-col gap-1 border-b px-4 py-2 sm:px-6"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-2 text-xs">
|
||||
<span className="bg-primary/15 text-primary inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 font-medium">
|
||||
<FileText className="size-3" aria-hidden="true" />
|
||||
{t("insights.coach.docScope.badge")}
|
||||
</span>
|
||||
<span className="text-muted-foreground truncate">
|
||||
{t("insights.coach.docScope.chattingAbout", { title: docScopeTitle })}
|
||||
</span>
|
||||
</div>
|
||||
{docScopeNotIndexed ? (
|
||||
<p className="text-muted-foreground text-[11px] leading-snug">
|
||||
{t("insights.coach.docScope.notIndexedHint")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
// v1.18.11 (W11) — the PAGE surface drops the top header bar and the
|
||||
// rail-tray strip entirely. The composer is the single control hub; the
|
||||
// thread (`[&>*]:max-w-2xl` inner gutter) and the docked composer
|
||||
@@ -671,6 +751,7 @@ export function CoachConversation({
|
||||
data-variant={surface}
|
||||
className={cn("flex min-h-0 flex-1 flex-col", className)}
|
||||
>
|
||||
{docScopeBanner}
|
||||
{/* v1.21.4 (A) — the page-toolbar gear was removed; Settings now lives
|
||||
in the composer's `+` actions menu alongside New chat and
|
||||
Conversations, keeping the page chrome to the composer alone. */}
|
||||
@@ -777,6 +858,8 @@ export function CoachConversation({
|
||||
{trailingHeaderActions}
|
||||
</header>
|
||||
|
||||
{docScopeBanner}
|
||||
|
||||
{/* Drawer surface keeps its existing body chrome: thread + rail-tray
|
||||
strip + docked composer, with the conversation list + sources as
|
||||
mobile trays. The "Conversations" affordance hands off to the
|
||||
@@ -807,6 +890,9 @@ export function CoachConversation({
|
||||
setCurrentConversationId(id);
|
||||
setHistoryTrayOpen(false);
|
||||
setPendingAdopt(null);
|
||||
// v1.28.51 — the selected thread's own `documentId` is now
|
||||
// authoritative; drop any pending `?doc=` seed so it can't leak.
|
||||
setPendingDocumentId(null);
|
||||
dispatchGuided({ type: "RESET" });
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { MessagesSquare, Search, Trash2 } from "lucide-react";
|
||||
import { FileText, MessagesSquare, Search, Trash2 } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
@@ -161,7 +161,18 @@ export function HistoryRail({
|
||||
className="min-w-0 flex-1 truncate text-left"
|
||||
data-slot="coach-history-select"
|
||||
>
|
||||
<span className="block truncate font-medium">{c.title}</span>
|
||||
<span className="flex min-w-0 items-center gap-1.5 font-medium">
|
||||
{/* v1.28.51 — a doc-scoped thread runs on the hardened
|
||||
fenced endpoint; badge it so the two are visibly
|
||||
distinct in the rail. */}
|
||||
{c.documentId ? (
|
||||
<FileText
|
||||
className="text-primary size-3.5 shrink-0"
|
||||
aria-label={t("insights.coach.docScope.badge")}
|
||||
/>
|
||||
) : null}
|
||||
<span className="truncate">{c.title}</span>
|
||||
</span>
|
||||
<span className="text-muted-foreground block text-[11px]">
|
||||
{formatRelativeTime(c.updatedAt, t)}
|
||||
</span>
|
||||
|
||||
@@ -267,6 +267,57 @@ export interface SendCoachMessageParams {
|
||||
* persisted with the message.
|
||||
*/
|
||||
guidedQuestion?: string;
|
||||
/**
|
||||
* v1.28.51 (Documents R3, Design A) — when set, this turn belongs to a
|
||||
* DOCUMENT-scoped conversation. It is sent to the HARDENED fenced document
|
||||
* endpoint (`/api/documents/inbound/<id>/chat`) — no tools, no health
|
||||
* snapshot, fenced doc text — and NEVER to the full Coach tool route. This is
|
||||
* the single branch that keeps untrusted document text off the write tools;
|
||||
* see `resolveCoachSendTarget`.
|
||||
*/
|
||||
documentId?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.28.51 (Documents R3, Design A) — the ONE branch point that decides which
|
||||
* backend a Coach turn hits. When `documentId` is set the turn goes to the
|
||||
* hardened, fenced document chat endpoint; otherwise the normal Coach route
|
||||
* (tool loop + health snapshot). Extracted as a pure function so a unit test
|
||||
* can prove a doc-scoped send never resolves to the tool route — the whole
|
||||
* prompt-injection fence rests on this decision.
|
||||
*/
|
||||
export function resolveCoachSendTarget(params: SendCoachMessageParams): {
|
||||
url: string;
|
||||
body: string;
|
||||
} {
|
||||
const documentId =
|
||||
typeof params.documentId === "string" && params.documentId.length > 0
|
||||
? params.documentId
|
||||
: null;
|
||||
if (documentId) {
|
||||
// Fenced document path. Only the three fields the document route accepts —
|
||||
// NOT `scope` / `guidedQuestion` / `prefill`, which drive the coach's
|
||||
// snapshot + tool behaviour and have no place on the hardened endpoint.
|
||||
return {
|
||||
url: `/api/documents/inbound/${encodeURIComponent(documentId)}/chat`,
|
||||
body: JSON.stringify({
|
||||
conversationId: params.conversationId,
|
||||
message: params.message,
|
||||
locale: params.locale,
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
url: "/api/insights/chat",
|
||||
body: JSON.stringify({
|
||||
conversationId: params.conversationId,
|
||||
message: params.message,
|
||||
prefill: params.prefill,
|
||||
locale: params.locale,
|
||||
scope: params.scope,
|
||||
guidedQuestion: params.guidedQuestion,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export interface UseSendCoachMessageOptions {
|
||||
@@ -362,24 +413,22 @@ export function useSendCoachMessage(opts: UseSendCoachMessageOptions = {}) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// v1.28.51 — resolve the target BEFORE the fetch. A doc-scoped turn
|
||||
// resolves to the hardened fenced document endpoint; everything else to
|
||||
// the Coach tool route. This is the prompt-injection fence's client edge.
|
||||
const target = resolveCoachSendTarget(params);
|
||||
|
||||
// apiFetchRaw: the chat POST streams SSE — the envelope helpers
|
||||
// would buffer and unwrap a body that never carries the envelope.
|
||||
let response: Response;
|
||||
try {
|
||||
response = await apiFetchRaw("/api/insights/chat", {
|
||||
response = await apiFetchRaw(target.url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "text/event-stream",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
conversationId: params.conversationId,
|
||||
message: params.message,
|
||||
prefill: params.prefill,
|
||||
locale: params.locale,
|
||||
scope: params.scope,
|
||||
guidedQuestion: params.guidedQuestion,
|
||||
}),
|
||||
body: target.body,
|
||||
signal: controller.signal,
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
Reference in new issue
Block a user