🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(topics): add filter and search bar for topic traces (#18662)
Nimar86bce8d8a16c
diff --git a/web/AGENTS.md b/web/AGENTS.mdindex d3e41d396a..907eabc1ba 100644--- a/web/AGENTS.md+++ b/web/AGENTS.md@@ -359,7 +359,7 @@ Sentry instrumentation skill first and decide whether it should capture at all<!-- BEGIN:nextjs-agent-rules -->-# This is NOT the Next.js you know+## This is NOT the Next.js you knowThis version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.diff --git a/web/src/components/table/data-table-pagination.tsx b/web/src/components/table/data-table-pagination.tsxindex 8a046c709a..af7621e3ab 100644--- a/web/src/components/table/data-table-pagination.tsx+++ b/web/src/components/table/data-table-pagination.tsx@@ -36,6 +36,7 @@ interface DataTablePaginationProps<TData> {paginationOptions?: number[];hideTotalCount?: boolean;canJumpPages?: boolean; // if we need a cursor (last_item_id), we can't jump pages+ resultCountLabel?: string;// Approx count for the "Total" footer; undefined = no footer (opt-in).approxTotalCount?: number | null;isApproxTotalCountLoading?: boolean;@@ -51,6 +52,7 @@ export function DataTablePagination<TData>({paginationOptions = [10, 20, 30, 40, 50],hideTotalCount = false,canJumpPages = true,+ resultCountLabel,approxTotalCount,isApproxTotalCountLoading = false,approxTotalCountIsPartialScope = false,@@ -122,8 +124,16 @@ export function DataTablePagination<TData>({"text-muted-foreground hidden text-sm font-normal whitespace-nowrap @min-[640px]/pagination:inline-flex @min-[640px]/pagination:items-center";return (- <div className="@container/pagination flex w-full min-w-0 items-center justify-end">- <div className="flex min-w-0 flex-wrap items-center justify-end gap-x-4 gap-y-2 @min-[520px]/pagination:gap-x-6 @min-[720px]/pagination:gap-x-8">+ <div className="@container/pagination flex w-full min-w-0 items-center justify-end gap-4">+ {resultCountLabel && (+ <span+ className="text-muted-foreground shrink-0 pl-2 text-xs font-normal"+ role="status"+ >+ {resultCountLabel}+ </span>+ )}+ <div className="flex min-w-0 flex-1 flex-wrap items-center justify-end gap-x-4 gap-y-2 @min-[520px]/pagination:gap-x-6 @min-[720px]/pagination:gap-x-8">{showExactTotal ? (// Result fits on the loaded page(s) — the total is exact, no estimate.<span className={totalCountClassName}>diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsxindex 6b18e345c4..a13944199c 100644--- a/web/src/components/table/data-table.tsx+++ b/web/src/components/table/data-table.tsx@@ -99,6 +99,8 @@ interface DataTableProps<TData, TValue> {options?: number[];hideTotalCount?: boolean;canJumpPages?: boolean;+ /** Result summary shown to the left of the pagination controls. */+ resultCountLabel?: string;/*** Approximate row/entity count matching the active filters. Rendered near* the pagination controls, but ONLY when the result set spans more than one@@ -775,6 +777,7 @@ export function DataTable<TData extends object, TValue>({paginationOptions={pagination.options}hideTotalCount={pagination.hideTotalCount}canJumpPages={pagination.canJumpPages}+ resultCountLabel={pagination.resultCountLabel}approxTotalCount={pagination.approxTotalCount}isApproxTotalCountLoading={pagination.isApproxTotalCountLoading}approxTotalCountIsPartialScope={diff --git a/web/src/features/search-bar/lib/fields.ts b/web/src/features/search-bar/lib/fields.tsindex 29445fc04f..0d5008dfe3 100644--- a/web/src/features/search-bar/lib/fields.ts+++ b/web/src/features/search-bar/lib/fields.ts@@ -96,6 +96,7 @@ export type FieldRegistry = {| "evalLogs"| "prompts"| "skills"+ | "topics"| "monitors"| "gatewayModels"| "experimentItems"diff --git a/web/src/features/topics/CurrentTopics.tsx b/web/src/features/topics/CurrentTopics.tsxindex 358b4228ac..04bd4b6f70 100644--- a/web/src/features/topics/CurrentTopics.tsx+++ b/web/src/features/topics/CurrentTopics.tsx@@ -1,29 +1,16 @@import type { TopicTimeRange } from "@langfuse/shared/topics";import { Alert } from "@/src/components/design-system/Alert/Alert";-import { useState, type MouseEvent } from "react";-import { useMediaQuery } from "react-responsive";import { cn } from "@/src/utils/tailwind";-import { type OnChangeFn, type PaginationState } from "@tanstack/react-table";import { keepPreviousData, useQuery } from "@tanstack/react-query";import { getQueryKey } from "@trpc/react-query";-import { DataTable } from "@/src/components/table/data-table";-import { type LangfuseColumnDef } from "@/src/components/table/types";import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";import { api, type RouterOutputs } from "@/src/utils/api";-import { Button } from "@/src/components/design-system/Button/Button";import { Dialog } from "@/src/components/design-system/Dialog/Dialog";import { DialogController } from "@/src/components/design-system/DialogController/DialogController";-import { TextLink } from "@/src/components/design-system/TextLink/TextLink";-import { Tabs } from "@/src/components/design-system/Tabs/Tabs";-import { useIsMobile } from "@/src/hooks/use-mobile";-import { TopicEmbeddingMap } from "./TopicEmbeddingMap";-import { TopicGroupCard } from "./TopicGroupCard";-import { topicBadgeColor, topicColor } from "./topic-map-colors";-import { TopicBadge } from "./TopicBadge";import { SummaryInspector } from "./SummaryInspector";import { isValidTopicTimeRange } from "./time-range";--type Facet = RouterOutputs["topics"]["currentResults"][number];+import { CurrentTopicsView } from "./CurrentTopicsView";+import type { useTopicTraceFilters } from "./useTopicTraceFilters";export function CurrentTopics({projectId,@@ -31,13 +18,8 @@ export function CurrentTopics({result,selectedFacetId,tracePanelRef,-}: {- projectId: string;- timeRange: TopicTimeRange;- result: ReturnType<typeof useCurrentTopics>;- selectedFacetId: string | undefined;- tracePanelRef?: (element: HTMLElement | null) => void;-}) {+ traceFilters,+}: CurrentTopicsProps) {const selectedFacet = result.data?.find((facet) => facet.facetId === selectedFacetId,);@@ -64,6 +46,7 @@ export function CurrentTopics({facet={selectedFacet}timeRange={timeRange}tracePanelRef={tracePanelRef}+ traceFilters={traceFilters}/>)}</section>@@ -75,348 +58,17 @@ function CurrentFacet({facet,timeRange,tracePanelRef,-}: {- projectId: string;- facet: Facet;- timeRange: TopicTimeRange;- tracePanelRef?: (element: HTMLElement | null) => void;-}) {- const [selection, setSelection] = useState<string | null>(null);- const [selectedTraceId, setSelectedTraceId] = useState<string | null>(null);- const isNarrow = useMediaQuery({ query: "(max-width: 1023px)" });- const [mobilePanel, setMobilePanel] = useState("traces");- const [pagination, setPagination] = useState<PaginationState>({- pageIndex: 0,- pageSize: 20,- });- function selectTopic(topicId: string | null) {- setSelection(topicId);- setSelectedTraceId(null);- setPagination((current) => ({ ...current, pageIndex: 0 }));- }- function selectAllTraces() {- selectTopic(null);- }- function selectOutliers() {- selectTopic("outliers");- }- function selectNoTopic() {- selectTopic("no_topic");- }- function selectAwaitingMap() {- selectTopic("awaiting_map");- }- const selected =- selection === "outliers" ||- selection === "no_topic" ||- selection === "awaiting_map" ||- facet.topics.some((topic) => topic.id === selection) ||- facet.map?.topics.some((topic) => topic.id === selection)- ? selection- : null;- const visible = facet.rows.filter((row) => {- if (selected === null) return true;- if (selected === "outliers") return row.outcome === "outlier";- if (selected === "no_topic")- return (- row.outcome === "not_applicable" || row.outcome === "insufficient_input"- );- if (selected === "awaiting_map") return row.outcome === "awaiting_map";- return row.topicId === selected;- });- const outliers = facet.rows.filter((row) => row.outcome === "outlier").length;- const noTopic = facet.rows.filter(- (row) =>- row.outcome === "not_applicable" || row.outcome === "insufficient_input",- ).length;- const topics = facet.map- ? [- ...facet.map.topics,- ...facet.topics.filter(- (topic) =>- !facet.map!.topics.some((mapped) => mapped.id === topic.id),- ),- ]- : facet.topics;- const counts = (- <p className="text-muted-foreground text-xs">- {facet.rows.length.toLocaleString()} traces · {facet.topics.length} topics- {facet.awaitingCount > 0 &&- ` · ${facet.awaitingCount.toLocaleString()} awaiting a map or updated assignment`}- </p>- );- const mapPanel = (- <section- aria-label="Topic map"- className="flex min-h-0 min-w-0 flex-col overflow-hidden"- >- {facet.map ? (- <TopicEmbeddingMap- timeRange={timeRange}- projectId={projectId}- runId={facet.map.runId}- topics={facet.map.topics}- selectedTopic={selected}- onSelectTopic={selectTopic}- onSelectTrace={setSelectedTraceId}- selectedTraceId={selectedTraceId}- fillContainer- />- ) : (- <div className="flex flex-col gap-1 rounded-md border p-2">- {counts}- <p className="text-muted-foreground text-xs">- {facet.usableCount.toLocaleString()} usable summaries collected for- v{facet.facetVersion ?? 1}. Run Update topics to cluster stored- summaries. You can configure the minimum there.- </p>- </div>- )}- </section>- );- const groupsPanel = (- <section- aria-label="Topic groups"- className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-md border"- >- <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2">- <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-1 xl:grid-cols-2">- {facet.topics.map((topic) => (- <TopicGroupCard- key={topic.id}- topic={topic}- isSelected={selected === topic.id}- color={topicColor(- topics.findIndex((item) => item.id === topic.id),- )}- onSelect={selectTopic}- />- ))}- </div>- {facet.topics.length === 0 && (- <p className="text-muted-foreground text-xs">- No topics yet. Inspect the collected summaries or update topics to- find recurring groups.- </p>- )}- </div>- </section>- );- const tracesPanel = (- <section- aria-label="Topic traces"- ref={isNarrow ? undefined : tracePanelRef}- className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-md border lg:col-start-2 lg:row-span-2 lg:row-start-1"- >- <div className="flex shrink-0 flex-wrap items-center gap-1 px-2 py-1.5">- <Button- text={`All traces (${facet.rows.length.toLocaleString()})`}- size="sm"- variant={selected === null ? "secondary" : "ghost"}- onClick={selectAllTraces}- />- {outliers > 0 && (- <Button- text={`Outliers (${outliers.toLocaleString()})`}- size="sm"- variant={selected === "outliers" ? "secondary" : "ghost"}- onClick={selectOutliers}- />- )}- {noTopic > 0 && (- <Button- text={`No topic (${noTopic.toLocaleString()})`}- size="sm"- variant={selected === "no_topic" ? "secondary" : "ghost"}- onClick={selectNoTopic}- />- )}- {facet.awaitingCount > 0 && (- <Button- text={`Awaiting update (${facet.awaitingCount.toLocaleString()})`}- size="sm"- variant={selected === "awaiting_map" ? "secondary" : "ghost"}- onClick={selectAwaitingMap}- />- )}- </div>- <CurrentTraceTable- projectId={projectId}- facetId={facet.facetId}- rows={visible}- topics={topics}- pagination={pagination}- onPaginationChange={setPagination}- />- </section>- );- return (- <div- className={cn(- "grid min-h-0 min-w-0 flex-1 gap-2 overflow-hidden lg:grid-cols-2",- facet.map- ? "grid-rows-[minmax(0,9fr)_minmax(0,11fr)] lg:grid-rows-[minmax(0,3fr)_minmax(0,2fr)]"- : "grid-rows-[auto_minmax(0,1fr)]",- )}- >- {mapPanel}- {isNarrow ? (- <Tabs- value={mobilePanel}- onValueChange={setMobilePanel}- layout="fill"- ref={tracePanelRef}- >- <div className="mb-2 shrink-0">- <Tabs.List- variant="inset"- size="sm"- layout="full"- aria-label="Topics panels"- >- <Tabs.Trigger value="topics" label="Topics" />- <Tabs.Trigger value="traces" label="Traces" />- </Tabs.List>- </div>- <Tabs.Content value="topics" layout="fill">- {groupsPanel}- </Tabs.Content>- <Tabs.Content value="traces" layout="fill">- {tracesPanel}- </Tabs.Content>- </Tabs>- ) : (- <>- {groupsPanel}- {tracesPanel}- </>- )}- </div>- );-}--function CurrentTraceTable({- projectId,- facetId,- rows,- topics,- pagination,- onPaginationChange,-}: {- projectId: string;- facetId: string;- rows: Facet["rows"];- topics: { id: string }[];- pagination: PaginationState;- onPaginationChange: OnChangeFn<PaginationState>;-}) {- const isMobile = useIsMobile();+ traceFilters,+}: CurrentFacetProps) {+ const mapResult = useCurrentTopicMap(projectId, facet.map?.runId, timeRange);const peekNavigation = usePeekNavigation({tableName: "topics-traces",isV4: false,queryParams: ["observation", "display", "timestamp", "traceId"],});- const peekConfig = { itemType: "TRACE" as const, ...peekNavigation };- const topicColors = new Map(- topics.map((topic, index) => [topic.id, topicBadgeColor(index)]),- );- const pageIndex = Math.min(- pagination.pageIndex,- Math.max(0, Math.ceil(rows.length / pagination.pageSize) - 1),- );- const columns = (- openInspector: (- source: Pick<- Facet["rows"][number],- "traceId" | "facetVersion" | "unitStartTime"- >,- ) => void,- ): LangfuseColumnDef<Facet["rows"][number]>[] => [- {- accessorKey: "traceId",- header: "Trace ID",- size: 132,- minSize: 100,- cell: ({ row }) => {- function openTrace() {- peekNavigation.openPeek(row.original.traceId);- }- return (- <TextLink- path={`/project/${projectId}/traces/${encodeURIComponent(row.original.traceId)}`}- value={row.original.traceId}- onClick={openTrace}- />- );- },- },- {- accessorKey: "topicName",- header: "Topic",- size: 148,- minSize: 100,- cell: ({ row }) => (- <TopicBadge- row={row.original}- color={topicColors.get(row.original.topicId ?? "")}- size="default"- />- ),- },- {- accessorKey: "summary",- header: "Summary",- size: 300,- minSize: 180,- isFlexWidth: true,- cell: ({ row }) => {- function openTrace() {- peekNavigation.openPeek(row.original.traceId);- }- function inspectTranscript(event: MouseEvent) {- event.stopPropagation();- openInspector({- traceId: row.original.traceId,- facetVersion: row.original.facetVersion,- unitStartTime: row.original.unitStartTime,- });- }- return (- <div className="flex flex-col items-start gap-1 py-1">- {isMobile && (- <div className="flex w-full min-w-0 items-center justify-between gap-2">- <div className="min-w-0">- <TopicBadge- row={row.original}- color={topicColors.get(row.original.topicId ?? "")}- size="sm"- />- </div>- <TextLink- path={`/project/${projectId}/traces/${encodeURIComponent(row.original.traceId)}`}- value="Open trace"- onClick={openTrace}- />- </div>- )}- <p className="break-words whitespace-pre-wrap">- {row.original.summary || "No applicable summary."}- </p>- <Button- text="Debug transcript"- variant="secondary"- size="sm"- onClick={inspectTranscript}- />- </div>- );- },- },- ];+ const peekView = { itemType: "TRACE" as const, ...peekNavigation };return (- <DialogController<- Pick<Facet["rows"][number], "traceId" | "facetVersion" | "unitStartTime">- >+ <DialogController<SummarySource>renderDialog={({ state }) => (<Dialog title="Summary source" size="lg" closeOnInteractionOutside><Dialog.Body>@@ -426,7 +78,7 @@ function CurrentTraceTable({</p><SummaryInspectorprojectId={projectId}- facetId={facetId}+ facetId={facet.facetId}{...state}/></div>@@ -435,34 +87,16 @@ function CurrentTraceTable({)}>{({ openDialog }) => (- <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">- <DataTable- tableName="topics-current-traces"- columns={columns(openDialog)}- columnVisibility={{ traceId: !isMobile, topicName: !isMobile }}- data={{- isLoading: false,- isError: false,- data: rows- .slice(- pageIndex * pagination.pageSize,- (pageIndex + 1) * pagination.pageSize,- )- .map((row) => ({ ...row, id: row.traceId })),- }}- pagination={{- totalCount: rows.length,- state: { ...pagination, pageIndex },- onChange: onPaginationChange,- options: [20, 50, 100],- }}- topAlignCells- className="min-h-0 overscroll-contain"- cellPadding="compact"- noResultsMessage="No traces in this selection."- peekView={peekConfig}- />- </div>+ <CurrentTopicsView+ projectId={projectId}+ facet={facet}+ mapResult={mapResult}+ tracePanelRef={tracePanelRef}+ traceFilters={traceFilters}+ onOpenTrace={peekNavigation.openPeek}+ onInspectTranscript={openDialog}+ peekView={peekView}+ />)}</DialogController>);@@ -499,4 +133,41 @@ export function useCurrentTopics({});}+function useCurrentTopicMap(+ projectId: string,+ runId: string | undefined,+ timeRange: TopicTimeRange,+) {+ return api.topics.map.useQuery(+ { projectId, runId: runId ?? "", timeRange },+ { enabled: Boolean(runId) },+ );+}++type CurrentTopicsProps = {+ projectId: string;+ timeRange: TopicTimeRange;+ result: Pick<+ ReturnType<typeof useCurrentTopics>,+ "data" | "isLoading" | "error"+ >;+ selectedFacetId: string | undefined;+ tracePanelRef?: (element: HTMLElement | null) => void;+ traceFilters: ReturnType<typeof useTopicTraceFilters>;+};++type CurrentFacetProps = {+ projectId: string;+ facet: Facet;+ timeRange: TopicTimeRange;+ tracePanelRef?: (element: HTMLElement | null) => void;+ traceFilters: ReturnType<typeof useTopicTraceFilters>;+};++type Facet = RouterOutputs["topics"]["currentResults"][number];+type SummarySource = Pick<+ Facet["rows"][number],+ "traceId" | "facetVersion" | "unitStartTime"+>;+export const __test = { useCurrentTopics };diff --git a/web/src/features/topics/CurrentTopicsView.stories.tsx b/web/src/features/topics/CurrentTopicsView.stories.tsxnew file mode 100644index 0000000000..8ec454b5e5--- /dev/null+++ b/web/src/features/topics/CurrentTopicsView.stories.tsx@@ -0,0 +1,263 @@+import { useState, type ComponentProps } from "react";+import { expect, fn, userEvent, waitFor, within } from "storybook/test";+import preview from "../../../.storybook/preview";+import { Button } from "@/src/components/design-system/Button/Button";+import { CurrentTopicsView } from "./CurrentTopicsView";+import {+ fitCamera,+ prepareTopicMap,+ screenPoint,+} from "./map/prepare-topic-map";++const topic = {+ id: "billing",+ name: "Billing questions",+ description: "Invoice support",+ count: 60,+};+const rows = Array.from({ length: 120 }, (_, index) => ({+ traceId: `trace-${index}`,+ summary: index >= 60 ? `Invoice refund ${index}` : `Account setup ${index}`,+ topicId: index % 2 === 0 ? "billing" : null,+ topicName: index % 2 === 0 ? "Billing questions" : null,+ outcome: index % 2 === 0 ? "assigned" : "outlier",+ facetVersion: 1,+ unitStartTime: "2026-10-01T00:00:00.000Z",+}));+const facet = {+ facetId: "intent",+ name: "Intent",+ facetVersion: 1,+ rows,+ topics: [topic],+ map: { runId: "run", topics: [topic] },+ awaitingCount: 0,+ usableCount: rows.length,+};+const mapData = {+ status: "ready" as const,+ reason: null,+ points: [0, 60, 61, 119].map((index, position) => ({+ traceId: rows[index].traceId,+ summary: rows[index].summary,+ topicId: rows[index].topicId,+ outcome: index % 2 === 0 ? ("assigned" as const) : ("outlier" as const),+ x: [0, 1, -1, 0][position],+ y: [0, 1, 1, -1][position],+ })),+ missingSummaryCount: 0,+ unpositionedCount: 0,+};++const defaultArgs: ComponentProps<typeof CurrentTopicsView> = {+ projectId: "storybook-topics",+ facet,+ mapResult: { data: mapData, error: null },+ traceFilters: {+ filters: [],+ setFilters: fn(),+ searchQuery: null,+ setSearchQuery: fn(),+ },+ onOpenTrace: fn(),+ onInspectTranscript: fn(),+ peekView: {+ itemType: "TRACE",+ tableName: "topics-current-traces",+ isV4: false,+ closePeek: fn(),+ },+};++const meta = preview.meta({+ component: CurrentTopicsView,+ args: defaultArgs,+ render: (args) => <ControlledTopics {...args} />,+});++export const Default = meta.story({});++export const FilteringResetsPagination = meta.story({+ name: "(Test) Filtering Resets Pagination and Shares Map Matches",+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const table = within(canvas.getByRole("region", { name: "Topic traces" }));+ await userEvent.click(table.getByRole("combobox", { name: "" }));+ await userEvent.click(body.getByRole("option", { name: "50" }));+ await userEvent.click(+ table.getByRole("button", { name: "Go to next page" }),+ );+ await expect(table.getByRole("link", { name: "trace-50" })).toBeVisible();+ const search = table.getByRole("combobox", { name: "Search" });+ await replaceQuery(search, "invoice");+ await waitFor(() => {+ expect(table.getByRole("status")).toHaveTextContent("60 of 120 traces");+ expect(table.getByRole("link", { name: "trace-60" })).toBeVisible();+ });+ await expect(+ canvas.getByRole("button", {+ name: "Map coverage: 3 of 4 mapped traces match",+ }),+ ).toBeVisible();+ await userEvent.click(+ table.getByRole("button", { name: "Go to next page" }),+ );+ await expect(table.getByRole("link", { name: "trace-110" })).toBeVisible();+ await replaceQuery(search, "");+ await waitFor(() =>+ expect(table.getByRole("status")).toHaveTextContent("120 of 120 traces"),+ );+ await expect(table.getByRole("link", { name: "trace-0" })).toBeVisible();+ await expect(+ canvas.getByRole("button", { name: "Map coverage: 4 mapped traces" }),+ ).toBeVisible();+ await userEvent.click(+ table.getByRole("button", { name: "Go to next page" }),+ );+ await expect(table.getByRole("link", { name: "trace-50" })).toBeVisible();+ const groups = within(canvas.getByRole("region", { name: "Topic groups" }));+ await userEvent.click(+ groups.getByRole("button", { name: /Billing questions/ }),+ );+ await waitFor(() => {+ expect(table.getByRole("status")).toHaveTextContent("60 of 120 traces");+ expect(table.getByRole("link", { name: "trace-0" })).toBeVisible();+ });+ await expect(+ canvas.getByRole("button", {+ name: "Map coverage: 2 of 4 mapped traces match",+ }),+ ).toBeVisible();+ },+});++export const EquivalentMatchesPreserveHoverAndFocus = meta.story({+ name: "(Test) Equivalent Matches Preserve Hover and Focus",+ args: {+ traceFilters: {+ ...defaultArgs.traceFilters,+ filters: [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: ["billing"],+ },+ ],+ },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const stage = canvas.getByRole("group", { name: /^Interactive topic map/ });+ await waitFor(() =>+ expect(stage.getBoundingClientRect().height).toBeGreaterThan(0),+ );+ const model = prepareTopicMap(mapData, [topic]);+ const rect = stage.getBoundingClientRect();+ const size = { width: rect.width, height: rect.height };+ const camera = fitCamera(model.bounds, model.bounds, size);+ const point = model.pointById.get("trace-0")!;+ const at = screenPoint(point, camera, model.bounds, size);+ let attempt = 0;+ await waitFor(() => {+ stage.dispatchEvent(+ new PointerEvent("pointermove", {+ bubbles: true,+ pointerId: 1,+ pointerType: "mouse",+ isPrimary: true,+ clientX: rect.left + at.x + (attempt++ % 2 ? 1 : -1),+ clientY: rect.top + at.y,+ }),+ );+ expect(+ canvasElement.querySelector(+ '[role="tooltip"][data-active="true"][data-trace-id="trace-0"]',+ ),+ ).not.toBeNull();+ });+ const refresh = canvas.getByRole("button", {+ name: "Refresh unchanged results",+ });+ refresh.click();+ await afterPaint();+ await expect(+ canvasElement.querySelector(+ '[role="tooltip"][data-active="true"][data-trace-id="trace-0"]',+ ),+ ).not.toBeNull();+ for (+ let attempt = 0;+ attempt < 16 &&+ canvas.queryAllByRole("button", { name: /^Select trace:/ }).length === 0;+ attempt+++ ) {+ await userEvent.click(+ canvas.getByRole("button", { name: "Zoom in (+)" }),+ );+ await afterPaint();+ }+ const card = (+ await canvas.findAllByRole("button", { name: /^Select trace:/ })+ )[0];+ card.focus();+ card.click();+ await afterPaint();+ await expect(card).toHaveFocus();+ refresh.click();+ await afterPaint();+ await expect(card).toHaveFocus();+ await expect(card.isConnected).toBe(true);+ },+});++function ControlledTopics(args: ControlledTopicsProps) {+ const [filters, setFilters] = useState(args.traceFilters.filters);+ const [searchQuery, setSearchQuery] = useState(args.traceFilters.searchQuery);+ const [revision, setRevision] = useState(0);+ function refresh() {+ setRevision((previous) => previous + 1);+ }+ return (+ <div className="flex h-[800px] flex-col gap-2">+ <Button+ text="Refresh unchanged results"+ variant="secondary"+ onClick={refresh}+ />+ <CurrentTopicsView+ {...args}+ facet={{+ ...args.facet,+ rows: (revision % 2+ ? [...args.facet.rows].reverse()+ : args.facet.rows+ ).map((row) => ({ ...row })),+ }}+ traceFilters={{+ ...args.traceFilters,+ filters: filters.map((filter) => ({ ...filter })),+ setFilters,+ searchQuery,+ setSearchQuery,+ }}+ />+ </div>+ );+}++async function replaceQuery(search: HTMLElement, query: string) {+ await userEvent.click(search);+ await userEvent.clear(search);+ if (query) await userEvent.type(search, query);+ await userEvent.keyboard("{Enter}");+}++async function afterPaint() {+ await new Promise<void>((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+}++type ControlledTopicsProps = ComponentProps<typeof CurrentTopicsView>;diff --git a/web/src/features/topics/CurrentTopicsView.tsx b/web/src/features/topics/CurrentTopicsView.tsxnew file mode 100644index 0000000000..69645a7c11--- /dev/null+++ b/web/src/features/topics/CurrentTopicsView.tsx@@ -0,0 +1,396 @@+import { computeSelectedValues, type FilterState } from "@langfuse/shared";+import { useMemo, useState, type ComponentProps, type MouseEvent } from "react";+import { useMediaQuery } from "react-responsive";+import { cn } from "@/src/utils/tailwind";+import { type OnChangeFn, type PaginationState } from "@tanstack/react-table";+import { DataTable } from "@/src/components/table/data-table";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import { type DataTablePeekViewProps } from "@/src/components/table/peek";+import { type RouterOutputs } from "@/src/utils/api";+import { Button } from "@/src/components/design-system/Button/Button";+import { TextLink } from "@/src/components/design-system/TextLink/TextLink";+import { Tabs } from "@/src/components/design-system/Tabs/Tabs";+import { useIsMobile } from "@/src/hooks/use-mobile";+import { TopicEmbeddingMap } from "./TopicEmbeddingMap";+import { TopicGroupCard } from "./TopicGroupCard";+import { topicBadgeColor, topicColor } from "./topic-map-colors";+import { TopicBadge } from "./TopicBadge";+import {+ filterTopicTraces,+ selectTopicTraceFilters,+} from "./topic-trace-filters";+import { TopicsTraceToolbar } from "./TopicsTraceToolbar";++export function CurrentTopicsView({+ projectId,+ facet,+ mapResult,+ onOpenTrace,+ onInspectTranscript,+ peekView,+ tracePanelRef,+ traceFilters,+}: CurrentTopicsViewProps) {+ const [selectedTraceId, setSelectedTraceId] = useState<string | null>(null);+ const isNarrow = useMediaQuery({ query: "(max-width: 1023px)" });+ const [mobilePanel, setMobilePanel] = useState("traces");+ const { filters, setFilters, searchQuery, setSearchQuery } = traceFilters;+ const filterKey = JSON.stringify([filters, searchQuery]);+ const [pageSize, setPageSize] = useState(20);+ function selectTopic(topicId: string | null) {+ setSelectedTraceId(null);+ setFilters(selectTopicTraceFilters(filters, topicId));+ }+ const visible = filterTopicTraces(facet.rows, filters, searchQuery);+ const isFiltered = filters.length > 0 || Boolean(searchQuery?.trim());+ const matchingTraceKey = isFiltered+ ? JSON.stringify([...new Set(visible.map((row) => row.traceId))].sort())+ : null;+ /** Frame identity changes only when matching IDs change, preserving hover and focus across refreshes. */+ const matchingTraceIds = useMemo(+ () =>+ matchingTraceKey === null+ ? undefined+ : new Set<string>(JSON.parse(matchingTraceKey)),+ [matchingTraceKey],+ );+ const topicFilters = filters.filter((filter) => filter.column === "topicId");+ const topics = facet.map+ ? [+ ...facet.map.topics,+ ...facet.topics.filter(+ (topic) =>+ !facet.map!.topics.some((mapped) => mapped.id === topic.id),+ ),+ ]+ : facet.topics;+ const selectedTopicIds = new Set(+ topicFilters.length === 0 ||+ topicFilters.some((filter) => filter.type !== "stringOptions")+ ? []+ : topicFilters.reduce(+ (values, filter) => {+ const kept = new Set(computeSelectedValues(values, filter));+ return values.filter((value) => kept.has(value));+ },+ topics.map((topic) => topic.id),+ ),+ );+ const counts = (+ <p className="text-muted-foreground text-xs">+ {facet.rows.length.toLocaleString()} traces · {facet.topics.length} topics+ {facet.awaitingCount > 0 &&+ ` · ${facet.awaitingCount.toLocaleString()} awaiting a map or updated assignment`}+ </p>+ );+ const mapPanel = (+ <section+ aria-label="Topic map"+ className="flex min-h-0 min-w-0 flex-col overflow-hidden"+ >+ {facet.map ? (+ <TopicEmbeddingMap+ key={facet.map.runId}+ query={mapResult}+ onOpenTrace={onOpenTrace}+ projectId={projectId}+ topics={facet.map.topics}+ selectedTopic={null}+ matchingTraceIds={matchingTraceIds}+ onSelectTopic={selectTopic}+ onSelectTrace={setSelectedTraceId}+ selectedTraceId={+ selectedTraceId &&+ (!matchingTraceIds || matchingTraceIds.has(selectedTraceId))+ ? selectedTraceId+ : null+ }+ fillContainer+ />+ ) : (+ <div className="flex flex-col gap-1 rounded-md border p-2">+ {counts}+ <p className="text-muted-foreground text-xs">+ {facet.usableCount.toLocaleString()} usable summaries collected for+ v{facet.facetVersion ?? 1}. Run Update topics to cluster stored+ summaries. You can configure the minimum there.+ </p>+ </div>+ )}+ </section>+ );+ const groupsPanel = (+ <section+ aria-label="Topic groups"+ className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-md border"+ >+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2">+ <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-1 xl:grid-cols-2">+ {facet.topics.map((topic) => (+ <TopicGroupCard+ key={topic.id}+ topic={topic}+ isSelected={selectedTopicIds.has(topic.id)}+ color={topicColor(+ topics.findIndex((item) => item.id === topic.id),+ )}+ onSelect={selectTopic}+ />+ ))}+ </div>+ {facet.topics.length === 0 && (+ <p className="text-muted-foreground text-xs">+ No topics yet. Inspect the collected summaries or update topics to+ find recurring groups.+ </p>+ )}+ </div>+ </section>+ );+ const tracesPanel = (+ <section+ aria-label="Topic traces"+ ref={isNarrow ? undefined : tracePanelRef}+ className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-md border lg:col-start-2 lg:row-span-2 lg:row-start-1"+ >+ <TopicsTraceToolbar+ projectId={projectId}+ topics={topics}+ filters={filters}+ onFiltersChange={setFilters}+ searchQuery={searchQuery}+ onSearchQueryChange={setSearchQuery}+ />+ <CurrentTraceTable+ key={filterKey}+ projectId={projectId}+ onOpenTrace={onOpenTrace}+ onInspectTranscript={onInspectTranscript}+ peekView={peekView}+ rows={visible}+ totalCount={facet.rows.length}+ topics={topics}+ pageSize={pageSize}+ onPageSizeChange={setPageSize}+ />+ </section>+ );+ return (+ <div+ className={cn(+ "grid min-h-0 min-w-0 flex-1 gap-2 overflow-hidden lg:grid-cols-2",+ facet.map+ ? "grid-rows-[minmax(0,9fr)_minmax(0,11fr)] lg:grid-rows-[minmax(0,3fr)_minmax(0,2fr)]"+ : "grid-rows-[auto_minmax(0,1fr)]",+ )}+ >+ {mapPanel}+ {isNarrow ? (+ <Tabs+ value={mobilePanel}+ onValueChange={setMobilePanel}+ layout="fill"+ ref={tracePanelRef}+ >+ <div className="mb-2 shrink-0">+ <Tabs.List+ variant="inset"+ size="sm"+ layout="full"+ aria-label="Topics panels"+ >+ <Tabs.Trigger value="topics" label="Topics" />+ <Tabs.Trigger value="traces" label="Traces" />+ </Tabs.List>+ </div>+ <Tabs.Content value="topics" layout="fill">+ {groupsPanel}+ </Tabs.Content>+ <Tabs.Content value="traces" layout="fill">+ {tracesPanel}+ </Tabs.Content>+ </Tabs>+ ) : (+ <>+ {groupsPanel}+ {tracesPanel}+ </>+ )}+ </div>+ );+}++function CurrentTraceTable({+ projectId,+ onOpenTrace,+ onInspectTranscript,+ peekView,+ rows,+ totalCount,+ topics,+ pageSize,+ onPageSizeChange,+}: CurrentTraceTableProps) {+ const [requestedPageIndex, setPageIndex] = useState(0);+ const isMobile = useIsMobile();+ const topicColors = new Map(+ topics.map((topic, index) => [topic.id, topicBadgeColor(index)]),+ );+ const pageIndex = Math.min(+ requestedPageIndex,+ Math.max(0, Math.ceil(rows.length / pageSize) - 1),+ );+ const pagination = { pageIndex, pageSize };+ const onPaginationChange: OnChangeFn<PaginationState> = (update) => {+ const next = typeof update === "function" ? update(pagination) : update;+ setPageIndex(next.pageIndex);+ onPageSizeChange(next.pageSize);+ };+ const columns: LangfuseColumnDef<Facet["rows"][number]>[] = [+ {+ accessorKey: "traceId",+ header: "Trace ID",+ size: 132,+ minSize: 100,+ cell: ({ row }) => {+ function openTrace() {+ onOpenTrace(row.original.traceId);+ }+ return (+ <TextLink+ path={`/project/${projectId}/traces/${encodeURIComponent(row.original.traceId)}`}+ value={row.original.traceId}+ onClick={openTrace}+ />+ );+ },+ },+ {+ accessorKey: "topicName",+ header: "Topic",+ size: 148,+ minSize: 100,+ cell: ({ row }) => (+ <TopicBadge+ row={row.original}+ color={topicColors.get(row.original.topicId ?? "")}+ size="default"+ />+ ),+ },+ {+ accessorKey: "summary",+ header: "Summary",+ size: 300,+ minSize: 180,+ isFlexWidth: true,+ cell: ({ row }) => {+ function openTrace() {+ onOpenTrace(row.original.traceId);+ }+ function inspectTranscript(event: MouseEvent) {+ event.stopPropagation();+ onInspectTranscript({+ traceId: row.original.traceId,+ facetVersion: row.original.facetVersion,+ unitStartTime: row.original.unitStartTime,+ });+ }+ return (+ <div className="flex flex-col items-start gap-1 py-1">+ {isMobile && (+ <div className="flex w-full min-w-0 items-center justify-between gap-2">+ <div className="min-w-0">+ <TopicBadge+ row={row.original}+ color={topicColors.get(row.original.topicId ?? "")}+ size="sm"+ />+ </div>+ <TextLink+ path={`/project/${projectId}/traces/${encodeURIComponent(row.original.traceId)}`}+ value="Open trace"+ onClick={openTrace}+ />+ </div>+ )}+ <p className="break-words whitespace-pre-wrap">+ {row.original.summary || "No applicable summary."}+ </p>+ <Button+ text="Debug transcript"+ variant="secondary"+ size="sm"+ onClick={inspectTranscript}+ />+ </div>+ );+ },+ },+ ];+ return (+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">+ <DataTable+ tableName="topics-current-traces"+ columns={columns}+ columnVisibility={{ traceId: !isMobile, topicName: !isMobile }}+ data={{+ isLoading: false,+ isError: false,+ data: rows+ .slice(+ pageIndex * pagination.pageSize,+ (pageIndex + 1) * pagination.pageSize,+ )+ .map((row) => ({ ...row, id: row.traceId })),+ }}+ pagination={{+ totalCount: rows.length,+ resultCountLabel: `${rows.length.toLocaleString()} of ${totalCount.toLocaleString()} traces`,+ state: { ...pagination, pageIndex },+ onChange: onPaginationChange,+ options: [20, 50, 100],+ }}+ topAlignCells+ className="min-h-0 overscroll-contain"+ cellPadding="compact"+ noResultsMessage="No matches. Adjust or clear your filters."+ peekView={peekView}+ />+ </div>+ );+}++type CurrentTraceTableProps = {+ projectId: string;+ onOpenTrace: (traceId: string) => void;+ onInspectTranscript: (source: SummarySource) => void;+ peekView: DataTablePeekViewProps;+ rows: Facet["rows"];+ totalCount: number;+ topics: { id: string }[];+ pageSize: number;+ onPageSizeChange: (pageSize: number) => void;+};++type CurrentTopicsViewProps = {+ projectId: string;+ facet: Facet;+ mapResult: ComponentProps<typeof TopicEmbeddingMap>["query"];+ tracePanelRef?: (element: HTMLElement | null) => void;+ traceFilters: {+ filters: FilterState;+ setFilters: (filters: FilterState) => void;+ searchQuery: string | null;+ setSearchQuery: (query: string | null) => void;+ };+ onOpenTrace: (traceId: string) => void;+ onInspectTranscript: (source: SummarySource) => void;+ peekView: DataTablePeekViewProps;+};++type Facet = RouterOutputs["topics"]["currentResults"][number];+type SummarySource = Pick<+ Facet["rows"][number],+ "traceId" | "facetVersion" | "unitStartTime"+>;diff --git a/web/src/features/topics/EmbeddingMapView.stories.tsx b/web/src/features/topics/EmbeddingMapView.stories.tsxindex e7e46951e2..729f191039 100644--- a/web/src/features/topics/EmbeddingMapView.stories.tsx+++ b/web/src/features/topics/EmbeddingMapView.stories.tsx@@ -336,6 +336,15 @@ export const DenseIssueCloud = meta.story({render: (args) => <ControlledExplorer {...args} />,});+export const OutliersSelected = meta.story({+ args: {+ topics: denseTopics,+ data: denseData,+ selectedTopic: "outliers",+ },+ render: (args) => <ControlledExplorer {...args} />,+});+export const MissingSummaries = meta.story({name: "(Test) Missing summaries coverage",args: { data: { ...data, missingSummaryCount: 2, unpositionedCount: 3 } },@@ -918,3 +927,87 @@ export const InterruptingTopicFlightKeepsPaintedZoom = meta.story({}},});++export const FilteringPreservesCamera = meta.story({+ name: "(Test) Filtering Preserves Camera",+ args: { data: nearbyCloudData, topics: denseTopics, selectedTopic: null },+ render: function Render(args) {+ const [matchingTraceIds, setMatchingTraceIds] =+ useState<ReadonlySet<string>>();+ const handleFilter = () =>+ setMatchingTraceIds(new Set([nearbyCloudData.points[0].traceId]));+ const handleNoMatches = () => setMatchingTraceIds(new Set());+ const handleClear = () => setMatchingTraceIds(undefined);+ return (+ <>+ <Button+ text="Filter matches"+ variant="secondary"+ onClick={handleFilter}+ />+ <Button+ text="No matches"+ variant="secondary"+ onClick={handleNoMatches}+ />+ <Button text="Clear filter" variant="secondary" onClick={handleClear} />+ <EmbeddingMapView {...args} matchingTraceIds={matchingTraceIds} />+ </>+ );+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const stage = canvas.getByRole("group", { name: /^Interactive topic map/ });+ await userEvent.click(canvas.getByRole("button", { name: "Zoom in (+)" }));+ await userEvent.click(canvas.getByRole("button", { name: "Zoom in (+)" }));+ await userEvent.click(canvas.getByRole("button", { name: "Zoom in (+)" }));+ await waitForMapSettled(canvasElement);+ const zoom = canvas.getByLabelText("Zoom level").textContent;+ const positions = () =>+ Array.from(+ canvasElement.querySelectorAll<HTMLElement>(+ "[data-topic-background-label]",+ ),+ ).map((label) => [+ label.dataset.topicBackgroundLabel,+ label.style.left,+ label.style.top,+ label.style.width,+ label.style.height,+ ]);+ const before = positions();+ expect(before.length).toBeGreaterThan(0);+ const total = nearbyCloudData.points.length.toLocaleString();+ await userEvent.click(+ canvas.getByRole("button", { name: "Filter matches" }),+ );+ await expect(+ canvas.getByRole("button", {+ name: `Map coverage: 1 of ${total} mapped traces match`,+ }),+ ).toBeVisible();+ await waitForMapSettled(canvasElement);+ expect(positions()).toEqual(before);+ expect(canvas.getByLabelText("Zoom level").textContent).toBe(zoom);+ await userEvent.click(canvas.getByRole("button", { name: "No matches" }));+ await expect(+ canvas.getByRole("button", {+ name: `Map coverage: 0 of ${total} mapped traces match`,+ }),+ ).toBeVisible();+ await waitForMapSettled(canvasElement);+ expect(positions()).toEqual(before);+ expect(canvas.getByLabelText("Zoom level").textContent).toBe(zoom);+ expect(canvasElement.querySelectorAll("[data-topic-node]")).toHaveLength(0);+ await expect(stage).toBeVisible();+ await userEvent.click(canvas.getByRole("button", { name: "Clear filter" }));+ await expect(+ canvas.getByRole("button", {+ name: `Map coverage: ${total} mapped traces`,+ }),+ ).toBeVisible();+ await waitForMapSettled(canvasElement);+ expect(positions()).toEqual(before);+ expect(canvas.getByLabelText("Zoom level").textContent).toBe(zoom);+ },+});diff --git a/web/src/features/topics/README.md b/web/src/features/topics/README.mdindex c37c2280d6..63b2efd2c5 100644--- a/web/src/features/topics/README.md+++ b/web/src/features/topics/README.md@@ -8,11 +8,29 @@ project permissions. Processing additionally requires the project allowlist.- `TopicsPage.tsx` owns facet configuration, the execution history drawer,the current-results query and facet selection. A compact header keeps the facetpicker, time range and processing action on one row; configuration, history and- refresh live in the overflow menu. `CurrentTopics.tsx` presents the selected+ refresh live in the overflow menu. `CurrentTopics.tsx` owns the map query, trace+ navigation and summary inspector; `CurrentTopicsView.tsx` presents the selectedfacet in independently scrolling panels: map and groups on the left, traces onthe right. Narrow views keep the map above Topics/Traces tabs, with readablesummary rows on phones and all processing controls in the mobile overflowmenu. Selecting a group filters traces without changing the active tab.+ `useTopicTraceFilters.ts` owns URL-backed facet selection; filters and search+ live only in localStorage, scoped to each project/facet. Switching facets+ restores that facet's state, defaulting to unfiltered on first visit. Filter+ and search URL parameters are neither read nor written.+ `TopicsTraceToolbar.tsx` uses the shared search bar for topic, assignment, and+ text filtering. `topic-trace-filters.ts` owns its registry and local evaluation:+ literal phrase search across summaries, topic names and trace IDs, OR within+ a selection and AND between fields. Filtering applies before pagination.+ Saved topic IDs absent from current options remain editable as unavailable+ topics; their matching semantics are preserved across date-range changes.+ Table results determine matching map IDs without changing saved positions or+ the camera; nonmatching dots remain faint and inspectable. The map reports+ its own matching count because its saved cohort can differ from current rows.+ Fit/Home/Escape retain table filters; editing or removing search tokens updates+ the same saved facet state. Search actions reuse metadata-only filter analytics with+ `tableName: topics` and `isV4: false`. Query text and topic names remain+ blocked from replay by the shared search bar.Peek defaults to the trace panel width and has its own resize preference.The results workspace stays mounted, includingwhile a run's status is open. Execution URL parameters open progress, errors@@ -74,7 +92,8 @@ project permissions. Processing additionally requires the project allowlist.open. It uses the same deterministic transcript loader as the worker, doesnot run inference, and explains when the source is unavailable or may differfrom the original input. Transcript content is marked `ph-no-capture`.-- `TopicEmbeddingMap.tsx` loads the published map and supplies trace navigation.+- `TopicEmbeddingMap.tsx` renders the published map's loading, error and ready states+ from supplied query data and trace-navigation callbacks.`EmbeddingMapView.tsx` preserves the controlled selection contract as a drop-inadapter to `map/TopicMapExplorer.tsx`. The renderer owns no queries or clustering.`map/prepare-topic-map.ts` prepares topic zones, colors, mapped-cohort counts,diff --git a/web/src/features/topics/TopicEmbeddingMap.tsx b/web/src/features/topics/TopicEmbeddingMap.tsxindex 99bb928bd6..23b65a3701 100644--- a/web/src/features/topics/TopicEmbeddingMap.tsx+++ b/web/src/features/topics/TopicEmbeddingMap.tsx@@ -1,46 +1,20 @@-import type { TopicTimeRange } from "@langfuse/shared/topics";import { Alert } from "@/src/components/design-system/Alert/Alert";-import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";-import { api, type RouterOutputs } from "@/src/utils/api";+import { type RouterOutputs } from "@/src/utils/api";import { EmbeddingMapView } from "./EmbeddingMapView";import { TopicMapLoading } from "./TopicMapLoading";-type Topic = Pick<- RouterOutputs["topics"]["currentResults"][number]["topics"][number],- "id" | "name"-> & { description?: string };-export function TopicEmbeddingMap({projectId,- runId,- timeRange,+ query,+ onOpenTrace,topics,selectedTopic,onSelectTopic,onSelectTrace,selectedTraceId,+ matchingTraceIds,fillContainer = false,-}: {- projectId: string;- runId: string;- timeRange: TopicTimeRange;- topics: Topic[];- selectedTopic: string | null;- onSelectTopic: (id: string | null) => void;- onSelectTrace: (traceId: string | null) => void;- selectedTraceId: string | null;- fillContainer?: boolean;-}) {- const { openPeek } = usePeekNavigation({- tableName: "topics-traces",- isV4: false,- queryParams: ["observation", "display", "timestamp", "traceId"],- });- const query = api.topics.map.useQuery({- projectId,- runId,- timeRange,- });+}: TopicEmbeddingMapProps) {if (query.error)return (<Alert variant="destructive" size="sm">@@ -60,16 +34,37 @@ export function TopicEmbeddingMap({);return (<EmbeddingMapView- key={runId}projectId={projectId}- onOpenTrace={openPeek}+ onOpenTrace={onOpenTrace}data={query.data}topics={topics}selectedTopic={selectedTopic}onSelectTopic={onSelectTopic}onSelectTrace={onSelectTrace}selectedTraceId={selectedTraceId}+ matchingTraceIds={matchingTraceIds}fillContainer={fillContainer}/>);}++type TopicEmbeddingMapProps = {+ projectId: string;+ query: {+ data?: RouterOutputs["topics"]["map"];+ error: { message: string } | null;+ };+ onOpenTrace: (traceId: string) => void;+ topics: Topic[];+ selectedTopic: string | null;+ onSelectTopic: (id: string | null) => void;+ onSelectTrace: (traceId: string | null) => void;+ selectedTraceId: string | null;+ matchingTraceIds?: ReadonlySet<string>;+ fillContainer?: boolean;+};++type Topic = Pick<+ RouterOutputs["topics"]["currentResults"][number]["topics"][number],+ "id" | "name"+> & { description?: string };diff --git a/web/src/features/topics/TopicsPage.clienttest.tsx b/web/src/features/topics/TopicsPage.clienttest.tsxindex ecf657a95b..4f2f8c20d5 100644--- a/web/src/features/topics/TopicsPage.clienttest.tsx+++ b/web/src/features/topics/TopicsPage.clienttest.tsx@@ -21,6 +21,7 @@ const state = vi.hoisted(() => ({vi.mock("use-query-params", () => ({StringParam: {},+ useQueryParam: () => [undefined, vi.fn()],useQueryParams: () => [{ dateRange: state.dateRange }, state.setQueryParams],}));vi.mock("@/src/components/layouts/page-header-controls-slot", () => ({diff --git a/web/src/features/topics/TopicsPage.tsx b/web/src/features/topics/TopicsPage.tsxindex 36573edcfc..6540f27a22 100644--- a/web/src/features/topics/TopicsPage.tsx+++ b/web/src/features/topics/TopicsPage.tsx@@ -44,8 +44,8 @@ import { CurrentTopics, useCurrentTopics } from "./CurrentTopics";import { TopicsFilters } from "./TopicsFilters";import { TopicsActionsMenu } from "./TopicsActionsMenu";import { TopicsWorkspaceGate } from "./TopicsWorkspaceGate";-import { resolveTopicFacetId } from "./topic-facet-selection";import { isValidTopicTimeRange } from "./time-range";+import { useTopicTraceFilters } from "./useTopicTraceFilters";const maxTimeRangeMs = TIME_RANGES.last90Days.minutes * 60_000;const sharedTimeRangePresets = [@@ -134,7 +134,6 @@ function TopicsWorkspaceView({fallback: "last7Days",});const [refreshedAt, setRefreshedAt] = useState(Date.now);- const [selectedFacetId, setSelectedFacetId] = useState<string>();const [tracePanel, setTracePanel] = useState<HTMLElement | null>(null);const peekNavigation = usePeekNavigation({tableName: "topics-traces",@@ -221,10 +220,8 @@ function TopicsWorkspaceView({refreshAfter: completedAt,timeRange: currentTimeRange,});- const selectedFacet = resolveTopicFacetId(- results.data ?? [],- selectedFacetId,- );+ const traceFilters = useTopicTraceFilters(projectId, results.data ?? []);+ const { selectedFacetId } = traceFilters;const refreshResults = () => {setRefreshedAt(Date.now());utils.topics.currentResults.invalidate({ projectId });@@ -423,13 +420,14 @@ function TopicsWorkspaceView({<TopicsFiltersfacets={results.data ?? []}selectedFacetId={selectedFacetId}- onSelectFacet={setSelectedFacetId}+ onSelectFacet={traceFilters.selectFacet}><CurrentTopicsprojectId={projectId}timeRange={currentTimeRange}result={results}- selectedFacetId={selectedFacet}+ selectedFacetId={selectedFacetId}+ traceFilters={traceFilters}tracePanelRef={setTracePanel}/></TopicsFilters>diff --git a/web/src/features/topics/TopicsTraceToolbar.stories.tsx b/web/src/features/topics/TopicsTraceToolbar.stories.tsxnew file mode 100644index 0000000000..17469b0c77--- /dev/null+++ b/web/src/features/topics/TopicsTraceToolbar.stories.tsx@@ -0,0 +1,320 @@+import { useState, type ComponentProps } from "react";+import { expect, fn, userEvent, waitFor, within } from "storybook/test";+import {+ QueryParamProvider,+ type QueryParamAdapterComponent,+} from "use-query-params";+import preview from "../../../.storybook/preview";+import { DataTable } from "@/src/components/table/data-table";+import { Tabs } from "@/src/components/design-system/Tabs/Tabs";+import { TopicsTraceToolbar } from "./TopicsTraceToolbar";+import { filterTopicTraces } from "./topic-trace-filters";+import { useTopicTraceFilters } from "./useTopicTraceFilters";++const facetPersistenceProject = "storybook-topics-toolbar-facet-persistence";+const facets = [{ facetId: "intent" }, { facetId: "sentiment" }];++const MemoryQueryAdapter: QueryParamAdapterComponent = ({ children }) => {+ const [location, setLocation] = useState({ search: "" });+ return children({ location, replace: setLocation, push: setLocation });+};++function FacetToolbarExample() {+ const state = useTopicTraceFilters(facetPersistenceProject, facets);+ return (+ <div className="flex max-w-2xl flex-col gap-2">+ <Tabs+ value={state.selectedFacetId ?? facets[0].facetId}+ onValueChange={state.selectFacet}+ >+ <Tabs.List variant="underline">+ <Tabs.Trigger value="intent" label="Intent" />+ <Tabs.Trigger value="sentiment" label="Sentiment" />+ </Tabs.List>+ </Tabs>+ <TopicsTraceToolbar+ topics={topics}+ filters={state.filters}+ searchQuery={state.searchQuery}+ onFiltersChange={state.setFilters}+ onSearchQueryChange={state.setSearchQuery}+ />+ </div>+ );+}++const topics = [+ { id: "billing", name: "Billing questions" },+ { id: "setup", name: "Project setup" },+];+const rows = [+ {+ traceId: "trace-1",+ summary: "Refund an invoice",+ topicId: "billing",+ topicName: "Billing questions",+ outcome: "assigned",+ },+ {+ traceId: "trace-2",+ summary: "Create a project",+ topicId: "setup",+ topicName: "Project setup",+ outcome: "assigned",+ },+ {+ traceId: "trace-3",+ summary: "Refund a subscription",+ topicId: null,+ topicName: null,+ outcome: "outlier",+ },+ {+ traceId: "trace-4",+ summary: null,+ topicId: null,+ topicName: null,+ outcome: "insufficient_input",+ },+];++function ToolbarExample(args: ComponentProps<typeof TopicsTraceToolbar>) {+ const [filters, setFilters] = useState(args.filters);+ const [searchQuery, setSearchQuery] = useState(args.searchQuery);+ const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 20 });+ const matches = filterTopicTraces(rows, filters, searchQuery);+ return (+ <div className="flex max-w-2xl flex-col gap-2">+ <TopicsTraceToolbar+ {...args}+ filters={filters}+ searchQuery={searchQuery}+ onFiltersChange={(next) => {+ setFilters(next);+ args.onFiltersChange(next);+ }}+ onSearchQueryChange={(next) => {+ setSearchQuery(next);+ args.onSearchQueryChange(next);+ }}+ />+ <DataTable+ tableName="topics-toolbar-example"+ columns={[+ {+ accessorKey: "summary",+ header: "Summary",+ cell: ({ row }) => row.original.summary ?? row.original.traceId,+ },+ ]}+ data={{ isLoading: false, isError: false, data: matches }}+ pagination={{+ totalCount: matches.length,+ resultCountLabel: `${matches.length} of ${rows.length} traces`,+ state: pagination,+ onChange: setPagination,+ }}+ noResultsMessage="No matches. Adjust or clear your filters."+ />+ </div>+ );+}++const meta = preview.meta({+ component: TopicsTraceToolbar,+ args: {+ topics,+ filters: [],+ searchQuery: null,+ onFiltersChange: fn(),+ onSearchQueryChange: fn(),+ },+ render: (args) => <ToolbarExample {...args} />,+});++export const Default = meta.story({});+export const WithFilters = meta.story({+ args: {+ filters: [+ {+ column: "assignment",+ type: "stringOptions",+ operator: "any of",+ value: ["outlier"],+ },+ ],+ searchQuery: "refund",+ },+});+export const NoMatches = meta.story({ args: { searchQuery: "missing trace" } });++async function replaceQuery(search: HTMLElement, query: string) {+ await userEvent.click(search);+ await userEvent.clear(search);+ if (query) await userEvent.type(search, query);+ await userEvent.keyboard("{Enter}");+}++export const SearchAndClear = meta.story({+ name: "(Test) Search, Combine Filters and Clear",+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const search = canvas.getByRole("combobox", { name: "Search" });+ await replaceQuery(search, "invoice");+ await waitFor(() =>+ expect(canvas.getByRole("status")).toHaveTextContent("1 of 4 traces"),+ );+ await replaceQuery(+ search,+ 'topic:("Billing questions" OR "Project setup") assignment:Outlier invoice',+ );+ await waitFor(() =>+ expect(canvas.getByRole("status")).toHaveTextContent("0 of 4 traces"),+ );+ await expect(+ canvas.getByText("No matches. Adjust or clear your filters."),+ ).toBeVisible();+ await expect(search).toHaveTextContent("invoice");+ await expect(search).not.toHaveTextContent("in:");+ await expect(args.onFiltersChange).toHaveBeenLastCalledWith([+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: ["billing", "setup"],+ },+ {+ column: "assignment",+ type: "stringOptions",+ operator: "any of",+ value: ["outlier"],+ },+ ]);+ await expect(args.onSearchQueryChange).toHaveBeenLastCalledWith("invoice");+ await replaceQuery(search, "");+ await waitFor(() =>+ expect(canvas.getByRole("status")).toHaveTextContent("4 of 4 traces"),+ );+ },+});++export const Exclusions = meta.story({+ name: "(Test) Exclusions Can Be Removed",+ args: {+ filters: [+ {+ column: "assignment",+ type: "stringOptions",+ operator: "none of",+ value: ["outlier", "no_topic"],+ },+ ],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.getByRole("status")).toHaveTextContent("2 of 4 traces");+ await userEvent.hover(canvas.getByTestId("search-bar-token"));+ await userEvent.click(+ await canvas.findByRole("button", { name: /Remove -assignment/ }),+ );+ await waitFor(() =>+ expect(canvas.getByRole("status")).toHaveTextContent("4 of 4 traces"),+ );+ },+});++export const TopicAutocomplete = meta.story({+ name: "(Test) Topic Autocomplete Uses Stable IDs",+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const search = canvas.getByRole("combobox", { name: "Search" });+ await userEvent.click(search);+ await userEvent.type(search, "topic:");+ const option = await body.findByRole("option", {+ name: /Billing questions/,+ });+ await expect(+ body.getByRole("option", { name: /Project setup/ }),+ ).toBeVisible();+ await expect(option.closest(".ph-no-capture")).not.toBeNull();+ await userEvent.click(option);+ await userEvent.keyboard("{Enter}");+ await waitFor(() =>+ expect(canvas.getByRole("status")).toHaveTextContent("1 of 4 traces"),+ );+ await expect(args.onFiltersChange).toHaveBeenLastCalledWith([+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: ["billing"],+ },+ ]);+ await expect(canvas.getByTestId("search-bar-token")).toHaveTextContent(+ 'topic:"Billing questions"',+ );+ },+});++export const UnsupportedRestoredFilter = meta.story({+ name: "(Test) Unsupported Restored Filter Can Be Cleared",+ args: {+ filters: [{ column: "topicId", type: "number", operator: "=", value: 1 }],+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.getByRole("status")).toHaveTextContent("0 of 4 traces");+ await replaceQuery(canvas.getByRole("combobox", { name: "Search" }), "");+ await waitFor(() =>+ expect(canvas.getByRole("status")).toHaveTextContent("4 of 4 traces"),+ );+ },+});++export const FacetFiltersPersist = meta.story({+ name: "(Test) Facets Remember Their Filters",+ beforeEach: () => {+ const storageKey = "topics-trace-filters-v1";+ const snapshots = JSON.parse(+ localStorage.getItem(storageKey) ?? "{}",+ ) as Record<string, unknown>;+ for (const { facetId } of facets) {+ delete snapshots[JSON.stringify([facetPersistenceProject, facetId])];+ }+ localStorage.setItem(storageKey, JSON.stringify(snapshots));+ },+ render: () => (+ <QueryParamProvider+ adapter={MemoryQueryAdapter}+ options={{ enableBatching: true }}+ >+ <FacetToolbarExample />+ </QueryParamProvider>+ ),+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const search = canvas.getByRole("combobox", { name: "Search" });+ await replaceQuery(search, 'topic:"Billing questions" invoice');+ await waitFor(() => expect(search).toHaveTextContent("invoice"));+ await userEvent.click(canvas.getByRole("tab", { name: "Sentiment" }));+ await waitFor(() => {+ expect(search).not.toHaveTextContent("invoice");+ expect(canvas.queryByTestId("search-bar-token")).not.toBeInTheDocument();+ });+ await replaceQuery(search, "assignment:Outlier subscription");+ await waitFor(() => expect(search).toHaveTextContent("subscription"));+ await userEvent.click(canvas.getByRole("tab", { name: "Intent" }));+ await waitFor(() => {+ expect(search).toHaveTextContent("invoice");+ expect(search).toHaveTextContent('topic:"Billing questions"');+ expect(search).not.toHaveTextContent("subscription");+ });+ await userEvent.click(canvas.getByRole("tab", { name: "Sentiment" }));+ await waitFor(() => {+ expect(search).toHaveTextContent("subscription");+ expect(search).toHaveTextContent("assignment:Outlier");+ expect(search).not.toHaveTextContent("invoice");+ });+ },+});diff --git a/web/src/features/topics/TopicsTraceToolbar.tsx b/web/src/features/topics/TopicsTraceToolbar.tsxnew file mode 100644index 0000000000..a0091a2394--- /dev/null+++ b/web/src/features/topics/TopicsTraceToolbar.tsx@@ -0,0 +1,56 @@+import type { FilterState } from "@langfuse/shared";+import { TableSearchBar } from "@/src/features/search-bar";+import {+ createTopicTraceRegistry,+ TOPIC_ASSIGNMENT_OPTIONS,+} from "./topic-trace-filters";++export function TopicsTraceToolbar({+ projectId,+ topics,+ filters,+ onFiltersChange,+ searchQuery,+ onSearchQueryChange,+}: TopicsTraceToolbarProps) {+ const registry = createTopicTraceRegistry(topics, filters);+ const topicField = registry.fields.find((field) => field.id === "topic");++ return (+ <div className="shrink-0 border-b p-2">+ <TableSearchBar+ projectId={projectId}+ tableName="topics"+ registry={registry}+ filterState={filters}+ setFilterState={onFiltersChange}+ observed={{+ topic: topics.map((topic) => ({+ value:+ topicField?.displayValueByFilterValue?.get(topic.id) ??+ topic.name,+ })),+ assignment: TOPIC_ASSIGNMENT_OPTIONS.map((option) => ({+ value: option.displayValue,+ })),+ }}+ isV4={false}+ inset+ search={{+ query: searchQuery,+ type: ["id"],+ setQuery: onSearchQueryChange,+ }}+ />+ </div>+ );+}++type TopicsTraceToolbarProps = {+ projectId?: string;+ topics: { id: string; name: string }[];+ filters: FilterState;+ onFiltersChange: (filters: FilterState) => void;+ searchQuery: string | null;+ onSearchQueryChange: (query: string | null) => void;+};diff --git a/web/src/features/topics/map/TopicMapCanvas.tsx b/web/src/features/topics/map/TopicMapCanvas.tsxindex 63a5bceb57..1407c9beaf 100644--- a/web/src/features/topics/map/TopicMapCanvas.tsx+++ b/web/src/features/topics/map/TopicMapCanvas.tsx@@ -22,6 +22,7 @@ export function TopicMapCanvas({store,selectedTopic,selectedTraceId,+ matchingTraceIds,}: TopicMapCanvasProps) {const ref = useRef<HTMLCanvasElement>(null);const presentation = useRef<Presentation | null>(null);@@ -111,6 +112,7 @@ export function TopicMapCanvas({size,scene.pointer,selectedTopic,+ matchingTraceIds,);const hover = getTopicMapHover(state, frame);for (const point of model.points) {@@ -173,6 +175,7 @@ export function TopicMapCanvas({camera.zoom,selectedTopic,selectedTraceId,+ matchingTraceIds,]);return (<canvas@@ -190,7 +193,7 @@ function drawMap() {const context = canvas.getContext("2d");if (!context) return;- const { model, camera, size, readingTopic } = frame;+ const { model, camera, size, matchingTraceIds } = frame;const ratio = Math.min(window.devicePixelRatio || 1, 2);if (canvas.width !== Math.round(size.width * ratio) ||@@ -211,6 +214,12 @@ function drawMap(const { x, y, rx, ry } = zoneHalo(zone, camera, model.bounds, size);if (x + rx < 0 || x - rx > size.width || y + ry < 0 || y - ry > size.height)continue;+ context.globalAlpha =+ cloudVisibility *+ (!matchingTraceIds ||+ zone.points.some((point) => matchingTraceIds.has(point.traceId))+ ? 1+ : 0.15);context.save();context.translate(x, y);context.scale(rx, ry);@@ -227,10 +236,9 @@ function drawMap(for (const node of frame.nodes) {const { point, rect, cornerRadius } = node;const active = emphasis.get(point.traceId) ?? 0;- const opacity =- readingTopic && point.groupId !== readingTopic- ? 0.22 + active * 0.78- : 0.75 + point.depth * 0.2;+ const opacity = !node.matchesFilters+ ? 0.08 + active * 0.92+ : 0.75 + point.depth * 0.2;context.beginPath();context.roundRect(rect.x, rect.y, rect.width, rect.height, cornerRadius);context.globalAlpha = opacity;@@ -267,6 +275,7 @@ type TopicMapCanvasProps = {store: TopicMapStore;selectedTopic: string | null;selectedTraceId: string | null;+ matchingTraceIds?: ReadonlySet<string>;};type Presentation = {diff --git a/web/src/features/topics/map/TopicMapExplorer.tsx b/web/src/features/topics/map/TopicMapExplorer.tsxindex 57b341f30f..ef0b794a11 100644--- a/web/src/features/topics/map/TopicMapExplorer.tsx+++ b/web/src/features/topics/map/TopicMapExplorer.tsx@@ -70,6 +70,7 @@ export function TopicMapExplorer({onSelectTopic,onSelectTrace,selectedTraceId,+ matchingTraceIds,onOpenTrace,fillContainer = false,}: TopicMapExplorerProps) {@@ -158,7 +159,7 @@ export function TopicMapExplorer({);} else {cancelFlight();- setCamera(null, id);+ if (selectedTopic !== null) setCamera(null, id);}onSelectTopic(id);};@@ -260,6 +261,7 @@ export function TopicMapExplorer({!frame ||frame.model !== model ||frame.readingTopic !== selectedTopic ||+ frame.matchingTraceIds !== matchingTraceIds ||frame.size.width !== size.width ||frame.size.height !== size.height ||frame.camera.zoom !== intended.zoom ||@@ -289,7 +291,10 @@ export function TopicMapExplorer({const rect = event.currentTarget.getBoundingClientRect();const frame = store.getState().frame;const point =- frame && frame.model === model && frame.readingTopic === selectedTopic+ frame &&+ frame.model === model &&+ frame.readingTopic === selectedTopic &&+ frame.matchingTraceIds === matchingTraceIds? hitMapNode(frame, {x: event.clientX - rect.left,y: event.clientY - rect.top,@@ -432,6 +437,7 @@ export function TopicMapExplorer({store={store}selectedTopic={selectedTopic}selectedTraceId={selectedTraceId}+ matchingTraceIds={matchingTraceIds}/><MapLabelsmodel={model}@@ -439,6 +445,7 @@ export function TopicMapExplorer({store={store}selectedTopic={selectedTopic}selectedTraceId={selectedTraceId}+ matchingTraceIds={matchingTraceIds}onSelectTrace={handleSelectTrace}/>{model.points.length === 0 && (@@ -451,7 +458,11 @@ export function TopicMapExplorer({store={store}initialCamera={initialCamera}scope={selectedTopic}- population={model.populationLabel}+ population={+ matchingTraceIds+ ? `${model.points.filter((point) => matchingTraceIds.has(point.traceId)).length.toLocaleString()} of ${model.populationLabel} match`+ : model.populationLabel+ }missingSummaryCount={data.missingSummaryCount}unpositionedCount={data.unpositionedCount}/>@@ -538,15 +549,9 @@ function MapLabels({store,selectedTopic,selectedTraceId,+ matchingTraceIds,onSelectTrace,-}: {- model: TopicMapModel;- size: Size;- store: TopicMapStore;- selectedTopic: string | null;- selectedTraceId: string | null;- onSelectTrace: (id: string) => void;-}) {+}: MapLabelsProps) {const state = useStore(store);const frame = state.frame;const hover = getTopicMapHover(state, frame);@@ -555,7 +560,8 @@ function MapLabels({frame.model === model &&frame.size.width === size.width &&frame.size.height === size.height &&- frame.readingTopic === selectedTopic;+ frame.readingTopic === selectedTopic &&+ frame.matchingTraceIds === matchingTraceIds;const handleTraceClick = (event: ReactMouseEvent<HTMLButtonElement>) => {const traceId = event.currentTarget.dataset.traceId;if (traceId) onSelectTrace(traceId);@@ -762,6 +768,7 @@ export type TopicMapExplorerProps = {onSelectTopic: (id: string | null) => void;onSelectTrace: (traceId: string | null) => void;selectedTraceId: string | null;+ matchingTraceIds?: ReadonlySet<string>;onOpenTrace: (traceId: string) => void;fillContainer?: boolean;};@@ -775,4 +782,14 @@ type LayoutReadoutProps = {unpositionedCount: number;};+type MapLabelsProps = {+ model: TopicMapModel;+ size: Size;+ store: TopicMapStore;+ selectedTopic: string | null;+ selectedTraceId: string | null;+ matchingTraceIds?: ReadonlySet<string>;+ onSelectTrace: (id: string) => void;+};+export const __test = { fitMapPoints };diff --git a/web/src/features/topics/map/prepare-topic-map.ts b/web/src/features/topics/map/prepare-topic-map.tsindex ef18aba931..4716e8d658 100644--- a/web/src/features/topics/map/prepare-topic-map.ts+++ b/web/src/features/topics/map/prepare-topic-map.ts@@ -38,6 +38,7 @@ export type MapPosition = { x: number; y: number };type MapRectangle = MapPosition & { width: number; height: number };type TopicMapNode = {point: MapPoint;+ matchesFilters: boolean;center: MapPosition;worldPosition: MapPosition;rect: MapRectangle;@@ -55,6 +56,7 @@ export type TopicMapNodeFrame = {size: Size;pointer: MapPosition;readingTopic: string | null;+ matchingTraceIds: ReadonlySet<string> | undefined;zones: TopicMapModel["zones"];nodes: TopicMapNode[];nodeById: ReadonlyMap<string, TopicMapNode>;@@ -246,6 +248,7 @@ export function prepareMapNodes(size: Size,pointer: MapPosition,readingTopic: string | null = null,+ matchingTraceIds?: ReadonlySet<string>,): TopicMapNodeFrame {const full = readingNodeSize(size);const blend = nodeDetailBlend(camera.zoom);@@ -261,7 +264,10 @@ export function prepareMapNodes(y: projected.y + pointer.y * depth * 6,};const diameter = (5 + depth) * Math.sqrt(Math.min(camera.zoom, 16));- const growth = readingTopic && point.groupId !== readingTopic ? 0 : blend;+ const matchesFilters =+ (!readingTopic || point.groupId === readingTopic) &&+ (!matchingTraceIds || matchingTraceIds.has(point.traceId));+ const growth = matchesFilters ? blend : 0;const growWidth = (full.width - diameter) * growth;const growHeight = (full.height - diameter) * growth;const cellX = Math.floor(center.x / cellWidth);@@ -272,6 +278,7 @@ export function prepareMapNodes(cells.set(key, cell);return {point,+ matchesFilters,worldPosition,center,diameter,@@ -328,6 +335,7 @@ export function prepareMapNodes(const textOpacity = smoothStep(76, 132, width) * smoothStep(30, 64, height);const node: TopicMapNode = {point: item.point,+ matchesFilters: item.matchesFilters,center: item.center,worldPosition: item.worldPosition,rect: {@@ -360,6 +368,7 @@ export function prepareMapNodes(size,pointer,readingTopic,+ matchingTraceIds,zones: model.zones,nodes,nodeById,@@ -379,7 +388,7 @@ type MapTextLabel = {};export function prepareMapTextLabels(frame: TopicMapNodeFrame): MapTextLabel[] {- const { camera, model, size, readingTopic } = frame;+ const { camera, model, size, readingTopic, matchingTraceIds } = frame;const visibility = smoothStep(1.5, 3, camera.zoom);if (!visibility) return [];const detailOpacity = smoothStep(3.5, 7, camera.zoom);@@ -440,6 +449,9 @@ export function prepareMapTextLabels(frame: TopicMapNodeFrame): MapTextLabel[] {height,};if (!visible(rect)) continue;+ const matchesFilters =+ !matchingTraceIds ||+ zone.points.some((point) => matchingTraceIds.has(point.traceId));labels.push({id: zone.id,kind: "zone",@@ -449,7 +461,9 @@ export function prepareMapTextLabels(frame: TopicMapNodeFrame): MapTextLabel[] {rect,fontSize,opacity:- visibility * (readingTopic && readingTopic !== zone.id ? 0.32 : 0.45),+ visibility *+ (readingTopic && readingTopic !== zone.id ? 0.32 : 0.45) *+ (matchesFilters ? 1 : 0.15),detailOpacity,});}diff --git a/web/src/features/topics/map/topic-map-store.ts b/web/src/features/topics/map/topic-map-store.tsindex 060dad0468..64a467b546 100644--- a/web/src/features/topics/map/topic-map-store.ts+++ b/web/src/features/topics/map/topic-map-store.ts@@ -130,7 +130,8 @@ function sameFrameContext(captured.camera.zoom === frame.camera.zoom &&captured.size.width === frame.size.width &&captured.size.height === frame.size.height &&- captured.readingTopic === frame.readingTopic+ captured.readingTopic === frame.readingTopic &&+ captured.matchingTraceIds === frame.matchingTraceIds);}diff --git a/web/src/features/topics/topic-map-geometry.clienttest.ts b/web/src/features/topics/topic-map-geometry.clienttest.tsindex 559fc2aeb5..64a0e7eb9c 100644--- a/web/src/features/topics/topic-map-geometry.clienttest.ts+++ b/web/src/features/topics/topic-map-geometry.clienttest.ts@@ -786,3 +786,39 @@ describe("explicit map hover", () => {expect(prepareMapHover(frame, "trace-0", "billing").zones).toHaveLength(0);});});++it("filters reading detail without moving dots or dropping nonmatching hit targets", () => {+ const before = frameAt([+ { x: 250, y: 300 },+ { x: 750, y: 300 },+ ]);+ expect(before.nodes.every((node) => node.textOpacity > 0)).toBe(true);+ const filtered = prepareMapNodes(+ before.model,+ before.camera,+ before.size,+ pointer,+ null,+ new Set(["trace-0"]),+ );+ for (const node of before.nodes) {+ const after = filtered.nodeById.get(node.point.traceId)!;+ expect(after.center).toEqual(node.center);+ expect(after.worldPosition).toEqual(node.worldPosition);+ expect(hitMapNode(filtered, after.center)?.traceId).toBe(+ node.point.traceId,+ );+ }+ expect(filtered.nodeById.get("trace-0")?.textOpacity).toBeGreaterThan(0);+ expect(filtered.nodeById.get("trace-1")?.textOpacity).toBe(0);+ const empty = prepareMapNodes(+ before.model,+ before.camera,+ before.size,+ pointer,+ null,+ new Set(),+ );+ expect(empty.nodes).toHaveLength(2);+ expect(empty.nodes.every((node) => node.textOpacity === 0)).toBe(true);+});diff --git a/web/src/features/topics/topic-trace-filters.clienttest.ts b/web/src/features/topics/topic-trace-filters.clienttest.tsnew file mode 100644index 0000000000..b271a3f885--- /dev/null+++ b/web/src/features/topics/topic-trace-filters.clienttest.ts@@ -0,0 +1,363 @@+// @vitest-environment node++import type { FilterState } from "@langfuse/shared";+import { describe, expect, it } from "vitest";+import { astToFilterState } from "@/src/features/search-bar/lib/adapter";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";+import { parse } from "@/src/features/search-bar/lib/langQ";+import { runSearchBarInvariants } from "@/src/features/search-bar/lib/searchBarInvariants";+import {+ createTopicTraceRegistry,+ filterTopicTraces,+ getTopicAssignment,+ selectTopicTraceFilters,+} from "./topic-trace-filters";++const topics = [+ { id: "billing", name: "Billing questions" },+ { id: "support", name: "Support" },+];+const rows = [+ {+ traceId: "trace-one",+ summary: "Refund policy for a*b",+ topicId: "billing",+ topicName: "Billing questions",+ outcome: "assigned",+ },+ {+ traceId: "trace-two",+ summary: "Refund other policy",+ topicId: "support",+ topicName: "Support",+ outcome: "assigned",+ },+ {+ traceId: "trace-three",+ summary: "Refund policy",+ topicId: null,+ topicName: null,+ outcome: "outlier",+ },+ {+ traceId: "trace-four",+ summary: null,+ topicId: null,+ topicName: null,+ outcome: "not_applicable",+ },+ {+ traceId: "trace-five",+ summary: null,+ topicId: null,+ topicName: null,+ outcome: "insufficient_input",+ },+ {+ traceId: "trace-six",+ summary: "Pending refund policy",+ topicId: null,+ topicName: null,+ outcome: "awaiting_map",+ },+];+const ids = (result: typeof rows) => result.map((row) => row.traceId);++describe("topic trace filtering", () => {+ it("turns map and card selections into canonical filters", () => {+ const activeFilters: FilterState = [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: ["support", "billing"],+ },+ {+ column: "assignment",+ type: "stringOptions",+ operator: "none of",+ value: ["outlier"],+ },+ ];+ expect(selectTopicTraceFilters(activeFilters, null)).toEqual(activeFilters);+ expect(selectTopicTraceFilters(activeFilters, "outliers")).toEqual([+ {+ column: "assignment",+ type: "stringOptions",+ operator: "any of",+ value: ["outlier"],+ },+ ]);+ const billing: FilterState = [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: ["billing"],+ },+ ];+ expect(selectTopicTraceFilters(activeFilters, "billing")).toEqual(billing);+ expect(selectTopicTraceFilters(billing, "billing")).toEqual([]);+ expect(+ selectTopicTraceFilters([...billing, activeFilters[1]!], "billing"),+ ).toEqual(billing);+ expect(+ selectTopicTraceFilters(+ [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "none of",+ value: ["billing"],+ },+ ],+ "billing",+ ),+ ).toEqual(billing);+ });++ it("combines fields with AND and values within a field with OR", () => {+ const filters: FilterState = [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: ["billing", "support"],+ },+ {+ column: "assignment",+ type: "stringOptions",+ operator: "any of",+ value: ["assigned"],+ },+ ];+ expect(ids(filterTopicTraces(rows, filters, null))).toEqual([+ "trace-one",+ "trace-two",+ ]);+ expect(ids(filterTopicTraces(rows, filters, "REFUND POLICY"))).toEqual([+ "trace-one",+ ]);+ });++ it("excludes selected topics while retaining rows without a topic", () => {+ expect(+ ids(+ filterTopicTraces(+ rows,+ [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "none of",+ value: ["billing", "support"],+ },+ ],+ null,+ ),+ ),+ ).toEqual(["trace-three", "trace-four", "trace-five", "trace-six"]);+ });++ it("groups no-topic outcomes and supports assignment exclusions", () => {+ expect(getTopicAssignment("not_applicable")).toBe("no_topic");+ expect(getTopicAssignment("insufficient_input")).toBe("no_topic");+ expect(+ ids(+ filterTopicTraces(+ rows,+ [+ {+ column: "assignment",+ type: "stringOptions",+ operator: "none of",+ value: ["assigned", "outlier"],+ },+ ],+ null,+ ),+ ),+ ).toEqual(["trace-four", "trace-five", "trace-six"]);+ });++ it("searches summary, topic name and trace ID as a literal case-insensitive phrase", () => {+ expect(ids(filterTopicTraces(rows, [], "BILLING QUESTIONS"))).toEqual([+ "trace-one",+ ]);+ expect(ids(filterTopicTraces(rows, [], "TRACE-FOUR"))).toEqual([+ "trace-four",+ ]);+ expect(ids(filterTopicTraces(rows, [], "a*b"))).toEqual(["trace-one"]);+ expect(filterTopicTraces(rows, [], "refund%policy")).toEqual([]);+ expect(filterTopicTraces(rows, [], "questions refund")).toEqual([]);+ });++ it("handles empty results, cleared filters and empty positive selections", () => {+ expect(filterTopicTraces([], [], null)).toEqual([]);+ expect(filterTopicTraces(rows, [], " ")).toEqual(rows);+ expect(+ filterTopicTraces(+ rows,+ [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: [],+ },+ ],+ null,+ ),+ ).toEqual([]);+ expect(+ filterTopicTraces(+ rows,+ [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: ["missing"],+ },+ ],+ null,+ ),+ ).toEqual([]);+ });+});++describe("topic search registry", () => {+ const registry = createTopicTraceRegistry(topics);++ it("round-trips readable labels to stable IDs", () => {+ const parsed = astToFilterState(+ parse('topic:"Billing questions" assignment:"In a topic"', registry).ast,+ undefined,+ registry,+ );+ expect(parsed.errors).toEqual([]);+ expect(parsed.filters).toEqual([+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: ["billing"],+ },+ {+ column: "assignment",+ type: "stringOptions",+ operator: "any of",+ value: ["assigned"],+ },+ ]);+ const roundTrip = filterStateToQueryText(parsed.filters, {}, registry);+ expect(roundTrip.skippedFilters).toEqual([]);+ expect(roundTrip.text).toContain('topic:"Billing questions"');+ expect(roundTrip.text).not.toContain("topicId:");+ expect(+ astToFilterState(+ parse('topicId:"Billing questions" assignment:"In a topic"', registry)+ .ast,+ undefined,+ registry,+ ).filters,+ ).toEqual(parsed.filters);+ expect(+ astToFilterState(parse(roundTrip.text, registry).ast, undefined, registry)+ .filters,+ ).toEqual(parsed.filters);+ });++ it("keeps duplicate topic labels distinct", () => {+ const duplicateRegistry = createTopicTraceRegistry([+ { id: "one", name: "Support" },+ { id: "two", name: "Support" },+ ]);+ const filters: FilterState = [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: ["one", "two"],+ },+ ];+ const query = filterStateToQueryText(filters, {}, duplicateRegistry);+ expect(+ astToFilterState(+ parse(query.text, duplicateRegistry).ast,+ undefined,+ duplicateRegistry,+ ).filters,+ ).toEqual(filters);+ });++ it.each([["retired"], ["billing", "retired"]])(+ "keeps saved topic selections editable when options disappear: %j",+ (...values) => {+ const filters: FilterState = [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: values,+ },+ ];+ const savedRegistry = createTopicTraceRegistry(topics, filters);+ const query = filterStateToQueryText(filters, {}, savedRegistry);+ expect(query.skippedFilters).toEqual([]);+ const committed = planCommit(+ `${query.text} assignment:"In a topic" invoice`,+ undefined,+ savedRegistry,+ );+ expect(committed).toMatchObject({+ status: "committed",+ filters: filters.concat({+ column: "assignment",+ type: "stringOptions",+ operator: "any of",+ value: ["assigned"],+ }),+ searchQuery: "invoice",+ });+ expect(query.text).toContain("Unavailable topic (retired)");+ expect(+ planCommit('assignment:"In a topic" invoice', undefined, savedRegistry),+ ).toMatchObject({+ status: "committed",+ filters: [+ {+ column: "assignment",+ type: "stringOptions",+ operator: "any of",+ value: ["assigned"],+ },+ ],+ });+ },+ );++ it("rejects operators and fields the local evaluator cannot apply", () => {+ for (const query of ["topic:>billing", "topic:*bill*", "summary:refund"]) {+ expect(+ astToFilterState(parse(query, registry).ast, undefined, registry)+ .errors,+ query,+ ).not.toEqual([]);+ }+ });++ it("preserves shared search-bar validation and serialization invariants", () => {+ expect(+ runSearchBarInvariants({+ name: "topics",+ registry,+ extraKeys: [],+ scoreContexts: [{}],+ fieldValues: ["billing", "Support", '"Billing questions"', "outlier"],+ freeTextValues: ["refund policy", "or", "a*b", "trace-one"],+ }),+ ).toEqual([]);+ });+});diff --git a/web/src/features/topics/topic-trace-filters.ts b/web/src/features/topics/topic-trace-filters.tsnew file mode 100644index 0000000000..98f85c8b78--- /dev/null+++ b/web/src/features/topics/topic-trace-filters.ts@@ -0,0 +1,189 @@+import type { ColumnDefinition, FilterState } from "@langfuse/shared";+import {+ createFieldRegistry,+ fieldRegistryFromColumns,+ withFieldOptions,+} from "@/src/features/search-bar/lib/fields";++export const TOPIC_ASSIGNMENT_OPTIONS = [+ { value: "assigned", displayValue: "In a topic" },+ { value: "outlier", displayValue: "Outlier" },+ { value: "no_topic", displayValue: "No topic" },+ { value: "awaiting_map", displayValue: "Awaiting update" },+];++export function createTopicTraceRegistry(+ topics: readonly { id: string; name: string }[],+ filters: FilterState = [],+) {+ const topicOptions = withUnavailableTopicOptions(+ buildTopicOptions(topics),+ filters,+ );+ const columns: ColumnDefinition[] = [+ {+ id: "topicId",+ name: "Topic",+ type: "stringOptions",+ internal: "topicId",+ options: topicOptions,+ },+ {+ id: "assignment",+ name: "Assignment state",+ type: "stringOptions",+ internal: "assignment",+ options: TOPIC_ASSIGNMENT_OPTIONS,+ },+ ];+ const baseRegistry = fieldRegistryFromColumns(columns, {+ id: "topics",+ allowFreeText: true,+ aiFilterPrompt: false,+ defaultSearchType: ["id"],+ freeTextScopeLabel: "summaries, topic names and trace IDs",+ searchExamples: ['assignment:"Outlier"', 'topic:"Billing questions"'],+ fields: {+ assignment: { aliases: ["state", "status"] },+ },+ filterStateErrors: (filters) =>+ filters.some((filter) => filter.type !== "stringOptions")+ ? [+ "Topics support exact topic and assignment selections. Use the search field for text matching.",+ ]+ : [],+ });+ const registry = createFieldRegistry({+ ...baseRegistry,+ fields: baseRegistry.fields.map((field) =>+ field.id === "topicId"+ ? {+ ...field,+ id: "topic",+ aliases: ["topicId"],+ filterColumn: "topicId",+ }+ : field,+ ),+ });+ return withFieldOptions(+ withFieldOptions(registry, "topic", topicOptions),+ "assignment",+ TOPIC_ASSIGNMENT_OPTIONS,+ );+}++export function selectTopicTraceFilters(+ filters: FilterState,+ topicId: string | null,+): FilterState {+ if (topicId === null) return filters;+ if (topicId === "outliers")+ return [+ {+ column: "assignment",+ type: "stringOptions",+ operator: "any of",+ value: ["outlier"],+ },+ ];+ const selected = filters[0];+ if (+ filters.length === 1 &&+ selected?.column === "topicId" &&+ selected.type === "stringOptions" &&+ selected.operator === "any of" &&+ selected.value.length === 1 &&+ selected.value[0] === topicId+ )+ return [];+ return [+ {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: [topicId],+ },+ ];+}++export function filterTopicTraces<Row extends TopicTraceRow>(+ rows: readonly Row[],+ filters: FilterState,+ searchQuery: string | null,+): Row[] {+ const phrase = searchQuery?.trim().toLowerCase() ?? "";+ return rows.filter((row) => {+ if (+ phrase &&+ ![row.summary, row.topicName, row.traceId].some((value) =>+ value?.toLowerCase().includes(phrase),+ )+ )+ return false;+ return filters.every((filter) => {+ if (filter.type !== "stringOptions") return false;+ if (filter.column !== "topicId" && filter.column !== "assignment")+ return false;+ const value =+ filter.column === "topicId"+ ? row.topicId+ : getTopicAssignment(row.outcome);+ const matches = value !== null && filter.value.includes(value);+ return filter.operator === "any of" ? matches : !matches;+ });+ });+}++export function getTopicAssignment(outcome: string) {+ if (+ outcome === "assigned" ||+ outcome === "outlier" ||+ outcome === "awaiting_map"+ )+ return outcome;+ return "no_topic";+}++function buildTopicOptions(topics: readonly { id: string; name: string }[]) {+ const nameCounts = new Map<string, number>();+ for (const topic of topics)+ nameCounts.set(topic.name, (nameCounts.get(topic.name) ?? 0) + 1);+ return topics.map((topic) => ({+ value: topic.id,+ displayValue:+ (nameCounts.get(topic.name) ?? 0) > 1+ ? `${topic.name} (${topic.id})`+ : topic.name,+ }));+}++function withUnavailableTopicOptions(+ options: readonly { value: string; displayValue: string }[],+ filters: FilterState,+) {+ const topicOptions = [...options];+ const topicIds = new Set(options.map((option) => option.value));+ const labels = new Set(options.map((option) => option.displayValue));+ for (const filter of filters) {+ if (filter.column !== "topicId" || filter.type !== "stringOptions")+ continue;+ for (const id of filter.value) {+ if (topicIds.has(id)) continue;+ let displayValue = `Unavailable topic (${id})`;+ while (labels.has(displayValue)) displayValue += ` (${id})`;+ topicOptions.push({ value: id, displayValue });+ topicIds.add(id);+ labels.add(displayValue);+ }+ }+ return topicOptions;+}++type TopicTraceRow = {+ traceId: string;+ summary: string | null;+ topicId: string | null;+ topicName: string | null;+ outcome: string;+};diff --git a/web/src/features/topics/useTopicTraceFilters.clienttest.tsx b/web/src/features/topics/useTopicTraceFilters.clienttest.tsxnew file mode 100644index 0000000000..f3a28ba71c--- /dev/null+++ b/web/src/features/topics/useTopicTraceFilters.clienttest.tsx@@ -0,0 +1,177 @@+import { useState, type ReactNode } from "react";+import { act, renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ QueryParamProvider,+ type QueryParamAdapterComponent,+} from "use-query-params";+import { encodeFiltersGeneric, type FilterState } from "@langfuse/shared";+import { useTopicTraceFilters } from "./useTopicTraceFilters";++const topic: FilterState[number] = {+ column: "topicId",+ type: "stringOptions",+ operator: "any of",+ value: ["billing"],+};+const assignment: FilterState[number] = {+ column: "assignment",+ type: "stringOptions",+ operator: "any of",+ value: ["assigned"],+};+const facets = [{ facetId: "intent" }, { facetId: "sentiment" }];++function setup(initialSearch = "", projectId = "project") {+ let search = initialSearch;+ let navigate: (search: string) => void = () => {};+ const Adapter: QueryParamAdapterComponent = ({ children }) => {+ const [location, setLocation] = useState({ search: initialSearch });+ search = location.search;+ navigate = (search) => setLocation({ search });+ return children({ location, replace: setLocation, push: setLocation });+ };+ const hook = renderHook(() => useTopicTraceFilters(projectId, facets), {+ wrapper: ({ children }: { children: ReactNode }) => (+ <QueryParamProvider adapter={Adapter} options={{ enableBatching: true }}>+ {children}+ </QueryParamProvider>+ ),+ });+ return {+ ...hook,+ getSearch: () => search,+ back: () => navigate(initialSearch),+ };+}++beforeEach(() => {+ vi.restoreAllMocks();+ localStorage.clear();+});++describe("Topics facet-local filters", () => {+ it("remembers independent filters and search when switching facets and navigating Back", async () => {+ const { result, getSearch, back } = setup();+ act(() => {+ result.current.setFilters([topic]);+ result.current.setSearchQuery("invoice");+ });+ expect(result.current.filters).toEqual([topic]);+ expect(result.current.searchQuery).toBe("invoice");+ expect(getSearch()).toBe("");++ act(() => result.current.selectFacet("sentiment"));+ await waitFor(() =>+ expect(result.current.selectedFacetId).toBe("sentiment"),+ );+ expect(result.current.filters).toEqual([]);+ expect(result.current.searchQuery).toBeNull();+ act(() => {+ result.current.setFilters([assignment]);+ result.current.setSearchQuery("happy customer");+ });+ expect(result.current.filters).toEqual([assignment]);+ expect(result.current.searchQuery).toBe("happy customer");+ expect(new URLSearchParams(getSearch()).get("topicFacet")).toBe(+ "sentiment",+ );+ expect(new URLSearchParams(getSearch()).has("filter")).toBe(false);+ expect(new URLSearchParams(getSearch()).has("search")).toBe(false);++ act(back);+ await waitFor(() => expect(result.current.selectedFacetId).toBe("intent"));+ expect(result.current.filters).toEqual([topic]);+ expect(result.current.searchQuery).toBe("invoice");+ act(() => result.current.selectFacet("sentiment"));+ await waitFor(() =>+ expect(result.current.selectedFacetId).toBe("sentiment"),+ );+ expect(result.current.filters).toEqual([assignment]);+ expect(result.current.searchQuery).toBe("happy customer");+ });++ it("restores local state on a fresh visit, isolates projects and ignores URL filters", () => {+ const first = setup();+ act(() => {+ first.result.current.setFilters([topic]);+ first.result.current.setSearchQuery("invoice");+ });+ first.unmount();+ const restored = setup();+ expect(restored.result.current.filters).toEqual([topic]);+ expect(restored.result.current.searchQuery).toBe("invoice");+ restored.unmount();+ const otherProject = setup("", "other-project");+ expect(otherProject.result.current.filters).toEqual([]);+ expect(otherProject.result.current.searchQuery).toBeNull();+ otherProject.unmount();++ const url = `?${new URLSearchParams({+ topicFacet: "intent",+ filter: encodeFiltersGeneric([assignment]),+ search: "URL search",+ })}`;+ const withUrl = setup(url);+ expect(withUrl.result.current.filters).toEqual([topic]);+ expect(withUrl.result.current.searchQuery).toBe("invoice");+ act(() => {+ withUrl.result.current.setFilters([]);+ withUrl.result.current.setSearchQuery("local search");+ });+ expect(withUrl.getSearch()).toBe(url);+ expect(withUrl.result.current.filters).toEqual([]);+ expect(withUrl.result.current.searchQuery).toBe("local search");+ });++ it("persists clearing both fields in one event without resetting other facets", async () => {+ const first = setup();+ act(() => {+ first.result.current.setFilters([topic]);+ first.result.current.setSearchQuery("invoice");+ });+ act(() => first.result.current.selectFacet("sentiment"));+ await waitFor(() =>+ expect(first.result.current.selectedFacetId).toBe("sentiment"),+ );+ act(() => {+ first.result.current.setFilters([assignment]);+ first.result.current.setSearchQuery("happy");+ });+ act(() => {+ first.result.current.setFilters([]);+ first.result.current.setSearchQuery(null);+ });+ expect(first.result.current.filters).toEqual([]);+ expect(first.result.current.searchQuery).toBeNull();+ first.unmount();++ const cleared = setup("?topicFacet=sentiment");+ expect(cleared.result.current.filters).toEqual([]);+ expect(cleared.result.current.searchQuery).toBeNull();+ act(() => cleared.result.current.selectFacet("intent"));+ await waitFor(() =>+ expect(cleared.result.current.selectedFacetId).toBe("intent"),+ );+ expect(cleared.result.current.filters).toEqual([topic]);+ expect(cleared.result.current.searchQuery).toBe("invoice");+ });++ it("does not write storage or URL for unchanged filters", () => {+ const { result, getSearch } = setup();+ const setItem = vi.spyOn(Storage.prototype, "setItem");+ act(() => result.current.setFilters(result.current.filters));+ expect(setItem).not.toHaveBeenCalled();+ expect(getSearch()).toBe("");+ });++ it("ignores malformed cached state", () => {+ localStorage.setItem(+ "topics-trace-filters-v1",+ JSON.stringify({ broken: null }),+ );+ const { result } = setup();+ expect(result.current.filters).toEqual([]);+ expect(result.current.searchQuery).toBeNull();+ });+});diff --git a/web/src/features/topics/useTopicTraceFilters.ts b/web/src/features/topics/useTopicTraceFilters.tsnew file mode 100644index 0000000000..f5d5c40ef8--- /dev/null+++ b/web/src/features/topics/useTopicTraceFilters.ts@@ -0,0 +1,68 @@+import { useMemo } from "react";+import { StringParam, useQueryParam } from "use-query-params";+import { encodeFiltersGeneric, type FilterState } from "@langfuse/shared";+import { z } from "zod";+import useLocalStorage from "@/src/components/useLocalStorage";+import { decodeAndNormalizeFilters } from "@/src/features/filters/hooks/useSidebarFilterState";+import { createTopicTraceRegistry } from "./topic-trace-filters";+import { resolveTopicFacetId } from "./topic-facet-selection";++const columns = [...createTopicTraceRegistry([]).columns];+const snapshotSchema = z.object({+ filter: z.string(),+ search: z.string().nullable(),+});+const snapshotsSchema = z.record(z.string(), snapshotSchema);+const emptySnapshot: FacetFilterSnapshot = { filter: "", search: null };+const emptySnapshots: Record<string, FacetFilterSnapshot> = {};++export function useTopicTraceFilters(+ projectId: string,+ facets: readonly { facetId: string }[],+) {+ const [facetId, setFacetId] = useQueryParam("topicFacet", StringParam);+ const selectedFacetId = resolveTopicFacetId(facets, facetId ?? undefined);+ const [stored, setStored] = useLocalStorage<unknown>(+ "topics-trace-filters-v1",+ emptySnapshots,+ );+ const parsed = snapshotsSchema.safeParse(stored);+ const snapshots = parsed.success ? parsed.data : emptySnapshots;+ const storageKey = JSON.stringify([projectId, selectedFacetId]);+ const snapshot = snapshots[storageKey] ?? emptySnapshot;+ const filters = useMemo(+ () => decodeAndNormalizeFilters(snapshot.filter, columns),+ [snapshot.filter],+ );++ function updateSnapshot(patch: Partial<FacetFilterSnapshot>) {+ if (!selectedFacetId) return;+ setStored((previous: unknown) => {+ const parsedPrevious = snapshotsSchema.safeParse(previous);+ const snapshots = parsedPrevious.success+ ? parsedPrevious.data+ : emptySnapshots;+ const current = snapshots[storageKey] ?? emptySnapshot;+ const next = { ...current, ...patch };+ if (next.filter === current.filter && next.search === current.search)+ return previous;+ return { ...snapshots, [storageKey]: next };+ });+ }++ function selectFacet(nextFacetId: string) {+ if (nextFacetId !== selectedFacetId) setFacetId(nextFacetId);+ }++ return {+ selectedFacetId,+ selectFacet,+ filters,+ setFilters: (filters: FilterState) =>+ updateSnapshot({ filter: encodeFiltersGeneric(filters) }),+ searchQuery: snapshot.search,+ setSearchQuery: (search: string | null) => updateSnapshot({ search }),+ };+}++type FacetFilterSnapshot = z.infer<typeof snapshotSchema>;