Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(web): bring back the Topics cluster map as a third results view (#19179)

Lysander Kiesel1443bdb446c7
diff --git a/web/src/features/topics/CurrentTopics.tsx b/web/src/features/topics/CurrentTopics.tsx
index 5d4c963f9f..69b4b9351f 100644
--- a/web/src/features/topics/CurrentTopics.tsx
+++ b/web/src/features/topics/CurrentTopics.tsx
@@ -6,9 +6,11 @@ import { getQueryKey } from "@trpc/react-query";
import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { api, type RouterOutputs } from "@/src/utils/api";
import { isValidTopicTimeRange } from "./time-range";
+import { CurrentTopicsView } from "./CurrentTopicsView";
import { TopicGridView } from "./TopicGridView";
import { TopicTreemapView } from "./TopicTreemapView";
import { type TopicsResultsView } from "./TopicsResultsViewSelect";
+import type { useTopicTraceFilters } from "./useTopicTraceFilters";
export function CurrentTopics({
projectId,
@@ -17,6 +19,7 @@ export function CurrentTopics({
selectedFacetId,
view,
tracePanelRef,
+ traceFilters,
onGenerateTopics,
canGenerateTopics,
}: CurrentTopicsProps) {
@@ -48,6 +51,7 @@ export function CurrentTopics({
timeRange={timeRange}
view={view}
tracePanelRef={tracePanelRef}
+ traceFilters={traceFilters}
onGenerateTopics={onGenerateTopics}
canGenerateTopics={canGenerateTopics}
/>
@@ -62,6 +66,7 @@ function CurrentFacet({
timeRange,
view,
tracePanelRef,
+ traceFilters,
onGenerateTopics,
canGenerateTopics,
}: CurrentFacetProps) {
@@ -86,6 +91,20 @@ function CurrentFacet({
peekView={peekView}
/>
);
+ if (view === "map")
+ return (
+ <CurrentTopicsView
+ projectId={projectId}
+ facet={facet}
+ mapResult={mapResult}
+ tracePanelRef={tracePanelRef}
+ traceFilters={traceFilters}
+ onGenerateTopics={onGenerateTopics}
+ canGenerateTopics={canGenerateTopics}
+ onOpenTrace={peekNavigation.openPeek}
+ peekView={peekView}
+ />
+ );
return (
<TopicGridView
projectId={projectId}
@@ -159,6 +178,7 @@ type CurrentTopicsProps = {
selectedFacetId: string | undefined;
view: TopicsResultsView;
tracePanelRef?: (element: HTMLElement | null) => void;
+ traceFilters: ReturnType<typeof useTopicTraceFilters>;
onGenerateTopics: () => void;
canGenerateTopics: boolean;
};
@@ -169,6 +189,7 @@ type CurrentFacetProps = {
timeRange: TopicTimeRange;
view: TopicsResultsView;
tracePanelRef?: (element: HTMLElement | null) => void;
+ traceFilters: ReturnType<typeof useTopicTraceFilters>;
onGenerateTopics: () => void;
canGenerateTopics: boolean;
};
diff --git a/web/src/features/topics/CurrentTopicsView.stories.tsx b/web/src/features/topics/CurrentTopicsView.stories.tsx
new file mode 100644
index 0000000000..a1b660568e
--- /dev/null
+++ b/web/src/features/topics/CurrentTopicsView.stories.tsx
@@ -0,0 +1,570 @@
+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(),
+ onGenerateTopics: fn(),
+ canGenerateTopics: true,
+ peekView: {
+ itemType: "TRACE",
+ tableName: "topics-current-traces",
+ isV4: false,
+ closePeek: fn(),
+ },
+};
+
+const meta = preview.meta({
+ component: CurrentTopicsView,
+ args: defaultArgs,
+ render: (args) => <ControlledTopics {...args} />,
+ beforeEach: () => {
+ sessionStorage.removeItem("topics-selected-trace:storybook-topics");
+ return () =>
+ sessionStorage.removeItem("topics-selected-trace:storybook-topics");
+ },
+});
+
+export const Default = meta.story({});
+
+export const LongTopicNames = meta.story({
+ args: {
+ facet: {
+ ...facet,
+ topics: [
+ { ...topic, name: "Unresolved issue handling failures" },
+ {
+ ...topic,
+ id: "results",
+ name: "Unsupported or incomplete final task results",
+ },
+ ],
+ rows: [
+ {
+ ...rows[0],
+ topicName: "Unresolved issue handling failures",
+ summary:
+ "The troubleshooting step claimed success without verifying that sending messages worked.",
+ },
+ {
+ ...rows[1],
+ topicId: "results",
+ topicName: "Unsupported or incomplete final task results",
+ outcome: "assigned",
+ },
+ { ...rows[2], topicId: null, topicName: null, outcome: "outlier" },
+ {
+ ...rows[3],
+ topicId: null,
+ topicName: null,
+ outcome: "insufficient_input",
+ summary: "",
+ },
+ ],
+ },
+ },
+});
+
+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>;
+
+export const SummariesWithoutTopics = meta.story({
+ name: "(Test) Summaries without topics open generation",
+ args: {
+ facet: {
+ ...facet,
+ map: null,
+ topics: [],
+ rows: rows.map((row) => ({
+ ...row,
+ topicId: null,
+ topicName: null,
+ outcome: "awaiting_map",
+ })),
+ },
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas.getByRole("region", { name: "Topic traces" }),
+ ).toBeVisible();
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Generate topics" }),
+ );
+ await expect(args.onGenerateTopics).toHaveBeenCalledOnce();
+ },
+});
+
+export const ExistingTopicsWithoutAssignments = meta.story({
+ name: "(Test) Empty range keeps existing topics without prompting regeneration",
+ args: { facet: { ...facet, topics: [], rows: [] } },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas.queryByRole("button", { name: "Generate topics" }),
+ ).not.toBeInTheDocument();
+ await expect(
+ canvas.getByRole("region", { name: "Topic traces" }),
+ ).toBeVisible();
+ },
+});
+
+export const PanelSizesPersistAcrossFacetsAndLayouts = meta.story({
+ name: "(Test) Panel sizes persist across facets and layouts",
+ beforeEach: resetPanelSizes,
+ render: function Render(args) {
+ const [facetId, setFacetId] = useState("intent");
+ function switchFacet() {
+ setFacetId((previous) =>
+ previous === "intent" ? "sentiment" : "intent",
+ );
+ }
+ return (
+ <div className="flex flex-col gap-2">
+ <Button text="Switch facet" onClick={switchFacet} />
+ <ControlledTopics
+ key={facetId}
+ {...args}
+ facet={{ ...args.facet, facetId }}
+ />
+ </div>
+ );
+ },
+ play: async ({ canvasElement }) => {
+ if (!("__vitest_browser__" in globalThis)) return;
+
+ const { page } = await import("vitest/browser");
+ const originalViewport = {
+ width: window.innerWidth,
+ height: window.innerHeight,
+ };
+ const canvas = within(canvasElement);
+ function panelSizes() {
+ return canvas
+ .getAllByRole("separator", { name: /^Resize topic/ })
+ .map((divider) => divider.getAttribute("aria-valuenow"));
+ }
+ async function resizePanel(name: string, key: string) {
+ canvas.getByRole("separator", { name }).focus();
+ await userEvent.keyboard(key);
+ }
+ async function switchFacet() {
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Switch facet" }),
+ );
+ }
+ try {
+ await page.viewport(1280, 900);
+ await resizePanel("Resize topic overview and traces", "{ArrowRight}");
+ await resizePanel("Resize topic map and groups", "{ArrowDown}");
+ const desktopSizes = panelSizes();
+ await switchFacet();
+ await waitFor(() => expect(panelSizes()).toEqual(desktopSizes));
+
+ await page.viewport(700, 900);
+ await canvas.findByRole("tab", { name: "Topics" });
+ await resizePanel("Resize topic map and groups", "{ArrowUp}");
+ const narrowSizes = panelSizes();
+ await switchFacet();
+ await waitFor(() => expect(panelSizes()).toEqual(narrowSizes));
+
+ await page.viewport(1280, 900);
+ await waitFor(() => expect(panelSizes()).toEqual(desktopSizes));
+ await page.viewport(700, 900);
+ await waitFor(() => expect(panelSizes()).toEqual(narrowSizes));
+ } finally {
+ await page.viewport(originalViewport.width, originalViewport.height);
+ }
+ },
+});
+
+function resetPanelSizes() {
+ const keys = [
+ "react-resizable-panels:topics-workspace-size:overview:traces",
+ "react-resizable-panels:topics-overview-size:map:groups",
+ "react-resizable-panels:topics-overview-size-narrow:map:groups",
+ ];
+ keys.forEach((key) => localStorage.removeItem(key));
+ return () => keys.forEach((key) => localStorage.removeItem(key));
+}
+
+export const TraceSelectionAcrossFacets = meta.story({
+ name: "(Test) Map selection follows traces across facets without opening peek",
+ args: {
+ peekView: { ...defaultArgs.peekView, openPeek: fn() },
+ },
+ render: function Render(args) {
+ const [facetId, setFacetId] = useState("intent");
+ function switchFacet() {
+ setFacetId((value) => (value === "intent" ? "sentiment" : "intent"));
+ }
+ return (
+ <div>
+ <Button text="Switch facet" onClick={switchFacet} />
+ <ControlledTopics
+ key={facetId}
+ {...args}
+ facet={{
+ ...args.facet,
+ facetId,
+ rows: [...args.facet.rows].reverse(),
+ }}
+ />
+ </div>
+ );
+ },
+ play: async ({ canvasElement, args }) => {
+ 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 at = screenPoint(
+ model.pointById.get("trace-0")!,
+ camera,
+ model.bounds,
+ size,
+ );
+ function clickMap(x = at.x, y = at.y) {
+ const map = canvas.getByRole("group", { name: /^Interactive topic map/ });
+ const bounds = map.getBoundingClientRect();
+ map.dispatchEvent(
+ new MouseEvent("click", {
+ bubbles: true,
+ clientX: bounds.left + x,
+ clientY: bounds.top + y,
+ }),
+ );
+ }
+ await afterPaint();
+ clickMap();
+ await expect(args.onOpenTrace).not.toHaveBeenCalled();
+ await waitFor(() => {
+ const row = canvas.getByRole("link", { name: "trace-0" }).closest("tr")!;
+ expect(row).toHaveAttribute("aria-selected", "true");
+ const panel = canvas.getByRole("region", { name: "Topic traces" });
+ expect(row.getBoundingClientRect().bottom).toBeLessThanOrEqual(
+ panel.getBoundingClientRect().bottom,
+ );
+ expect(
+ JSON.parse(
+ sessionStorage.getItem("topics-selected-trace:storybook-topics")!,
+ ),
+ ).toBe("trace-0");
+ });
+ const refresh = canvas.getByRole("button", {
+ name: "Refresh unchanged results",
+ });
+ await userEvent.click(refresh);
+ await expect(
+ canvas.getByRole("link", { name: "trace-0" }).closest("tr"),
+ ).toHaveAttribute("aria-selected", "true");
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Go to next page" }),
+ );
+ await userEvent.click(refresh);
+ await expect(canvas.getByRole("link", { name: "trace-99" })).toBeVisible();
+ clickMap();
+ await waitFor(() =>
+ expect(canvas.getByRole("link", { name: "trace-0" })).toBeVisible(),
+ );
+ clickMap(5, 5);
+ await waitFor(() =>
+ expect(
+ canvas.getByRole("link", { name: "trace-0" }).closest("tr"),
+ ).not.toHaveAttribute("aria-selected"),
+ );
+ clickMap();
+ await userEvent.click(canvas.getByRole("button", { name: "Switch facet" }));
+ await expect(
+ canvas.getByRole("link", { name: "trace-0" }).closest("tr"),
+ ).toHaveAttribute("aria-selected", "true");
+ for (
+ let attempt = 0;
+ attempt < 16 &&
+ !canvas.queryByRole("button", {
+ name: /^Select trace:.*Account setup 0/,
+ });
+ attempt++
+ ) {
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Zoom in (+)" }),
+ );
+ await afterPaint();
+ }
+ const selected = canvas.getByRole("button", {
+ name: /^Select trace:.*Account setup 0/,
+ });
+ await expect(selected).toHaveAttribute("aria-pressed", "true");
+ await userEvent.click(selected);
+ await expect(args.onOpenTrace).not.toHaveBeenCalled();
+ await userEvent.click(canvas.getByRole("link", { name: "trace-0" }));
+ await expect(args.onOpenTrace).toHaveBeenCalledOnce();
+ await expect(args.onOpenTrace).toHaveBeenCalledWith("trace-0");
+ await userEvent.click(canvas.getByText("Account setup 1"));
+ await expect(args.peekView.openPeek).toHaveBeenCalledOnce();
+ await expect(
+ canvas.getByRole("link", { name: "trace-1" }).closest("tr"),
+ ).toHaveAttribute("aria-selected", "true");
+ const search = canvas.getByRole("combobox", { name: "Search" });
+ await replaceQuery(search, "invoice");
+ await waitFor(() =>
+ expect(
+ canvas.queryByRole("link", { name: "trace-0" }),
+ ).not.toBeInTheDocument(),
+ );
+ clickMap();
+ await afterPaint();
+ await expect(
+ sessionStorage.getItem("topics-selected-trace:storybook-topics"),
+ ).toBe(JSON.stringify("trace-1"));
+ await replaceQuery(search, "");
+ await waitFor(() =>
+ expect(
+ canvas.getByRole("link", { name: "trace-1" }).closest("tr"),
+ ).toHaveAttribute("aria-selected", "true"),
+ );
+ },
+});
diff --git a/web/src/features/topics/CurrentTopicsView.tsx b/web/src/features/topics/CurrentTopicsView.tsx
new file mode 100644
index 0000000000..7bafecfd9b
--- /dev/null
+++ b/web/src/features/topics/CurrentTopicsView.tsx
@@ -0,0 +1,569 @@
+import { computeSelectedValues, type FilterState } from "@langfuse/shared";
+import {
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ComponentProps,
+ type ReactNode,
+} from "react";
+import { useMediaQuery } from "react-responsive";
+import { type OnChangeFn, type PaginationState } from "@tanstack/react-table";
+import { DataTable } from "@/src/components/table/data-table";
+import useSessionStorage from "@/src/components/useSessionStorage";
+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 {
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+ useDefaultLayout,
+} from "@/src/components/ui/resizable";
+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";
+
+const OVERVIEW_PANEL_IDS = ["map", "groups"];
+const WORKSPACE_PANEL_IDS = ["overview", "traces"];
+
+export function CurrentTopicsView({
+ projectId,
+ facet,
+ mapResult,
+ onOpenTrace,
+ peekView,
+ tracePanelRef,
+ traceFilters,
+ onGenerateTopics,
+ canGenerateTopics,
+}: CurrentTopicsViewProps) {
+ const [selectedTraceId, setSelectedTraceId] = useSessionStorage<
+ string | null
+ >(`topics-selected-trace:${projectId}`, 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);
+ const [pageRequest, setPageRequest] = useState({
+ filterKey,
+ pageIndex: 0,
+ followSelection: true,
+ });
+ if (pageRequest.filterKey !== filterKey) {
+ setPageRequest({ filterKey, pageIndex: 0, followSelection: true });
+ }
+ function selectTopic(topicId: string | null) {
+ setFilters(selectTopicTraceFilters(filters, topicId));
+ }
+ function openTrace(traceId: string) {
+ selectTrace(traceId);
+ onOpenTrace(traceId);
+ }
+ const { visible, matchingTraceKey } = useMemo(() => {
+ const isFiltered = filters.length > 0 || Boolean(searchQuery?.trim());
+ const visible = isFiltered
+ ? filterTopicTraces(facet.rows, filters, searchQuery)
+ : facet.rows;
+ return {
+ visible,
+ matchingTraceKey: isFiltered
+ ? JSON.stringify([...new Set(visible.map((row) => row.traceId))].sort())
+ : null,
+ };
+ }, [facet.rows, filters, searchQuery]);
+ const selectedRowIndex = visible.findIndex(
+ (row) => row.traceId === selectedTraceId,
+ );
+ const { followSelection } = pageRequest;
+ const pageIndex = Math.min(
+ followSelection && selectedRowIndex >= 0
+ ? Math.floor(selectedRowIndex / pageSize)
+ : pageRequest.pageIndex,
+ Math.max(0, Math.ceil(visible.length / pageSize) - 1),
+ );
+ const pagination = { pageIndex, pageSize };
+ function selectTrace(traceId: string | null) {
+ setSelectedTraceId(traceId);
+ setPageRequest({ filterKey, pageIndex, followSelection: traceId !== null });
+ }
+ const onPaginationChange: OnChangeFn<PaginationState> = (update) => {
+ const next = typeof update === "function" ? update(pagination) : update;
+ setPageRequest({
+ filterKey,
+ pageIndex: next.pageIndex,
+ followSelection: false,
+ });
+ setPageSize(next.pageSize);
+ };
+ /** 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 mapPanel = (
+ <section
+ aria-label="Topic map"
+ className="flex h-full min-h-0 min-w-0 flex-col overflow-hidden"
+ >
+ {facet.map ? (
+ <TopicEmbeddingMap
+ key={facet.map.runId}
+ query={mapResult}
+ projectId={projectId}
+ topics={facet.map.topics}
+ selectedTopic={null}
+ matchingTraceIds={matchingTraceIds}
+ onSelectTopic={selectTopic}
+ onSelectTrace={selectTrace}
+ selectedTraceId={
+ selectedTraceId &&
+ (!matchingTraceIds || matchingTraceIds.has(selectedTraceId))
+ ? selectedTraceId
+ : null
+ }
+ fillContainer
+ />
+ ) : null}
+ </section>
+ );
+ const emptyTopics = (
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 p-6 text-center">
+ <h3 className="text-lg font-bold">Find patterns in your summaries</h3>
+ <p className="text-muted-foreground max-w-sm text-sm">
+ Generate topics to group similar summaries and discover recurring themes
+ for this facet. Choose a time range and the facets to include in Manual
+ processing.
+ </p>
+ <Button
+ text="Generate topics"
+ size="sm"
+ disabled={!canGenerateTopics}
+ onClick={onGenerateTopics}
+ />
+ </div>
+ );
+ const groupsPanel = (
+ <section
+ aria-label="Topic groups"
+ className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-md border"
+ >
+ <div className="flex min-h-0 flex-1 flex-col 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 &&
+ (facet.map?.topics.length ? (
+ <p className="text-muted-foreground p-6 text-center text-sm">
+ No topic assignments in this time range. Choose a different time
+ range to explore existing topics.
+ </p>
+ ) : (
+ emptyTopics
+ ))}
+ </div>
+ </section>
+ );
+ const tracesPanel = (
+ <section
+ aria-label="Topic traces"
+ ref={isNarrow ? undefined : tracePanelRef}
+ className="flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-md border"
+ >
+ <TopicsTraceToolbar
+ projectId={projectId}
+ topics={topics}
+ filters={filters}
+ onFiltersChange={setFilters}
+ searchQuery={searchQuery}
+ onSearchQueryChange={setSearchQuery}
+ />
+ <CurrentTraceTable
+ key={filterKey}
+ projectId={projectId}
+ onOpenTrace={openTrace}
+ selectedTraceId={selectedTraceId}
+ onSelectTrace={selectTrace}
+ peekView={peekView}
+ rows={visible}
+ totalCount={facet.rows.length}
+ topics={topics}
+ pagination={pagination}
+ onPaginationChange={onPaginationChange}
+ revealRowIndex={followSelection ? selectedRowIndex : -1}
+ />
+ </section>
+ );
+ const detailsPanel = isNarrow ? (
+ <TopicsDetailsTabs
+ value={mobilePanel}
+ onValueChange={setMobilePanel}
+ tracePanelRef={tracePanelRef}
+ groupsPanel={groupsPanel}
+ tracesPanel={tracesPanel}
+ />
+ ) : (
+ groupsPanel
+ );
+ const overviewPanel = (
+ <TopicsOverviewSplit
+ isNarrow={isNarrow}
+ hasMap={facet.map !== null}
+ mapPanel={mapPanel}
+ >
+ {detailsPanel}
+ </TopicsOverviewSplit>
+ );
+
+ return (
+ <TopicsWorkspaceSplit
+ isNarrow={isNarrow}
+ overviewPanel={overviewPanel}
+ tracesPanel={tracesPanel}
+ />
+ );
+}
+
+function TopicsDetailsTabs({
+ value,
+ onValueChange,
+ tracePanelRef,
+ groupsPanel,
+ tracesPanel,
+}: TopicsDetailsTabsProps) {
+ return (
+ <Tabs
+ value={value}
+ onValueChange={onValueChange}
+ 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>
+ );
+}
+
+function TopicsOverviewSplit({
+ isNarrow,
+ hasMap,
+ mapPanel,
+ children,
+}: TopicsOverviewSplitProps) {
+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({
+ id: isNarrow ? "topics-overview-size-narrow" : "topics-overview-size",
+ panelIds: OVERVIEW_PANEL_IDS,
+ storage: "local",
+ });
+
+ if (!hasMap) return children;
+
+ return (
+ <ResizablePanelGroup
+ orientation="vertical"
+ defaultLayout={defaultLayout}
+ onLayoutChanged={onLayoutChanged}
+ className="min-h-0 min-w-0 flex-1"
+ >
+ <ResizablePanel
+ id="map"
+ defaultSize={isNarrow ? "45%" : "60%"}
+ minSize="20%"
+ >
+ {mapPanel}
+ </ResizablePanel>
+ <ResizableHandle
+ withHandle
+ aria-label="Resize topic map and groups"
+ className="my-1"
+ />
+ <ResizablePanel id="groups" minSize="20%">
+ {children}
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ );
+}
+
+function TopicsWorkspaceSplit({
+ isNarrow,
+ overviewPanel,
+ tracesPanel,
+}: TopicsWorkspaceSplitProps) {
+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({
+ id: "topics-workspace-size",
+ panelIds: WORKSPACE_PANEL_IDS,
+ storage: "local",
+ });
+ if (isNarrow) return overviewPanel;
+
+ return (
+ <ResizablePanelGroup
+ orientation="horizontal"
+ defaultLayout={defaultLayout}
+ onLayoutChanged={onLayoutChanged}
+ className="min-h-0 min-w-0 flex-1"
+ >
+ <ResizablePanel id="overview" defaultSize="50%" minSize="25%">
+ {overviewPanel}
+ </ResizablePanel>
+ <ResizableHandle
+ withHandle
+ aria-label="Resize topic overview and traces"
+ className="mx-1"
+ />
+ <ResizablePanel id="traces" minSize="25%">
+ {tracesPanel}
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ );
+}
+
+function CurrentTraceTable({
+ projectId,
+ onOpenTrace,
+ selectedTraceId,
+ onSelectTrace,
+ peekView,
+ rows,
+ totalCount,
+ topics,
+ pagination,
+ onPaginationChange,
+ revealRowIndex,
+}: CurrentTraceTableProps) {
+ const tableRef = useRef<HTMLDivElement>(null);
+ const { pageIndex } = pagination;
+ useEffect(() => {
+ if (revealRowIndex >= 0) {
+ tableRef.current
+ ?.querySelector('[aria-selected="true"]')
+ ?.scrollIntoView({ block: "nearest" });
+ }
+ }, [selectedTraceId, revealRowIndex, pageIndex]);
+ const isMobile = useIsMobile();
+ const topicColors = new Map(
+ topics.map((topic, index) => [topic.id, topicBadgeColor(index)]),
+ );
+ function selectRow(row: Facet["rows"][number]) {
+ onSelectTrace(row.traceId);
+ }
+ 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);
+ }
+ return (
+ <div className="flex flex-col items-start gap-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>
+ </div>
+ );
+ },
+ },
+ ];
+ return (
+ <div
+ ref={tableRef}
+ 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="relaxed"
+ noResultsMessage="No matches. Adjust or clear your filters."
+ rowSelection={selectedTraceId ? { [selectedTraceId]: true } : {}}
+ onRowClick={selectRow}
+ peekView={peekView}
+ />
+ </div>
+ );
+}
+
+type TopicsDetailsTabsProps = {
+ value: string;
+ onValueChange: (value: string) => void;
+ tracePanelRef: CurrentTopicsViewProps["tracePanelRef"];
+ groupsPanel: ReactNode;
+ tracesPanel: ReactNode;
+};
+
+type TopicsOverviewSplitProps = {
+ isNarrow: boolean;
+ hasMap: boolean;
+ mapPanel: ReactNode;
+ children: ReactNode;
+};
+
+type TopicsWorkspaceSplitProps = {
+ isNarrow: boolean;
+ overviewPanel: ReactNode;
+ tracesPanel: ReactNode;
+};
+
+type CurrentTraceTableProps = {
+ projectId: string;
+ onOpenTrace: (traceId: string) => void;
+ selectedTraceId: string | null;
+ onSelectTrace: (traceId: string) => void;
+ peekView: DataTablePeekViewProps;
+ rows: Facet["rows"];
+ totalCount: number;
+ topics: { id: string }[];
+ pagination: PaginationState;
+ onPaginationChange: OnChangeFn<PaginationState>;
+ revealRowIndex: number;
+};
+
+type CurrentTopicsViewProps = {
+ projectId: string;
+ facet: Facet;
+ onGenerateTopics: () => void;
+ canGenerateTopics: boolean;
+ 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;
+ peekView: DataTablePeekViewProps;
+};
+
+type Facet = RouterOutputs["topics"]["currentResults"]["facets"][number];
diff --git a/web/src/features/topics/EmbeddingMapView.stories.tsx b/web/src/features/topics/EmbeddingMapView.stories.tsx
new file mode 100644
index 0000000000..ace0cb8034
--- /dev/null
+++ b/web/src/features/topics/EmbeddingMapView.stories.tsx
@@ -0,0 +1,1025 @@
+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 { EmbeddingMapView } from "./EmbeddingMapView";
+import {
+ fitCamera,
+ prepareTopicMap,
+ screenPoint,
+ zoomCamera,
+} from "./map/prepare-topic-map";
+
+type ExplorerProps = ComponentProps<typeof EmbeddingMapView>;
+
+const data = {
+ points: [
+ {
+ traceId: "trace-billing",
+ summary: "Customer asks for a copy of an invoice.",
+ topicId: "billing",
+ outcome: "assigned",
+ x: 0,
+ y: 0,
+ },
+ {
+ traceId: "trace-outlier",
+ summary: "Customer asks about a new integration.",
+ topicId: null,
+ outcome: "outlier",
+ x: 3,
+ y: 1,
+ },
+ ],
+ missingSummaryCount: 0,
+ unpositionedCount: 0,
+} satisfies ComponentProps<typeof EmbeddingMapView>["data"];
+
+const issueClusters = [
+ {
+ id: "product-context",
+ name: "Stale product context",
+ description:
+ "Answers rely on older catalog pages instead of current product details.",
+ center: [-55, -28],
+ count: 36,
+ summaries: [
+ "The assistant quotes a discontinued product warranty from an archived catalog page.",
+ "A comparison uses last season's product specifications after retrieval returns an older document.",
+ "The answer recommends an unavailable size because the retrieved stock guide is out of date.",
+ ],
+ },
+ {
+ id: "payment-retries",
+ name: "Payment retries",
+ description:
+ "Payment requests repeat after the provider reports an ambiguous result.",
+ center: [-52, 23],
+ count: 28,
+ summaries: [
+ "The checkout tool retries a payment after a timeout without checking the original transaction.",
+ "A declined payment sends the conversation back to checkout without explaining the provider response.",
+ "The assistant repeats the same payment request after the user asks whether the first attempt succeeded.",
+ ],
+ },
+ {
+ id: "inventory-timeouts",
+ name: "Inventory timeouts",
+ description:
+ "Stock lookups time out and leave product availability unresolved.",
+ center: [-5, -25],
+ count: 34,
+ summaries: [
+ "An inventory lookup times out twice and the assistant cannot confirm whether the item is in stock.",
+ "The stock service returns a gateway timeout; the assistant asks the user to repeat the same product request.",
+ "A warehouse lookup stalls before returning availability, so the conversation ends without an answer.",
+ ],
+ },
+ {
+ id: "account-permissions",
+ name: "Account permission failures",
+ description:
+ "Authenticated order lookups fail because the tool lacks access to the account.",
+ center: [4, 28],
+ count: 22,
+ summaries: [
+ "The order lookup returns permission denied after sign-in and the assistant requests another sign-in.",
+ "A support tool cannot access the user's account and no alternative verification path is offered.",
+ "The assistant treats an access-denied response as a missing order instead of explaining the permission issue.",
+ ],
+ },
+ {
+ id: "delivery-loops",
+ name: "Delivery status loops",
+ description:
+ "Repeated tracking calls return the same status without advancing the request.",
+ center: [48, -24],
+ count: 26,
+ summaries: [
+ "The assistant calls tracking four times with the same order number and repeats the pending status.",
+ "A delivery question loops between address confirmation and a tracking response that never changes.",
+ "The user asks for a delivery date, but repeated tracking calls only return label created.",
+ ],
+ },
+ {
+ id: "missing-handoffs",
+ name: "Missing handoffs",
+ description:
+ "Requests needing a human end without creating the promised support handoff.",
+ center: [57, 27],
+ count: 18,
+ summaries: [
+ "The assistant promises to escalate a damaged-item claim but no support ticket is created.",
+ "A refund needs manual approval; the assistant ends the conversation without contacting support.",
+ "The user asks for a human, but the handoff tool is never called and the request remains unresolved.",
+ ],
+ },
+] as const;
+
+const denseTopics = issueClusters.map(({ id, name, description }) => ({
+ id,
+ name,
+ description,
+}));
+const denseData = {
+ points: [
+ ...issueClusters.flatMap((cluster) =>
+ Array.from({ length: cluster.count }, (_, index) => {
+ const angle = index * 2.399963229728653;
+ const radius = 2 + Math.sqrt((index + 0.5) / cluster.count) * 10;
+ return {
+ traceId: `demo-${cluster.id}-${index + 1}`,
+ summary: `${cluster.summaries[index % cluster.summaries.length]} Request ${index + 1}.`,
+ topicId: cluster.id,
+ outcome: "assigned" as const,
+ x: cluster.center[0] + Math.cos(angle) * radius,
+ y: cluster.center[1] + Math.sin(angle) * radius * 0.7,
+ };
+ }),
+ ),
+ ...Array.from({ length: 8 }, (_, index) => ({
+ traceId: `demo-outlier-${index + 1}`,
+ summary:
+ "A gift-wrapping request does not match the recurring operational issues.",
+ topicId: null,
+ outcome: "outlier" as const,
+ x: -30 + index * 8,
+ y: 2 + Math.sin(index) * 5,
+ })),
+ ...Array.from({ length: 5 }, (_, index) => ({
+ traceId: `demo-unassigned-${index + 1}`,
+ summary:
+ "An exchange-policy summary has saved coordinates but its topic assignment is unavailable.",
+ topicId: null,
+ outcome: "unassigned" as const,
+ x: 73 + index * 2,
+ y: -4 + index * 3,
+ })),
+ ],
+ missingSummaryCount: 0,
+ unpositionedCount: 0,
+} satisfies ExplorerProps["data"];
+
+const nearbyCloudData = {
+ ...denseData,
+ points: denseData.points.map((point) =>
+ point.topicId === "inventory-timeouts"
+ ? { ...point, x: point.x - 40, y: point.y + 5 }
+ : point,
+ ),
+} satisfies ExplorerProps["data"];
+
+function ControlledExplorer(args: ExplorerProps) {
+ const [selectedTopic, setSelectedTopic] = useState(args.selectedTopic);
+ const [selectedTraceId, setSelectedTraceId] = useState(args.selectedTraceId);
+ const handleSelectTopic = (id: string | null) => {
+ setSelectedTopic(id);
+ setSelectedTraceId(null);
+ args.onSelectTopic(id);
+ };
+ const handleSelectTrace = (id: string | null) => {
+ setSelectedTraceId(id);
+ args.onSelectTrace(id);
+ };
+ return (
+ <EmbeddingMapView
+ {...args}
+ selectedTopic={selectedTopic}
+ selectedTraceId={selectedTraceId}
+ onSelectTopic={handleSelectTopic}
+ onSelectTrace={handleSelectTrace}
+ />
+ );
+}
+
+async function waitForMapSettled(canvasElement: HTMLElement) {
+ let previous = "";
+ let changedAt = performance.now();
+ await waitFor(
+ () => {
+ const current = Array.from(
+ canvasElement.querySelectorAll<HTMLElement>(
+ "[data-topic-background-label], [data-topic-node]",
+ ),
+ )
+ .map((element) => element.getAttribute("style"))
+ .join(";");
+ expect(current).not.toBe("");
+ if (current !== previous) {
+ previous = current;
+ changedAt = performance.now();
+ }
+ expect(performance.now() - changedAt).toBeGreaterThan(150);
+ },
+ { timeout: 3000 },
+ );
+}
+
+async function zoomToInlineNodes(canvasElement: HTMLElement) {
+ const canvas = within(canvasElement);
+ await waitForMapSettled(canvasElement);
+ for (
+ let attempt = 0;
+ attempt < 14 &&
+ canvas.queryAllByRole("button", { name: /^Select trace:/ }).length === 0;
+ attempt++
+ ) {
+ const before = canvas.getByLabelText("Zoom level").textContent;
+ await userEvent.click(canvas.getByRole("button", { name: "Zoom in (+)" }));
+ await waitFor(() =>
+ expect(canvas.getByLabelText("Zoom level").textContent).not.toBe(before),
+ );
+ await waitForMapSettled(canvasElement);
+ }
+ await waitFor(
+ () =>
+ expect(
+ canvas.queryAllByRole("button", { name: /^Select trace:/ }).length,
+ ).toBeGreaterThan(0),
+ { timeout: 2000 },
+ );
+}
+
+async function hoverInlineNode(canvasElement: HTMLElement) {
+ const canvas = within(canvasElement);
+ const stage = canvas.getByRole("group", { name: /^Interactive topic map/ });
+ const result: {
+ hovered?: { node: HTMLElement; clientX: number; clientY: number };
+ } = {};
+ let attempt = 0;
+ await waitFor(
+ () => {
+ const stageRect = stage.getBoundingClientRect();
+ const candidates = Array.from(
+ canvasElement.querySelectorAll<HTMLElement>("[data-topic-node]"),
+ )
+ .map((node) => ({ node, rect: node.getBoundingClientRect() }))
+ .filter(
+ ({ rect }) =>
+ rect.left + rect.width / 2 > stageRect.left + 8 &&
+ rect.left + rect.width / 2 < stageRect.right - 8 &&
+ rect.top + rect.height / 2 > stageRect.top + 8 &&
+ rect.top + rect.height / 2 < stageRect.bottom - 8,
+ )
+ .sort(
+ (a, b) =>
+ Math.hypot(
+ a.rect.left +
+ a.rect.width / 2 -
+ (stageRect.left + stageRect.width / 2),
+ a.rect.top +
+ a.rect.height / 2 -
+ (stageRect.top + stageRect.height / 2),
+ ) -
+ Math.hypot(
+ b.rect.left +
+ b.rect.width / 2 -
+ (stageRect.left + stageRect.width / 2),
+ b.rect.top +
+ b.rect.height / 2 -
+ (stageRect.top + stageRect.height / 2),
+ ),
+ );
+ expect(candidates.length).toBeGreaterThan(0);
+ const { node, rect } = candidates[0];
+ const clientX = rect.left + rect.width / 2 + (attempt++ % 2 ? 2 : -2);
+ const clientY = rect.top + rect.height / 2;
+ node.dispatchEvent(
+ new PointerEvent("pointermove", {
+ bubbles: true,
+ pointerId: 1,
+ pointerType: "mouse",
+ isPrimary: true,
+ clientX,
+ clientY,
+ }),
+ );
+ expect(node).toHaveAttribute("data-hovered", "true");
+ result.hovered = { node, clientX, clientY };
+ },
+ { timeout: 2000 },
+ );
+ if (!result.hovered)
+ throw new Error("No visible inline node could be hovered.");
+ return result.hovered;
+}
+
+const meta = preview.meta({
+ component: EmbeddingMapView,
+ args: {
+ projectId: "storybook-project",
+ topics: [{ id: "billing", name: "Billing" }],
+ data,
+ selectedTopic: null,
+ selectedTraceId: null,
+ onSelectTopic: fn(),
+ onSelectTrace: fn(),
+ },
+});
+
+export const Default = meta.story({});
+
+export const SummaryLengths = meta.story({
+ args: {
+ data: {
+ ...data,
+ points: [
+ data.points[0],
+ {
+ ...data.points[1],
+ summary:
+ "The customer asks how to connect a new integration, configure its authentication credentials, and verify that events arrive in the correct project. The assistant walks through setup, explains how to troubleshoot missing events, and confirms that the connection is working before ending the conversation.",
+ },
+ ],
+ },
+ },
+});
+
+export const SelectedTopic = meta.story({
+ args: { selectedTopic: "billing", selectedTraceId: "trace-billing" },
+});
+
+export const Empty = meta.story({
+ args: { data: { ...data, points: [] } },
+});
+
+export const DenseIssueCloud = meta.story({
+ args: {
+ topics: denseTopics,
+ data: denseData,
+ },
+ 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 } },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const stage = canvas.getByRole("group", { name: /^Interactive topic map/ });
+ const baseline = stage.getBoundingClientRect();
+ const trigger = canvas.getByRole("button", { name: /^Map coverage/ });
+ expect(getComputedStyle(trigger).pointerEvents).toBe("auto");
+ await userEvent.hover(trigger);
+ const body = within(canvasElement.ownerDocument.body);
+ await waitFor(() => {
+ const tooltip = body.getByRole("tooltip");
+ expect(getComputedStyle(tooltip).pointerEvents).toBe("none");
+ expect(tooltip).toHaveTextContent(
+ "2 saved map points have no current summary.",
+ );
+ expect(tooltip).toHaveTextContent(
+ "3 current summaries have no saved coordinates.",
+ );
+ });
+ const after = stage.getBoundingClientRect();
+ expect(after.width).toBe(baseline.width);
+ expect(after.height).toBe(baseline.height);
+ expect(after.top).toBe(baseline.top);
+ },
+});
+
+export const ExploreZoneAndTrace = meta.story({
+ name: "(Test) Select Trace And Reset Map",
+ args: {
+ topics: denseTopics,
+ data: denseData,
+ selectedTopic: "inventory-timeouts",
+ selectedTraceId: null,
+ onSelectTopic: fn(),
+ onSelectTrace: fn(),
+ },
+ render: (args) => <ControlledExplorer {...args} />,
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await zoomToInlineNodes(canvasElement);
+
+ const zoomBefore = Number.parseInt(
+ canvas.getByLabelText("Zoom level").textContent ?? "0",
+ 10,
+ );
+ await userEvent.click(canvas.getByRole("button", { name: "Zoom in (+)" }));
+ await waitFor(() =>
+ expect(
+ Number.parseInt(
+ canvas.getByLabelText("Zoom level").textContent ?? "0",
+ 10,
+ ),
+ ).toBeGreaterThan(zoomBefore),
+ );
+
+ const { node: summaryButton } = await hoverInlineNode(canvasElement);
+ const trace = denseData.points.find(
+ (point) => point.traceId === summaryButton.getAttribute("data-trace-id"),
+ );
+ if (!trace)
+ throw new Error("The inline summary has no matching fixture trace.");
+ await expect(summaryButton).toHaveAttribute("data-hovered", "true");
+ await expect(summaryButton).toBeVisible();
+ await userEvent.click(summaryButton);
+ await expect(args.onSelectTrace).toHaveBeenCalledWith(trace.traceId);
+ const stage = canvas.getByRole("group", {
+ name: /^Interactive topic map/,
+ });
+ await expect(summaryButton).toHaveAttribute("aria-pressed", "true");
+ stage.focus();
+ await userEvent.keyboard("0");
+ await expect(args.onSelectTopic).toHaveBeenLastCalledWith(null);
+ await userEvent.keyboard("{Home}");
+ await expect(args.onSelectTopic).toHaveBeenLastCalledWith(null);
+ await userEvent.click(canvas.getByRole("button", { name: "Fit map (0)" }));
+ await expect(args.onSelectTopic).toHaveBeenLastCalledWith(null);
+ },
+});
+
+export const NavigationClearsHover = meta.story({
+ name: "(Test) Navigation Clears Hover",
+ args: {
+ topics: denseTopics,
+ data: denseData,
+ selectedTopic: "inventory-timeouts",
+ selectedTraceId: null,
+ },
+ render: (args) => <ControlledExplorer {...args} />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const stage = canvas.getByRole("group", {
+ name: /^Interactive topic map/,
+ });
+ await zoomToInlineNodes(canvasElement);
+ const { node, ...at } = await hoverInlineNode(canvasElement);
+ const send = (type: string, offset: number, buttons: number) =>
+ node.dispatchEvent(
+ new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ pointerId: 1,
+ pointerType: "mouse",
+ isPrimary: true,
+ buttons,
+ clientX: at.clientX + offset,
+ clientY: at.clientY,
+ }),
+ );
+ const activeHover = () =>
+ canvasElement.querySelector('[data-hovered="true"]');
+ const capture = stage.setPointerCapture;
+ stage.setPointerCapture = () => undefined;
+ try {
+ await expect(activeHover()).not.toBeNull();
+ send("pointerdown", 0, 1);
+ send("pointermove", 4, 1);
+ await waitFor(() => expect(activeHover()).toBeNull());
+ stage.dispatchEvent(
+ new PointerEvent("pointerup", {
+ bubbles: true,
+ pointerId: 1,
+ pointerType: "mouse",
+ buttons: 0,
+ clientX: at.clientX + 4,
+ clientY: at.clientY,
+ }),
+ );
+ await new Promise<void>((resolve) =>
+ requestAnimationFrame(() => resolve()),
+ );
+
+ const { clientX, clientY } = await hoverInlineNode(canvasElement);
+ const move = () =>
+ stage.dispatchEvent(
+ new PointerEvent("pointermove", {
+ bubbles: true,
+ pointerType: "mouse",
+ clientX,
+ clientY,
+ }),
+ );
+ await expect(activeHover()).not.toBeNull();
+ stage.focus();
+ await userEvent.keyboard("+");
+ await waitFor(() => expect(activeHover()).toBeNull());
+ move();
+ await expect(activeHover()).toBeNull();
+
+ await hoverInlineNode(canvasElement);
+ const section = canvas.getByRole("region", { name: "Embedding map" });
+ const originalStyleWidth = section.style.width;
+ const originalStageWidth = stage.getBoundingClientRect().width;
+ try {
+ section.style.width = `${section.getBoundingClientRect().width - 80}px`;
+ await waitFor(() =>
+ expect(stage.getBoundingClientRect().width).toBeLessThan(
+ originalStageWidth,
+ ),
+ );
+ await waitFor(() => expect(activeHover()).toBeNull());
+ section.style.width = originalStyleWidth;
+ await waitFor(() =>
+ expect(stage.getBoundingClientRect().width).toBe(originalStageWidth),
+ );
+ let previousBounds = "";
+ let changedAt = performance.now();
+ await waitFor(
+ () => {
+ const bounds = Array.from(
+ canvasElement.querySelectorAll<HTMLElement>("[data-topic-node]"),
+ )
+ .map((node) => node.getAttribute("style"))
+ .join(";");
+ if (bounds !== previousBounds) {
+ previousBounds = bounds;
+ changedAt = performance.now();
+ }
+ expect(performance.now() - changedAt).toBeGreaterThan(150);
+ },
+ { timeout: 2000 },
+ );
+ await expect(activeHover()).toBeNull();
+ } finally {
+ section.style.width = originalStyleWidth;
+ }
+ } finally {
+ stage.setPointerCapture = capture;
+ }
+ },
+});
+
+export const ReadingKeepsZoomedCloud = meta.story({
+ name: "(Test) Reading Keeps Zoomed Cloud",
+ args: {
+ topics: denseTopics,
+ data: nearbyCloudData,
+ selectedTopic: null,
+ selectedTraceId: null,
+ onSelectTopic: fn(),
+ },
+ render: (args) => <ControlledExplorer {...args} />,
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const stage = canvas.getByRole("group", {
+ name: /^Interactive topic map/,
+ });
+ await new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ );
+ const model = prepareTopicMap(nearbyCloudData, denseTopics);
+ const cloud = model.zones.find((zone) => zone.id === "inventory-timeouts");
+ if (!cloud) throw new Error("The inventory cloud fixture is missing.");
+ const stageRect = stage.getBoundingClientRect();
+ const plot = { width: stageRect.width, height: stageRect.height };
+ const initial = fitCamera(model.bounds, model.bounds, plot);
+ const at = screenPoint(cloud, initial, model.bounds, plot);
+ const zoomInput = new WheelEvent("wheel", {
+ bubbles: true,
+ cancelable: true,
+ ctrlKey: true,
+ deltaY: -40 * Math.log2(10),
+ clientX: stageRect.left + at.x,
+ clientY: stageRect.top + at.y,
+ });
+ const zoomed = zoomCamera(
+ initial,
+ Math.log2(10),
+ {
+ x: (zoomInput.clientX - stageRect.left) / plot.width,
+ y: (zoomInput.clientY - stageRect.top) / plot.height,
+ },
+ model.bounds,
+ plot,
+ );
+ stage.dispatchEvent(zoomInput);
+ await waitFor(() =>
+ expect(canvas.getByLabelText("Zoom level")).toHaveTextContent("1000%"),
+ );
+ await hoverInlineNode(canvasElement);
+ const result: { node?: HTMLElement } = {};
+ await waitFor(
+ () => {
+ const nodes = Array.from(
+ canvasElement.querySelectorAll<HTMLElement>("[data-topic-node]"),
+ )
+ .map((node) => {
+ const rect = node.getBoundingClientRect();
+ return {
+ node,
+ rect,
+ distance: Math.hypot(
+ rect.left + rect.width / 2 - (stageRect.left + at.x),
+ rect.top + rect.height / 2 - (stageRect.top + at.y),
+ ),
+ };
+ })
+ .filter(
+ ({ node, rect }) =>
+ Number(node.style.opacity) > 0.05 &&
+ node.dataset.traceId?.startsWith("demo-inventory-timeouts-") &&
+ rect.left >= stageRect.left + 4 &&
+ rect.right <= stageRect.right - 4 &&
+ rect.top >= stageRect.top + 4 &&
+ rect.bottom <= stageRect.bottom - 4,
+ )
+ .sort((a, b) => a.distance - b.distance);
+ expect(nodes.length).toBeGreaterThan(0);
+ expect(nodes[0].node.dataset.traceId).toMatch(
+ /^demo-inventory-timeouts-/,
+ );
+ const saved = model.pointById.get(nodes[0].node.dataset.traceId ?? "");
+ if (!saved)
+ throw new Error("The inline node has no saved fixture coordinate.");
+ const expected = screenPoint(saved, zoomed, model.bounds, plot);
+ expect(
+ nodes[0].rect.left + nodes[0].rect.width / 2 - stageRect.left,
+ ).toBeCloseTo(expected.x, 1);
+ expect(
+ nodes[0].rect.top + nodes[0].rect.height / 2 - stageRect.top,
+ ).toBeCloseTo(expected.y, 1);
+ result.node = nodes[0].node;
+ },
+ { timeout: 2000 },
+ );
+ await expect(args.onSelectTopic).not.toHaveBeenCalled();
+ if (!result.node)
+ throw new Error("No readable trace remains near the zoom anchor.");
+ const node = result.node;
+ const beforePan = node.getBoundingClientRect();
+ stage.dispatchEvent(
+ new WheelEvent("wheel", {
+ bubbles: true,
+ cancelable: true,
+ deltaX: 40,
+ deltaY: -20,
+ }),
+ );
+ await waitFor(
+ () => {
+ const rect = node.getBoundingClientRect();
+ expect(Math.abs(rect.left - (beforePan.left - 40))).toBeLessThan(0.2);
+ expect(Math.abs(rect.top - (beforePan.top + 20))).toBeLessThan(0.2);
+ },
+ { timeout: 2000 },
+ );
+ await expect(canvas.getByLabelText("Zoom level")).toHaveTextContent(
+ "1000%",
+ );
+ await expect(args.onSelectTopic).not.toHaveBeenCalled();
+ },
+});
+
+export const HoverPreservesMapGeometry = meta.story({
+ name: "(Test) Hover Preserves Map Geometry",
+ args: {
+ fillContainer: true,
+ data,
+ topics: [
+ {
+ id: "billing",
+ name: "Billing, invoices, subscriptions, and account administration",
+ },
+ ],
+ selectedTopic: null,
+ selectedTraceId: null,
+ onSelectTrace: fn(),
+ },
+ render: (args) => (
+ <div style={{ height: 680 }}>
+ <ControlledExplorer {...args} />
+ </div>
+ ),
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const stage = canvas.getByRole("group", { name: /^Interactive topic map/ });
+ await waitFor(() =>
+ expect(stage.getBoundingClientRect().height).toBeGreaterThan(0),
+ );
+ const model = prepareTopicMap(args.data, args.topics);
+ const trace = model.pointById.get("trace-billing");
+ if (!trace) throw new Error("The hover fixture trace is missing.");
+ const baseline = stage.getBoundingClientRect();
+ const plot = { width: baseline.width, height: baseline.height };
+ const initial = fitCamera(model.bounds, model.bounds, plot);
+ const position = screenPoint(trace, initial, model.bounds, plot);
+ let attempt = 0;
+ await waitFor(
+ () => {
+ stage.dispatchEvent(
+ new PointerEvent("pointermove", {
+ bubbles: true,
+ pointerId: 1,
+ pointerType: "mouse",
+ isPrimary: true,
+ clientX: baseline.left + position.x + (attempt++ % 2 ? 1 : -1),
+ clientY: baseline.top + position.y,
+ }),
+ );
+ const active = canvasElement.querySelectorAll<HTMLElement>(
+ '[role="tooltip"][data-active="true"]',
+ );
+ expect(active).toHaveLength(1);
+ expect(active[0]).toHaveAttribute("data-trace-id", trace.traceId);
+ },
+ { timeout: 3000 },
+ );
+ const tooltip = canvas.getByRole("tooltip", { name: /^Trace summary:/ });
+ await waitFor(() =>
+ expect(Number(getComputedStyle(tooltip).opacity)).toBeCloseTo(0.96, 2),
+ );
+ const topicName = args.topics[0].name;
+ await expect(tooltip).toHaveAccessibleName(
+ `Trace summary: ${topicName}. ${trace.summary}`,
+ );
+ const topicLabel = within(tooltip).getByText(topicName);
+ await expect(topicLabel).toBeVisible();
+ await expect(topicLabel.scrollHeight).toBeLessThanOrEqual(
+ topicLabel.clientHeight,
+ );
+ await expect(getComputedStyle(tooltip).pointerEvents).toBe("none");
+ await expect(tooltip).not.toHaveAttribute("tabindex");
+ const tooltipBounds = tooltip.getBoundingClientRect();
+ const beneath = canvasElement.ownerDocument.elementFromPoint(
+ tooltipBounds.left + tooltipBounds.width / 2,
+ tooltipBounds.top + tooltipBounds.height / 2,
+ );
+ await expect(beneath?.closest('[role="tooltip"]')).toBeNull();
+ const assertStageBounds = () => {
+ const current = stage.getBoundingClientRect();
+ expect(current.x).toBeCloseTo(baseline.x, 2);
+ expect(current.y).toBeCloseTo(baseline.y, 2);
+ expect(current.width).toBeCloseTo(baseline.width, 2);
+ expect(current.height).toBeCloseTo(baseline.height, 2);
+ };
+ assertStageBounds();
+ stage.dispatchEvent(
+ new MouseEvent("click", {
+ bubbles: true,
+ clientX: baseline.left + position.x,
+ clientY: baseline.top + position.y,
+ }),
+ );
+ await expect(args.onSelectTrace).toHaveBeenLastCalledWith(trace.traceId);
+ await waitFor(assertStageBounds);
+ stage.dispatchEvent(
+ new MouseEvent("click", {
+ bubbles: true,
+ clientX: baseline.left + baseline.width / 2,
+ clientY: baseline.top + baseline.height / 2,
+ }),
+ );
+ await expect(args.onSelectTrace).toHaveBeenLastCalledWith(null);
+ await waitFor(assertStageBounds);
+ await waitFor(() =>
+ expect(canvasElement.querySelectorAll('[role="tooltip"]')).toHaveLength(
+ 0,
+ ),
+ );
+ },
+});
+
+export const InterruptingTopicFlightKeepsPaintedZoom = meta.story({
+ name: "(Test) Interrupting Topic Flight Keeps Painted Zoom",
+ args: {
+ topics: denseTopics,
+ data: {
+ ...denseData,
+ points: [
+ {
+ traceId: "flight-marker-left",
+ summary: "An inventory lookup times out before returning stock.",
+ topicId: "inventory-timeouts",
+ outcome: "assigned",
+ x: -5,
+ y: -25,
+ },
+ {
+ traceId: "flight-marker-right",
+ summary: "A repeated inventory lookup returns the same timeout.",
+ topicId: "inventory-timeouts",
+ outcome: "assigned",
+ x: -4.75,
+ y: -25,
+ },
+ ...denseData.points,
+ ],
+ },
+ selectedTopic: "inventory-timeouts",
+ },
+ render: function Render(args) {
+ const [selectedTopic, setSelectedTopic] = useState(args.selectedTopic);
+ const handleRestoreOverview = () => setSelectedTopic(null);
+ return (
+ <>
+ <Button
+ text="Restore overview"
+ variant="secondary"
+ onClick={handleRestoreOverview}
+ />
+ <EmbeddingMapView {...args} selectedTopic={selectedTopic} />
+ </>
+ );
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const stage = canvas.getByRole("group", { name: /^Interactive topic map/ });
+ await new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ );
+ const drawing = stage.querySelector("canvas");
+ const context = drawing?.getContext("2d");
+ if (!context) throw new Error("The map canvas context is unavailable.");
+ const clearRect = context.clearRect;
+ const scale = context.scale;
+ const roundRect = context.roundRect;
+ const painted = {
+ scale: null as number | null,
+ distance: null as number | null,
+ centers: [] as { x: number; y: number }[],
+ at: 0,
+ };
+ context.clearRect = (x, y, width, height) => {
+ painted.scale = null;
+ painted.distance = null;
+ painted.centers = [];
+ painted.at = performance.now();
+ clearRect.call(context, x, y, width, height);
+ };
+ context.scale = (x, y) => {
+ if (painted.scale === null) painted.scale = x;
+ scale.call(context, x, y);
+ };
+ context.roundRect = (x, y, width, height, radii) => {
+ if (painted.centers.length < 2) {
+ painted.centers.push({ x: x + width / 2, y: y + height / 2 });
+ if (painted.centers.length === 2)
+ painted.distance = Math.hypot(
+ painted.centers[0].x - painted.centers[1].x,
+ painted.centers[0].y - painted.centers[1].y,
+ );
+ }
+ roundRect.call(context, x, y, width, height, radii);
+ };
+ try {
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Restore overview" }),
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 150));
+ const before = painted.scale;
+ if (before === null || before <= 0)
+ throw new Error("The topic flight has not painted a cloud scale.");
+ const rect = stage.getBoundingClientRect();
+ const interruptedAt = performance.now();
+ stage.dispatchEvent(
+ new WheelEvent("wheel", {
+ bubbles: true,
+ cancelable: true,
+ ctrlKey: true,
+ deltaY: -1,
+ clientX: rect.left + rect.width / 2,
+ clientY: rect.top + rect.height / 2,
+ }),
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 240));
+ await waitFor(() => {
+ expect(painted.at).toBeGreaterThan(interruptedAt);
+ expect(painted.scale).not.toBeNull();
+ const ratio = painted.scale! / before;
+ expect(ratio).toBeGreaterThan(0.7);
+ expect(ratio).toBeLessThan(1.3);
+ });
+
+ await waitForMapSettled(canvasElement);
+ stage.dispatchEvent(
+ new WheelEvent("wheel", {
+ bubbles: true,
+ cancelable: true,
+ ctrlKey: true,
+ deltaY: -120,
+ clientX: rect.left + rect.width / 2,
+ clientY: rect.top + rect.height / 2,
+ }),
+ );
+ await waitForMapSettled(canvasElement);
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Fit map (0)" }),
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 420));
+ const beforeFitInterrupt = painted.distance;
+ if (beforeFitInterrupt === null || beforeFitInterrupt <= 0)
+ throw new Error("The fit flight has not painted both trace markers.");
+ const fitInterruptedAt = performance.now();
+ stage.dispatchEvent(
+ new WheelEvent("wheel", {
+ bubbles: true,
+ cancelable: true,
+ ctrlKey: true,
+ deltaY: -1,
+ clientX: rect.left + rect.width / 2,
+ clientY: rect.top + rect.height / 2,
+ }),
+ );
+ await new Promise<void>((resolve) => setTimeout(resolve, 240));
+ await waitFor(() => {
+ expect(painted.at).toBeGreaterThan(fitInterruptedAt);
+ expect(painted.distance).not.toBeNull();
+ const ratio = painted.distance! / beforeFitInterrupt;
+ expect(ratio).toBeGreaterThan(0.97);
+ expect(ratio).toBeLessThan(1.06);
+ });
+ } finally {
+ context.clearRect = clearRect;
+ context.scale = scale;
+ context.roundRect = roundRect;
+ }
+ },
+});
+
+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/EmbeddingMapView.tsx b/web/src/features/topics/EmbeddingMapView.tsx
new file mode 100644
index 0000000000..63469448db
--- /dev/null
+++ b/web/src/features/topics/EmbeddingMapView.tsx
@@ -0,0 +1,4 @@
+export {
+ TopicMapExplorer as EmbeddingMapView,
+ __test,
+} from "./map/TopicMapExplorer";
diff --git a/web/src/features/topics/README.md b/web/src/features/topics/README.md
index ae212de67e..6a400883e3 100644
--- a/web/src/features/topics/README.md
+++ b/web/src/features/topics/README.md
@@ -8,14 +8,22 @@ project permissions. Processing additionally requires the project allowlist.
- `TopicsPage.tsx` owns facet configuration, the execution history drawer,
the current-results query and facet selection. The header shows the facet
tabs, then "Visualize as" (`TopicsResultsViewSelect.tsx`) with Treemap
- (default) and Grid, remembered in localStorage; time range and processing
+ (default), Grid and Map, remembered in localStorage; time range and processing
actions sit on the right, configuration and history in the overflow menu.
- `CurrentTopics.tsx` owns the map query (Grid only) and trace navigation.
+ `CurrentTopics.tsx` owns the map query (Grid and Map) and trace navigation.
Treemap sizes one tile per topic by trace count, plus a grey Unassigned tile
for traces without a topic, traces below; Grid snaps the
saved map projection onto one square per trace (sampled above 1,000), legend
under it and traces on the right. Both list the selected topic's traces in
`TopicTraceList`, with an Open in Tracing link limited to those trace IDs.
+ Map is the original cluster map (`CurrentTopicsView.tsx`) with its trace table.
+ Map clicks select a trace without opening peek. `CurrentTopicsView` keeps
+ that trace ID in project-scoped sessionStorage, shared across facets, and
+ highlights its map point and table row. Selection changes reveal the trace's
+ table page and follow it through result refreshes until the user paginates.
+ Clearing selection preserves the current page. Filtered-out map points cannot
+ replace selection; filters can hide a selection without discarding it. Table row
+ and trace-link clicks select the trace and open peek.
`useTopicTraceFilters.ts` owns URL-backed facet selection.
Peek defaults to the trace panel width and has its own resize preference.
The results workspace stays mounted, including
diff --git a/web/src/features/topics/TopicBadge.tsx b/web/src/features/topics/TopicBadge.tsx
new file mode 100644
index 0000000000..4b9ac59b96
--- /dev/null
+++ b/web/src/features/topics/TopicBadge.tsx
@@ -0,0 +1,19 @@
+import { type ComponentProps } from "react";
+import { Badge } from "@/src/components/design-system/Badge/Badge";
+
+export function TopicBadge({ row, color, size }: TopicBadgeProps) {
+ return (
+ <Badge
+ text={row.topicName ?? row.outcome.replaceAll("_", " ")}
+ color={color}
+ size={size}
+ shouldWrap
+ />
+ );
+}
+
+type TopicBadgeProps = {
+ row: { topicName: string | null; outcome: string };
+ color: ComponentProps<typeof Badge>["color"];
+ size: "default" | "sm";
+};
diff --git a/web/src/features/topics/TopicEmbeddingMap.tsx b/web/src/features/topics/TopicEmbeddingMap.tsx
new file mode 100644
index 0000000000..9ace910afc
--- /dev/null
+++ b/web/src/features/topics/TopicEmbeddingMap.tsx
@@ -0,0 +1,67 @@
+import { Alert } from "@/src/components/design-system/Alert/Alert";
+import { type RouterOutputs } from "@/src/utils/api";
+import { EmbeddingMapView } from "./EmbeddingMapView";
+import { TopicMapLoading } from "./TopicMapLoading";
+
+export function TopicEmbeddingMap({
+ projectId,
+ query,
+ topics,
+ selectedTopic,
+ onSelectTopic,
+ onSelectTrace,
+ selectedTraceId,
+ matchingTraceIds,
+ fillContainer = false,
+}: TopicEmbeddingMapProps) {
+ if (query.error)
+ return (
+ <Alert variant="destructive" size="sm">
+ <Alert.Description>
+ <p className="break-words">
+ Map could not load: {query.error.message}
+ </p>
+ </Alert.Description>
+ </Alert>
+ );
+ if (!query.data) return <TopicMapLoading fillContainer={fillContainer} />;
+ if (query.data.status !== "ready")
+ return (
+ <p className="text-muted-foreground rounded-lg border p-4 text-sm">
+ {query.data.reason ?? "This run has no saved embedding projection."}
+ </p>
+ );
+ return (
+ <EmbeddingMapView
+ projectId={projectId}
+ 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;
+ };
+ 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"]["facets"][number]["topics"][number],
+ "id" | "name"
+> & { description?: string };
diff --git a/web/src/features/topics/TopicGroupCard.tsx b/web/src/features/topics/TopicGroupCard.tsx
new file mode 100644
index 0000000000..47d6de3159
--- /dev/null
+++ b/web/src/features/topics/TopicGroupCard.tsx
@@ -0,0 +1,44 @@
+import { Badge } from "@/src/components/design-system/Badge/Badge";
+import { cn } from "@/src/utils/tailwind";
+
+export function TopicGroupCard({
+ topic,
+ color,
+ isSelected,
+ onSelect,
+}: TopicGroupCardProps) {
+ function selectTopic() {
+ onSelect(topic.id);
+ }
+ return (
+ <button
+ onClick={selectTopic}
+ aria-pressed={isSelected}
+ className={cn(
+ "ph-no-capture hover:bg-muted/50 flex flex-col gap-1 rounded-md border p-2 text-left",
+ isSelected && "border-primary bg-muted/30",
+ )}
+ >
+ <div className="flex w-full items-start justify-between gap-2">
+ <h4 className="flex min-w-0 items-start gap-1.5 text-xs font-bold">
+ <span
+ className="mt-1 inline-block h-2 w-2 shrink-0 rounded-full"
+ style={{ backgroundColor: color }}
+ />
+ {topic.name}
+ </h4>
+ <Badge text={topic.count.toLocaleString()} size="sm" />
+ </div>
+ <p className="text-muted-foreground text-xs leading-relaxed">
+ {topic.description}
+ </p>
+ </button>
+ );
+}
+
+type TopicGroupCardProps = {
+ topic: { id: string; name: string; count: number; description: string };
+ color: string;
+ isSelected: boolean;
+ onSelect: (topicId: string) => void;
+};
diff --git a/web/src/features/topics/TopicMapLoading.stories.tsx b/web/src/features/topics/TopicMapLoading.stories.tsx
new file mode 100644
index 0000000000..30c1bb5907
--- /dev/null
+++ b/web/src/features/topics/TopicMapLoading.stories.tsx
@@ -0,0 +1,48 @@
+import { expect, fn, waitFor, within } from "storybook/test";
+import preview from "../../../.storybook/preview";
+import { EmbeddingMapView } from "./EmbeddingMapView";
+import { TopicMapLoading } from "./TopicMapLoading";
+
+const meta = preview.meta({
+ component: TopicMapLoading,
+ render: (args) => (
+ <div className="grid grid-cols-2 gap-2">
+ <div className="flex h-[680px] min-h-0 flex-col">
+ <TopicMapLoading {...args} />
+ </div>
+ <div className="flex h-[680px] min-h-0 flex-col">
+ <EmbeddingMapView
+ projectId="project"
+ data={{ points: [], missingSummaryCount: 0, unpositionedCount: 0 }}
+ topics={[]}
+ selectedTopic={null}
+ selectedTraceId={null}
+ onSelectTopic={fn()}
+ onSelectTrace={fn()}
+ fillContainer={args.fillContainer}
+ />
+ </div>
+ </div>
+ ),
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const loading = canvas.getByRole("status");
+ const loaded = canvas.getByRole("region", { name: "Embedding map" });
+ await waitFor(() => {
+ const loadingBounds = loading.getBoundingClientRect();
+ const loadedBounds = loaded.getBoundingClientRect();
+ expect(loadingBounds.width).toBeCloseTo(loadedBounds.width, 1);
+ expect(loadingBounds.height).toBeCloseTo(loadedBounds.height, 1);
+ });
+ },
+});
+
+export const FillContainer = meta.story({
+ name: "(Test) Loading matches loaded container size",
+ args: { fillContainer: true },
+});
+
+export const Standalone = meta.story({
+ name: "(Test) Loading matches loaded standalone size",
+ args: { fillContainer: false },
+});
diff --git a/web/src/features/topics/TopicMapLoading.tsx b/web/src/features/topics/TopicMapLoading.tsx
new file mode 100644
index 0000000000..7bab20229d
--- /dev/null
+++ b/web/src/features/topics/TopicMapLoading.tsx
@@ -0,0 +1,28 @@
+import { cn } from "@/src/utils/tailwind";
+
+export function TopicMapLoading({ fillContainer }: TopicMapLoadingProps) {
+ return (
+ <div
+ role="status"
+ className={cn(
+ "bg-muted/20 flex min-w-0 flex-col overflow-hidden rounded-lg border text-sm",
+ fillContainer && "h-full min-h-0",
+ )}
+ >
+ <div
+ className={cn(
+ "flex items-center justify-center",
+ fillContainer
+ ? "min-h-0 flex-1"
+ : "h-[clamp(380px,64vh,820px)] min-h-[340px]",
+ )}
+ >
+ Loading embedding map…
+ </div>
+ </div>
+ );
+}
+
+type TopicMapLoadingProps = {
+ fillContainer: boolean;
+};
diff --git a/web/src/features/topics/TopicsPage.tsx b/web/src/features/topics/TopicsPage.tsx
index 54c1b63b00..e3c47792c2 100644
--- a/web/src/features/topics/TopicsPage.tsx
+++ b/web/src/features/topics/TopicsPage.tsx
@@ -569,7 +569,7 @@ function TopicsWorkspaceContent({
<div
className={cn(
"ph-no-capture flex min-h-0 flex-1 flex-col gap-2 overflow-hidden",
- showOnboarding && "p-2",
+ (showOnboarding || resultsView === "map") && "p-2",
)}
>
{isTimeRangeCapped && (
@@ -721,6 +721,7 @@ function TopicsWorkspaceContent({
result={results}
selectedFacetId={selectedFacetId}
view={resultsView}
+ traceFilters={traceFilters}
tracePanelRef={setTracePanel}
onGenerateTopics={openTopicGeneration}
canGenerateTopics={canWrite && !running && configured}
diff --git a/web/src/features/topics/TopicsResultsViewSelect.tsx b/web/src/features/topics/TopicsResultsViewSelect.tsx
index 5f46056e2c..efe47ea8af 100644
--- a/web/src/features/topics/TopicsResultsViewSelect.tsx
+++ b/web/src/features/topics/TopicsResultsViewSelect.tsx
@@ -6,6 +6,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePos
const VIEWS = [
{ value: "treemap", label: "Treemap" },
{ value: "grid", label: "Grid" },
+ { value: "map", label: "Map" },
] as const;
export type TopicsResultsView = (typeof VIEWS)[number]["value"];
diff --git a/web/src/features/topics/TopicsTraceToolbar.stories.tsx b/web/src/features/topics/TopicsTraceToolbar.stories.tsx
new file mode 100644
index 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.tsx
new file mode 100644
index 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.tsx
new file mode 100644
index 0000000000..920ee3bf84
--- /dev/null
+++ b/web/src/features/topics/map/TopicMapCanvas.tsx
@@ -0,0 +1,293 @@
+import { useEffect, useEffectEvent, useRef } from "react";
+import {
+ prepareMapNodes,
+ nodeDetailBlend,
+ zoneHalo,
+ type Camera,
+ type MapPosition,
+ type Size,
+ type TopicMapModel,
+ type TopicMapNodeFrame,
+} from "./prepare-topic-map";
+import {
+ getTopicMapHover,
+ publishTopicMapFrame,
+ type TopicMapStore,
+} from "./topic-map-store";
+
+export function TopicMapCanvas({
+ model,
+ size,
+ camera,
+ store,
+ selectedTopic,
+ selectedTraceId,
+ matchingTraceIds,
+}: TopicMapCanvasProps) {
+ const ref = useRef<HTMLCanvasElement>(null);
+ const presentation = useRef<Presentation | null>(null);
+ const draw = useEffectEvent((now: number) => {
+ if (!ref.current) return false;
+ const state = store.getState();
+ const target =
+ state.scope === selectedTopic && state.camera ? state.camera : camera;
+ const targetPointer = state.reducedMotion ? { x: 0, y: 0 } : state.pointer;
+ let scene = presentation.current;
+ if (!scene || scene.frame?.model !== model) {
+ scene = {
+ frame: null,
+ camera: target,
+ scope: selectedTopic,
+ flight: null,
+ pointer: targetPointer,
+ emphasis: new Map(),
+ lastTime: now,
+ };
+ presentation.current = scene;
+ }
+ const elapsed = Math.min(64, Math.max(1, now - scene.lastTime));
+ scene.lastTime = now;
+ let unsettled = false;
+ const approach = (
+ value: number,
+ goal: number,
+ duration: number,
+ epsilon: number,
+ ) => {
+ if (state.reducedMotion || Math.abs(goal - value) <= epsilon) return goal;
+ unsettled = true;
+ return value + (goal - value) * (1 - Math.exp(-elapsed / duration));
+ };
+ if (scene.scope !== selectedTopic) {
+ scene.scope = selectedTopic;
+ scene.flight = state.reducedMotion
+ ? null
+ : { start: scene.camera, target, started: now };
+ }
+ if (
+ scene.flight &&
+ (scene.flight.target.x !== target.x ||
+ scene.flight.target.y !== target.y ||
+ scene.flight.target.zoom !== target.zoom)
+ )
+ scene.flight = null;
+ if (scene.flight && !state.reducedMotion) {
+ const { start, started } = scene.flight;
+ const progress = Math.min(1, (now - started) / 1050);
+ const t = progress ** 3 * (progress * (progress * 6 - 15) + 10);
+ scene.camera = {
+ x: start.x + (target.x - start.x) * t,
+ y: start.y + (target.y - start.y) * t,
+ zoom: Math.exp(
+ Math.log(start.zoom) + Math.log(target.zoom / start.zoom) * t,
+ ),
+ };
+ if (progress < 1) unsettled = true;
+ else {
+ scene.camera = target;
+ scene.flight = null;
+ }
+ } else {
+ const targetLogZoom = Math.log(target.zoom);
+ const logZoom = approach(
+ Math.log(scene.camera.zoom),
+ targetLogZoom,
+ 65,
+ 0.0001,
+ );
+ scene.camera = {
+ x: approach(scene.camera.x, target.x, 65, 0.00001),
+ y: approach(scene.camera.y, target.y, 65, 0.00001),
+ zoom: logZoom === targetLogZoom ? target.zoom : Math.exp(logZoom),
+ };
+ }
+ const cameraMoving = unsettled;
+ scene.pointer = {
+ x: approach(scene.pointer.x, targetPointer.x, 120, 0.001),
+ y: approach(scene.pointer.y, targetPointer.y, 120, 0.001),
+ };
+ const frame = prepareMapNodes(
+ model,
+ scene.camera,
+ size,
+ scene.pointer,
+ selectedTopic,
+ matchingTraceIds,
+ );
+ const hover = getTopicMapHover(state, frame);
+ for (const point of model.points) {
+ const goal =
+ point.traceId === selectedTraceId || point.traceId === hover.hoveredId
+ ? 1
+ : 0;
+ const strength = approach(
+ scene.emphasis.get(point.traceId) ?? 0,
+ goal,
+ 80,
+ 0.002,
+ );
+ if (strength) scene.emphasis.set(point.traceId, strength);
+ else scene.emphasis.delete(point.traceId);
+ }
+ drawMap(ref.current, frame, scene.emphasis);
+ scene.frame = frame;
+ publishTopicMapFrame(store, frame, cameraMoving);
+ return unsettled;
+ });
+ // Canvas owns presentation interpolation; DOM content and hit testing share its painted frame.
+ useEffect(() => {
+ let raf = 0;
+ const step = (now: number) => {
+ raf = 0;
+ if (draw(now) && !raf) raf = requestAnimationFrame(step);
+ };
+ const schedule = () => {
+ if (!raf) raf = requestAnimationFrame(step);
+ };
+ schedule();
+ const unsubscribe = store.subscribe((next, previous) => {
+ if (
+ next.camera !== previous.camera ||
+ next.scope !== previous.scope ||
+ next.pointer !== previous.pointer ||
+ next.hoveredId !== previous.hoveredId ||
+ next.reducedMotion !== previous.reducedMotion
+ )
+ schedule();
+ });
+ const theme = new MutationObserver(schedule);
+ theme.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ["class", "style"],
+ });
+ return () => {
+ unsubscribe();
+ theme.disconnect();
+ cancelAnimationFrame(raf);
+ };
+ }, [
+ store,
+ model,
+ size.width,
+ size.height,
+ camera.x,
+ camera.y,
+ camera.zoom,
+ selectedTopic,
+ selectedTraceId,
+ matchingTraceIds,
+ ]);
+ return (
+ <canvas
+ ref={ref}
+ aria-hidden
+ className="pointer-events-none absolute inset-0 h-full w-full"
+ />
+ );
+}
+
+function drawMap(
+ canvas: HTMLCanvasElement,
+ frame: TopicMapNodeFrame,
+ emphasis: ReadonlyMap<string, number>,
+) {
+ const context = canvas.getContext("2d");
+ if (!context) return;
+ const { model, camera, size, matchingTraceIds } = frame;
+ const ratio = Math.min(window.devicePixelRatio || 1, 2);
+ if (
+ canvas.width !== Math.round(size.width * ratio) ||
+ canvas.height !== Math.round(size.height * ratio)
+ ) {
+ canvas.width = Math.round(size.width * ratio);
+ canvas.height = Math.round(size.height * ratio);
+ }
+ context.setTransform(ratio, 0, 0, ratio, 0, 0);
+ context.clearRect(0, 0, size.width, size.height);
+ const theme = getComputedStyle(canvas);
+ const surface = `hsl(${theme.getPropertyValue("--background").trim()})`;
+ const cloudVisibility = 1 - nodeDetailBlend(camera.zoom);
+ context.globalAlpha = cloudVisibility;
+ for (const zone of frame.zones) {
+ if (!cloudVisibility) break;
+ if (zone.id === "outliers" || zone.id === "awaiting_map") continue;
+ 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);
+ const gradient = context.createRadialGradient(0, 0, 0, 0, 0, 1);
+ gradient.addColorStop(0, `${zone.color}24`);
+ gradient.addColorStop(0.7, `${zone.color}0c`);
+ gradient.addColorStop(1, `${zone.color}00`);
+ context.fillStyle = gradient;
+ context.beginPath();
+ context.arc(0, 0, 1, 0, Math.PI * 2);
+ context.fill();
+ context.restore();
+ }
+ for (const node of frame.nodes) {
+ const { point, rect, cornerRadius } = node;
+ const active = emphasis.get(point.traceId) ?? 0;
+ 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;
+ context.fillStyle = point.color;
+ context.fill();
+ if (node.backgroundOpacity > 0) {
+ context.globalAlpha = node.backgroundOpacity * Math.min(1, opacity + 0.2);
+ context.fillStyle = surface;
+ context.fill();
+ }
+ if (node.strokeOpacity > 0 || active > 0) {
+ context.globalAlpha = (node.strokeOpacity * 0.4 + active * 0.6) * opacity;
+ context.strokeStyle = point.color;
+ context.lineWidth = 1 + active;
+ context.stroke();
+ }
+ if (active > 0.001) {
+ context.globalAlpha = active * 0.7;
+ context.lineWidth = 1.5;
+ context.beginPath();
+ context.roundRect(
+ rect.x - 4,
+ rect.y - 4,
+ rect.width + 8,
+ rect.height + 8,
+ cornerRadius + 4,
+ );
+ context.stroke();
+ }
+ }
+ context.globalAlpha = 1;
+}
+
+type TopicMapCanvasProps = {
+ model: TopicMapModel;
+ size: Size;
+ camera: Camera;
+ store: TopicMapStore;
+ selectedTopic: string | null;
+ selectedTraceId: string | null;
+ matchingTraceIds?: ReadonlySet<string>;
+};
+
+type Presentation = {
+ frame: TopicMapNodeFrame | null;
+ camera: Camera;
+ scope: string | null;
+ flight: { start: Camera; target: Camera; started: number } | null;
+ pointer: MapPosition;
+ emphasis: Map<string, number>;
+ lastTime: number;
+};
diff --git a/web/src/features/topics/map/TopicMapExplorer.tsx b/web/src/features/topics/map/TopicMapExplorer.tsx
new file mode 100644
index 0000000000..7c615053ea
--- /dev/null
+++ b/web/src/features/topics/map/TopicMapExplorer.tsx
@@ -0,0 +1,785 @@
+import {
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type KeyboardEvent as ReactKeyboardEvent,
+ type MouseEvent as ReactMouseEvent,
+ type PointerEvent as ReactPointerEvent,
+ type TransitionEvent as ReactTransitionEvent,
+} from "react";
+import { useStore } from "zustand";
+import { LocateFixed, Maximize2, Minus, Plus, X } from "@langfuse/icons";
+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";
+import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";
+import { useElementSize } from "@/src/hooks/useElementSize";
+import { usePanZoomGestures } from "@/src/hooks/usePanZoomGestures";
+import { cn } from "@/src/utils/tailwind";
+import { TopicMapCanvas } from "./TopicMapCanvas";
+import styles from "./topic-map.module.css";
+import {
+ clearTopicMapHover,
+ createTopicMapStore,
+ finishTopicMapHover,
+ getTopicMapHover,
+ setTopicMapHover,
+ type TopicMapStore,
+} from "./topic-map-store";
+import {
+ fitCamera,
+ fitMapPoints,
+ hitMapNode,
+ panCamera,
+ prepareMapHover,
+ prepareMapTextLabels,
+ prepareTopicMap,
+ nodeDetailBlend,
+ zoomCamera,
+ type Camera,
+ type MapData,
+ type MapTopic,
+ type Size,
+ type TopicMapModel,
+} from "./prepare-topic-map";
+
+const arrowKeyPan: Readonly<
+ Record<string, { dx: number; dy: number } | undefined>
+> = {
+ ArrowLeft: { dx: 80, dy: 0 },
+ ArrowRight: { dx: -80, dy: 0 },
+ ArrowUp: { dx: 0, dy: 80 },
+ ArrowDown: { dx: 0, dy: -80 },
+};
+const zoomKeyLevels: Readonly<Record<string, number | undefined>> = {
+ "+": 0.5,
+ "=": 0.5,
+ "-": -0.5,
+};
+const mapKeys = new Set([
+ ...Object.keys(arrowKeyPan),
+ ...Object.keys(zoomKeyLevels),
+ "0",
+ "Home",
+ "Escape",
+]);
+
+export function TopicMapExplorer({
+ data,
+ topics,
+ selectedTopic,
+ onSelectTopic,
+ onSelectTrace,
+ selectedTraceId,
+ matchingTraceIds,
+ fillContainer = false,
+}: TopicMapExplorerProps) {
+ // Projection preparation is independent of the high-frequency camera store.
+ const model = useMemo(() => prepareTopicMap(data, topics), [data, topics]);
+ const [store] = useState(createTopicMapStore);
+ const [stageRef, stageSize] = useElementSize<HTMLDivElement>();
+ const sectionRef = useRef<HTMLElement>(null);
+ const animationRef = useRef(0);
+ const size = {
+ width: stageSize?.width || 960,
+ height: stageSize?.height || 560,
+ };
+ const selectedZone = model.zones.find((zone) => zone.id === selectedTopic);
+ const initialCamera = fitCamera(
+ selectedZone?.bounds ?? model.bounds,
+ model.bounds,
+ size,
+ );
+ const fullscreen = useStore(store, (s) => s.isFullscreen);
+ const fullscreenError = useStore(store, (s) => s.fullscreenError);
+ const getCamera = () => {
+ const state = store.getState();
+ return state.scope === selectedTopic && state.camera
+ ? state.camera
+ : initialCamera;
+ };
+ const setCamera = (camera: Camera | null, scope = selectedTopic) => {
+ clearTopicMapHover(store);
+ store.setState({ camera, scope });
+ };
+ const cancelFlight = () => {
+ const manualFlight = animationRef.current !== 0;
+ cancelAnimationFrame(animationRef.current);
+ animationRef.current = 0;
+ const state = store.getState();
+ const frame = state.frame;
+ if (
+ state.isMoving &&
+ (manualFlight ||
+ state.scope !== selectedTopic ||
+ state.camera === null) &&
+ frame?.model === model &&
+ frame.readingTopic === selectedTopic &&
+ frame.size.width === size.width &&
+ frame.size.height === size.height
+ )
+ setCamera(frame.camera);
+ };
+ const flyTo = (target: Camera, scope: string | null, fit = false) => {
+ cancelFlight();
+ clearTopicMapHover(store);
+ const start = getCamera();
+ if (store.getState().reducedMotion) {
+ setCamera(fit ? null : target, scope);
+ return;
+ }
+ const started = performance.now();
+ const step = (now: number) => {
+ animationRef.current = 0;
+ const progress = Math.min(1, (now - started) / 1050);
+ const t = progress ** 3 * (progress * (progress * 6 - 15) + 10);
+ setCamera(
+ {
+ x: start.x + (target.x - start.x) * t,
+ y: start.y + (target.y - start.y) * t,
+ zoom: Math.exp(
+ Math.log(start.zoom) + Math.log(target.zoom / start.zoom) * t,
+ ),
+ },
+ scope,
+ );
+ if (progress < 1) animationRef.current = requestAnimationFrame(step);
+ else if (fit) setCamera(null, scope);
+ };
+ setCamera(start, scope);
+ animationRef.current = requestAnimationFrame(step);
+ };
+ const chooseZone = (id: string | null) => {
+ if (id === selectedTopic) {
+ const zone = model.zones.find((item) => item.id === id);
+ flyTo(
+ fitCamera(zone?.bounds ?? model.bounds, model.bounds, size),
+ id,
+ true,
+ );
+ } else {
+ cancelFlight();
+ if (selectedTopic !== null) setCamera(null, id);
+ }
+ onSelectTopic(id);
+ };
+ const zoom = (levels: number, anchor = { x: 0.5, y: 0.5 }) => {
+ const before = getCamera();
+ const next = zoomCamera(before, levels, anchor, model.bounds, size);
+ setCamera(next);
+ };
+ const handlePan = (dx: number, dy: number) => {
+ setCamera(panCamera(getCamera(), dx, dy, model.bounds, size));
+ };
+ const handleInteractionStart = () => {
+ cancelFlight();
+ clearTopicMapHover(store);
+ };
+ const gestures = usePanZoomGestures({
+ target: stageRef,
+ onPan: handlePan,
+ onZoom: zoom,
+ onInteractionStart: handleInteractionStart,
+ });
+ // Browser fullscreen and OS motion preferences are external subscriptions.
+ useEffect(() => {
+ const motion = window.matchMedia("(prefers-reduced-motion: reduce)");
+ const updateMotion = () => {
+ if (motion.matches) setTopicMapHover(store, null, null, { x: 0, y: 0 });
+ store.setState({
+ reducedMotion: motion.matches,
+ });
+ };
+ const updateFullscreen = () => {
+ clearTopicMapHover(store);
+ store.setState({
+ isFullscreen: document.fullscreenElement === sectionRef.current,
+ });
+ };
+ updateMotion();
+ motion.addEventListener("change", updateMotion);
+ document.addEventListener("fullscreenchange", updateFullscreen);
+ return () => {
+ motion.removeEventListener("change", updateMotion);
+ document.removeEventListener("fullscreenchange", updateFullscreen);
+ cancelAnimationFrame(animationRef.current);
+ };
+ }, [store]);
+ const toggleFullscreen = async () => {
+ cancelFlight();
+ clearTopicMapHover(store);
+ store.setState({ fullscreenError: false });
+ try {
+ if (document.fullscreenElement === sectionRef.current)
+ await document.exitFullscreen();
+ else await sectionRef.current?.requestFullscreen();
+ } catch {
+ store.setState({ fullscreenError: true });
+ }
+ };
+ const selectTrace = (id: string | null) => {
+ if (id !== null && matchingTraceIds && !matchingTraceIds.has(id)) return;
+ clearTopicMapHover(store);
+ onSelectTrace(id);
+ };
+ const handlePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
+ gestures.pointerHandlers.onPointerMove(event);
+ if (event.pointerType !== "mouse") return;
+ const pointerAt = { x: event.clientX, y: event.clientY };
+ if (event.buttons !== 0) {
+ clearTopicMapHover(store);
+ store.setState({ pointerAt });
+ return;
+ }
+ const previous = store.getState().pointerAt;
+ if (
+ previous &&
+ Math.hypot(pointerAt.x - previous.x, pointerAt.y - previous.y) <= 0.5
+ )
+ return;
+ if (gestures.isDragging) return;
+ const rect = event.currentTarget.getBoundingClientRect();
+ const at = {
+ x: event.clientX - rect.left,
+ y: event.clientY - rect.top,
+ };
+ const pointer = store.getState().reducedMotion
+ ? { x: 0, y: 0 }
+ : {
+ x: (at.x / size.width - 0.5) * 2,
+ y: (at.y / size.height - 0.5) * 2,
+ };
+ const frame = store.getState().frame;
+ const intended = getCamera();
+ if (
+ store.getState().isMoving ||
+ !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 ||
+ frame.camera.x !== intended.x ||
+ frame.camera.y !== intended.y
+ ) {
+ setTopicMapHover(store, null, null, pointer, pointerAt);
+ return;
+ }
+ const hovered = hitMapNode(frame, at);
+ const traceLabel =
+ event.target instanceof Element
+ ? event.target.closest<HTMLElement>(
+ '[data-topic-trace]:not([data-active="false"])',
+ )
+ : null;
+ setTopicMapHover(
+ store,
+ traceLabel?.dataset.topicTrace ?? hovered?.traceId ?? null,
+ null,
+ pointer,
+ pointerAt,
+ );
+ };
+ const handleStageClick = (event: ReactMouseEvent<HTMLDivElement>) => {
+ if (event.target !== event.currentTarget) return;
+ const rect = event.currentTarget.getBoundingClientRect();
+ const frame = store.getState().frame;
+ const point =
+ frame &&
+ frame.model === model &&
+ frame.readingTopic === selectedTopic &&
+ frame.matchingTraceIds === matchingTraceIds
+ ? hitMapNode(frame, {
+ x: event.clientX - rect.left,
+ y: event.clientY - rect.top,
+ })
+ : null;
+ selectTrace(point?.traceId ?? null);
+ };
+ const handleStageDoubleClick = (event: ReactMouseEvent<HTMLDivElement>) => {
+ if (event.target !== event.currentTarget) return;
+ const rect = event.currentTarget.getBoundingClientRect();
+ cancelFlight();
+ zoom(1, {
+ x: (event.clientX - rect.left) / size.width,
+ y: (event.clientY - rect.top) / size.height,
+ });
+ };
+ const handlePointerLeave = () => {
+ setTopicMapHover(store, null, null, { x: 0, y: 0 });
+ };
+ const handleStageKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ if (event.target !== event.currentTarget || !mapKeys.has(event.key)) return;
+ event.preventDefault();
+ cancelFlight();
+ const zoomLevels = zoomKeyLevels[event.key];
+ if (zoomLevels !== undefined) {
+ zoom(zoomLevels);
+ return;
+ }
+ const pan = arrowKeyPan[event.key];
+ if (pan) {
+ handlePan(pan.dx, pan.dy);
+ return;
+ }
+ if (event.key === "Escape") {
+ handleEscape();
+ return;
+ }
+ chooseZone(null);
+ };
+ const handleEscape = () => {
+ if (document.fullscreenElement === sectionRef.current) {
+ toggleFullscreen();
+ return;
+ }
+ if (selectedTraceId) {
+ onSelectTrace(null);
+ return;
+ }
+ chooseZone(null);
+ };
+ const handleControlPointerEnter = () => clearTopicMapHover(store);
+ const handleFitMap = () => chooseZone(null);
+ const handleZoomOut = () => {
+ cancelFlight();
+ zoom(-0.5);
+ };
+ const handleZoomIn = () => {
+ cancelFlight();
+ zoom(0.5);
+ };
+ const handleToggleFullscreen = () => {
+ toggleFullscreen();
+ };
+ return (
+ <section
+ ref={sectionRef}
+ aria-label="Embedding map"
+ className={cn(
+ "ph-no-capture bg-background flex min-w-0 flex-col overflow-hidden rounded-lg border",
+ fillContainer && "h-full min-h-0",
+ fullscreen && "h-dvh rounded-none border-0",
+ )}
+ >
+ {fullscreenError && (
+ <p role="status" className="text-muted-foreground px-4 py-2 text-xs">
+ Fullscreen is unavailable in this browser. You can still pan and zoom
+ here.
+ </p>
+ )}
+ <div
+ ref={stageRef}
+ tabIndex={0}
+ role="group"
+ aria-label="Interactive topic map. Drag or scroll to pan, pinch or control scroll to zoom. Arrow keys pan, plus and minus zoom, zero fits the map."
+ className={cn(
+ "bg-muted/10 focus-visible:ring-ring relative w-full overflow-hidden overscroll-contain outline-none focus-visible:ring-2 focus-visible:ring-inset",
+ fullscreen || fillContainer
+ ? "min-h-0 flex-1"
+ : "h-[clamp(380px,64vh,820px)] min-h-[340px]",
+ gestures.isDragging ? "cursor-grabbing" : "cursor-grab",
+ )}
+ style={{ touchAction: "none" }}
+ {...gestures.pointerHandlers}
+ onPointerMove={handlePointerMove}
+ onPointerLeave={handlePointerLeave}
+ onClick={handleStageClick}
+ onDoubleClick={handleStageDoubleClick}
+ onKeyDown={handleStageKeyDown}
+ >
+ <div
+ role="toolbar"
+ aria-label="Map controls"
+ className="bg-background/85 absolute top-2 right-2 z-20 flex items-center gap-0.5 rounded-md border p-0.5 shadow-sm backdrop-blur-sm"
+ onPointerDown={stopPointerPropagation}
+ onPointerMove={stopPointerPropagation}
+ onPointerEnter={handleControlPointerEnter}
+ >
+ <IconButton
+ icon={LocateFixed}
+ label="Fit map (0)"
+ onClick={handleFitMap}
+ />
+ <IconButton
+ icon={Minus}
+ label="Zoom out (-)"
+ onClick={handleZoomOut}
+ />
+ <ZoomReadout
+ store={store}
+ initialCamera={initialCamera}
+ scope={selectedTopic}
+ />
+ <IconButton icon={Plus} label="Zoom in (+)" onClick={handleZoomIn} />
+ <IconButton
+ icon={fullscreen ? X : Maximize2}
+ label={fullscreen ? "Exit fullscreen" : "Enter fullscreen"}
+ onClick={handleToggleFullscreen}
+ />
+ </div>
+ <MapBackgroundLabels store={store} />
+ <TopicMapCanvas
+ model={model}
+ size={size}
+ camera={initialCamera}
+ store={store}
+ selectedTopic={selectedTopic}
+ selectedTraceId={selectedTraceId}
+ matchingTraceIds={matchingTraceIds}
+ />
+ <MapLabels
+ model={model}
+ size={size}
+ store={store}
+ selectedTopic={selectedTopic}
+ selectedTraceId={selectedTraceId}
+ matchingTraceIds={matchingTraceIds}
+ onSelectTrace={selectTrace}
+ />
+ {model.points.length === 0 && (
+ <div className="text-muted-foreground pointer-events-none absolute inset-0 flex items-center justify-center p-6 text-center text-sm">
+ No plotted summaries in this selection. Try a wider time range.
+ </div>
+ )}
+ <div className="text-muted-foreground pointer-events-none absolute right-4 bottom-3 left-4 flex flex-wrap items-center justify-between gap-2 text-[11px]">
+ <LayoutReadout
+ store={store}
+ initialCamera={initialCamera}
+ scope={selectedTopic}
+ population={
+ matchingTraceIds
+ ? `${model.points.filter((point) => matchingTraceIds.has(point.traceId)).length.toLocaleString()} of ${model.populationLabel} match`
+ : model.populationLabel
+ }
+ missingSummaryCount={data.missingSummaryCount}
+ unpositionedCount={data.unpositionedCount}
+ />
+ {!fillContainer && (
+ <span>
+ Drag / scroll to pan · Pinch / Ctrl or ⌘ + scroll to zoom
+ </span>
+ )}
+ </div>
+ </div>
+ </section>
+ );
+}
+
+function ZoomReadout({
+ store,
+ initialCamera,
+ scope,
+}: {
+ store: TopicMapStore;
+ initialCamera: Camera;
+ scope: string | null;
+}) {
+ const camera = useStore(store, (s) => s.camera);
+ const cameraScope = useStore(store, (s) => s.scope);
+ return (
+ <span
+ className="text-muted-foreground w-12 text-center text-xs tabular-nums"
+ aria-label="Zoom level"
+ >
+ {Math.round(
+ (cameraScope === scope && camera ? camera.zoom : initialCamera.zoom) *
+ 100,
+ )}
+ %
+ </span>
+ );
+}
+
+function LayoutReadout({
+ store,
+ initialCamera,
+ scope,
+ population,
+ missingSummaryCount,
+ unpositionedCount,
+}: LayoutReadoutProps) {
+ const camera = useStore(store, (s) => s.camera);
+ const cameraScope = useStore(store, (s) => s.scope);
+ const current = cameraScope === scope && camera ? camera : initialCamera;
+ const handlePointerEnter = () => clearTopicMapHover(store);
+ return (
+ <Tooltip
+ label={mapCoverageLabel(
+ population,
+ missingSummaryCount,
+ unpositionedCount,
+ )}
+ hoverableContent={false}
+ >
+ {({ getTriggerProps }) => (
+ <button
+ {...getTriggerProps()}
+ type="button"
+ aria-label={`Map coverage: ${population}`}
+ className="focus-visible:outline-ring pointer-events-auto cursor-help text-left focus-visible:outline-2"
+ onPointerDown={stopPointerPropagation}
+ onPointerMove={stopPointerPropagation}
+ onPointerEnter={handlePointerEnter}
+ >
+ {population} ·{" "}
+ {nodeDetailBlend(current.zoom) > 0
+ ? "Adaptive detail"
+ : "Saved 2D projection"}
+ </button>
+ )}
+ </Tooltip>
+ );
+}
+
+function MapLabels({
+ model,
+ size,
+ store,
+ selectedTopic,
+ selectedTraceId,
+ matchingTraceIds,
+ onSelectTrace,
+}: MapLabelsProps) {
+ const state = useStore(store);
+ const frame = state.frame;
+ const hover = getTopicMapHover(state, frame);
+ const current =
+ frame !== null &&
+ frame.model === model &&
+ frame.size.width === size.width &&
+ frame.size.height === size.height &&
+ frame.readingTopic === selectedTopic &&
+ frame.matchingTraceIds === matchingTraceIds;
+ const handleTraceClick = (event: ReactMouseEvent<HTMLButtonElement>) => {
+ const traceId = event.currentTarget.dataset.traceId;
+ if (traceId) onSelectTrace(traceId);
+ };
+ const handleHoverTransitionEnd = (
+ event: ReactTransitionEvent<HTMLDivElement>,
+ ) => {
+ if (
+ event.currentTarget.dataset.active === "false" &&
+ event.propertyName === "opacity"
+ )
+ finishTopicMapHover(
+ store,
+ Number(event.currentTarget.dataset.hoverToken),
+ );
+ };
+ return (
+ <div className="pointer-events-none absolute inset-0">
+ {current &&
+ frame!.nodes
+ .filter((node) => node.textOpacity > 0.001)
+ .map((node) => (
+ <button
+ key={node.point.traceId}
+ type="button"
+ data-topic-node=""
+ data-topic-trace={node.point.traceId}
+ data-trace-id={node.point.traceId}
+ data-testid="topic-map-trace-card"
+ data-hovered={node.point.traceId === hover.hoveredId}
+ data-text-opacity={node.textOpacity}
+ tabIndex={node.textOpacity >= 0.9 ? 0 : -1}
+ aria-pressed={node.point.traceId === selectedTraceId}
+ aria-label={`Select trace: ${node.point.summary}`}
+ onClick={handleTraceClick}
+ className="text-foreground focus-visible:outline-ring pointer-events-auto absolute cursor-pointer overflow-hidden rounded-lg px-2 py-1.5 text-left leading-relaxed focus-visible:outline-2"
+ style={{
+ left: node.rect.x,
+ top: node.rect.y,
+ width: node.rect.width,
+ height: node.rect.height,
+ opacity: node.textOpacity,
+ fontSize: node.fontSize,
+ }}
+ >
+ <span className="block">{node.excerpt}</span>
+ </button>
+ ))}
+ {state.hoverLabels.map((label) => {
+ if (!frame || frame.model !== model) return null;
+ const active =
+ current &&
+ label.active &&
+ (label.kind === "trace"
+ ? hover.hoveredId === label.id
+ : hover.hoveredZoneId === label.id) &&
+ (label.kind !== "trace" ||
+ (frame.nodeById.get(label.id)?.textOpacity ?? 1) < 0.65);
+ const source = active ? frame : label.frame;
+ if (!source) return null;
+ const hints = prepareMapHover(
+ source,
+ label.kind === "trace" ? label.id : null,
+ label.kind === "zone" ? label.id : null,
+ );
+ const trace = hints.traces[0];
+ const zone = hints.zones[0];
+ if (!trace && !zone) return null;
+ const rect = trace?.card ?? zone!.label;
+ const topicPrefix = trace?.topicName ? `${trace.topicName}. ` : "";
+ return (
+ <div
+ key={label.token}
+ role="tooltip"
+ data-testid="topic-map-hover-card"
+ data-topic-trace={trace?.point.traceId}
+ data-topic-zone={zone?.id}
+ data-trace-id={trace?.point.traceId}
+ data-active={active}
+ data-hover-token={label.token}
+ data-hovered={active && label.kind === "trace"}
+ aria-hidden={!active}
+ aria-label={
+ trace
+ ? `Trace summary: ${topicPrefix}${trace.point.summary}`
+ : `${zone!.name}, ${zone!.countLabel}`
+ }
+ onTransitionEnd={handleHoverTransitionEnd}
+ className={cn(
+ "bg-background/85 text-foreground pointer-events-none absolute overflow-hidden rounded-lg border px-3 py-2.5 text-left text-xs leading-relaxed shadow-md backdrop-blur-sm",
+ styles.hoverCard,
+ active ? styles.enter : styles.exit,
+ )}
+ style={{
+ left: rect.x,
+ top: rect.anchorY,
+ width: rect.width,
+ maxHeight: rect.height,
+ // Percentages use the rendered height; clamp keeps the card inside its reserved bounds.
+ translate: `0 clamp(${rect.y - rect.anchorY}px, ${-100 * rect.anchorFraction}%, calc(${rect.y + rect.height - rect.anchorY}px - 100%))`,
+ borderLeftColor: trace?.point.color ?? zone!.color,
+ borderLeftWidth: 2,
+ }}
+ >
+ {trace ? (
+ <>
+ {trace.topicName && (
+ <span
+ className="mb-1 line-clamp-2"
+ style={{ color: trace.point.color }}
+ >
+ {trace.topicName}
+ </span>
+ )}
+ <span className="line-clamp-6">{trace.excerpt}</span>
+ </>
+ ) : (
+ <>
+ <span
+ className="block text-xs font-bold"
+ style={{ color: zone!.color }}
+ >
+ {zone!.name}
+ </span>
+ <span className="text-muted-foreground mb-1 block text-[10px]">
+ {zone!.countLabel} · {zone!.shareLabel}
+ </span>
+ <span className="line-clamp-3 text-[11px]">{zone!.detail}</span>
+ </>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+function MapBackgroundLabels({ store }: { store: TopicMapStore }) {
+ const frame = useStore(store, (state) => state.frame);
+ return (
+ <div
+ className="pointer-events-none absolute inset-0 overflow-hidden"
+ aria-hidden
+ >
+ {frame &&
+ prepareMapTextLabels(frame).map((label) => (
+ <div
+ key={label.id}
+ data-topic-background-label={label.id}
+ data-label-kind={label.kind}
+ className={cn(
+ "text-muted-foreground pointer-events-none absolute overflow-hidden text-center",
+ styles.backgroundLabel,
+ )}
+ style={{
+ left: label.rect.x,
+ top: label.rect.y,
+ width: label.rect.width,
+ height: label.rect.height,
+ opacity: label.opacity,
+ }}
+ >
+ <span
+ className={cn(
+ "line-clamp-2 block leading-[1.2]",
+ label.kind === "zone" && "font-bold",
+ )}
+ style={{
+ fontSize: label.fontSize,
+ color: `color-mix(in srgb, ${label.color} 35%, hsl(var(--muted-foreground)))`,
+ }}
+ >
+ {label.title}
+ </span>
+ {label.description.length > 0 && (
+ <span
+ className="mt-1 line-clamp-2 block text-[11px] leading-relaxed"
+ style={{ opacity: label.detailOpacity }}
+ >
+ {label.description}
+ </span>
+ )}
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function stopPointerPropagation(event: ReactPointerEvent<HTMLElement>) {
+ event.stopPropagation();
+}
+
+function mapCoverageLabel(
+ population: string,
+ missingSummaryCount: number,
+ unpositionedCount: number,
+) {
+ return `${population}.\n${missingSummaryCount.toLocaleString()} saved map points have no current summary.\n${unpositionedCount.toLocaleString()} current summaries have no saved coordinates.`;
+}
+
+export type TopicMapExplorerProps = {
+ projectId: string;
+ data: MapData;
+ topics: MapTopic[];
+ selectedTopic: string | null;
+ onSelectTopic: (id: string | null) => void;
+ onSelectTrace: (traceId: string | null) => void;
+ selectedTraceId: string | null;
+ matchingTraceIds?: ReadonlySet<string>;
+ fillContainer?: boolean;
+};
+
+type LayoutReadoutProps = {
+ store: TopicMapStore;
+ initialCamera: Camera;
+ scope: string | null;
+ population: string;
+ missingSummaryCount: number;
+ 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.ts
new file mode 100644
index 0000000000..3a705cc357
--- /dev/null
+++ b/web/src/features/topics/map/prepare-topic-map.ts
@@ -0,0 +1,729 @@
+import type { RouterOutputs } from "@/src/utils/api";
+import { topicColor } from "../topic-map-colors";
+
+export type MapData = Pick<
+ RouterOutputs["topics"]["map"],
+ "points" | "missingSummaryCount" | "unpositionedCount"
+>;
+export type MapTopic = { id: string; name: string; description?: string };
+export type Bounds = { minX: number; maxX: number; minY: number; maxY: number };
+export type Camera = { x: number; y: number; zoom: number };
+export type Size = { width: number; height: number };
+export type MapPoint = MapData["points"][number] & {
+ groupId: string;
+ color: string;
+ depth: number;
+};
+type MapZone = {
+ id: string;
+ name: string;
+ description: string;
+ color: string;
+ points: MapPoint[];
+ bounds: Bounds;
+ x: number;
+ y: number;
+ countLabel: string;
+ shareLabel: string;
+};
+export type TopicMapModel = {
+ points: MapPoint[];
+ zones: MapZone[];
+ bounds: Bounds;
+ pointById: Map<string, MapPoint>;
+ populationLabel: string;
+};
+
+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;
+ cornerRadius: number;
+ expansion: number;
+ backgroundOpacity: number;
+ strokeOpacity: number;
+ textOpacity: number;
+ fontSize: number;
+ excerpt: string;
+};
+export type TopicMapNodeFrame = {
+ model: TopicMapModel;
+ camera: Camera;
+ size: Size;
+ pointer: MapPosition;
+ readingTopic: string | null;
+ matchingTraceIds: ReadonlySet<string> | undefined;
+ zones: TopicMapModel["zones"];
+ nodes: TopicMapNode[];
+ nodeById: ReadonlyMap<string, TopicMapNode>;
+};
+
+const emptyBounds = { minX: -0.5, maxX: 0.5, minY: -0.5, maxY: 0.5 };
+function pointBounds(points: { x: number; y: number }[]): Bounds {
+ if (points.length === 0) return emptyBounds;
+ let minX = Infinity,
+ maxX = -Infinity,
+ minY = Infinity,
+ maxY = -Infinity;
+ for (const point of points) {
+ minX = Math.min(minX, point.x);
+ maxX = Math.max(maxX, point.x);
+ minY = Math.min(minY, point.y);
+ maxY = Math.max(maxY, point.y);
+ }
+ return { minX, maxX, minY, maxY };
+}
+
+function rotatePoints<T extends { x: number; y: number }>(
+ points: T[],
+ cohort: T[],
+) {
+ const count = Math.max(cohort.length, 1);
+ const x = cohort.reduce((sum, p) => sum + p.x, 0) / count;
+ const y = cohort.reduce((sum, p) => sum + p.y, 0) / count;
+ let xx = 0,
+ yy = 0,
+ xy = 0;
+ for (const p of cohort) {
+ xx += (p.x - x) ** 2;
+ yy += (p.y - y) ** 2;
+ xy += (p.x - x) * (p.y - y);
+ }
+ // One rotation for the discovery cohort preserves distances and orientation.
+ const angle = Math.atan2(2 * xy, xx - yy) / 2;
+ return points.map((p) => ({
+ ...p,
+ x: (p.x - x) * Math.cos(angle) + (p.y - y) * Math.sin(angle),
+ y: -(p.x - x) * Math.sin(angle) + (p.y - y) * Math.cos(angle),
+ }));
+}
+
+export function baseScale(bounds: Bounds, size: Size) {
+ return Math.min(
+ Math.max(size.width - 100, 1) / Math.max(bounds.maxX - bounds.minX, 0.1),
+ Math.max(size.height - 100, 1) / Math.max(bounds.maxY - bounds.minY, 0.1),
+ );
+}
+
+export function fitCamera(bounds: Bounds, whole: Bounds, size: Size): Camera {
+ return {
+ x: (bounds.minX + bounds.maxX) / 2,
+ y: (bounds.minY + bounds.maxY) / 2,
+ zoom: Math.min(
+ 32,
+ Math.max(0.4, baseScale(bounds, size) / baseScale(whole, size)),
+ ),
+ };
+}
+
+export function screenPoint(
+ point: { x: number; y: number },
+ camera: Camera,
+ bounds: Bounds,
+ size: Size,
+) {
+ const scale = baseScale(bounds, size) * camera.zoom;
+ return {
+ x: size.width / 2 + (point.x - camera.x) * scale,
+ y: size.height / 2 - (point.y - camera.y) * scale,
+ };
+}
+
+export function zoomCamera(
+ camera: Camera,
+ levels: number,
+ anchor: { x: number; y: number },
+ bounds: Bounds,
+ size: Size,
+): Camera {
+ const zoom = Math.min(128, Math.max(0.4, camera.zoom * 2 ** levels));
+ const before = baseScale(bounds, size) * camera.zoom;
+ const after = baseScale(bounds, size) * zoom;
+ const dx = (anchor.x - 0.5) * size.width;
+ const dy = (anchor.y - 0.5) * size.height;
+ return {
+ x: camera.x + dx / before - dx / after,
+ y: camera.y - dy / before + dy / after,
+ zoom,
+ };
+}
+
+export function panCamera(
+ camera: Camera,
+ dx: number,
+ dy: number,
+ bounds: Bounds,
+ size: Size,
+): Camera {
+ const scale = baseScale(bounds, size) * camera.zoom;
+ return { ...camera, x: camera.x - dx / scale, y: camera.y + dy / scale };
+}
+
+function visualDepth(id: string) {
+ let hash = 0;
+ for (let i = 0; i < id.length; i++)
+ hash = (hash * 31 + id.charCodeAt(i)) % 1000003;
+ return (hash % 1000) / 1000;
+}
+
+export function prepareTopicMap(
+ data: MapData,
+ topics: MapTopic[],
+): TopicMapModel {
+ const known = new Map(
+ topics.map((topic, i) => [topic.id, { ...topic, color: topicColor(i) }]),
+ );
+ const points: MapPoint[] = data.points.map((point) => ({
+ ...point,
+ groupId:
+ point.outcome === "unassigned"
+ ? "awaiting_map"
+ : (point.topicId ?? "outliers"),
+ color: topicColor(topics.findIndex((t) => t.id === point.topicId)),
+ // This is decorative depth, independent of embedding distance or quality.
+ depth: visualDepth(point.traceId),
+ }));
+ const grouped = new Map<string, MapPoint[]>();
+ for (const point of points) {
+ const group = grouped.get(point.groupId) ?? [];
+ group.push(point);
+ grouped.set(point.groupId, group);
+ }
+ const zones = Array.from(grouped, ([id, members]): MapZone => {
+ const topic = known.get(id);
+ const center = {
+ x: members.reduce((sum, p) => sum + p.x, 0) / members.length,
+ y: members.reduce((sum, p) => sum + p.y, 0) / members.length,
+ };
+ let description =
+ topic?.description?.trim() ||
+ "No description is available for this topic.";
+ if (id === "outliers")
+ description = "Summaries outside the discovered topics.";
+ if (id === "awaiting_map")
+ description = "These summaries have no current assignment.";
+ return {
+ id,
+ name:
+ topic?.name ??
+ (id === "awaiting_map" ? "Assignment unavailable" : "Outliers"),
+ description,
+ color: topic?.color ?? topicColor(-1),
+ points: members,
+ bounds: pointBounds(members),
+ ...center,
+ countLabel: `${members.length.toLocaleString()} mapped traces`,
+ shareLabel: `${Math.round((members.length / Math.max(points.length, 1)) * 100)}% of map`,
+ };
+ }).sort((a, b) => b.points.length - a.points.length);
+ return {
+ points,
+ zones,
+ bounds: pointBounds(points),
+ pointById: new Map(points.map((p) => [p.traceId, p])),
+ populationLabel: `${points.length.toLocaleString()} mapped traces`,
+ };
+}
+
+function smoothStep(from: number, to: number, value: number) {
+ const progress = Math.min(1, Math.max(0, (value - from) / (to - from)));
+ return progress * progress * (3 - 2 * progress);
+}
+
+export function nodeDetailBlend(zoom: number) {
+ return smoothStep(3, 10, zoom);
+}
+
+function readingNodeSize(size: Size) {
+ return { width: Math.max(6, Math.min(264, size.width - 48)), height: 144 };
+}
+
+export function prepareMapNodes(
+ model: TopicMapModel,
+ camera: Camera,
+ size: Size,
+ pointer: MapPosition,
+ readingTopic: string | null = null,
+ matchingTraceIds?: ReadonlySet<string>,
+): TopicMapNodeFrame {
+ const full = readingNodeSize(size);
+ const blend = nodeDetailBlend(camera.zoom);
+ const cells = new Map<string, number[]>();
+ const cellWidth = full.width + 8;
+ const cellHeight = full.height + 8;
+ const prepared = model.points.map((point, index) => {
+ const worldPosition = { x: point.x, y: point.y };
+ const projected = screenPoint(worldPosition, camera, model.bounds, size);
+ const depth = point.depth * (1 - blend);
+ const center = {
+ x: projected.x + pointer.x * depth * 6,
+ y: projected.y + pointer.y * depth * 6,
+ };
+ const diameter = (5 + depth) * Math.sqrt(Math.min(camera.zoom, 16));
+ 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);
+ const cellY = Math.floor(center.y / cellHeight);
+ const key = `${cellX},${cellY}`;
+ const cell = cells.get(key) ?? [];
+ cell.push(index);
+ cells.set(key, cell);
+ return {
+ point,
+ matchesFilters,
+ worldPosition,
+ center,
+ diameter,
+ growWidth,
+ growHeight,
+ growth,
+ cellX,
+ cellY,
+ };
+ });
+ const axisLimit = (distance: number, base: number, growth: number) => {
+ if (growth > 0) return (Math.abs(distance) - base - 8) / growth;
+ return Math.abs(distance) >= base + 8 ? Infinity : -Infinity;
+ };
+ const nodeById = new Map<string, TopicMapNode>();
+ const nodes: TopicMapNode[] = [];
+ for (const item of prepared) {
+ let clearance = 1;
+ if (item.growth) {
+ neighbors: for (let x = item.cellX - 1; x <= item.cellX + 1; x++) {
+ for (let y = item.cellY - 1; y <= item.cellY + 1; y++) {
+ for (const index of cells.get(`${x},${y}`) ?? []) {
+ const other = prepared[index];
+ if (other === item) continue;
+ const base = (item.diameter + other.diameter) / 2;
+ const limit = Math.max(
+ 0,
+ Math.min(
+ 1,
+ Math.max(
+ axisLimit(
+ item.center.x - other.center.x,
+ base,
+ (item.growWidth + other.growWidth) / 2,
+ ),
+ axisLimit(
+ item.center.y - other.center.y,
+ base,
+ (item.growHeight + other.growHeight) / 2,
+ ),
+ ),
+ ),
+ );
+ clearance = Math.min(clearance, limit);
+ if (!clearance) break neighbors;
+ }
+ }
+ }
+ }
+ const width = item.diameter + item.growWidth * clearance;
+ const height = item.diameter + item.growHeight * clearance;
+ const expansion = item.growth * clearance;
+ const smaller = Math.min(width, height);
+ 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: {
+ x: item.center.x - width / 2,
+ y: item.center.y - height / 2,
+ width,
+ height,
+ },
+ cornerRadius:
+ smaller / 2 + (Math.min(8, smaller / 2) - smaller / 2) * textOpacity,
+ expansion,
+ backgroundOpacity: textOpacity,
+ strokeOpacity: textOpacity,
+ textOpacity,
+ fontSize: 9 + smoothStep(100, 264, width) * 3,
+ excerpt: item.point.summary,
+ };
+ nodeById.set(item.point.traceId, node);
+ if (
+ node.rect.x <= size.width &&
+ node.rect.x + width >= 0 &&
+ node.rect.y <= size.height &&
+ node.rect.y + height >= 0
+ )
+ nodes.push(node);
+ }
+ return {
+ model,
+ camera,
+ size,
+ pointer,
+ readingTopic,
+ matchingTraceIds,
+ zones: model.zones,
+ nodes,
+ nodeById,
+ };
+}
+
+type MapTextLabel = {
+ id: string;
+ kind: "zone";
+ title: string;
+ color: string;
+ description: string;
+ rect: MapRectangle;
+ fontSize: number;
+ opacity: number;
+ detailOpacity: number;
+};
+
+export function prepareMapTextLabels(frame: TopicMapNodeFrame): MapTextLabel[] {
+ 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);
+ const labels: MapTextLabel[] = [];
+ const fontSize = 15 + smoothStep(3, 8, camera.zoom) * 3;
+ const visible = (rect: MapRectangle) =>
+ rect.x + rect.width > 0 &&
+ rect.y + rect.height > 0 &&
+ rect.x < size.width &&
+ rect.y < size.height;
+ for (const zone of frame.zones) {
+ const width = Math.min(
+ Math.max(120, zone.name.length * fontSize * 0.55),
+ 260,
+ Math.max(80, size.width - 32),
+ );
+ const titleHeight =
+ Math.min(2, Math.ceil((zone.name.length * fontSize * 0.55) / width)) *
+ fontSize *
+ 1.2;
+ const height = titleHeight + 40 * detailOpacity;
+ const topLeft = screenPoint(
+ { x: zone.bounds.minX, y: zone.bounds.maxY },
+ camera,
+ model.bounds,
+ size,
+ );
+ const bottomRight = screenPoint(
+ { x: zone.bounds.maxX, y: zone.bounds.minY },
+ camera,
+ model.bounds,
+ size,
+ );
+ const left = Math.max(0, topLeft.x);
+ const right = Math.min(size.width, bottomRight.x);
+ const top = Math.max(0, topLeft.y);
+ const bottom = Math.min(size.height, bottomRight.y);
+ // A zone keeps one geographic label as its center moves beyond the viewport.
+ // Clamping to the visible intersection is continuous through pan and zoom.
+ if (right < left || bottom < top) continue;
+ const center = screenPoint(zone, camera, model.bounds, size);
+ const xInset = Math.min(width / 2 + 12, (right - left) / 2);
+ const yInset = Math.min(height / 2 + 12, (bottom - top) / 2);
+ const x = Math.max(left + xInset, Math.min(right - xInset, center.x));
+ const y = Math.max(top + yInset, Math.min(bottom - yInset, center.y));
+ const topInset = Math.min(44, size.height / 4);
+ const bottomInset = Math.min(28, size.height / 4);
+ const rect = {
+ x: Math.min(
+ Math.max(8, x - width / 2),
+ Math.max(8, size.width - width - 8),
+ ),
+ y: Math.min(
+ Math.max(topInset, y - height / 2),
+ Math.max(topInset, size.height - height - bottomInset),
+ ),
+ width,
+ height,
+ };
+ if (!visible(rect)) continue;
+ const matchesFilters =
+ !matchingTraceIds ||
+ zone.points.some((point) => matchingTraceIds.has(point.traceId));
+ labels.push({
+ id: zone.id,
+ kind: "zone",
+ title: zone.name,
+ color: zone.color,
+ description: zone.description,
+ rect,
+ fontSize,
+ opacity:
+ visibility *
+ (readingTopic && readingTopic !== zone.id ? 0.32 : 0.45) *
+ (matchesFilters ? 1 : 0.15),
+ detailOpacity,
+ });
+ }
+
+ const shown: MapTextLabel[] = [];
+ for (const label of labels) {
+ let separation = 1;
+ for (const other of shown) {
+ const x =
+ Math.abs(
+ label.rect.x +
+ label.rect.width / 2 -
+ other.rect.x -
+ other.rect.width / 2,
+ ) /
+ ((label.rect.width + other.rect.width) / 2 + 16);
+ const y =
+ Math.abs(
+ label.rect.y +
+ label.rect.height / 2 -
+ other.rect.y -
+ other.rect.height / 2,
+ ) /
+ ((label.rect.height + other.rect.height) / 2 + 12);
+ separation = Math.min(separation, smoothStep(0.8, 1.15, Math.max(x, y)));
+ }
+ label.opacity *= separation;
+ if (label.opacity > 0.01) shown.push(label);
+ }
+ return labels;
+}
+
+function roundedDistance(node: TopicMapNode, at: MapPosition) {
+ const radius = node.cornerRadius;
+ const dx = Math.abs(at.x - node.center.x) - node.rect.width / 2 + radius;
+ const dy = Math.abs(at.y - node.center.y) - node.rect.height / 2 + radius;
+ return (
+ Math.min(Math.max(dx, dy), 0) +
+ Math.hypot(Math.max(dx, 0), Math.max(dy, 0)) -
+ radius
+ );
+}
+
+export function hitMapNode(
+ frame: TopicMapNodeFrame,
+ at: MapPosition,
+): MapPoint | null {
+ let nearest: TopicMapNode | null = null;
+ let distance = Infinity;
+ let inside = false;
+ for (const node of frame.nodes) {
+ const contains = roundedDistance(node, at) <= 0;
+ const proximity = Math.hypot(node.center.x - at.x, node.center.y - at.y);
+ if (!contains && (inside || proximity > 12)) continue;
+ if (
+ (contains && !inside) ||
+ proximity < distance ||
+ (proximity === distance &&
+ node.point.traceId < (nearest?.point.traceId ?? ""))
+ ) {
+ nearest = node;
+ distance = proximity;
+ inside = contains;
+ }
+ }
+ return nearest?.point ?? null;
+}
+
+export function zoneHalo(
+ zone: TopicMapModel["zones"][number],
+ camera: Camera,
+ bounds: Bounds,
+ size: Size,
+) {
+ const center = screenPoint(zone, camera, bounds, size);
+ const scale = baseScale(bounds, size) * camera.zoom;
+ return {
+ ...center,
+ rx: Math.max(28, (zone.bounds.maxX - zone.bounds.minX) * scale * 0.62),
+ ry: Math.max(28, (zone.bounds.maxY - zone.bounds.minY) * scale * 0.62),
+ };
+}
+
+type MapHoverRectangle = MapRectangle & {
+ anchorY: number;
+ anchorFraction: 0 | 0.5 | 1;
+};
+
+function hoverRectangle(
+ anchor: MapRectangle,
+ size: Size,
+ desired: Size,
+): MapHoverRectangle | null {
+ if (size.width <= 0 || size.height <= 0) return null;
+ const margin = Math.min(12, size.width / 4, size.height / 4);
+ const width = Math.min(desired.width, size.width - margin * 2);
+ const height = Math.min(desired.height, size.height - margin * 2);
+ const center = {
+ x: anchor.x + anchor.width / 2,
+ y: anchor.y + anchor.height / 2,
+ };
+ const clampCard = (
+ left: number,
+ top: number,
+ w = width,
+ h = height,
+ ): MapHoverRectangle => {
+ const x = Math.min(Math.max(margin, left), size.width - w - margin);
+ const y = Math.min(Math.max(margin, top), size.height - h - margin);
+ let anchorY = center.y;
+ let anchorFraction: MapHoverRectangle["anchorFraction"] = 0.5;
+ if (y + h <= anchor.y - 4) {
+ anchorY = y + h;
+ anchorFraction = 1;
+ } else if (y >= anchor.y + anchor.height + 4) {
+ anchorY = y;
+ anchorFraction = 0;
+ }
+ return {
+ x,
+ y,
+ width: w,
+ height: h,
+ anchorY,
+ anchorFraction,
+ };
+ };
+ const candidates = [
+ [anchor.x + anchor.width + 12, center.y - height / 2],
+ [anchor.x - width - 12, center.y - height / 2],
+ [center.x - width / 2, anchor.y + anchor.height + 12],
+ [center.x - width / 2, anchor.y - height - 12],
+ ];
+ for (const [x, y] of candidates) {
+ const card = clampCard(x, y);
+ if (
+ card.x >= anchor.x + anchor.width + 4 ||
+ card.x + card.width <= anchor.x - 4 ||
+ card.y >= anchor.y + anchor.height + 4 ||
+ card.y + card.height <= anchor.y - 4
+ )
+ return card;
+ }
+ const regions = [
+ {
+ x: anchor.x + anchor.width + 12,
+ y: center.y - height / 2,
+ width: size.width - margin - anchor.x - anchor.width - 12,
+ height: size.height - margin * 2,
+ },
+ {
+ x: margin,
+ y: center.y - height / 2,
+ width: anchor.x - margin - 12,
+ height: size.height - margin * 2,
+ },
+ {
+ x: margin,
+ y: anchor.y + anchor.height + 12,
+ width: size.width - margin * 2,
+ height: size.height - margin - anchor.y - anchor.height - 12,
+ },
+ {
+ x: margin,
+ y: anchor.y - height - 12,
+ width: size.width - margin * 2,
+ height: anchor.y - margin - 12,
+ },
+ ]
+ .filter((region) => region.width > 0 && region.height > 0)
+ .map((region) => ({
+ ...region,
+ width: Math.min(width, region.width),
+ height: Math.min(height, region.height),
+ }))
+ .sort((a, b) => b.width * b.height - a.width * a.height);
+ const region = regions[0];
+ if (region) return clampCard(region.x, region.y, region.width, region.height);
+ return clampCard(center.x - width / 2, center.y - height / 2);
+}
+
+type TraceHover = {
+ point: MapPoint;
+ topicName: string | undefined;
+ node: TopicMapNode;
+ position: MapPosition;
+ card: MapHoverRectangle;
+ excerpt: string;
+ reading: boolean;
+};
+type ZoneHover = MapZone & {
+ position: MapPosition;
+ label: MapHoverRectangle;
+ detail: string;
+};
+export function prepareMapHover(
+ frame: TopicMapNodeFrame,
+ hoveredId: string | null,
+ hoveredZoneId: string | null,
+): { traces: TraceHover[]; zones: ZoneHover[] } {
+ const node = hoveredId ? frame.nodeById.get(hoveredId) : undefined;
+ if (node) {
+ if (node.textOpacity >= 0.9 || !frame.nodes.includes(node))
+ return { traces: [], zones: [] };
+ const card = hoverRectangle(node.rect, frame.size, {
+ width: 264,
+ height: 184,
+ });
+ return {
+ traces: card
+ ? [
+ {
+ point: node.point,
+ topicName: frame.model.zones.find(
+ (zone) => zone.id === node.point.groupId,
+ )?.name,
+ node,
+ position: node.center,
+ card,
+ excerpt: node.excerpt,
+ reading: true,
+ },
+ ]
+ : [],
+ zones: [],
+ };
+ }
+ const zone = frame.zones.find((item) => item.id === hoveredZoneId);
+ if (!zone) return { traces: [], zones: [] };
+ const position = screenPoint(
+ zone,
+ frame.camera,
+ frame.model.bounds,
+ frame.size,
+ );
+ const label = hoverRectangle(
+ { ...position, width: 0, height: 0 },
+ frame.size,
+ { width: 264, height: 108 },
+ );
+ return {
+ traces: [],
+ zones: label
+ ? [{ ...zone, position, label, detail: zone.description }]
+ : [],
+ };
+}
+
+export function fitMapPoints(
+ points: MapData["points"],
+ cohort: MapData["points"],
+ width: number,
+ height: number,
+) {
+ const rotated = rotatePoints(points, cohort);
+ const bounds = pointBounds(rotated);
+ const size = { width, height };
+ const camera = fitCamera(bounds, bounds, size);
+ return rotated.map((point) => ({
+ ...point,
+ ...screenPoint(point, camera, bounds, size),
+ }));
+}
diff --git a/web/src/features/topics/map/topic-map-store.ts b/web/src/features/topics/map/topic-map-store.ts
new file mode 100644
index 0000000000..64a467b546
--- /dev/null
+++ b/web/src/features/topics/map/topic-map-store.ts
@@ -0,0 +1,147 @@
+import { createStore } from "zustand/vanilla";
+import type { Camera, TopicMapNodeFrame } from "./prepare-topic-map";
+
+export function createTopicMapStore() {
+ return createStore(() => ({
+ camera: null as Camera | null,
+ scope: null as string | null,
+ pointer: { x: 0, y: 0 },
+ // Client coordinates distinguish physical movement from layout-driven events.
+ pointerAt: null as PointerPosition | null,
+ frame: null as TopicMapNodeFrame | null,
+ isMoving: false,
+ hoverFrame: null as TopicMapNodeFrame | null,
+ hoveredId: null as string | null,
+ hoveredZoneId: null as string | null,
+ hoverLabels: [] as HoverLabel[],
+ hoverToken: 0,
+ isFullscreen: false,
+ reducedMotion: true,
+ fullscreenError: false,
+ }));
+}
+
+export function publishTopicMapFrame(
+ store: TopicMapStore,
+ frame: TopicMapNodeFrame,
+ isMoving = false,
+) {
+ store.setState((state) => {
+ const invalid =
+ isMoving ||
+ (state.hoverFrame !== null && !sameFrameContext(state.hoverFrame, frame));
+ return {
+ frame,
+ isMoving,
+ ...(invalid && {
+ hoveredId: null,
+ hoveredZoneId: null,
+ hoverFrame: null,
+ hoverLabels: state.hoverLabels.map((label) =>
+ label.active ? { ...label, active: false } : label,
+ ),
+ }),
+ };
+ });
+}
+
+export function clearTopicMapHover(store: TopicMapStore) {
+ setTopicMapHover(store, null, null);
+}
+
+export function setTopicMapHover(
+ store: TopicMapStore,
+ hoveredId: string | null,
+ hoveredZoneId: string | null,
+ pointer?: PointerPosition,
+ pointerAt?: PointerPosition | null,
+) {
+ store.setState((state) => {
+ let label: Pick<HoverLabel, "kind" | "id"> | null = null;
+ if (hoveredId) label = { kind: "trace", id: hoveredId };
+ else if (hoveredZoneId) label = { kind: "zone", id: hoveredZoneId };
+ const active = state.hoverLabels.find((item) => item.active);
+ const changed = active?.kind !== label?.kind || active?.id !== label?.id;
+ let hoverLabels = state.hoverLabels;
+ let hoverToken = state.hoverToken;
+ if (changed) {
+ hoverLabels = hoverLabels
+ .filter((item) => item.kind !== label?.kind || item.id !== label?.id)
+ .map((item) => ({ ...item, active: false }));
+ if (label)
+ hoverLabels.push({
+ ...label,
+ token: ++hoverToken,
+ active: true,
+ frame: state.frame,
+ });
+ hoverLabels = hoverLabels.slice(-4);
+ }
+ if (
+ !changed &&
+ state.hoveredId === hoveredId &&
+ state.hoveredZoneId === hoveredZoneId &&
+ pointer === undefined &&
+ pointerAt === undefined
+ )
+ return state;
+ return {
+ hoveredId,
+ hoveredZoneId,
+ hoverLabels,
+ hoverToken,
+ hoverFrame: label ? state.frame : null,
+ ...(pointer !== undefined && { pointer }),
+ ...(pointerAt !== undefined && { pointerAt }),
+ };
+ });
+}
+
+export function finishTopicMapHover(store: TopicMapStore, token: number) {
+ store.setState((state) => {
+ if (!state.hoverLabels.some((item) => item.token === token)) return state;
+ return {
+ hoverLabels: state.hoverLabels.filter((item) => item.token !== token),
+ };
+ });
+}
+
+export function getTopicMapHover(
+ state: ReturnType<TopicMapStore["getState"]>,
+ frame: TopicMapNodeFrame | null,
+) {
+ const valid = !state.isMoving && sameFrameContext(state.hoverFrame, frame);
+ return {
+ hoveredId: valid ? state.hoveredId : null,
+ hoveredZoneId: valid ? state.hoveredZoneId : null,
+ };
+}
+
+function sameFrameContext(
+ captured: TopicMapNodeFrame | null,
+ frame: TopicMapNodeFrame | null,
+) {
+ return (
+ captured !== null &&
+ frame !== null &&
+ captured.model === frame.model &&
+ captured.camera.x === frame.camera.x &&
+ captured.camera.y === frame.camera.y &&
+ captured.camera.zoom === frame.camera.zoom &&
+ captured.size.width === frame.size.width &&
+ captured.size.height === frame.size.height &&
+ captured.readingTopic === frame.readingTopic &&
+ captured.matchingTraceIds === frame.matchingTraceIds
+ );
+}
+
+export type TopicMapStore = ReturnType<typeof createTopicMapStore>;
+
+type PointerPosition = { x: number; y: number };
+type HoverLabel = {
+ kind: "trace" | "zone";
+ id: string;
+ token: number;
+ active: boolean;
+ frame: TopicMapNodeFrame | null;
+};
diff --git a/web/src/features/topics/map/topic-map.module.css b/web/src/features/topics/map/topic-map.module.css
new file mode 100644
index 0000000000..ebf656aa10
--- /dev/null
+++ b/web/src/features/topics/map/topic-map.module.css
@@ -0,0 +1,47 @@
+.hoverCard {
+ pointer-events: none;
+ transform-origin: center;
+ opacity: 0;
+ transform: translateY(4px) scale(0.94);
+ transition:
+ opacity 180ms cubic-bezier(0.2, 0.8, 0.2, 1),
+ transform 180ms cubic-bezier(0.2, 0.8, 0.2, 1);
+}
+
+.enter {
+ opacity: 0.96;
+ transform: translateY(0) scale(1);
+}
+
+.exit {
+ pointer-events: none;
+ transform: translateY(3px) scale(0.96);
+ transition-duration: 130ms;
+}
+
+.backgroundLabel {
+ animation: labelEnter 180ms ease-out;
+ transition: opacity 180ms ease-out;
+}
+
+@keyframes labelEnter {
+ from {
+ opacity: 0;
+ }
+}
+
+@starting-style {
+ .enter {
+ opacity: 0;
+ transform: translateY(4px) scale(0.94);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .enter,
+ .exit,
+ .backgroundLabel {
+ animation-duration: 1ms;
+ transition-duration: 1ms;
+ }
+}
diff --git a/web/src/features/topics/topic-map-colors.ts b/web/src/features/topics/topic-map-colors.ts
index 4bb5a6000b..902d6ef18b 100644
--- a/web/src/features/topics/topic-map-colors.ts
+++ b/web/src/features/topics/topic-map-colors.ts
@@ -1,19 +1,24 @@
/** Canvas colors match the category tokens in styles/globals.css. */
const COLORS = [
- "#7c3aed",
- "#0284c7",
- "#059669",
- "#d97706",
- "#db2777",
- "#4f46e5",
- "#0d9488",
- "#c2410c",
- "#65a30d",
- "#a21caf",
+ { color: "#7c3aed", badgeColor: "violetTint" },
+ { color: "#0284c7", badgeColor: "skyTint" },
+ { color: "#059669", badgeColor: "emeraldTint" },
+ { color: "#d97706", badgeColor: "amberTint" },
+ { color: "#db2777", badgeColor: "pinkTint" },
+ { color: "#4f46e5", badgeColor: "indigoTint" },
+ { color: "#0d9488", badgeColor: "tealTint" },
+ { color: "#c2410c", badgeColor: "orangeTint" },
+ { color: "#65a30d", badgeColor: "limeTint" },
+ { color: "#a21caf", badgeColor: "fuchsiaTint" },
] as const;
export const topicColor = (index: number) =>
- index < 0 ? "#94a3b8" : COLORS[index % COLORS.length];
+ index < 0 ? "#94a3b8" : COLORS[index % COLORS.length].color;
+
+export const topicBadgeColor = (
+ index: number,
+): (typeof COLORS)[number]["badgeColor"] | "primary" =>
+ index < 0 ? "primary" : COLORS[index % COLORS.length].badgeColor;
const TREEMAP_HUES = [
{
diff --git a/web/src/features/topics/topic-map-geometry.clienttest.ts b/web/src/features/topics/topic-map-geometry.clienttest.ts
new file mode 100644
index 0000000000..64a0e7eb9c
--- /dev/null
+++ b/web/src/features/topics/topic-map-geometry.clienttest.ts
@@ -0,0 +1,824 @@
+import { describe, expect, it } from "vitest";
+import { __test } from "./EmbeddingMapView";
+import {
+ baseScale,
+ fitCamera,
+ hitMapNode,
+ panCamera,
+ prepareMapHover,
+ prepareMapNodes,
+ prepareMapTextLabels,
+ prepareTopicMap,
+ screenPoint,
+ zoomCamera,
+ type Camera,
+ type MapData,
+ type Size,
+ type TopicMapModel,
+ type TopicMapNodeFrame,
+} from "./map/prepare-topic-map";
+import {
+ createTopicMapStore,
+ finishTopicMapHover,
+ getTopicMapHover,
+ publishTopicMapFrame,
+ setTopicMapHover,
+} from "./map/topic-map-store";
+
+const size = { width: 1000, height: 600 };
+const bounds = { minX: -100, maxX: 100, minY: -50, maxY: 50 };
+const camera = { x: 10, y: -5, zoom: 2 };
+const pointer = { x: 0, y: 0 };
+const topics = [
+ {
+ id: "billing",
+ name: "Billing",
+ description: "Invoice and payment requests.",
+ },
+ {
+ id: "retrieval",
+ name: "Retrieval",
+ description: "Finding relevant context.",
+ },
+];
+
+function point(
+ traceId: string,
+ x: number,
+ y: number,
+ overrides: Partial<MapData["points"][number]> = {},
+): MapData["points"][number] {
+ return {
+ traceId,
+ x,
+ y,
+ topicId: "billing",
+ outcome: "assigned",
+ summary: `Stored summary for ${traceId}`,
+ ...overrides,
+ };
+}
+
+function data(points: MapData["points"]): MapData {
+ return { points, missingSummaryCount: 0, unpositionedCount: 0 };
+}
+
+function worldAtScreen(at: { x: number; y: number }, view: Camera, plot: Size) {
+ const scale = baseScale(bounds, plot) * view.zoom;
+ return {
+ x: view.x + (at.x - plot.width / 2) / scale,
+ y: view.y - (at.y - plot.height / 2) / scale,
+ };
+}
+
+function frameFor(
+ model: TopicMapModel,
+ zoom: number,
+ plot = size,
+ readingTopic: string | null = null,
+ movingPointer = pointer,
+) {
+ return prepareMapNodes(
+ model,
+ { ...fitCamera(model.bounds, model.bounds, plot), zoom },
+ plot,
+ movingPointer,
+ readingTopic,
+ );
+}
+function frameAt(
+ positions: { x: number; y: number }[],
+ plot = size,
+ zoom = 10,
+): TopicMapNodeFrame {
+ const view = { x: 0, y: 0, zoom };
+ const scale = baseScale(bounds, plot) * zoom;
+ const model = {
+ ...prepareTopicMap(
+ data(
+ positions.map((position, i) =>
+ point(
+ `trace-${i}`,
+ (position.x - plot.width / 2) / scale,
+ -(position.y - plot.height / 2) / scale,
+ ),
+ ),
+ ),
+ topics,
+ ),
+ bounds,
+ };
+ return prepareMapNodes(model, view, plot, pointer);
+}
+function overlaps(
+ a: { x: number; y: number; width: number; height: number },
+ b: { x: number; y: number; width: number; height: number },
+) {
+ return (
+ a.x < b.x + b.width &&
+ a.x + a.width > b.x &&
+ a.y < b.y + b.height &&
+ a.y + a.height > b.y
+ );
+}
+it("fits a tall cohort across the landscape plot while preserving pairwise distances", () => {
+ const points = [
+ [0, 0],
+ [0, 10],
+ [2, 20],
+ [1, 30],
+ ].map(([x, y], index) => ({
+ traceId: `trace-${index}`,
+ summary: `Summary ${index}`,
+ topicId: null,
+ outcome: "outlier" as const,
+ x,
+ y,
+ }));
+ const positions = __test.fitMapPoints(points, points, 960, 320);
+ const spanX =
+ Math.max(...positions.map((point) => point.x)) -
+ Math.min(...positions.map((point) => point.x));
+ const spanY =
+ Math.max(...positions.map((point) => point.y)) -
+ Math.min(...positions.map((point) => point.y));
+ expect(spanX).toBeGreaterThan(spanY);
+ const distance = (a: { x: number; y: number }, b: { x: number; y: number }) =>
+ Math.hypot(a.x - b.x, a.y - b.y);
+ const scale =
+ distance(positions[0], positions[1]) / distance(points[0], points[1]);
+ for (let a = 0; a < points.length; a++) {
+ for (let b = a + 1; b < points.length; b++) {
+ expect(
+ distance(positions[a], positions[b]) / distance(points[a], points[b]),
+ ).toBeCloseTo(scale, 8);
+ }
+ }
+});
+
+describe("topic map camera", () => {
+ it.each([
+ { levels: 1.5, anchor: { x: 0.22, y: 0.73 } },
+ { levels: -1, anchor: { x: 0.91, y: 0.08 } },
+ { levels: 20, anchor: { x: 0.04, y: 0.96 } },
+ { levels: -20, anchor: { x: 0.75, y: 0.25 } },
+ ])(
+ "keeps the world point under a zoom anchor fixed ($levels levels)",
+ ({ levels, anchor }) => {
+ const at = { x: anchor.x * size.width, y: anchor.y * size.height };
+ const world = worldAtScreen(at, camera, size);
+ const zoomed = zoomCamera(camera, levels, anchor, bounds, size);
+ const after = screenPoint(world, zoomed, bounds, size);
+
+ expect(after.x).toBeCloseTo(at.x, 8);
+ expect(after.y).toBeCloseTo(at.y, 8);
+ expect(Number.isFinite(zoomed.zoom)).toBe(true);
+ expect(zoomed.zoom).toBeGreaterThan(0);
+ },
+ );
+
+ it("moves content by the gesture's pixel delta at any zoom", () => {
+ const world = { x: 30, y: 15 };
+ for (const zoom of [0.5, 1, 12]) {
+ const beforeCamera = { ...camera, zoom };
+ const before = screenPoint(world, beforeCamera, bounds, size);
+ const afterCamera = panCamera(beforeCamera, 83, -37, bounds, size);
+ const after = screenPoint(world, afterCamera, bounds, size);
+
+ expect(after.x - before.x).toBeCloseTo(83, 8);
+ expect(after.y - before.y).toBeCloseTo(-37, 8);
+ expect(afterCamera.zoom).toBe(zoom);
+ }
+ });
+
+ it.each([
+ { width: 1200, height: 400 },
+ { width: 400, height: 900 },
+ ])(
+ "fits a selected zone into $width by $height without stretching distances",
+ (plot) => {
+ const selectedBounds = { minX: -20, maxX: 10, minY: -15, maxY: 5 };
+ const view = fitCamera(selectedBounds, bounds, plot);
+ const corners = [
+ { x: selectedBounds.minX, y: selectedBounds.minY },
+ { x: selectedBounds.maxX, y: selectedBounds.maxY },
+ ];
+ const projected = corners.map((p) => screenPoint(p, view, bounds, plot));
+
+ for (const p of projected) {
+ expect(p.x).toBeGreaterThanOrEqual(0);
+ expect(p.x).toBeLessThanOrEqual(plot.width);
+ expect(p.y).toBeGreaterThanOrEqual(0);
+ expect(p.y).toBeLessThanOrEqual(plot.height);
+ }
+ const horizontal = screenPoint({ x: 1, y: 0 }, view, bounds, plot);
+ const vertical = screenPoint({ x: 0, y: 1 }, view, bounds, plot);
+ const origin = screenPoint({ x: 0, y: 0 }, view, bounds, plot);
+ expect(horizontal.x - origin.x).toBeCloseTo(origin.y - vertical.y, 8);
+ const center = screenPoint(
+ {
+ x: (selectedBounds.minX + selectedBounds.maxX) / 2,
+ y: (selectedBounds.minY + selectedBounds.maxY) / 2,
+ },
+ view,
+ bounds,
+ plot,
+ );
+ expect(center).toEqual({ x: plot.width / 2, y: plot.height / 2 });
+ },
+ );
+
+ it("keeps empty and coincident maps navigable with finite coordinates", () => {
+ for (const points of [[], [point("one", 0, 0), point("two", 0, 0)]]) {
+ const model = prepareTopicMap(data(points), topics);
+ const fitted = fitCamera(model.bounds, model.bounds, size);
+ const moved = panCamera(fitted, 50, -50, model.bounds, size);
+ const zoomed = zoomCamera(
+ moved,
+ 1,
+ { x: 0.25, y: 0.75 },
+ model.bounds,
+ size,
+ );
+ for (const value of Object.values(zoomed))
+ expect(Number.isFinite(value)).toBe(true);
+ for (const p of model.points) {
+ const position = screenPoint(p, zoomed, model.bounds, size);
+ expect(Number.isFinite(position.x)).toBe(true);
+ expect(Number.isFinite(position.y)).toBe(true);
+ }
+ }
+ });
+});
+
+describe("topic map preparation", () => {
+ it("keeps the original saved coordinates without rotating or recentering the projection", () => {
+ const input = data([
+ point("invoice", -12, 3),
+ point("refund", 4, 8),
+ point("context", 13, -6, { topicId: "retrieval" }),
+ ]);
+ const before = structuredClone(input);
+ const model = prepareTopicMap(input, topics);
+ for (const saved of input.points) {
+ const prepared = model.pointById.get(saved.traceId)!;
+ expect({ x: prepared.x, y: prepared.y }).toEqual({
+ x: saved.x,
+ y: saved.y,
+ });
+ }
+ expect(input).toEqual(before);
+ });
+
+ it("keeps saved world positions and neutral-pointer centers fixed at every detail level", () => {
+ const model = prepareTopicMap(
+ data([
+ point("invoice", -12, 3),
+ point("refund", 4, 8),
+ point("context", 13, -6, { topicId: "retrieval" }),
+ ]),
+ topics,
+ );
+ for (const plot of [size, { width: 360, height: 500 }]) {
+ for (const zoom of [1, 4, 8, 10, 20, 64, 128]) {
+ for (const scope of [null, "billing"]) {
+ const frame = frameFor(model, zoom, plot, scope);
+ for (const p of model.points) {
+ const node = frame.nodeById.get(p.traceId)!;
+ expect(node.worldPosition).toEqual({ x: p.x, y: p.y });
+ expect(node.center).toEqual(
+ screenPoint(p, frame.camera, model.bounds, plot),
+ );
+ }
+ }
+ }
+ }
+ });
+
+ it("does not use individual trace text as missing historical topic context", () => {
+ const trace = point("historical-trace", 0, 0);
+ for (const description of [undefined, "", " "]) {
+ const model = prepareTopicMap(data([trace]), [
+ { id: "billing", name: "Billing", description },
+ ]);
+ expect(model.zones[0].description).not.toBe(trace.summary);
+ expect(model.zones[0].description).toMatch(
+ /description.*(available|saved)/i,
+ );
+ }
+ });
+
+ it("groups the discovery cohort separately from outliers and unavailable assignments", () => {
+ const model = prepareTopicMap(
+ data([
+ point("invoice", -5, -1),
+ point("refund", -4, 2),
+ point("context", 6, 1, { topicId: "retrieval" }),
+ point("new-request", 0, 8, { topicId: null, outcome: "outlier" }),
+ point("stale-assignment", 0, -8, {
+ topicId: null,
+ outcome: "unassigned",
+ }),
+ ]),
+ topics,
+ );
+ const zones = new Map(model.zones.map((zone) => [zone.id, zone]));
+
+ expect(zones.get("billing")?.points.map((p) => p.traceId)).toEqual([
+ "invoice",
+ "refund",
+ ]);
+ expect(zones.get("retrieval")?.points).toHaveLength(1);
+ expect(zones.get("outliers")?.points[0].outcome).toBe("outlier");
+ expect(zones.get("awaiting_map")?.points[0].outcome).toBe("unassigned");
+ expect(zones.get("billing")?.description).toBe(topics[0].description);
+ expect(
+ model.zones.reduce((count, zone) => count + zone.points.length, 0),
+ ).toBe(model.points.length);
+ expect(
+ new Set(model.zones.flatMap((zone) => zone.points.map((p) => p.traceId)))
+ .size,
+ ).toBe(model.points.length);
+ for (const zone of model.zones) {
+ expect(zone.x).toBeGreaterThanOrEqual(zone.bounds.minX);
+ expect(zone.x).toBeLessThanOrEqual(zone.bounds.maxX);
+ expect(zone.y).toBeGreaterThanOrEqual(zone.bounds.minY);
+ expect(zone.y).toBeLessThanOrEqual(zone.bounds.maxY);
+ }
+ });
+
+ it("keeps depth attached to trace identity across data and topic ordering", () => {
+ const input = data([
+ point("invoice", -8, -4),
+ point("refund", 0, 3),
+ point("context", 9, 1, { topicId: "retrieval" }),
+ ]);
+ const before = structuredClone(input);
+ const first = prepareTopicMap(input, topics);
+ const reordered = prepareTopicMap(
+ data([...input.points].reverse()),
+ [...topics].reverse(),
+ );
+
+ for (const p of first.points) {
+ expect(p.depth).toBe(reordered.pointById.get(p.traceId)?.depth);
+ expect(p.depth).toBeGreaterThanOrEqual(0);
+ expect(p.depth).toBeLessThan(1);
+ }
+ expect(new Set(first.points.map((p) => p.depth)).size).toBeGreaterThan(1);
+ expect(input).toEqual(before);
+ });
+
+ it("preserves canonical points and keeps interaction state local while preparing nodes", () => {
+ const model = prepareTopicMap(
+ data([
+ point("invoice", -10, -3),
+ point("refund", -8, 3),
+ point("context", 10, 0, { topicId: "retrieval" }),
+ ]),
+ topics,
+ );
+ const before = structuredClone(model.points);
+ const first = createTopicMapStore();
+ const second = createTopicMapStore();
+ const untouched = second.getState();
+ first.setState({
+ scope: "billing",
+ camera,
+ hoveredId: "invoice",
+ pointer: { x: 1, y: 1 },
+ isFullscreen: true,
+ });
+ const frame = frameFor(model, 10, size, "billing");
+ prepareMapHover(frame, "invoice", "billing");
+ expect(model.points).toEqual(before);
+ expect(frame.nodeById.size).toBe(3);
+ expect(frame.nodeById.has("context")).toBe(true);
+ expect(second.getState()).toBe(untouched);
+ });
+});
+describe("fixed projection detail", () => {
+ it("keeps surrounding topics at saved coordinates while only the selected zone grows", () => {
+ const model = prepareTopicMap(
+ data([
+ point("billing", -5, 0),
+ point("foreign", 5, 0, { topicId: "retrieval" }),
+ ]),
+ topics,
+ );
+ const frame = frameFor(model, 10, size, "billing");
+ expect(frame.nodeById.size).toBe(2);
+ for (const p of model.points) {
+ expect(frame.nodeById.get(p.traceId)?.worldPosition).toEqual({
+ x: p.x,
+ y: p.y,
+ });
+ expect(frame.nodeById.get(p.traceId)?.center).toEqual(
+ screenPoint(p, frame.camera, model.bounds, size),
+ );
+ }
+ expect(frame.nodeById.get("foreign")?.expansion).toBe(0);
+ expect(frame.nodeById.get("foreign")?.textOpacity).toBe(0);
+ expect(frame.nodeById.get("billing")?.expansion).toBeGreaterThan(0);
+ });
+
+ it("keeps a saved trace under the cursor throughout progressive detail zoom", () => {
+ const model = prepareTopicMap(
+ data([
+ point("left", -20, 0),
+ point("chosen", 0, 0),
+ point("right", 20, 4),
+ ]),
+ topics,
+ );
+ let view = fitCamera(model.bounds, model.bounds, size);
+ const chosen = model.pointById.get("chosen")!;
+ const anchor = screenPoint(chosen, view, model.bounds, size);
+ for (let level = 0; level < 7; level++) {
+ view = zoomCamera(
+ view,
+ 1,
+ { x: anchor.x / size.width, y: anchor.y / size.height },
+ model.bounds,
+ size,
+ );
+ const frame = prepareMapNodes(model, view, size, pointer);
+ const node = frame.nodeById.get(chosen.traceId)!;
+ expect(node.center.x).toBeCloseTo(anchor.x, 8);
+ expect(node.center.y).toBeCloseTo(anchor.y, 8);
+ expect(node.worldPosition).toEqual({ x: chosen.x, y: chosen.y });
+ expect(hitMapNode(frame, anchor)?.traceId).toBe(chosen.traceId);
+ }
+ });
+});
+describe("continuous trace nodes", () => {
+ it("grows overview dots during zoom before reading rectangles open", () => {
+ const model = prepareTopicMap(data([point("trace", 0, 0)]), topics);
+ const dots = [1, 2, 3].map((zoom) => frameFor(model, zoom).nodes[0]);
+ expect(dots[1].rect.width).toBeGreaterThan(dots[0].rect.width);
+ expect(dots[2].rect.width).toBeGreaterThan(dots[1].rect.width);
+ for (const dot of dots) {
+ expect(dot.rect.width).toBe(dot.rect.height);
+ expect(dot.expansion).toBe(0);
+ expect(dot.textOpacity).toBe(0);
+ }
+ });
+
+ it("keeps readable content centered on the trace that grows into it", () => {
+ const model = prepareTopicMap(data([point("trace", 0, 0)]), topics);
+ let previousWidth = 0;
+ for (const zoom of [1, 3, 4, 6, 8, 10, 20]) {
+ const node = frameFor(model, zoom).nodes[0];
+ expect(node.rect.x + node.rect.width / 2).toBeCloseTo(node.center.x, 8);
+ expect(node.rect.y + node.rect.height / 2).toBeCloseTo(node.center.y, 8);
+ expect(node.rect.width).toBeGreaterThanOrEqual(previousWidth - 0.01);
+ expect(node.excerpt).toBe(model.points[0].summary);
+ previousWidth = node.rect.width;
+ }
+ });
+ it("keeps abstract filled shapes until there is space for text and grows the readable font", () => {
+ const model = prepareTopicMap(data([point("trace", 0, 0)]), topics);
+ const abstract = frameFor(model, 4).nodes[0];
+ const partial = frameFor(model, 6).nodes[0];
+ const reading = frameFor(model, 10).nodes[0];
+ expect(abstract.expansion).toBeGreaterThan(0);
+ expect(abstract.textOpacity).toBe(0);
+ expect(abstract.backgroundOpacity).toBe(0);
+ expect(abstract.strokeOpacity).toBe(0);
+ expect(abstract.cornerRadius).toBe(
+ Math.min(abstract.rect.width, abstract.rect.height) / 2,
+ );
+ expect(partial.textOpacity).toBeGreaterThan(0);
+ expect(partial.textOpacity).toBeLessThan(reading.textOpacity);
+ expect(partial.fontSize).toBeLessThan(reading.fontSize);
+ expect(partial.fontSize).toBeGreaterThanOrEqual(9);
+ expect(reading.fontSize).toBeLessThanOrEqual(12);
+ expect(reading.textOpacity).toBe(1);
+ expect(
+ frameAt([
+ { x: 400, y: 300 },
+ { x: 440, y: 300 },
+ ]).nodes.every((node) => node.textOpacity === 0),
+ ).toBe(true);
+ });
+ it.each([3, 10])(
+ "changes footprints continuously across detail transition %s",
+ (zoom) => {
+ const model = prepareTopicMap(
+ data([point("a", -2, 1), point("b", 2, -1)]),
+ topics,
+ );
+ const before = frameFor(model, zoom - 0.0001);
+ const after = frameFor(model, zoom + 0.0001);
+ for (const p of model.points) {
+ const a = before.nodeById.get(p.traceId)!;
+ const b = after.nodeById.get(p.traceId)!;
+ expect(a.worldPosition).toEqual(b.worldPosition);
+ expect(Math.abs(a.rect.width - b.rect.width)).toBeLessThan(0.1);
+ expect(Math.abs(a.rect.height - b.rect.height)).toBeLessThan(0.1);
+ }
+ },
+ );
+ it("limits growth so rectangles do not cover neighboring nodes", () => {
+ const frame = frameAt([
+ { x: 300, y: 250 },
+ { x: 440, y: 250 },
+ { x: 590, y: 300 },
+ ]);
+ expect(
+ frame.nodes.every((node) => node.expansion > 0 && node.expansion < 1),
+ ).toBe(true);
+ for (let i = 0; i < frame.nodes.length; i++)
+ for (let j = i + 1; j < frame.nodes.length; j++)
+ expect(overlaps(frame.nodes[i].rect, frame.nodes[j].rect)).toBe(false);
+ });
+
+ it("keeps growing nodes separated beside foreign dots without rearranging the projection", () => {
+ const model = prepareTopicMap(
+ data(
+ Array.from({ length: 100 }, (_, i) =>
+ point(`trace-${i}`, (i % 10) * 0.6, Math.floor(i / 10) * 0.5, {
+ topicId: i % 5 === 0 ? "retrieval" : "billing",
+ }),
+ ),
+ ),
+ topics,
+ );
+ for (const zoom of [3.01, 4, 5, 6, 7, 8, 9, 10, 16]) {
+ const all = [...frameFor(model, zoom, size, "billing").nodeById.values()];
+ for (let i = 0; i < all.length; i++) {
+ for (let j = i + 1; j < all.length; j++) {
+ if (all[i].expansion === 0 && all[j].expansion === 0) continue;
+ expect(overlaps(all[i].rect, all[j].rect)).toBe(false);
+ }
+ }
+ }
+ });
+ it("reserves local clearance for nodes outside the viewport", () => {
+ const plot = { width: 360, height: 500 };
+ const crowded = frameAt(
+ [
+ { x: 10, y: 250 },
+ { x: -70, y: 250 },
+ ],
+ plot,
+ );
+ const alone = frameAt([{ x: 10, y: 250 }], plot);
+ expect(crowded.nodes).toHaveLength(1);
+ expect(crowded.nodeById.size).toBe(2);
+ expect(crowded.nodes[0].rect.width).toBeLessThan(alone.nodes[0].rect.width);
+ expect(
+ overlaps(crowded.nodes[0].rect, crowded.nodeById.get("trace-1")!.rect),
+ ).toBe(false);
+ });
+ it("retains every visible glyph in dense and coincident cohorts", () => {
+ const frame = frameAt(
+ Array.from({ length: 500 }, (_, i) => ({
+ x: 20 + (i % 30) * 20,
+ y: 20 + Math.floor(i / 30) * 20,
+ })),
+ );
+ expect(frame.nodes).toHaveLength(500);
+ expect(frame.nodeById.size).toBe(500);
+ const coincident = frameAt([
+ { x: 500, y: 300 },
+ { x: 500, y: 300 },
+ ]);
+ expect(coincident.nodes).toHaveLength(2);
+ expect(
+ coincident.nodes.every(
+ (node) => node.expansion === 0 && node.textOpacity === 0,
+ ),
+ ).toBe(true);
+ });
+ it("hit-tests the grown rounded rectangle instead of only its original dot", () => {
+ const frame = frameAt([{ x: 500, y: 300 }]);
+ const node = frame.nodes[0];
+ expect(
+ hitMapNode(frame, { x: node.center.x + 100, y: node.center.y })?.traceId,
+ ).toBe(node.point.traceId);
+ expect(
+ hitMapNode(frame, { x: node.rect.x + 1, y: node.rect.y + 1 }),
+ ).toBeNull();
+ expect(
+ hitMapNode(frame, {
+ x: node.rect.x + node.rect.width + 20,
+ y: node.center.y,
+ }),
+ ).toBeNull();
+ });
+ it("shares parallax positions with hits and fades decorative motion in reading mode", () => {
+ const model = prepareTopicMap(
+ data(
+ Array.from({ length: 20 }, (_, i) => point(`trace-${i}`, i * 10, 0)),
+ ),
+ topics,
+ );
+ const chosen = [...model.points].sort((a, b) => b.depth - a.depth)[0];
+ const moving = frameFor(model, 1, size, null, { x: 1, y: 0 });
+ const node = moving.nodeById.get(chosen.traceId)!;
+ const at = { x: node.center.x + 10, y: node.center.y };
+ expect(hitMapNode(moving, at)?.traceId).toBe(chosen.traceId);
+ expect(hitMapNode(frameFor(model, 1), at)).toBeNull();
+ expect(
+ frameFor(model, 10, size, null, { x: 1, y: -1 }).nodeById.get(
+ chosen.traceId,
+ )?.center,
+ ).toEqual(frameFor(model, 10).nodeById.get(chosen.traceId)?.center);
+ });
+});
+describe("background group labels", () => {
+ it("reveals group context gradually and returns only one label per group", () => {
+ const model = prepareTopicMap(
+ data([
+ point("invoice", 0, 0),
+ point("context", 0, 0, { topicId: "retrieval" }),
+ point("outlier", 0, 0, { topicId: null, outcome: "outlier" }),
+ point("unassigned", 0, 0, { topicId: null, outcome: "unassigned" }),
+ ]),
+ topics,
+ );
+ expect(prepareMapTextLabels(frameFor(model, 1))).toEqual([]);
+ const titles = prepareMapTextLabels(frameFor(model, 2));
+ const details = prepareMapTextLabels(frameFor(model, 6));
+ expect(new Set(details.map((label) => label.id)).size).toBe(details.length);
+ expect(details.map((label) => label.id).sort()).toEqual(
+ model.zones.map((zone) => zone.id).sort(),
+ );
+ expect(titles.find((label) => label.id === "billing")?.detailOpacity).toBe(
+ 0,
+ );
+ expect(
+ details.find((label) => label.id === "billing")?.detailOpacity,
+ ).toBeGreaterThan(0);
+ expect(details.find((label) => label.id === "billing")?.description).toBe(
+ topics[0].description,
+ );
+ expect(details.every((label) => label.kind === "zone")).toBe(true);
+ });
+
+ it("keeps one Outliers label within the viewport when the group center is offscreen", () => {
+ const model = prepareTopicMap(
+ data([
+ point("distant-outlier", -90, 0, { topicId: null, outcome: "outlier" }),
+ point("visible-outlier", 90, 0, { topicId: null, outcome: "outlier" }),
+ ]),
+ topics,
+ );
+ const zone = model.zones[0];
+ for (const zoom of [4, 8, 16, 32]) {
+ const view = { x: 90, y: 0, zoom };
+ expect(screenPoint(zone, view, model.bounds, size).x).toBeLessThan(0);
+ const frame = prepareMapNodes(model, view, size, pointer);
+ expect(
+ frame.nodes.some((node) => node.point.traceId === "visible-outlier"),
+ ).toBe(true);
+ const labels = prepareMapTextLabels(frame);
+ expect(labels).toHaveLength(1);
+ expect(labels[0].id).toBe("outliers");
+ expect(labels[0].title).toBe("Outliers");
+ expect(labels[0].opacity).toBeGreaterThan(0);
+ expect(labels[0].rect.x).toBeGreaterThanOrEqual(0);
+ expect(labels[0].rect.y).toBeGreaterThanOrEqual(0);
+ expect(labels[0].rect.x + labels[0].rect.width).toBeLessThanOrEqual(
+ size.width,
+ );
+ expect(labels[0].rect.y + labels[0].rect.height).toBeLessThanOrEqual(
+ size.height,
+ );
+ expect(frame.nodeById.get("visible-outlier")?.worldPosition).toEqual({
+ x: 90,
+ y: 0,
+ });
+ }
+ });
+});
+
+describe("explicit map hover", () => {
+ it("does not revive a stationary hover when the original viewport returns", () => {
+ const frame = frameAt([{ x: 500, y: 300 }], size, 1);
+ const store = createTopicMapStore();
+ const pointerAt = { x: 500, y: 300 };
+ publishTopicMapFrame(store, frame);
+ setTopicMapHover(store, "trace-0", "billing", pointer, pointerAt);
+ const token = store.getState().hoverLabels[0].token;
+ expect(getTopicMapHover(store.getState(), frame).hoveredId).toBe("trace-0");
+
+ const resized = { ...frame, size: { ...size, width: size.width - 100 } };
+ publishTopicMapFrame(store, resized);
+ expect(getTopicMapHover(store.getState(), resized).hoveredId).toBeNull();
+ finishTopicMapHover(store, token);
+ publishTopicMapFrame(store, frame);
+
+ expect(getTopicMapHover(store.getState(), frame)).toEqual({
+ hoveredId: null,
+ hoveredZoneId: null,
+ });
+ expect(store.getState().pointerAt).toEqual(pointerAt);
+ });
+ it("requires fresh hover input after nodes move with an unchanged camera", () => {
+ const frame = frameAt([{ x: 500, y: 300 }], size, 1);
+ const store = createTopicMapStore();
+ publishTopicMapFrame(store, frame);
+ setTopicMapHover(store, "trace-0", "billing", pointer, { x: 500, y: 300 });
+
+ publishTopicMapFrame(store, frame, true);
+ expect(getTopicMapHover(store.getState(), frame).hoveredId).toBeNull();
+ publishTopicMapFrame(store, frame);
+ expect(getTopicMapHover(store.getState(), frame).hoveredId).toBeNull();
+
+ setTopicMapHover(store, "trace-0", "billing", pointer, { x: 501, y: 300 });
+ expect(getTopicMapHover(store.getState(), frame).hoveredId).toBe("trace-0");
+ });
+ it("shows only explicit tooltips and suppresses them over readable nodes", () => {
+ const frame = frameAt([{ x: 500, y: 300 }]);
+ expect(prepareMapHover(frame, null, null)).toEqual({
+ traces: [],
+ zones: [],
+ });
+ expect(prepareMapHover(frame, "trace-0", "billing")).toEqual({
+ traces: [],
+ zones: [],
+ });
+ const cloud = frameAt([{ x: 500, y: 300 }], size, 1);
+ const hover = prepareMapHover(cloud, "trace-0", "billing");
+ expect(hover.traces).toHaveLength(1);
+ expect(hover.zones).toHaveLength(0);
+ expect(hover.traces[0].excerpt).toBe(cloud.model.points[0].summary);
+ });
+ it.each([
+ { edge: "left", x: 2, y: 250 },
+ { edge: "right", x: 358, y: 250 },
+ { edge: "top", x: 180, y: 2 },
+ { edge: "bottom", x: 180, y: 498 },
+ { edge: "clipped left", x: -2, y: 250 },
+ { edge: "clipped bottom", x: 180, y: 502 },
+ ])(
+ "keeps hover bounded at the $edge without covering its node",
+ ({ x, y }) => {
+ const plot = { width: 360, height: 500 };
+ const frame = frameAt([{ x, y }], plot, 1);
+ const tooltip = prepareMapHover(frame, "trace-0", "billing").traces[0];
+ expect(tooltip).toBeDefined();
+ expect(tooltip.card.x).toBeGreaterThanOrEqual(0);
+ expect(tooltip.card.y).toBeGreaterThanOrEqual(0);
+ expect(tooltip.card.x + tooltip.card.width).toBeLessThanOrEqual(
+ plot.width,
+ );
+ expect(tooltip.card.y + tooltip.card.height).toBeLessThanOrEqual(
+ plot.height,
+ );
+ expect(overlaps(tooltip.card, tooltip.node.rect)).toBe(false);
+ },
+ );
+ it("keeps hover anchors independent of other hover labels", () => {
+ const frame = frameAt(
+ [
+ { x: 500, y: 300 },
+ { x: 510, y: 300 },
+ ],
+ size,
+ 1,
+ );
+ expect(prepareMapHover(frame, "trace-0", "billing").traces[0].card).toEqual(
+ prepareMapHover(frame, "trace-0", null).traces[0].card,
+ );
+ 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.ts b/web/src/features/topics/topic-trace-filters.ts
index b81af23a8d..98f85c8b78 100644
--- a/web/src/features/topics/topic-trace-filters.ts
+++ b/web/src/features/topics/topic-trace-filters.ts
@@ -5,7 +5,7 @@ import {
withFieldOptions,
} from "@/src/features/search-bar/lib/fields";
-const TOPIC_ASSIGNMENT_OPTIONS = [
+export const TOPIC_ASSIGNMENT_OPTIONS = [
{ value: "assigned", displayValue: "In a topic" },
{ value: "outlier", displayValue: "Outlier" },
{ value: "no_topic", displayValue: "No topic" },