🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(web): Treemap and Grid views for Topics results (#19106)
Trang Nguyen7f9d25641ede
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex eca4814be2..e11354b148 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -787,6 +787,9 @@ importers:csv-parse:specifier: ^7.0.2version: 7.0.2+ d3-hierarchy:+ specifier: ^3.1.2+ version: 3.1.2d3-scale:specifier: ^4.0.2version: 4.0.2@@ -1010,6 +1013,9 @@ importers:'@types/cors':specifier: ^2.8.19version: 2.8.19+ '@types/d3-hierarchy':+ specifier: ^3.1.7+ version: 3.1.7'@types/d3-scale':specifier: ^4.0.9version: 4.0.9diff --git a/web/.storybook/docs/ThemeTokens/Color.tsx b/web/.storybook/docs/ThemeTokens/Color.tsxindex d97657a21b..6d3c6adb16 100644--- a/web/.storybook/docs/ThemeTokens/Color.tsx+++ b/web/.storybook/docs/ThemeTokens/Color.tsx@@ -42,6 +42,7 @@ type SectionId =| "qlang"| "sidebar"| "findMatch"+ | "category"| "other";/**@@ -67,6 +68,7 @@ const SECTION_MATCHERS: Array<{{ id: "qlang", test: (n) => n.startsWith("--qlang-") },{ id: "sidebar", test: (n) => n.startsWith("--sidebar-") },{ id: "findMatch", test: (n) => n.startsWith("--find-match-") },+ { id: "category", test: (n) => n.startsWith("--category-") },{ id: "controls", test: (n) => n.startsWith("--control-") },{id: "brand",@@ -138,6 +140,11 @@ const VISIBLE_SECTIONS: SectionDef[] = [title: "Sidebar",blurb: "Side navigation chrome, nav-item states and its hairline.",},+ {+ id: "category",+ title: "Category fills",+ blurb: "Tint and highlight pairs for categorical tiles (treemap).",+ },];/** Low-traffic sections, collapsed at the bottom. */diff --git a/web/package.json b/web/package.jsonindex 0ddb2b8beb..39047f6854 100644--- a/web/package.json+++ b/web/package.json@@ -118,6 +118,7 @@"core-js": "^3.38.1","cors": "^2.8.6","csv-parse": "^7.0.2",+ "d3-hierarchy": "^3.1.2","d3-scale": "^4.0.2","d3-selection": "^3.0.0","d3-shape": "^3.2.0",@@ -194,6 +195,7 @@"@types/bcryptjs": "^2.4.6","@types/chroma-js": "^3.1.2","@types/cors": "^2.8.19",+ "@types/d3-hierarchy": "^3.1.7","@types/d3-scale": "^4.0.9","@types/d3-selection": "^3.0.11","@types/d3-shape": "^3.2.0",diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex 4876f660e6..0b094e5697 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -447,6 +447,7 @@ const events = {"message_sent","community_hours_click",], // also used on landing page for consistency+ topics: ["results_view_select"],in_app_agent: ["activity_opened","entry_point_click",diff --git a/web/src/features/topics/CurrentTopics.tsx b/web/src/features/topics/CurrentTopics.tsxindex bef71d536f..5d4c963f9f 100644--- a/web/src/features/topics/CurrentTopics.tsx+++ b/web/src/features/topics/CurrentTopics.tsx@@ -6,16 +6,17 @@ 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 type { useTopicTraceFilters } from "./useTopicTraceFilters";+import { TopicGridView } from "./TopicGridView";+import { TopicTreemapView } from "./TopicTreemapView";+import { type TopicsResultsView } from "./TopicsResultsViewSelect";export function CurrentTopics({projectId,timeRange,result,selectedFacetId,+ view,tracePanelRef,- traceFilters,onGenerateTopics,canGenerateTopics,}: CurrentTopicsProps) {@@ -45,8 +46,8 @@ export function CurrentTopics({projectId={projectId}facet={selectedFacet}timeRange={timeRange}+ view={view}tracePanelRef={tracePanelRef}- traceFilters={traceFilters}onGenerateTopics={onGenerateTopics}canGenerateTopics={canGenerateTopics}/>@@ -59,25 +60,38 @@ function CurrentFacet({projectId,facet,timeRange,+ view,tracePanelRef,- traceFilters,onGenerateTopics,canGenerateTopics,}: CurrentFacetProps) {- const mapResult = useCurrentTopicMap(projectId, facet.map?.runId, timeRange);+ const mapResult = useCurrentTopicMap(+ projectId,+ view === "treemap" ? undefined : facet.map?.runId,+ timeRange,+ );const peekNavigation = usePeekNavigation({tableName: "topics-traces",isV4: false,queryParams: ["observation", "display", "timestamp", "traceId"],});const peekView = { itemType: "TRACE" as const, ...peekNavigation };+ if (view === "treemap")+ return (+ <TopicTreemapView+ projectId={projectId}+ facet={facet}+ onGenerateTopics={onGenerateTopics}+ canGenerateTopics={canGenerateTopics}+ peekView={peekView}+ />+ );return (- <CurrentTopicsView+ <TopicGridViewprojectId={projectId}facet={facet}mapResult={mapResult}tracePanelRef={tracePanelRef}- traceFilters={traceFilters}onGenerateTopics={onGenerateTopics}canGenerateTopics={canGenerateTopics}onOpenTrace={peekNavigation.openPeek}@@ -143,8 +157,8 @@ type CurrentTopicsProps = {"data" | "isLoading" | "error">;selectedFacetId: string | undefined;+ view: TopicsResultsView;tracePanelRef?: (element: HTMLElement | null) => void;- traceFilters: ReturnType<typeof useTopicTraceFilters>;onGenerateTopics: () => void;canGenerateTopics: boolean;};@@ -153,8 +167,8 @@ type CurrentFacetProps = {projectId: string;facet: Facet;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.tsxdeleted file mode 100644index a1b660568e..0000000000--- a/web/src/features/topics/CurrentTopicsView.stories.tsx+++ /dev/null@@ -1,570 +0,0 @@-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.tsxdeleted file mode 100644index 7bafecfd9b..0000000000--- a/web/src/features/topics/CurrentTopicsView.tsx+++ /dev/null@@ -1,569 +0,0 @@-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.tsxdeleted file mode 100644index ace0cb8034..0000000000--- a/web/src/features/topics/EmbeddingMapView.stories.tsx+++ /dev/null@@ -1,1025 +0,0 @@-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.tsxdeleted file mode 100644index 63469448db..0000000000--- a/web/src/features/topics/EmbeddingMapView.tsx+++ /dev/null@@ -1,4 +0,0 @@-export {- TopicMapExplorer as EmbeddingMapView,- __test,-} from "./map/TopicMapExplorer";diff --git a/web/src/features/topics/README.md b/web/src/features/topics/README.mdindex 8fa860c1e0..ae212de67e 100644--- a/web/src/features/topics/README.md+++ b/web/src/features/topics/README.md@@ -6,41 +6,17 @@ sidebar, direct page, and Topics API also require deployment enablement andproject permissions. Processing additionally requires the project allowlist.- `TopicsPage.tsx` owns facet configuration, the execution history drawer,- the current-results query and facet selection. A compact header keeps the facet- picker, time range and processing action on one row; configuration, history and- refresh live in the overflow menu. `CurrentTopics.tsx` owns the map query and- trace navigation; `CurrentTopicsView.tsx` presents the selected- facet in independently scrolling, resizable panels: map and groups on the left,- traces on the right. Both splits use the shared `useDefaultLayout` helper with- localStorage preferences shared across facets and projects, with separate- map-height preferences for desktop and narrow layouts. Narrow views keep- the resizable map above Topics/Traces tabs, with readable- summary rows on phones and all processing controls in the mobile overflow- menu. Selecting a group filters traces without changing the active tab.- 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; filters and search- live only in localStorage, scoped to each project/facet. Switching facets- restores that facet's state, defaulting to unfiltered on first visit. Filter- and search URL parameters are neither read nor written.- `TopicsTraceToolbar.tsx` uses the shared search bar for topic, assignment, and- text filtering. `topic-trace-filters.ts` owns its registry and local evaluation:- literal phrase search across summaries, topic names and trace IDs, OR within- a selection and AND between fields. Filtering applies before pagination.- Saved topic IDs absent from current options remain editable as unavailable- topics; their matching semantics are preserved across date-range changes.- Table results determine matching map IDs without changing saved positions or- the camera; nonmatching dots remain faint and inspectable. The map reports- its own matching count because its saved cohort can differ from current rows.- Fit/Home/Escape retain table filters; editing or removing search tokens updates- the same saved facet state. Search actions reuse metadata-only filter analytics with- `tableName: topics` and `isV4: false`. Query text and topic names remain- blocked from replay by the shared search bar.+ 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+ actions sit on the right, configuration and history in the overflow menu.+ `CurrentTopics.tsx` owns the map query (Grid only) 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.+ `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, includingwhile a run's status is open. Execution URL parameters open progress, errorsdiff --git a/web/src/features/topics/TopicBadge.tsx b/web/src/features/topics/TopicBadge.tsxdeleted file mode 100644index 4b9ac59b96..0000000000--- a/web/src/features/topics/TopicBadge.tsx+++ /dev/null@@ -1,19 +0,0 @@-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.tsxdeleted file mode 100644index 9ace910afc..0000000000--- a/web/src/features/topics/TopicEmbeddingMap.tsx+++ /dev/null@@ -1,67 +0,0 @@-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/TopicGridView.stories.tsx b/web/src/features/topics/TopicGridView.stories.tsxnew file mode 100644index 0000000000..bf898d5958--- /dev/null+++ b/web/src/features/topics/TopicGridView.stories.tsx@@ -0,0 +1,121 @@+import { type ComponentProps } from "react";+import { fn } from "storybook/test";+import preview from "../../../.storybook/preview";+import { TopicGridView } from "./TopicGridView";++const topics = [+ { id: "billing", name: "Billing questions", description: "", count: 0 },+ { id: "login", name: "Login and access problems", description: "", count: 0 },+ { id: "export", name: "Data export requests", description: "", count: 0 },+ {+ id: "pricing",+ name: "Pricing and plan changes",+ description: "",+ count: 0,+ },+ {+ id: "bugs",+ name: "Unexpected errors in the editor",+ description: "",+ count: 0,+ },+ { id: "howto", name: "How-to and onboarding", description: "", count: 0 },+];+const clusters: { topic: number | null; x: number; y: number; n: number }[] = [+ { topic: 0, x: -6, y: -4, n: 70 },+ { topic: 1, x: 5, y: -5, n: 55 },+ { topic: 2, x: 6, y: 4, n: 40 },+ { topic: 3, x: -5, y: 5, n: 60 },+ { topic: 4, x: 0, y: 0, n: 35 },+ { topic: 5, x: 1, y: 7, n: 45 },+ { topic: null, x: 0, y: -1, n: 30 },+];++const random = mulberry32(7);+const points = clusters.flatMap((cluster, clusterIndex) =>+ Array.from({ length: cluster.n }, (_, index) => {+ const spread = cluster.topic === null ? 6 : 1.4;+ const topic = cluster.topic === null ? null : topics[cluster.topic];+ return {+ traceId: `trace-${clusterIndex}-${index}-${random().toString(36).slice(2, 10)}`,+ summary: topic+ ? `${topic.name}: user asked about case ${index + 1} and expected a quicker resolution than they got.`+ : `Unrelated request ${index + 1} that did not fit any topic.`,+ topicId: topic?.id ?? null,+ outcome: topic ? ("assigned" as const) : ("outlier" as const),+ x: cluster.x + gaussian(random) * spread,+ y: cluster.y + gaussian(random) * spread,+ };+ }),+);+const rows = points.map((point, index) => ({+ traceId: point.traceId,+ summary: point.summary,+ topicId: point.topicId,+ topicName: topics.find((topic) => topic.id === point.topicId)?.name ?? null,+ outcome: point.outcome,+ facetVersion: 1,+ unitStartTime: new Date(Date.now() - index * 7 * 60_000).toISOString(),+}));+const facet = {+ facetId: "intent",+ name: "Intent",+ facetVersion: 1,+ rows,+ topics: topics.map((topic) => ({+ ...topic,+ count: rows.filter((row) => row.topicId === topic.id).length,+ })),+ map: { runId: "run", topics },+ awaitingCount: 0,+ usableCount: rows.length,+};+const mapData = {+ status: "ready" as const,+ reason: null,+ points,+ missingSummaryCount: 0,+ unpositionedCount: 0,+};++const defaultArgs: ComponentProps<typeof TopicGridView> = {+ projectId: "storybook-topics",+ facet,+ mapResult: { data: mapData, error: null },+ onOpenTrace: fn(),+ onGenerateTopics: fn(),+ canGenerateTopics: true,+ peekView: {+ itemType: "TRACE",+ tableName: "topics-topic-traces",+ isV4: false,+ closePeek: fn(),+ },+};++const meta = preview.meta({+ component: TopicGridView,+ args: defaultArgs,+ render: (args) => (+ <div className="flex h-[800px] flex-col">+ <TopicGridView {...args} />+ </div>+ ),+});++export const Default = meta.story({});++/** Seeded linear congruential generator so the story renders the same grid every time. */+function mulberry32(seed: number) {+ let state = seed;+ return () => {+ state = (state * 1664525 + 1013904223) % 4294967296;+ return state / 4294967296;+ };+}++function gaussian(next: () => number) {+ const u = 1 - next();+ const v = next();+ return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);+}diff --git a/web/src/features/topics/TopicGridView.tsx b/web/src/features/topics/TopicGridView.tsxnew file mode 100644index 0000000000..1a1daa1934--- /dev/null+++ b/web/src/features/topics/TopicGridView.tsx@@ -0,0 +1,576 @@+import { type RouterOutputs } from "@/src/utils/api";+import {+ useMemo,+ useState,+ type MouseEvent,+ type PointerEvent,+ type ReactNode,+} from "react";+import { Minus, Plus } from "@langfuse/icons";+import { Button } from "@/src/components/design-system/Button/Button";+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";+import { type DataTablePeekViewProps } from "@/src/components/table/peek";+import { useElementSize } from "@/src/hooks/useElementSize";+import { formatCompactRelativeTime } from "@/src/utils/dates";+import { cn } from "@/src/utils/tailwind";+import { TopicsEmptyState } from "./TopicsEmptyState";+import {+ type Facet,+ type FacetRow,+ allTopicsLabel,+ orderedFacetTopics,+} from "./facet-topics";+import { topicColor } from "./topic-map-colors";+import {+ layoutTopicGrid,+ sampleGridPoints,+ type GridCell,+ type GridPoint,+} from "./topic-grid-layout";+import { TopicTraceList } from "./TopicTraceList";++const ZOOM_MIN = -3;+const ZOOM_MAX = 6;+const ZOOM_STEP = 1.25;+const CELL_MIN = 3;+const CELL_MAX = 28;+const PAD_X = 16;+const PAD_Y = 16;+const CARD_OFFSET = 8;++export function TopicGridView({+ projectId,+ facet,+ mapResult,+ onOpenTrace,+ peekView,+ tracePanelRef,+ onGenerateTopics,+ canGenerateTopics,+}: TopicGridViewProps) {+ const [selectedTopicId, setSelectedTopicId] = useState<string | null>(null);+ const counts = new Map(facet.topics.map((topic) => [topic.id, topic.count]));+ const topics = orderedFacetTopics(facet).map((topic, index) => ({+ ...topic,+ count: counts.get(topic.id) ?? 0,+ color: topicColor(index),+ }));+ const selectedTopic =+ topics.find((topic) => topic.id === selectedTopicId) ?? null;+ const rowsById = useMemo(+ () => new Map(facet.rows.map((row) => [row.traceId, row])),+ [facet.rows],+ );+ const mapData = mapResult.data;+ const { points, perDot } = useMemo(() => {+ if (mapData?.status !== "ready") return { points: [], perDot: 1 };+ const indexById = new Map(+ orderedFacetTopics(facet).map((topic, index) => [topic.id, index]),+ );+ return sampleGridPoints(+ mapData.points.map(+ (point): GridPoint => ({+ id: point.traceId,+ x: point.x,+ y: point.y,+ topicIndex: point.topicId ? (indexById.get(point.topicId) ?? -1) : -1,+ }),+ ),+ );+ }, [mapData, facet]);+ if (topics.length === 0) {+ return (+ <TopicsEmptyState+ onGenerateTopics={onGenerateTopics}+ canGenerateTopics={canGenerateTopics}+ />+ );+ }+ const selectedIndex = selectedTopic+ ? topics.findIndex((topic) => topic.id === selectedTopic.id)+ : null;+ const message = facet.map+ ? gridMessage(mapResult)+ : "No map published for this facet.";+ const listRows = selectedTopic+ ? facet.rows.filter((row) => row.topicId === selectedTopic.id)+ : facet.rows;++ return (+ <div className="flex h-full min-h-0 min-w-0 flex-col lg:flex-row">+ <section+ aria-label="Topic grid"+ className="flex min-h-48 min-w-0 shrink-0 basis-1/2 flex-col overflow-hidden lg:shrink lg:basis-3/5"+ >+ {message ? (+ <GridMessage>{message}</GridMessage>+ ) : (+ <TopicGrid+ points={points}+ perDot={perDot}+ topics={topics}+ rowsById={rowsById}+ selectedIndex={selectedIndex}+ onSelectTopic={setSelectedTopicId}+ onOpenTrace={onOpenTrace}+ />+ )}+ </section>+ <TopicTraceList+ projectId={projectId}+ title={selectedTopic?.name ?? allTopicsLabel(facet.name)}+ description={selectedTopic?.description}+ swatchColor={+ selectedIndex !== null ? topics[selectedIndex]?.color : undefined+ }+ rows={listRows}+ peekView={peekView}+ tracePanelRef={tracePanelRef}+ divider="side"+ />+ </div>+ );+}++function GridMessage({ children }: { children: ReactNode }) {+ return <p className="text-muted-foreground p-4 text-sm">{children}</p>;+}++function TopicGrid({+ points,+ perDot,+ topics,+ rowsById,+ selectedIndex,+ onSelectTopic,+ onOpenTrace,+}: TopicGridProps) {+ const [zoom, setZoom] = useState(0);+ const [hoveredId, setHoveredId] = useState<string | null>(null);+ const [hoveredLabelIndex, setHoveredLabelIndex] = useState<number | null>(+ null,+ );+ const [containerRef, size] = useElementSize<HTMLDivElement>();+ const innerWidth = size ? Math.max(1, size.width - 2 * PAD_X) : 0;+ const innerHeight = size ? Math.max(1, size.height - 2 * PAD_Y) : 0;+ const aspect = size ? Math.round((innerWidth / innerHeight) * 4) / 4 : 1;+ const layout = useMemo(+ () => layoutTopicGrid(points, aspect),+ [points, aspect],+ );+ const cellById = useMemo(+ () => new Map(layout.cells.map((cell) => [cell.id, cell])),+ [layout],+ );+ const countByIndex = useMemo(() => {+ const counts = new Map<number, number>();+ for (const cell of layout.cells) {+ counts.set(cell.topicIndex, (counts.get(cell.topicIndex) ?? 0) + 1);+ }+ return counts;+ }, [layout]);++ const selectedId =+ selectedIndex === null ? null : (topics[selectedIndex]?.id ?? null);+ const hoveredCell = hoveredId ? (cellById.get(hoveredId) ?? null) : null;+ const hoveredIndex = hoveredCell ? hoveredCell.topicIndex : hoveredLabelIndex;+ const fit = size+ ? Math.min(innerWidth / layout.cols, innerHeight / layout.rows)+ : 0;+ // Zoom from the displayed size, so steps take effect even when fit exceeds the cap.+ const baseCell = clamp(fit, CELL_MIN, CELL_MAX);+ const cell = clamp(baseCell * ZOOM_STEP ** zoom, CELL_MIN, CELL_MAX);+ const gap = Math.max(0.5, cell * 0.16);+ const radius = cell * 0.18;+ const gridWidth = layout.cols * cell;+ const gridHeight = layout.rows * cell;++ function traceIdAt(event: PointerEvent<SVGElement> | MouseEvent<SVGElement>) {+ const target = event.target as Element;+ return target.getAttribute("data-trace-id");+ }+ function handlePointerMove(event: PointerEvent<SVGSVGElement>) {+ const id = traceIdAt(event);+ if (id !== hoveredId) setHoveredId(id);+ }+ function handlePointerLeave() {+ setHoveredId(null);+ }+ function handleClick(event: MouseEvent<SVGSVGElement>) {+ const id = traceIdAt(event);+ if (id) onOpenTrace(id);+ }+ function showAllTopics() {+ onSelectTopic(null);+ }+ function zoomIn() {+ setZoom((current) => Math.min(ZOOM_MAX, current + 1));+ }+ function zoomOut() {+ setZoom((current) => Math.max(ZOOM_MIN, current - 1));+ }++ const squares = hoveredCell+ ? [...layout.cells.filter((item) => item.id !== hoveredId), hoveredCell]+ : layout.cells;++ return (+ <>+ <div className="flex h-12 shrink-0 items-center justify-end gap-2 px-4">+ <div className="flex items-center gap-0.5">+ <IconButton+ icon={Minus}+ label="Zoom out (−)"+ size="sm"+ disabled={zoom <= ZOOM_MIN || cell <= CELL_MIN}+ onClick={zoomOut}+ />+ <IconButton+ icon={Plus}+ label="Zoom in (+)"+ size="sm"+ disabled={zoom >= ZOOM_MAX || cell >= CELL_MAX}+ onClick={zoomIn}+ />+ </div>+ </div>+ <div className="flex min-h-0 flex-1 flex-col border-t">+ <div+ ref={containerRef}+ className="relative flex min-h-0 flex-[2] overflow-auto overscroll-contain"+ >+ {points.length === 0 ? (+ <GridMessage>No positioned traces in this time range.</GridMessage>+ ) : (+ size && (+ <div+ className="m-auto shrink-0"+ style={{ padding: `${PAD_Y}px ${PAD_X}px` }}+ >+ <div+ className="relative"+ style={{ width: gridWidth, height: gridHeight }}+ >+ <svg+ width={gridWidth}+ height={gridHeight}+ role="img"+ aria-label={`Topic grid, ${points.length.toLocaleString()} traces`}+ className="block"+ onPointerMove={handlePointerMove}+ onPointerLeave={handlePointerLeave}+ onClick={handleClick}+ >+ {squares.map((square) => {+ const isHovered = square.id === hoveredId;+ const grow = isHovered ? gap / 2 : 0;+ return (+ <rect+ key={square.id}+ data-trace-id={square.id}+ className="cursor-pointer"+ x={square.col * cell + gap / 2 - grow}+ y={square.row * cell + gap / 2 - grow}+ width={cell - gap + grow * 2}+ height={cell - gap + grow * 2}+ rx={radius}+ fill={colorAt(topics, square.topicIndex)}+ fillOpacity={squareOpacity(+ square.topicIndex,+ selectedIndex,+ hoveredIndex,+ isHovered,+ )}+ stroke={isHovered ? "hsl(var(--foreground))" : "none"}+ strokeWidth={1.5}+ />+ );+ })}+ </svg>+ {hoveredCell && (+ <GridHoverCard+ cell={hoveredCell}+ topicName={+ topics[hoveredCell.topicIndex]?.name ?? "No topic"+ }+ count={+ topics[hoveredCell.topicIndex]?.count ??+ (countByIndex.get(hoveredCell.topicIndex) ?? 0) * perDot+ }+ row={rowsById.get(hoveredCell.id)}+ members={(+ hoveredCell.memberIds ?? [hoveredCell.id]+ ).flatMap((id) => {+ const member = rowsById.get(id);+ return member ? [member] : [];+ })}+ color={colorAt(topics, hoveredCell.topicIndex)}+ cellSize={cell}+ grid={layout}+ />+ )}+ </div>+ </div>+ )+ )}+ </div>+ <GridLegend+ topics={topics}+ selectedIndex={selectedIndex}+ onSelectTopic={onSelectTopic}+ onHoverTopic={setHoveredLabelIndex}+ >+ <span>+ {perDot > 1+ ? `1 dot ≈ ${perDot.toLocaleString()} traces`+ : "1 dot = 1 trace"}+ </span>+ <Button+ text="Show all topics"+ variant="ghost"+ size="sm"+ disabled={selectedId === null}+ onClick={showAllTopics}+ />+ </GridLegend>+ </div>+ </>+ );+}++function GridLegend({+ topics,+ selectedIndex,+ onSelectTopic,+ onHoverTopic,+ children,+}: GridLegendProps) {+ const entries = topics+ .map((topic, topicIndex) => ({ topic, topicIndex }))+ .filter(({ topic }) => topic.count > 0)+ .sort((a, b) => b.topic.count - a.topic.count);+ function clearHover() {+ onHoverTopic(null);+ }+ return (+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden border-t">+ <ul+ aria-label="Topics"+ className="grid min-h-0 grid-cols-2 gap-x-4 gap-y-0.5 overflow-y-auto p-2"+ >+ {entries.map((entry) => {+ const { topic } = entry;+ const isSelected = entry.topicIndex === selectedIndex;+ function select() {+ onSelectTopic(isSelected ? null : topic.id);+ }+ function hover() {+ onHoverTopic(entry.topicIndex);+ }+ return (+ <li key={topic.id} className="min-w-0">+ <button+ type="button"+ aria-pressed={isSelected}+ onClick={select}+ onPointerEnter={hover}+ onPointerLeave={clearHover}+ onFocus={hover}+ onBlur={clearHover}+ className={cn(+ "hover:bg-accent focus-visible:ring-ring flex w-full min-w-0 items-center gap-2 rounded-sm px-1.5 py-1 text-left text-sm focus-visible:ring-2 focus-visible:outline-hidden",+ isSelected && "bg-accent font-bold",+ selectedIndex !== null &&+ !isSelected &&+ "text-muted-foreground",+ )}+ >+ <span+ aria-hidden+ className="size-2.5 shrink-0 rounded-xs"+ style={{ backgroundColor: colorAt(topics, entry.topicIndex) }}+ />+ <span className="min-w-0 flex-1 truncate" title={topic.name}>+ {topic.name}+ </span>+ <span className="text-muted-foreground shrink-0 font-mono text-xs">+ {topic.count.toLocaleString()}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ <div className="text-muted-foreground flex shrink-0 items-center gap-2 px-3.5 pb-2 text-xs">+ {children}+ </div>+ </div>+ );+}++function GridHoverCard({+ cell,+ topicName,+ count,+ row,+ cellSize,+ grid,+ members,+ color,+}: GridHoverCardProps) {+ // Card sits above/below the dot, growing toward the grid center, so it never covers it.+ const toLeft = cell.col >= grid.cols / 2;+ const below = cell.row < grid.rows / 2;+ const left = (cell.col + (toLeft ? 1 : 0)) * cellSize;+ const top = below+ ? (cell.row + 1) * cellSize + CARD_OFFSET+ : cell.row * cellSize - CARD_OFFSET;+ const shortId = cell.id.length > 8 ? `${cell.id.slice(0, 8)}…` : cell.id;+ const started = row+ ? formatCompactRelativeTime(new Date(row.unitStartTime))+ : null;+ return (+ <div+ role="tooltip"+ className="bg-popover text-popover-foreground pointer-events-none absolute w-64 rounded-md border p-2 shadow-md"+ style={{+ left,+ top,+ translate: `${toLeft ? "-100%" : "0"} ${below ? "0" : "-100%"}`,+ }}+ >+ <div className="flex items-center gap-1.5 text-xs">+ <span+ aria-hidden+ className="size-2.5 shrink-0 rounded-xs"+ style={{ backgroundColor: color }}+ />+ <span className="min-w-0 truncate font-bold" title={topicName}>+ {topicName}+ </span>+ <span className="text-muted-foreground text-2xs ml-auto shrink-0 font-mono">+ {count.toLocaleString()} traces+ </span>+ </div>+ {members.length > 1 ? (+ <>+ <ul className="mt-1 flex flex-col gap-0.5 text-xs">+ {members.slice(0, 3).map((member) => (+ <li key={member.traceId} className="line-clamp-1">+ {member.summary || "No applicable summary."}+ </li>+ ))}+ </ul>+ <p className="text-muted-foreground text-2xs mt-1 font-mono">+ {[+ `${members.length.toLocaleString()} traces in this dot`,+ members.length > 3+ ? `+${(members.length - 3).toLocaleString()} more`+ : null,+ "click to open the first",+ ]+ .filter(Boolean)+ .join(" · ")}+ </p>+ </>+ ) : (+ <>+ <p className="mt-1 line-clamp-2 text-xs">+ {row?.summary || "No applicable summary."}+ </p>+ <p+ className="text-muted-foreground text-2xs mt-1 truncate font-mono"+ title={cell.id}+ >+ {[shortId, started, "click to open"].filter(Boolean).join(" · ")}+ </p>+ </>+ )}+ </div>+ );+}++function gridMessage(mapResult: TopicGridViewProps["mapResult"]) {+ if (mapResult.error) return `Grid could not load: ${mapResult.error.message}`;+ if (!mapResult.data) return "Loading grid…";+ if (mapResult.data.status !== "ready") {+ return (+ mapResult.data.reason ?? "This run has no saved embedding projection."+ );+ }+ return null;+}++function squareOpacity(+ topicIndex: number,+ selectedIndex: number | null,+ hoveredIndex: number | null,+ isHovered: boolean,+) {+ if (isHovered) return 1;+ const hasSelection = selectedIndex !== null;+ let opacity: number;+ if (topicIndex < 0) opacity = hasSelection ? 0.1 : 0.2;+ else if (!hasSelection) opacity = 0.35;+ else opacity = topicIndex === selectedIndex ? 1 : 0.12;+ if (topicIndex >= 0 && topicIndex === hoveredIndex) {+ opacity = Math.max(opacity, 0.7);+ }+ return opacity;+}++function colorAt(topics: GridTopic[], topicIndex: number) {+ return topics[topicIndex]?.color ?? topicColor(-1);+}++function clamp(value: number, min: number, max: number) {+ return Math.min(max, Math.max(min, value));+}++type TopicGridViewProps = {+ projectId: string;+ facet: Facet;+ mapResult: {+ data?: RouterOutputs["topics"]["map"];+ error: { message: string } | null;+ };+ onOpenTrace: (traceId: string) => void;+ peekView: DataTablePeekViewProps;+ tracePanelRef?: (element: HTMLElement | null) => void;+ onGenerateTopics: () => void;+ canGenerateTopics: boolean;+};++type TopicGridProps = {+ points: GridPoint[];+ perDot: number;+ topics: GridTopic[];+ rowsById: Map<string, FacetRow>;+ selectedIndex: number | null;+ onSelectTopic: (topicId: string | null) => void;+ onOpenTrace: (traceId: string) => void;+};++type GridHoverCardProps = {+ cell: GridCell;+ topicName: string;+ count: number;+ row: FacetRow | undefined;+ cellSize: number;+ grid: { cols: number; rows: number };+ members: FacetRow[];+ color: string;+};++type GridTopic = ReturnType<typeof orderedFacetTopics>[number] & {+ count: number;+ color: string;+};++type GridLegendProps = {+ children: ReactNode;+ topics: TopicGridProps["topics"];+ selectedIndex: number | null;+ onSelectTopic: (topicId: string | null) => void;+ onHoverTopic: (topicIndex: number | null) => void;+};diff --git a/web/src/features/topics/TopicGroupCard.tsx b/web/src/features/topics/TopicGroupCard.tsxdeleted file mode 100644index 47d6de3159..0000000000--- a/web/src/features/topics/TopicGroupCard.tsx+++ /dev/null@@ -1,44 +0,0 @@-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.tsxdeleted file mode 100644index 30c1bb5907..0000000000--- a/web/src/features/topics/TopicMapLoading.stories.tsx+++ /dev/null@@ -1,48 +0,0 @@-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.tsxdeleted file mode 100644index 7bab20229d..0000000000--- a/web/src/features/topics/TopicMapLoading.tsx+++ /dev/null@@ -1,28 +0,0 @@-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/TopicSetupNotice.tsx b/web/src/features/topics/TopicSetupNotice.tsxindex 22f1689156..901f3f28ea 100644--- a/web/src/features/topics/TopicSetupNotice.tsx+++ b/web/src/features/topics/TopicSetupNotice.tsx@@ -144,18 +144,6 @@ export function TopicSetupNotice({/></div>) : null}- {status?.kind === "models" && !showOnboarding ? (- <Alert variant="info">- <Alert.Title>Choose the models Topics runs on</Alert.Title>- <Alert.Description>- <p>- Topics uses your LLM connections for three jobs: facet summaries,- embeddings, and topic clustering. Open Configure Topics to set all- three.- </p>- </Alert.Description>- </Alert>- ) : null}</>);}diff --git a/web/src/features/topics/TopicTraceList.tsx b/web/src/features/topics/TopicTraceList.tsxnew file mode 100644index 0000000000..47045ae82a--- /dev/null+++ b/web/src/features/topics/TopicTraceList.tsx@@ -0,0 +1,173 @@+import { useState } from "react";+import { type OnChangeFn, type PaginationState } from "@tanstack/react-table";+import { ExternalLink } from "@langfuse/icons";+import { DataTable } from "@/src/components/table/data-table";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import { type DataTablePeekViewProps } from "@/src/components/table/peek";+import { Button } from "@/src/components/design-system/Button/Button";+import { formatCompactRelativeTime } from "@/src/utils/dates";+import { cn } from "@/src/utils/tailwind";+import { useReadPath } from "@/src/features/events/hooks/useReadPath";+import { type FacetRow, topicTracesHref } from "./facet-topics";++/** With the table's own 4px (8px on the first column), cells end up 16px from each edge. */+const CELL = "block px-3";+const FIRST_CELL = "block pr-3 pl-2";++export function TopicTraceList({+ projectId,+ title,+ description,+ swatchColor,+ rows,+ peekView,+ tracePanelRef,+ divider,+}: TopicTraceListProps) {+ const [pagination, setPagination] = useState<PaginationState>({+ pageIndex: 0,+ pageSize: 20,+ });+ const pageIndex = Math.min(+ pagination.pageIndex,+ Math.max(0, Math.ceil(rows.length / pagination.pageSize) - 1),+ );+ const onPaginationChange: OnChangeFn<PaginationState> = (update) => {+ setPagination((current) =>+ typeof update === "function" ? update(current) : update,+ );+ };+ const { isV4 } = useReadPath();+ const tracingHref = topicTracesHref(projectId, rows, isV4);+ const columns: LangfuseColumnDef<FacetRow>[] = [+ {+ accessorKey: "traceId",+ header: () => <span className={FIRST_CELL}>Trace ID</span>,+ size: 128,+ minSize: 96,+ cell: ({ row }) => (+ <span+ className={cn(+ "text-link block truncate font-mono text-xs",+ FIRST_CELL,+ )}+ title={row.original.traceId}+ >+ {row.original.traceId}+ </span>+ ),+ },+ {+ accessorKey: "summary",+ header: () => <span className={CELL}>Summary</span>,+ size: 300,+ minSize: 180,+ isFlexWidth: true,+ cell: ({ row }) => {+ const summary = row.original.summary || "No applicable summary.";+ return (+ <p className={cn("truncate", CELL)} title={summary}>+ {summary}+ </p>+ );+ },+ },+ {+ accessorKey: "unitStartTime",+ header: () => <span className={CELL}>Started</span>,+ size: 96,+ minSize: 88,+ cell: ({ row }) => (+ <span className={cn("text-muted-foreground block tabular-nums", CELL)}>+ {compactAge(row.original.unitStartTime)}+ </span>+ ),+ },+ ];+ return (+ <section+ aria-label="Topic traces"+ ref={tracePanelRef}+ className={cn(+ "flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",+ divider === "side" && "border-t lg:border-t-0 lg:border-l",+ divider === "top" && "border-t",+ !divider && "rounded-md border",+ )}+ >+ <div className="flex h-12 shrink-0 items-center justify-between gap-2 px-4">+ <h3 className="flex min-w-0 items-baseline gap-2 text-base leading-none font-bold">+ {swatchColor ? (+ <span+ aria-hidden+ className="size-2.5 shrink-0 self-center rounded-xs"+ style={{ backgroundColor: swatchColor }}+ />+ ) : null}+ <span className="truncate" title={title}>+ {title}+ </span>+ <span className="text-muted-foreground shrink-0 font-mono text-xs font-normal">+ {rows.length.toLocaleString()} traces+ </span>+ </h3>+ {tracingHref ? (+ <Button+ href={tracingHref}+ text="Open in Tracing"+ variant="secondary"+ size="sm"+ icon={ExternalLink}+ />+ ) : null}+ </div>+ {description ? (+ <p+ className="bg-muted text-muted-foreground mx-4 mb-3 line-clamp-3 rounded-md px-3 py-2 text-sm"+ title={description}+ >+ {description}+ </p>+ ) : null}+ <DataTable+ tableName="topics-topic-traces"+ columns={columns}+ data={{+ isLoading: false,+ isError: false,+ data: rows+ .slice(+ pageIndex * pagination.pageSize,+ (pageIndex + 1) * pagination.pageSize,+ )+ .map((row) => ({ ...row, id: row.traceId })),+ }}+ pagination={{+ totalCount: rows.length,+ state: { ...pagination, pageIndex },+ onChange: onPaginationChange,+ options: [20, 50, 100],+ }}+ className="min-h-0 overscroll-contain"+ cellPadding="relaxed"+ noResultsMessage="No trace summaries."+ peekView={peekView}+ />+ </section>+ );+}++type TopicTraceListProps = {+ projectId: string;+ title: string;+ description?: string;+ swatchColor?: string;+ rows: FacetRow[];+ peekView: DataTablePeekViewProps;+ tracePanelRef?: (element: HTMLElement | null) => void;+ divider?: "top" | "side";+};++function compactAge(timestamp: string) {+ return formatCompactRelativeTime(new Date(timestamp)).replace(/ ago$/, "");+}diff --git a/web/src/features/topics/TopicTreemapView.stories.tsx b/web/src/features/topics/TopicTreemapView.stories.tsxnew file mode 100644index 0000000000..f6f9994b42--- /dev/null+++ b/web/src/features/topics/TopicTreemapView.stories.tsx@@ -0,0 +1,105 @@+import { type ComponentProps } from "react";+import { expect, fn, userEvent, within } from "storybook/test";+import preview from "../../../.storybook/preview";+import { TopicTreemapView } from "./TopicTreemapView";++const counts = [55, 45, 27, 23, 21, 20, 20, 18, 17, 16, 15, 15, 14, 14, 13];+const names = [+ "Langfuse user assistance",+ "Dashboard widget management",+ "Trace analysis title requests",+ "Trace and observation filtering",+ "Trace cost analysis",+ "Conversation title generation",+ "Human evaluation workflow",+ "LLM-as-a-judge evaluator setup",+ "Failure analysis and prioritization",+ "Langfuse session and trace review",+ "Weekly cost comparisons",+ "Failed trace error analysis",+ "Trace performance review",+ "Langfuse trace export",+ "Recommendation requests",+];+const topics = names.map((name, index) => ({+ id: `topic-${index}`,+ name,+ description: "",+ count: counts[index],+}));+const assignedRows = topics.flatMap((topic) =>+ Array.from({ length: topic.count }, (_, index) => ({+ traceId: `${topic.id}-trace-${index}`,+ summary: `${topic.name} question ${index + 1}`,+ topicId: topic.id,+ topicName: topic.name,+ outcome: "assigned" as const,+ facetVersion: 1,+ unitStartTime: new Date(Date.now() - index * 7 * 60_000).toISOString(),+ })),+);++const rows = [+ ...assignedRows,+ ...Array.from({ length: 12 }, (_, index) => ({+ traceId: `unassigned-trace-${index}`,+ summary: `Unrelated request ${index + 1} that fit no topic`,+ topicId: null,+ topicName: null,+ outcome: "outlier" as const,+ facetVersion: 1,+ unitStartTime: new Date(Date.now() - index * 11 * 60_000).toISOString(),+ })),+];++const facet: ComponentProps<typeof TopicTreemapView>["facet"] = {+ facetId: "intent",+ name: "Intent",+ facetVersion: 1,+ rows,+ topics,+ map: null,+ awaitingCount: 0,+ usableCount: rows.length,+};++const defaultArgs: ComponentProps<typeof TopicTreemapView> = {+ projectId: "storybook-topics",+ facet,+ onGenerateTopics: fn(),+ canGenerateTopics: true,+ peekView: {+ itemType: "TRACE",+ tableName: "topics-topic-traces",+ isV4: false,+ closePeek: fn(),+ },+};++const meta = preview.meta({+ component: TopicTreemapView,+ args: defaultArgs,+ render: (args) => (+ <div className="flex h-screen flex-col p-2">+ <TopicTreemapView {...args} />+ </div>+ ),+});++export const Default = meta.story({});++export const SelectTopic = meta.story({+ name: "(Test) Selecting a tile lists its traces",+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const tile = await canvas.findByRole("button", {+ name: "Trace cost analysis, 21 traces",+ });+ await userEvent.click(tile);+ await expect(tile).toHaveAttribute("aria-pressed", "true");+ const list = canvas.getByRole("region", { name: "Topic traces" });+ await expect(+ within(list).getByRole("heading", { name: /Trace cost analysis/ }),+ ).toBeVisible();+ },+});diff --git a/web/src/features/topics/TopicTreemapView.tsx b/web/src/features/topics/TopicTreemapView.tsxnew file mode 100644index 0000000000..c0d4315d5e--- /dev/null+++ b/web/src/features/topics/TopicTreemapView.tsx@@ -0,0 +1,265 @@+import { useState } from "react";+import { useElementSize } from "@/src/hooks/useElementSize";+import { CustomTooltip } from "@/src/components/design-system/CustomTooltip/CustomTooltip";+import { type DataTablePeekViewProps } from "@/src/components/table/peek";+import { cn } from "@/src/utils/tailwind";+import { TopicsEmptyState } from "./TopicsEmptyState";+import { type Facet, type FacetTopic } from "./facet-topics";+import {+ treemapSwatchColor,+ treemapTileClasses,+ UNASSIGNED_SWATCH_COLOR,+ unassignedTileClasses,+} from "./topic-map-colors";+import { layoutTreemap } from "./topic-treemap-layout";+import { TopicTraceList } from "./TopicTraceList";++const TILE_GAP = 8;+const UNASSIGNED_ID = "__unassigned";+/** Tiles above this area (px²) get the stronger resting tint. */+const BIG_TILE_AREA = 30_000;++const TILE_PADDING: Record<TileTier, string> = {+ large: "p-3",+ medium: "p-3",+ small: "p-2",+ tiny: "p-0",+};++const COUNT_SIZE: Record<TileTier, string> = {+ large: "text-3xl",+ medium: "text-xl",+ small: "text-sm",+ tiny: "",+};++export function TopicTreemapView({+ projectId,+ facet,+ peekView,+ onGenerateTopics,+ canGenerateTopics,+}: TopicTreemapViewProps) {+ const [selectedTopicId, setSelectedTopicId] = useState<string | null>(null);+ if (facet.topics.length === 0) {+ return (+ <TopicsEmptyState+ onGenerateTopics={onGenerateTopics}+ canGenerateTopics={canGenerateTopics}+ />+ );+ }+ const unassignedCount = facet.rows.filter((row) => !row.topicId).length;+ const topics: FacetTopic[] =+ unassignedCount > 0+ ? [+ ...facet.topics,+ {+ id: UNASSIGNED_ID,+ name: "Unassigned",+ description: "",+ count: unassignedCount,+ },+ ]+ : facet.topics;+ const selected =+ topics.find((topic) => topic.id === selectedTopicId) ?? topics[0];+ const selectedRowTopicId = selected.id === UNASSIGNED_ID ? null : selected.id;+ const rows = facet.rows.filter(+ (row) => (row.topicId ?? null) === selectedRowTopicId,+ );+ return (+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">+ <TopicTreemap+ facet={facet}+ topics={topics}+ selectedTopicId={selected.id}+ onSelectTopic={setSelectedTopicId}+ />+ <TopicTraceList+ key={selected.id}+ projectId={projectId}+ title={selected.name}+ description={selected.description}+ swatchColor={swatchFor(facet, selected.id)}+ rows={rows}+ peekView={peekView}+ divider="top"+ />+ </div>+ );+}++function TopicTreemap({+ facet,+ topics,+ selectedTopicId,+ onSelectTopic,+}: TopicTreemapProps) {+ const [ref, size] = useElementSize<HTMLDivElement>();+ const total = facet.rows.length;+ function tileColors(topicId: string, big: boolean) {+ if (topicId === UNASSIGNED_ID) return unassignedTileClasses;+ return treemapTileClasses(+ facet.topics.findIndex((topic) => topic.id === topicId),+ big,+ );+ }+ const tiles = size+ ? layoutTreemap(topics, size.width, size.height, TILE_GAP)+ : [];+ return (+ <section+ aria-label="Topics"+ ref={ref}+ className="relative m-4 min-h-48 min-w-0 shrink-0 basis-1/2"+ >+ {tiles.map(({ item, x, y, width, height }) => (+ <TopicTile+ key={item.id}+ topic={item}+ share={total > 0 ? item.count / total : 0}+ colors={tileColors(item.id, width * height > BIG_TILE_AREA)}+ isSelected={item.id === selectedTopicId}+ onSelect={onSelectTopic}+ rect={{ left: x, top: y, width, height }}+ tier={tileTier(width, height)}+ />+ ))}+ </section>+ );+}++function TopicTile(props: TopicTileProps) {+ const { topic, share, tier } = props;+ const shareLabel = `${Math.round(share * 100)}% of traces`;+ if (tier === "large" || tier === "medium") {+ return <TopicTileButton {...props} shareLabel={shareLabel} />;+ }+ return (+ <CustomTooltip+ placement="top"+ content={+ <span className="ph-no-capture flex flex-col gap-0.5">+ <span className="font-bold">{topic.name}</span>+ <span className="text-muted-foreground text-xs">+ {topic.count.toLocaleString()} traces · {shareLabel}+ </span>+ </span>+ }+ >+ {({ getTriggerProps }) => (+ <TopicTileButton+ {...props}+ shareLabel={shareLabel}+ triggerProps={getTriggerProps()}+ />+ )}+ </CustomTooltip>+ );+}++function TopicTileButton({+ topic,+ colors,+ isSelected,+ onSelect,+ rect,+ tier,+ shareLabel,+ triggerProps,+}: TopicTileButtonProps) {+ function selectTopic() {+ onSelect(topic.id);+ }+ const showName = tier === "large" || tier === "medium";+ return (+ <button+ {...triggerProps}+ type="button"+ onClick={selectTopic}+ aria-pressed={isSelected}+ aria-label={`${topic.name}, ${topic.count} traces`}+ style={rect}+ className={cn(+ "absolute flex flex-col justify-between overflow-hidden rounded-md text-left",+ TILE_PADDING[tier],+ isSelected+ ? cn(+ colors.active,+ "text-foreground outline-foreground outline-2 outline-offset-2",+ )+ : cn(+ colors.tile,+ colors.hover,+ "text-muted-foreground hover:text-foreground",+ ),+ )}+ >+ {showName && (+ <span+ className={cn(+ "line-clamp-3 font-bold",+ tier === "large" ? "text-lg" : "text-sm",+ )}+ >+ {topic.name}+ </span>+ )}+ {tier !== "tiny" && (+ <span className="flex flex-col gap-0.5">+ <span className={cn("font-bold tabular-nums", COUNT_SIZE[tier])}>+ {topic.count.toLocaleString()}+ </span>+ {showName && <span className="text-xs opacity-80">{shareLabel}</span>}+ </span>+ )}+ </button>+ );+}++function tileTier(width: number, height: number): TileTier {+ if (width >= 240 && height >= 160) return "large";+ if (width >= 112 && height >= 80) return "medium";+ if (width >= 40 && height >= 32) return "small";+ return "tiny";+}++function swatchFor(facet: Facet, topicId: string) {+ if (topicId === UNASSIGNED_ID) return UNASSIGNED_SWATCH_COLOR;+ return treemapSwatchColor(+ facet.topics.findIndex((topic) => topic.id === topicId),+ );+}++type TopicTreemapViewProps = {+ projectId: string;+ facet: Facet;+ peekView: DataTablePeekViewProps;+ onGenerateTopics: () => void;+ canGenerateTopics: boolean;+};++type TopicTreemapProps = {+ facet: Facet;+ topics: FacetTopic[];+ selectedTopicId: string;+ onSelectTopic: (topicId: string) => void;+};++type TileTier = "large" | "medium" | "small" | "tiny";++type TopicTileProps = {+ topic: FacetTopic;+ share: number;+ colors: { tile: string; active: string; hover: string };+ isSelected: boolean;+ onSelect: (topicId: string) => void;+ rect: { left: number; top: number; width: number; height: number };+ tier: TileTier;+};++type TopicTileButtonProps = TopicTileProps & {+ shareLabel: string;+ triggerProps?: Record<string, unknown>;+};diff --git a/web/src/features/topics/TopicsEmptyState.tsx b/web/src/features/topics/TopicsEmptyState.tsxnew file mode 100644index 0000000000..4b5e195b98--- /dev/null+++ b/web/src/features/topics/TopicsEmptyState.tsx@@ -0,0 +1,28 @@+import { Button } from "@/src/components/design-system/Button/Button";++export function TopicsEmptyState({+ onGenerateTopics,+ canGenerateTopics,+}: TopicsEmptyStateProps) {+ return (+ <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>+ );+}++type TopicsEmptyStateProps = {+ onGenerateTopics: () => void;+ canGenerateTopics: boolean;+};diff --git a/web/src/features/topics/TopicsFacetTabs.tsx b/web/src/features/topics/TopicsFacetTabs.tsxnew file mode 100644index 0000000000..e452d7da0d--- /dev/null+++ b/web/src/features/topics/TopicsFacetTabs.tsx@@ -0,0 +1,29 @@+import { Tabs } from "@/src/components/design-system/Tabs/Tabs";++export function TopicsFacetTabs({+ facets,+ selectedFacet,+ onSelectFacet,+}: TopicsFacetTabsProps) {+ return (+ <div className="ph-no-capture">+ <Tabs value={selectedFacet} onValueChange={onSelectFacet}>+ <Tabs.List variant="inset" size="sm" aria-label="Topics facets">+ {facets.map((facet) => (+ <Tabs.Trigger+ key={facet.facetId}+ value={facet.facetId}+ label={facet.name}+ />+ ))}+ </Tabs.List>+ </Tabs>+ </div>+ );+}++type TopicsFacetTabsProps = {+ facets: readonly { facetId: string; name: string }[];+ selectedFacet: string;+ onSelectFacet: (facetId: string) => void;+};diff --git a/web/src/features/topics/TopicsFilters.stories.tsx b/web/src/features/topics/TopicsFilters.stories.tsxdeleted file mode 100644index 380ba0ba45..0000000000--- a/web/src/features/topics/TopicsFilters.stories.tsx+++ /dev/null@@ -1,74 +0,0 @@-import { useState } from "react";-import { expect, fn, userEvent, within } from "storybook/test";-import preview from "../../../.storybook/preview";-import { Button } from "@/src/components/design-system/Button/Button";-import { TopicsFilters } from "./TopicsFilters";--const filterArgs = {- facets: [- { facetId: "intent", name: "Intent" },- { facetId: "sentiment", name: "Sentiment" },- { facetId: "outcome", name: "Outcome" },- { facetId: "issues", name: "Issues" },- ],- selectedFacetId: undefined,- onSelectFacet: fn(),-};--const meta = preview.meta({ component: TopicsFilters });--export const Default = meta.story({- args: filterArgs,-});--export const RetainsSelectionThroughRefresh = meta.story({- name: "(Test) Retains selection through refresh and falls back after removal",- args: filterArgs,- render: (args) => {- const [facets, setFacets] = useState(args.facets);- const [selectedFacetId, setSelectedFacetId] = useState(- args.selectedFacetId,- );- function selectFacet(facetId: string) {- setSelectedFacetId(facetId);- args.onSelectFacet(facetId);- }- function refreshFacets() {- setFacets((current) => current.map((facet) => ({ ...facet })));- }- function removeSelectedFacet() {- setFacets((current) =>- current.filter((facet) => facet.facetId !== selectedFacetId),- );- }- return (- <div className="flex flex-col items-start gap-2">- <TopicsFilters- {...args}- facets={facets}- selectedFacetId={selectedFacetId}- onSelectFacet={selectFacet}- />- <Button text="Refresh facets" onClick={refreshFacets} />- <Button text="Remove selected facet" onClick={removeSelectedFacet} />- </div>- );- },- play: async ({ canvasElement, args }) => {- const canvas = within(canvasElement);- const intent = canvas.getByRole("tab", { name: "Intent" });- const issues = canvas.getByRole("tab", { name: "Issues" });- await expect(intent).toHaveAttribute("aria-selected", "true");- await userEvent.click(issues);- await expect(args.onSelectFacet).toHaveBeenCalledWith("issues");- await expect(issues).toHaveAttribute("aria-selected", "true");- await userEvent.click(- canvas.getByRole("button", { name: "Refresh facets" }),- );- await expect(issues).toHaveAttribute("aria-selected", "true");- await userEvent.click(- canvas.getByRole("button", { name: "Remove selected facet" }),- );- await expect(intent).toHaveAttribute("aria-selected", "true");- },-});diff --git a/web/src/features/topics/TopicsFilters.tsx b/web/src/features/topics/TopicsFilters.tsxdeleted file mode 100644index 82ddc8c480..0000000000--- a/web/src/features/topics/TopicsFilters.tsx+++ /dev/null@@ -1,54 +0,0 @@-import { Plus } from "@langfuse/icons";-import { Badge } from "@/src/components/design-system/Badge/Badge";-import { Button } from "@/src/components/design-system/Button/Button";-import { type ReactNode } from "react";-import { Tabs } from "@/src/components/design-system/Tabs/Tabs";-import { resolveTopicFacetId } from "./topic-facet-selection";--export function TopicsFilters({- facets,- selectedFacetId,- onSelectFacet,- children,-}: TopicsFiltersProps) {- const selectedFacet = resolveTopicFacetId(facets, selectedFacetId);- if (!selectedFacet) return children;-- return (- <div className="ph-no-capture flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">- <Tabs value={selectedFacet} onValueChange={onSelectFacet} layout="fill">- <div className="shrink-0 overflow-x-auto">- <Tabs.List variant="underline" aria-label="Topics facets">- {facets.map((facet) => (- <Tabs.Trigger- key={facet.facetId}- value={facet.facetId}- label={facet.name}- />- ))}- <div className="flex shrink-0 items-center gap-1 px-2">- <Button- text="Custom facet"- icon={Plus}- variant="ghost"- size="sm"- disabled- />- <Badge text="Coming soon" color="blue" size="sm" />- </div>- </Tabs.List>- </div>- <Tabs.Content value={selectedFacet} layout="fill">- <div className="flex min-h-0 flex-1 flex-col pt-2">{children}</div>- </Tabs.Content>- </Tabs>- </div>- );-}--type TopicsFiltersProps = {- facets: readonly { facetId: string; name: string }[];- selectedFacetId: string | undefined;- onSelectFacet: (facetId: string) => void;- children?: ReactNode;-};diff --git a/web/src/features/topics/TopicsPage.tsx b/web/src/features/topics/TopicsPage.tsxindex 2c8d0d93c2..a128c096a4 100644--- a/web/src/features/topics/TopicsPage.tsx+++ b/web/src/features/topics/TopicsPage.tsx@@ -41,7 +41,14 @@ import {} from "@langfuse/shared/topics";import { useTopicPipelineForm } from "./TopicPipelineForm";import { ManualTopicsFormContent } from "./ManualTopicsFormContent";+import { cn } from "@/src/utils/tailwind";+import { TopicsFacetTabs } from "./TopicsFacetTabs";+import { resolveTopicFacetId } from "./topic-facet-selection";import { TopicsHeaderActions } from "./TopicsHeaderActions";+import {+ TopicsResultsViewSelect,+ useTopicsResultsView,+} from "./TopicsResultsViewSelect";import { DialogController } from "@/src/components/design-system/DialogController/DialogController";import { HeaderActionMenuRow } from "@/src/components/HeaderActionMenuRow";import { useRegenerateTopics } from "./useRegenerateTopics";@@ -50,7 +57,6 @@ import { AutomaticProcessingDialogController } from "./AutomaticProcessingDialogimport { ConfigureTopicsDialogController } from "./ConfigureTopicsDialogController";import { TopicSetupNotice } from "./TopicSetupNotice";import { CurrentTopics, useCurrentTopics } from "./CurrentTopics";-import { TopicsFilters } from "./TopicsFilters";import { TopicsActionsMenu } from "./TopicsActionsMenu";import { TopicsWorkspaceGate } from "./TopicsWorkspaceGate";import { isValidTopicTimeRange } from "./time-range";@@ -188,6 +194,7 @@ function TopicsWorkspaceContent({openAutomaticProcessing,}: TopicsWorkspaceContentProps) {const [historyOpen, setHistoryOpen] = useState(false);+ const [resultsView, setResultsView] = useTopicsResultsView();const [generationRange, setGenerationRange] = useState<{selection: TimeRange;bounds: TopicTimeRange;@@ -386,6 +393,10 @@ function TopicsWorkspaceContent({openManual("update");}const hasStoredSummaries = Boolean(results.data?.hasStoredSummaries);+ const headerFacetId = resolveTopicFacetId(+ results.data?.facets ?? [],+ selectedFacetId,+ );const showOnboarding =validTimeRange &&results.data !== undefined &&@@ -396,10 +407,24 @@ function TopicsWorkspaceContent({<PageheaderProps={{title: "Topics",- help: {- description:- "Explore recurring themes across traces, one facet at a time.",- },+ actionButtonsLeft: showOnboarding ? null : (+ <div className="flex items-center gap-3">+ {validTimeRange && headerFacetId && (+ <TopicsFacetTabs+ facets={results.data?.facets ?? []}+ selectedFacet={headerFacetId}+ onSelectFacet={traceFilters.selectFacet}+ />+ )}+ <span className="text-muted-foreground flex items-center gap-1 text-sm">+ Visualize as+ <TopicsResultsViewSelect+ value={resultsView}+ onValueChange={setResultsView}+ />+ </span>+ </div>+ ),actionButtonsRight: (<TopicsHeaderActionsautomaticProcessing={automaticProcessing}@@ -458,7 +483,12 @@ function TopicsWorkspaceContent({/></PageHeaderControlsPortal>)}- <div className="ph-no-capture flex min-h-0 flex-1 flex-col gap-2 overflow-hidden p-2">+ <div+ className={cn(+ "ph-no-capture flex min-h-0 flex-1 flex-col gap-2 overflow-hidden",+ showOnboarding && "p-2",+ )}+ >{isTimeRangeCapped && (<prole="status"@@ -582,22 +612,18 @@ function TopicsWorkspaceContent({widthStorageKey="topicsPeekViewWidthFraction"/>{validTimeRange && !showOnboarding && (- <TopicsFilters- facets={results.data?.facets ?? []}- selectedFacetId={selectedFacetId}- onSelectFacet={traceFilters.selectFacet}- >+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden"><CurrentTopicsprojectId={projectId}timeRange={currentTimeRange}result={results}selectedFacetId={selectedFacetId}- traceFilters={traceFilters}+ view={resultsView}tracePanelRef={setTracePanel}onGenerateTopics={openTopicGeneration}canGenerateTopics={canWrite && !running && configured}/>- </TopicsFilters>+ </div>)}{facets.isLoading && <p>Loading facets…</p>}{facets.error && (diff --git a/web/src/features/topics/TopicsResultsViewSelect.tsx b/web/src/features/topics/TopicsResultsViewSelect.tsxnew file mode 100644index 0000000000..5f46056e2c--- /dev/null+++ b/web/src/features/topics/TopicsResultsViewSelect.tsx@@ -0,0 +1,63 @@+import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";+import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import useLocalStorage from "@/src/components/useLocalStorage";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";++const VIEWS = [+ { value: "treemap", label: "Treemap" },+ { value: "grid", label: "Grid" },+] as const;++export type TopicsResultsView = (typeof VIEWS)[number]["value"];++export function TopicsResultsViewSelect({+ value,+ onValueChange,+}: TopicsResultsViewSelectProps) {+ const capture = usePostHogClientCapture();+ function changeView(view: TopicsResultsView) {+ if (view === value) return;+ capture("topics:results_view_select", { view, previousView: value });+ onValueChange(view);+ }+ const selected = VIEWS.find((option) => option.value === value);+ return (+ <DropdownMenu+ ariaLabel="Topics view"+ items={VIEWS.map((option) => ({+ type: "item" as const,+ id: option.value,+ title: option.label,+ onClick: () => changeView(option.value),+ }))}+ >+ {({ getTriggerProps }) => (+ <button+ {...getTriggerProps()}+ type="button"+ aria-label={`Topics view: ${selected?.label ?? ""}`}+ className="text-foreground hover:bg-accent focus-visible:ring-ring inline-flex items-center gap-1 rounded-md px-2 py-1 text-sm font-bold focus-visible:ring-2 focus-visible:outline-hidden"+ >+ {selected?.label}+ <DropdownIndicator />+ </button>+ )}+ </DropdownMenu>+ );+}++export function useTopicsResultsView() {+ const [view, setView] = useLocalStorage<TopicsResultsView>(+ "topicsResultsView",+ "treemap",+ );+ return [+ VIEWS.some((option) => option.value === view) ? view : "treemap",+ setView,+ ] as const;+}++type TopicsResultsViewSelectProps = {+ value: TopicsResultsView;+ onValueChange: (view: TopicsResultsView) => void;+};diff --git a/web/src/features/topics/TopicsTraceToolbar.stories.tsx b/web/src/features/topics/TopicsTraceToolbar.stories.tsxdeleted file mode 100644index 17469b0c77..0000000000--- a/web/src/features/topics/TopicsTraceToolbar.stories.tsx+++ /dev/null@@ -1,320 +0,0 @@-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.tsxdeleted file mode 100644index a0091a2394..0000000000--- a/web/src/features/topics/TopicsTraceToolbar.tsx+++ /dev/null@@ -1,56 +0,0 @@-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/TopicsWorkspaceGate.stories.tsx b/web/src/features/topics/TopicsWorkspaceGate.stories.tsxindex f4253cfa6c..92711c1e19 100644--- a/web/src/features/topics/TopicsWorkspaceGate.stories.tsx+++ b/web/src/features/topics/TopicsWorkspaceGate.stories.tsx@@ -2,13 +2,13 @@ import { useState } from "react";import { expect, fn, userEvent, within } from "storybook/test";import preview from "../../../.storybook/preview";import { Button } from "@/src/components/design-system/Button/Button";-import { TopicsFilters } from "./TopicsFilters";+import { TopicsFacetTabs } from "./TopicsFacetTabs";import { TopicsWorkspaceGate } from "./TopicsWorkspaceGate";const controls = (- <TopicsFilters+ <TopicsFacetTabsfacets={[{ facetId: "intent", name: "Intent" }]}- selectedFacetId="intent"+ selectedFacet="intent"onSelectFacet={fn()}/>);diff --git a/web/src/features/topics/facet-topics.ts b/web/src/features/topics/facet-topics.tsnew file mode 100644index 0000000000..869e3112fb--- /dev/null+++ b/web/src/features/topics/facet-topics.ts@@ -0,0 +1,61 @@+import {+ encodeFiltersGeneric,+ MAX_URL_FILTER_QUERY_LENGTH,+} from "@langfuse/shared";+import { type RouterOutputs } from "@/src/utils/api";+import { rangeToString } from "@/src/utils/date-range-utils";++export type Facet = RouterOutputs["topics"]["currentResults"]["facets"][number];+export type FacetRow = Facet["rows"][number];+export type FacetTopic = Facet["topics"][number];++/** Map topics first, then topics only seen in assignments. Index order drives topic colors in every view. */+export function orderedFacetTopics(facet: Facet) {+ if (!facet.map) return facet.topics;+ const mapped = facet.map.topics;+ return [+ ...mapped,+ ...facet.topics.filter(+ (topic) => !mapped.some((item) => item.id === topic.id),+ ),+ ];+}++/** Tracing link limited to these traces and their time span; null when the IDs exceed the URL budget. */+export function topicTracesHref(+ projectId: string,+ rows: FacetRow[],+ isV4: boolean,+) {+ if (rows.length === 0) return null;+ const filter = encodeFiltersGeneric([+ // v4 lists observations; root ones stand for their traces.+ ...(isV4+ ? [+ {+ column: "isRootObservation",+ type: "boolean" as const,+ operator: "=" as const,+ value: true,+ },+ ]+ : []),+ {+ column: isV4 ? "traceId" : "id",+ type: "stringOptions",+ operator: "any of",+ value: rows.map((row) => row.traceId),+ },+ ]);+ if (filter.length > MAX_URL_FILTER_QUERY_LENGTH) return null;+ const times = rows.map((row) => new Date(row.unitStartTime).getTime());+ const dateRange = rangeToString({+ from: new Date(Math.min(...times) - 60_000),+ to: new Date(Math.max(...times) + 60_000),+ });+ return `/project/${projectId}/traces?filter=${encodeURIComponent(filter)}&dateRange=${encodeURIComponent(dateRange)}`;+}++export function allTopicsLabel(facetName: string) {+ return `${facetName} summaries`;+}diff --git a/web/src/features/topics/map/TopicMapCanvas.tsx b/web/src/features/topics/map/TopicMapCanvas.tsxdeleted file mode 100644index 920ee3bf84..0000000000--- a/web/src/features/topics/map/TopicMapCanvas.tsx+++ /dev/null@@ -1,293 +0,0 @@-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.tsxdeleted file mode 100644index 7c615053ea..0000000000--- a/web/src/features/topics/map/TopicMapExplorer.tsx+++ /dev/null@@ -1,785 +0,0 @@-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.tsdeleted file mode 100644index 3a705cc357..0000000000--- a/web/src/features/topics/map/prepare-topic-map.ts+++ /dev/null@@ -1,729 +0,0 @@-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.tsdeleted file mode 100644index 64a467b546..0000000000--- a/web/src/features/topics/map/topic-map-store.ts+++ /dev/null@@ -1,147 +0,0 @@-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.cssdeleted file mode 100644index ebf656aa10..0000000000--- a/web/src/features/topics/map/topic-map.module.css+++ /dev/null@@ -1,47 +0,0 @@-.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-grid-layout.clienttest.ts b/web/src/features/topics/topic-grid-layout.clienttest.tsnew file mode 100644index 0000000000..1cc4a73b51--- /dev/null+++ b/web/src/features/topics/topic-grid-layout.clienttest.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from "vitest";+import {+ layoutTopicGrid,+ sampleGridPoints,+ type GridPoint,+} from "./topic-grid-layout";++function cluster(topicIndex: number, cx: number, cy: number, n: number) {+ return Array.from({ length: n }, (_, i): GridPoint => {+ const angle = (i * 2.399963) % (Math.PI * 2);+ const radius = Math.sqrt(i / n) * 0.8;+ return {+ id: `t${topicIndex}-${i}`,+ x: cx + Math.cos(angle) * radius,+ y: cy + Math.sin(angle) * radius,+ topicIndex,+ };+ });+}++const points = [+ ...cluster(0, -5, -5, 60),+ ...cluster(1, 5, 5, 60),+ ...cluster(-1, 0, 0, 10),+];++describe("layoutTopicGrid", () => {+ it("places every point in its own cell inside the grid", () => {+ const layout = layoutTopicGrid(points, 16 / 9);+ const keys = new Set(layout.cells.map((cell) => `${cell.col},${cell.row}`));+ expect(keys.size).toBe(points.length);+ expect(layout.cells.length).toBe(points.length);+ for (const cell of layout.cells) {+ expect(cell.col).toBeGreaterThanOrEqual(0);+ expect(cell.col).toBeLessThan(layout.cols);+ expect(cell.row).toBeGreaterThanOrEqual(0);+ expect(cell.row).toBeLessThan(layout.rows);+ }+ });++ it("is deterministic for the same input", () => {+ const shuffled = [...points].reverse();+ expect(layoutTopicGrid(points, 1.5)).toEqual(layoutTopicGrid(points, 1.5));+ expect(layoutTopicGrid(shuffled, 1.5)).toEqual(+ layoutTopicGrid(points, 1.5),+ );+ });++ it("keeps far-apart clusters apart", () => {+ const layout = layoutTopicGrid(points, 1);+ const colsOf = (topic: number) =>+ layout.cells+ .filter((cell) => cell.topicIndex === topic)+ .map((c) => c.col);+ expect(Math.max(...colsOf(0))).toBeLessThan(Math.min(...colsOf(1)));+ });++ it("samples large inputs per topic, keeping topic shares", () => {+ const points = Array.from({ length: 5000 }, (_, index) => ({+ id: `t-${String(index).padStart(4, "0")}`,+ x: index % 100,+ y: Math.floor(index / 100),+ topicIndex: index < 4000 ? 0 : 1,+ }));+ const { points: sampled, perDot } = sampleGridPoints(points, 1000);+ expect(perDot).toBe(5);+ expect(sampled.filter((point) => point.topicIndex === 0)).toHaveLength(800);+ expect(sampled.filter((point) => point.topicIndex === 1)).toHaveLength(200);+ expect(+ sampled.reduce((sum, point) => sum + (point.memberIds?.length ?? 0), 0),+ ).toBe(5000);+ expect(sampleGridPoints(points.slice(0, 900), 1000).perDot).toBe(1);+ });+});diff --git a/web/src/features/topics/topic-grid-layout.ts b/web/src/features/topics/topic-grid-layout.tsnew file mode 100644index 0000000000..7489ee7eb0--- /dev/null+++ b/web/src/features/topics/topic-grid-layout.ts@@ -0,0 +1,159 @@+export type GridPoint = {+ id: string;+ x: number;+ y: number;+ /** Index into the ordered topic list; negative for outliers. */+ topicIndex: number;+ /** Trace IDs this point stands for when the grid is sampled; first is `id`. */+ memberIds?: string[];+};++export type GridCell = GridPoint & { col: number; row: number };++export type GridLayout = {+ cols: number;+ rows: number;+ cells: GridCell[];+};++/** Most squares drawn; above it each square stands for several traces. */+const MAX_GRID_DOTS = 1000;++/** Bands per axis used to keep each sampled point's members spatially close. */+const SAMPLE_BANDS = 24;++/** One point per run of `perDot` neighbours within a topic, keeping cluster shapes and topic shares. */+export function sampleGridPoints(+ points: GridPoint[],+ maxDots = MAX_GRID_DOTS,+): { points: GridPoint[]; perDot: number } {+ const perDot = Math.max(1, Math.ceil(points.length / maxDots));+ if (perDot === 1) return { points, perDot };+ const byTopic = new Map<number, GridPoint[]>();+ for (const point of points) {+ const list = byTopic.get(point.topicIndex) ?? [];+ list.push(point);+ byTopic.set(point.topicIndex, list);+ }+ const ys = points.map((point) => point.y);+ const minY = Math.min(...ys);+ const spanY = Math.max(...ys) - minY || 1;+ const band = (point: GridPoint) =>+ Math.floor(((point.y - minY) / spanY) * (SAMPLE_BANDS - 1));+ const sampled: GridPoint[] = [];+ for (const list of byTopic.values()) {+ list.sort(+ (a, b) => band(a) - band(b) || a.x - b.x || a.id.localeCompare(b.id),+ );+ for (let index = 0; index < list.length; index += perDot) {+ const members = list.slice(index, index + perDot);+ sampled.push({+ ...members[0],+ memberIds: members.map((member) => member.id),+ });+ }+ }+ return { points: sampled, perDot };+}++/** Cells per point; the slack keeps cluster shapes readable after snapping. */+const CELL_DENSITY = 2.5;++export function layoutTopicGrid(+ points: GridPoint[],+ aspectRatio: number,+): GridLayout {+ if (points.length === 0) return { cols: 0, rows: 0, cells: [] };+ const aspect =+ aspectRatio > 0 && Number.isFinite(aspectRatio) ? aspectRatio : 1;+ const totalCells = Math.ceil(points.length * CELL_DENSITY);+ const cols = Math.max(1, Math.round(Math.sqrt(totalCells * aspect)));+ const rows = Math.max(1, Math.ceil(totalCells / cols));++ const xs = points.map((point) => point.x);+ const ys = points.map((point) => point.y);+ const minX = Math.min(...xs);+ const maxX = Math.max(...xs);+ const minY = Math.min(...ys);+ const maxY = Math.max(...ys);+ const spanX = maxX - minX || 1;+ const spanY = maxY - minY || 1;+ const targets = points.map((point) => ({+ point,+ col: ((point.x - minX) / spanX) * (cols - 1),+ row: ((point.y - minY) / spanY) * (rows - 1),+ }));++ const centroids = new Map<number, { col: number; row: number; n: number }>();+ for (const target of targets) {+ const centroid = centroids.get(target.point.topicIndex) ?? {+ col: 0,+ row: 0,+ n: 0,+ };+ centroid.col += target.col;+ centroid.row += target.row;+ centroid.n += 1;+ centroids.set(target.point.topicIndex, centroid);+ }+ const ordered = targets+ .map((target) => {+ const centroid = centroids.get(target.point.topicIndex)!;+ const dc = target.col - centroid.col / centroid.n;+ const dr = target.row - centroid.row / centroid.n;+ return { ...target, distance: Math.hypot(dc, dr) };+ })+ .sort(+ (a, b) =>+ Number(a.point.topicIndex < 0) - Number(b.point.topicIndex < 0) ||+ a.distance - b.distance ||+ compareIds(a.point.id, b.point.id),+ );++ const taken = new Uint8Array(cols * rows);+ const cells: GridCell[] = [];+ for (const target of ordered) {+ const cell = nearestFreeCell(target.col, target.row, cols, rows, taken);+ taken[cell.row * cols + cell.col] = 1;+ cells.push({ ...target.point, col: cell.col, row: cell.row });+ }+ cells.sort((a, b) => compareIds(a.id, b.id));++ return { cols, rows, cells };+}++function nearestFreeCell(+ targetCol: number,+ targetRow: number,+ cols: number,+ rows: number,+ taken: Uint8Array,+) {+ const startCol = clamp(Math.round(targetCol), 0, cols - 1);+ const startRow = clamp(Math.round(targetRow), 0, rows - 1);+ const maxRadius = Math.max(cols, rows);+ for (let radius = 0; radius <= maxRadius; radius++) {+ let best: { col: number; row: number; distance: number } | null = null;+ for (let row = startRow - radius; row <= startRow + radius; row++) {+ if (row < 0 || row >= rows) continue;+ const onEdge = Math.abs(row - startRow) === radius;+ const step = onEdge || radius === 0 ? 1 : radius * 2;+ for (let col = startCol - radius; col <= startCol + radius; col += step) {+ if (col < 0 || col >= cols || taken[row * cols + col]) continue;+ const distance = Math.hypot(col - targetCol, row - targetRow);+ if (!best || distance < best.distance) best = { col, row, distance };+ }+ }+ if (best) return best;+ }+ throw new Error("Grid has fewer cells than points");+}++function compareIds(a: string, b: string) {+ if (a === b) return 0;+ return a < b ? -1 : 1;+}++function clamp(value: number, min: number, max: number) {+ return Math.min(max, Math.max(min, value));+}diff --git a/web/src/features/topics/topic-map-colors.ts b/web/src/features/topics/topic-map-colors.tsindex 65060092a9..4bb5a6000b 100644--- a/web/src/features/topics/topic-map-colors.ts+++ b/web/src/features/topics/topic-map-colors.ts@@ -1,21 +1,58 @@/** Canvas colors match the category tokens in styles/globals.css. */const COLORS = [- { 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" },+ "#7c3aed",+ "#0284c7",+ "#059669",+ "#d97706",+ "#db2777",+ "#4f46e5",+ "#0d9488",+ "#c2410c",+ "#65a30d",+ "#a21caf",] as const;export const topicColor = (index: number) =>- index < 0 ? "#94a3b8" : COLORS[index % COLORS.length].color;+ index < 0 ? "#94a3b8" : COLORS[index % COLORS.length];-export const topicBadgeColor = (- index: number,-): (typeof COLORS)[number]["badgeColor"] | "primary" =>- index < 0 ? "primary" : COLORS[index % COLORS.length].badgeColor;+const TREEMAP_HUES = [+ {+ big: "bg-category-violet-highlight/35",+ small: "bg-category-violet-highlight/20",+ active: "bg-category-violet-highlight",+ hover: "hover:bg-category-violet-highlight",+ },+ {+ big: "bg-category-blue-highlight/35",+ small: "bg-category-blue-highlight/20",+ active: "bg-category-blue-highlight",+ hover: "hover:bg-category-blue-highlight",+ },+ {+ big: "bg-category-amber-highlight/35",+ small: "bg-category-amber-highlight/20",+ active: "bg-category-amber-highlight",+ hover: "hover:bg-category-amber-highlight",+ },+] as const;++export const treemapTileClasses = (rank: number, big: boolean) => {+ const hue = TREEMAP_HUES[Math.max(0, rank) % TREEMAP_HUES.length];+ return {+ tile: big ? hue.big : hue.small,+ active: hue.active,+ hover: hue.hover,+ };+};++export const treemapSwatchColor = (rank: number) =>+ `var(--category-${["violet", "blue", "amber"][Math.max(0, rank) % 3]}-highlight)`;++/** Grey tile for traces without a topic. */+export const unassignedTileClasses = {+ tile: "bg-category-neutral-tint",+ active: "bg-category-neutral-highlight",+ hover: "hover:bg-category-neutral-highlight",+};++export const UNASSIGNED_SWATCH_COLOR = "var(--category-neutral-highlight)";diff --git a/web/src/features/topics/topic-map-geometry.clienttest.ts b/web/src/features/topics/topic-map-geometry.clienttest.tsdeleted file mode 100644index 64a0e7eb9c..0000000000--- a/web/src/features/topics/topic-map-geometry.clienttest.ts+++ /dev/null@@ -1,824 +0,0 @@-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.tsindex 98f85c8b78..b81af23a8d 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";-export const TOPIC_ASSIGNMENT_OPTIONS = [+const TOPIC_ASSIGNMENT_OPTIONS = [{ value: "assigned", displayValue: "In a topic" },{ value: "outlier", displayValue: "Outlier" },{ value: "no_topic", displayValue: "No topic" },diff --git a/web/src/features/topics/topic-treemap-layout.ts b/web/src/features/topics/topic-treemap-layout.tsnew file mode 100644index 0000000000..2b0ff8550d--- /dev/null+++ b/web/src/features/topics/topic-treemap-layout.ts@@ -0,0 +1,42 @@+import { hierarchy, treemap, treemapSquarify } from "d3-hierarchy";++export type TreemapTile<T> = {+ item: T;+ x: number;+ y: number;+ width: number;+ height: number;+};++type TreemapNode<T> = { item?: T; children?: TreemapNode<T>[] };++export function layoutTreemap<T extends { count: number }>(+ items: T[],+ width: number,+ height: number,+ gap: number,+): TreemapTile<T>[] {+ if (width <= 0 || height <= 0 || items.length === 0) return [];+ const root = hierarchy<TreemapNode<T>>({+ children: items.map((item) => ({ item })),+ }).sum((node) => node.item?.count ?? 0);+ return treemap<TreemapNode<T>>()+ .tile(treemapSquarify)+ .size([width, height])+ .paddingInner(gap)+ .round(true)(root)+ .leaves()+ .flatMap((leaf) =>+ leaf.data.item+ ? [+ {+ item: leaf.data.item,+ x: leaf.x0,+ y: leaf.y0,+ width: leaf.x1 - leaf.x0,+ height: leaf.y1 - leaf.y0,+ },+ ]+ : [],+ );+}diff --git a/web/src/styles/globals.css b/web/src/styles/globals.cssindex 3844ebcccc..93e3f6794b 100644--- a/web/src/styles/globals.css+++ b/web/src/styles/globals.css@@ -148,6 +148,12 @@--color-category-orange: #c2410c;--color-category-lime: #65a30d;--color-category-fuchsia: #a21caf;+ /* Category fills at one OKLCH lightness and chroma per state. */+ --color-category-violet-highlight: var(--category-violet-highlight);+ --color-category-blue-highlight: var(--category-blue-highlight);+ --color-category-amber-highlight: var(--category-amber-highlight);+ --color-category-neutral-tint: var(--category-neutral-tint);+ --color-category-neutral-highlight: var(--category-neutral-highlight);/* Search-bar query syntax highlighting (key:value token parts). Operators(`:` `-` `(` `)`) reuse muted-foreground, so no token for them here. */@@ -335,6 +341,11 @@@layer base {:root {+ --category-violet-highlight: oklch(0.82 0.11 293);+ --category-blue-highlight: oklch(0.82 0.11 252);+ --category-amber-highlight: oklch(0.82 0.11 70);+ --category-neutral-tint: oklch(0.92 0 0);+ --category-neutral-highlight: oklch(0.82 0 0);--background: 0 0% 100%;--foreground: 240 3.7% 15.9%; /* zinc-800 */@@ -561,6 +572,11 @@}.dark {+ --category-violet-highlight: oklch(0.45 0.11 293);+ --category-blue-highlight: oklch(0.45 0.11 252);+ --category-amber-highlight: oklch(0.45 0.11 70);+ --category-neutral-tint: oklch(0.3 0 0);+ --category-neutral-highlight: oklch(0.45 0 0);/* Surface ladder — "layers become one step lighter with each addedlayer" (Carbon's dark-theme layering model; Hex and Cloudflare Kumofollow the same structure). The GLOBAL FRAME (header/sidebar chrome)