feat(coach): full-history search + pagination; document the labs watchdog

Coach conversation history was capped at the rail's first ~20 threads and
searched only that loaded page. The rail and the standalone conversations
page now walk the caller's entire history via cursor pagination
(useInfiniteQuery + a scroll sentinel), and search runs server-side against
the conversation title (GET /api/insights/chat?q=) instead of filtering an
already-truncated client array.

Also extends the "automatic screening" info line in the metric catalog to
name the labs "what changed since your last panel" card alongside the
rhythm/breathing/health-status watchdogs it already covered — it un-mounts
the same way when there's nothing to flag and was missing from the copy.
This commit is contained in:
Marc-André Bombeck committed 2026-07-18 05:06:24 +02:00
1 parent 8dd04e0170
commit 1a642f1173
20 files changed
+691 -61

No files matched your search

@@ -3,23 +3,46 @@ import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { HistoryRail } from "../history-rail";
import type { CoachConversationsPage } from "@/lib/ai/coach/types";
/**
* v1.4.20 phase B2b — history-rail render snapshot.
* v1.30.2 (QoL H1) — the rail now reads `useCoachConversationHistory`
* (`useInfiniteQuery`), so the seeded cache shape moved from a single
* `CoachConversationsPage` under the flat `coachConversations()` key to the
* `{ pages, pageParams }` infinite-query shape under
* `queryKeys.coachConversationHistory(search)`.
*
* The rail mounts a TanStack Query subscription so we have to wrap it
* in a `<QueryClientProvider>`. We seed the cache with a synthetic
* conversations page so the rail renders the populated state in one
* pass — server-side rendering doesn't drive a real network call.
* in a `<QueryClientProvider>`. We seed the cache with synthetic page(s)
* so the rail renders the populated state in one pass — server-side
* rendering doesn't drive a real network call.
*/
function makeClientWithConversations(page: CoachConversationsPage) {
function makeClientWithConversations(
page: CoachConversationsPage,
search = "",
) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
client.setQueryData(["coachConversations"], page);
client.setQueryData(queryKeys.coachConversationHistory(search), {
pages: [page],
pageParams: [null],
});
return client;
}
function makeClientWithPages(pages: CoachConversationsPage[], search = "") {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
client.setQueryData(queryKeys.coachConversationHistory(search), {
pages,
pageParams: pages.map((_, i) => (i === 0 ? null : `cursor-${i}`)),
});
return client;
}
@@ -152,4 +175,55 @@ describe("<HistoryRail>", () => {
const buttons = html.match(/data-slot="coach-history-delete"/g) ?? [];
expect(buttons.length).toBe(2);
});
// v1.30.2 (QoL H1) — infinite history: reachability beyond the first page.
it("renders every conversation across multiple cached pages (not just page one)", () => {
const client = makeClientWithPages([
samplePage,
{
conversations: [
{
id: "c3",
title: "A much older thread",
createdAt: "2026-01-01T08:00:00.000Z",
updatedAt: "2026-01-01T08:01:00.000Z",
messageCount: 1,
fenced: false,
},
],
nextCursor: null,
},
]);
const html = render(
<HistoryRail activeId={null} onSelect={() => {}} />,
client,
);
const rows = html.match(/data-slot="coach-history-item"/g) ?? [];
expect(rows.length).toBe(3);
expect(html).toContain("A much older thread");
});
it("renders the load-more sentinel when a cached page still carries a nextCursor", () => {
const client = makeClientWithConversations({
...samplePage,
nextCursor: "c2",
});
const html = render(
<HistoryRail activeId={null} onSelect={() => {}} />,
client,
);
// The sentinel div is aria-hidden — IntersectionObserver never fires
// during a static SSR render, but the element itself must be present
// for the rail to ever pull the next page in a real browser.
expect(html).toMatch(/aria-hidden="true"[^>]*class="h-px"/);
});
it("does not render the load-more sentinel once the caller has reached the end", () => {
const client = makeClientWithConversations(samplePage); // nextCursor: null
const html = render(
<HistoryRail activeId={null} onSelect={() => {}} />,
client,
);
expect(html).not.toMatch(/class="h-px"/);
});
});
@@ -1,7 +1,14 @@
"use client";
import { useMemo, useState } from "react";
import { MessagesSquare, Paperclip, Search, Trash2 } from "lucide-react";
import {
Loader2,
MessagesSquare,
Paperclip,
RotateCw,
Search,
Trash2,
} from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
@@ -9,10 +16,12 @@ import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
import { formatRelativeTime } from "@/lib/i18n/relative-time";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { useLoadMoreSentinel } from "@/hooks/use-load-more-sentinel";
import { COACH_SCROLLBAR } from "./message-thread";
import {
useCoachConversations,
useCoachConversationHistory,
useDeleteCoachConversationWithUndo,
} from "./use-coach";
@@ -20,9 +29,10 @@ import {
* v1.4.20 phase B2b — conversation history rail.
*
* Lives in the left column of the Coach drawer on `lg+`. Renders the
* paginated list returned by `GET /api/insights/chat`, lets the user
* filter by title (substring match), select one to resume, and delete
* with a confirm-then-go flow.
* caller's FULL conversation history (v1.30.2 — cursor-paginated via
* `useInfiniteQuery`, loaded incrementally as the list scrolls near its
* end), lets the user search by title (server-side, debounced 200 ms),
* select one to resume, and delete with an undo-able confirm.
*
* Selection / activeId is a controlled prop so the drawer owns the
* authoritative state across the message thread + composer.
@@ -55,17 +65,41 @@ export function HistoryRail({
hideHeading = false,
}: HistoryRailProps) {
const { t } = useTranslations();
const { conversations, isLoading } = useCoachConversations();
const [filter, setFilter] = useState<string>("");
// v1.30.2 (QoL H1) — the search box now drives a SERVER-side query
// (title-only substring, see the route doc comment), so debounce the
// keystroke draft rather than re-issuing a request per character.
const debouncedFilter = useDebouncedValue(filter, 200);
const {
conversations,
isLoading,
isError,
refetch,
hasNextPage,
isFetchingNextPage,
fetchNextPage,
} = useCoachConversationHistory({ search: debouncedFilter });
const { pendingDeleteIds, requestDelete, undoDelete } =
useDeleteCoachConversationWithUndo();
const [filter, setFilter] = useState<string>("");
const filtered = useMemo(() => {
const q = filter.trim().toLowerCase();
const visible = conversations.filter((c) => !pendingDeleteIds.has(c.id));
if (!q) return visible;
return visible.filter((c) => c.title.toLowerCase().includes(q));
}, [conversations, filter, pendingDeleteIds]);
// pendingDeleteIds is a client-only hide filter for the just-armed undo
// window — the server-side search already resolved the rest of `visible`.
const visible = useMemo(
() => conversations.filter((c) => !pendingDeleteIds.has(c.id)),
[conversations, pendingDeleteIds],
);
const isSearching = debouncedFilter.trim().length > 0;
// A `useState`-backed callback ref (not a plain `useRef`) so the
// container's assignment itself triggers a re-render — the sentinel
// hook's effect depends on `root` and must re-run once the real DOM
// node exists (it's null during the very first render pass).
const [listNode, setListNode] = useState<HTMLDivElement | null>(null);
const sentinelRef = useLoadMoreSentinel({
enabled: hasNextPage && !isFetchingNextPage,
onLoadMore: fetchNextPage,
root: listNode,
});
// v1.30.1 M5 — a single tap hides the row and schedules the real
// delete; the toast's Undo action cancels it within the grace
@@ -126,6 +160,7 @@ export function HistoryRail({
/>
</div>
<div
ref={setListNode}
data-slot="coach-history-list"
className={cn(
"-mx-1 flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto px-1",
@@ -133,22 +168,37 @@ export function HistoryRail({
COACH_SCROLLBAR,
)}
>
{isLoading && conversations.length === 0 ? (
{isLoading && visible.length === 0 ? (
<p
data-slot="coach-history-loading"
className="text-muted-foreground px-2 py-3 text-sm"
>
{t("common.loading")}
</p>
) : filtered.length === 0 ? (
) : isError && visible.length === 0 ? (
// A load failure must not masquerade as "no conversations yet" —
// offer a retry instead of the empty copy.
<div
data-slot="coach-history-error"
className="text-muted-foreground flex flex-col items-start gap-2 px-2 py-3 text-sm"
>
<p>{t("common.loadFailed")}</p>
<Button variant="outline" size="sm" onClick={() => refetch()}>
<RotateCw className="size-3.5" aria-hidden="true" />
{t("common.retry")}
</Button>
</div>
) : visible.length === 0 ? (
<p
data-slot="coach-history-empty"
className="text-muted-foreground px-2 py-3 text-sm leading-relaxed"
>
{t("insights.coach.historyEmpty")}
{isSearching
? t("insights.coach.historySearchEmpty")
: t("insights.coach.historyEmpty")}
</p>
) : (
filtered.map((c) => {
visible.map((c) => {
const isActive = c.id === activeId;
return (
<div
@@ -214,6 +264,26 @@ export function HistoryRail({
);
})
)}
{/* v1.30.2 (QoL H1) — IntersectionObserver sentinel: scrolling this
div into the rail's own scrollport pulls the next cursor page.
Empty + aria-hidden — the loading row right below it is the
a11y-visible signal. */}
{visible.length > 0 && hasNextPage ? (
<div ref={sentinelRef} aria-hidden="true" className="h-px" />
) : null}
{isFetchingNextPage ? (
<div
data-slot="coach-history-loading-more"
role="status"
className="text-muted-foreground flex items-center justify-center gap-2 px-2 py-3 text-xs"
>
<Loader2
className="size-3.5 animate-spin motion-reduce:animate-none"
aria-hidden="true"
/>
{t("insights.coach.historyLoadingMore")}
</div>
) : null}
</div>
</div>
);
@@ -1,7 +1,12 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
useInfiniteQuery,
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import type {
CoachConversationAttachmentDTO,
@@ -41,10 +46,13 @@ const QUERY_KEYS = {
};
/**
* List of conversations for the rail. Cursor pagination is exposed via
* `loadMore` — the rail can call it when the user scrolls past the
* end. v1.4.20 lands with default-page-only; cursors are pre-wired so
* v1.4.21 / v1.5 can add infinite scroll without reshaping the hook.
* The single (first) page of conversations. Used ONLY for the
* auto-open-most-recent-thread behaviour on mount
* (`coach-conversation.tsx`), which never needs more than the rail's
* server-authoritative head. Every surface that lets the user BROWSE or
* SEARCH history (the drawer rail, the standalone conversations page) reads
* `useCoachConversationHistory` below instead — it walks the full cursor
* chain via `useInfiniteQuery` rather than stopping at page one.
*/
export function useCoachConversations(enabled = true) {
const query = useQuery({
@@ -67,6 +75,76 @@ export function useCoachConversations(enabled = true) {
};
}
const HISTORY_PAGE_LIMIT = 20;
export interface UseCoachConversationHistoryOptions {
/**
* Server-side title search (see `GET /api/insights/chat?q=`). The caller
* debounces the raw input (`useDebouncedValue`) before passing it here —
* every distinct value keys its own cache page chain, so a fast typist
* never sees a stale search's tail page bleed into a fresh one.
*/
search?: string;
enabled?: boolean;
}
/**
* v1.30.2 (QoL H1) — the full, paginated + server-searched conversation
* history. Replaces the old "first page only, client-side substring
* filter" behaviour: `useInfiniteQuery` walks the cursor chain
* (`nextCursor`) so every conversation the caller has ever had is
* reachable via `fetchNextPage`, and `search` narrows the SERVER'S query
* (title-only — see the route doc comment) rather than filtering an
* already-truncated client array.
*
* Shared by the drawer's `<HistoryRail>` and the standalone
* `/coach/conversations` page so the two surfaces can never drift onto
* different pagination behaviour again.
*/
export function useCoachConversationHistory(
options: UseCoachConversationHistoryOptions = {},
) {
const { search = "", enabled = true } = options;
const trimmedSearch = search.trim();
const query = useInfiniteQuery({
queryKey: queryKeys.coachConversationHistory(trimmedSearch),
queryFn: async ({
pageParam,
}: {
pageParam: string | null;
}): Promise<CoachConversationsPage> => {
const params = new URLSearchParams();
if (pageParam) params.set("cursor", pageParam);
params.set("limit", String(HISTORY_PAGE_LIMIT));
if (trimmedSearch) params.set("q", trimmedSearch);
return apiGet<CoachConversationsPage>(
`/api/insights/chat?${params.toString()}`,
{ headers: { Accept: "application/json" } },
);
},
initialPageParam: null as string | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled,
staleTime: 30 * 1000,
});
const conversations = useMemo(
() => query.data?.pages.flatMap((page) => page.conversations) ?? [],
[query.data],
);
return {
conversations,
isLoading: query.isLoading,
isError: query.isError,
hasNextPage: query.hasNextPage,
isFetchingNextPage: query.isFetchingNextPage,
fetchNextPage: query.fetchNextPage,
refetch: query.refetch,
};
}
/**
* Fetch one conversation with every message decrypted server-side.
* `id === null` disables the query so the drawer can mount without a