🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(topics): add adaptive map exploration and compact workspace (#18492)
Nikita Kabardinab8afebee5bf
diff --git a/web/src/__tests__/server/unit/topics.servertest.ts b/web/src/__tests__/server/unit/topics.servertest.tsindex 3d74235d7f..b5fe985703 100644--- a/web/src/__tests__/server/unit/topics.servertest.ts+++ b/web/src/__tests__/server/unit/topics.servertest.ts@@ -976,6 +976,47 @@ describe("Topics local execution access and publication", () => {});describe("Topics current results", () => {+ it("retains published map descriptions when reprocessed traces await assignment", async () => {+ mocks.listTopicFacets.mockResolvedValue([+ { id: facetId, name: "Intent", versions: [{ version: facetVersion }] },+ ]);+ mocks.getPublishedTopicRun.mockResolvedValue(run);+ mocks.getLatestFacetSummaries.mockResolvedValue([+ { ...summary, processedAt: "2026-09-17T00:00:00Z" },+ ]);+ mocks.readLatestTopicAssignments.mockResolvedValue([+ {+ projectId,+ facetId,+ facetVersion,+ traceId: summary.traceId,+ unitStartTime: summary.unitStartTime,+ summaryProcessedAt: summary.processedAt,+ topicId: run.topics[0].topicId,+ runId: run.id,+ },+ ]);++ const [result] = await caller("VIEWER").currentResults({+ projectId,+ timeRange,+ });++ expect(result.topics).toEqual([]);+ expect(result.rows[0]).toMatchObject({+ outcome: "awaiting_map",+ topicId: null,+ });+ expect(result.map?.topics).toEqual([+ {+ id: run.topics[0].topicId,+ name: run.topics[0].name,+ description: run.topics[0].description,+ },+ ]);+ expect(mocks.getTopicRuns).toHaveBeenCalledExactlyOnceWith(projectId, []);+ });+it("serves current and historical topic names to viewers without exposing vectors", async () => {mocks.listTopicFacets.mockResolvedValue([{diff --git a/web/src/components/design-system/CustomTooltip/CustomTooltip.tsx b/web/src/components/design-system/CustomTooltip/CustomTooltip.tsxindex eaab57c72b..818ac11ef7 100644--- a/web/src/components/design-system/CustomTooltip/CustomTooltip.tsx+++ b/web/src/components/design-system/CustomTooltip/CustomTooltip.tsx@@ -18,6 +18,7 @@ import {import * as React from "react";import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";+import { cn } from "@/src/utils/tailwind";type CustomTooltipProps = {children: (controls: {@@ -88,7 +89,10 @@ function CustomTooltip({<FloatingPortal root={layerContainer}><divref={refs.setFloating}- className="bg-popover text-popover-foreground animate-in fade-in-0 zoom-in-95 max-w-xs overflow-hidden rounded-md border px-3 py-1.5 text-sm shadow-md"+ className={cn(+ "bg-popover text-popover-foreground animate-in fade-in-0 zoom-in-95 max-w-xs overflow-hidden rounded-md border px-3 py-1.5 text-sm shadow-md",+ !hoverableContent && "pointer-events-none",+ )}style={floatingStyles}{...getFloatingProps()}>diff --git a/web/src/components/design-system/Tooltip/Tooltip.stories.tsx b/web/src/components/design-system/Tooltip/Tooltip.stories.tsxindex 6733b81e4f..9f549b6d2b 100644--- a/web/src/components/design-system/Tooltip/Tooltip.stories.tsx+++ b/web/src/components/design-system/Tooltip/Tooltip.stories.tsx@@ -55,9 +55,11 @@ export const TestHoverAndFocus = meta.story({const trigger = canvas.getByRole("button", { name: "Hover or focus me" });await userEvent.hover(trigger);- await waitFor(() =>- expect(body.getByRole("tooltip")).toHaveTextContent("Additional context"),- );+ await waitFor(() => {+ const tooltip = body.getByRole("tooltip");+ expect(tooltip).toHaveTextContent("Additional context");+ expect(getComputedStyle(tooltip).pointerEvents).toBe("auto");+ });await userEvent.unhover(trigger);const viewport = canvasElement.ownerDocument.documentElement;@@ -103,3 +105,16 @@ export const TestShortcutRendersKeycap = meta.story({await expect(kbd).toHaveClass("border");},});++export const TestPointerTransparentContent = meta.story({+ name: "(Test) Pointer transparent content",+ args: { hoverableContent: false },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const trigger = canvas.getByRole("button", { name: "Hover or focus me" });+ await userEvent.hover(trigger);+ const tooltip = await waitFor(() => body.getByRole("tooltip"));+ await expect(getComputedStyle(tooltip).pointerEvents).toBe("none");+ },+});diff --git a/web/src/components/table/peek.tsx b/web/src/components/table/peek.tsxindex 43448eee87..15ff812513 100644--- a/web/src/components/table/peek.tsx+++ b/web/src/components/table/peek.tsx@@ -82,6 +82,8 @@ type TablePeekViewProps = Pick<| "isV4"> & {title?: string;+ defaultWidthTarget?: HTMLElement | null;+ widthStorageKey?: string;/*** Item-specific header actions (star / publish / delete …), shared with the* full detail page so the peek and the page expose the same controls.@@ -220,6 +222,8 @@ function TablePeekViewComponent(props: TablePeekViewProps) {isOpen: !!itemId,isExpanded,onExpandedChange: setExpanded,+ defaultWidthTarget: props.defaultWidthTarget,+ widthStorageKey: props.widthStorageKey,onResized: useCallback((widthFraction: number, trigger: "drag" | "keyboard") => {capture("peek:resized", {@@ -320,7 +324,7 @@ function TablePeekViewComponent(props: TablePeekViewProps) {// fresh provider, dropping that state. It unmounts only on close (the early// `return null` above), which is what resets the state (see README).return (- <PeekTableStateProvider>+ <PeekTableStateProvider getPanelWidthPx={panel.getPanelWidthPx}>{isHandheld ? (// Mobile: a vaul bottom drawer with native swipe-down dismissal.<Drawerdiff --git a/web/src/components/table/peek/contexts/PeekTableStateContext.tsx b/web/src/components/table/peek/contexts/PeekTableStateContext.tsxindex 57cad339ad..b0efd27f73 100644--- a/web/src/components/table/peek/contexts/PeekTableStateContext.tsx+++ b/web/src/components/table/peek/contexts/PeekTableStateContext.tsx@@ -19,13 +19,20 @@ export interface PeekTableState {export interface PeekTableStateContextValue {tableState: PeekTableState;setTableState: Dispatch<SetStateAction<PeekTableState>>;+ getPanelWidthPx?: () => number;}const PeekTableStateContext = createContext<PeekTableStateContextValue | undefined>(undefined);-export function PeekTableStateProvider({ children }: { children: ReactNode }) {+export function PeekTableStateProvider({+ children,+ getPanelWidthPx,+}: {+ children: ReactNode;+ getPanelWidthPx?: () => number;+}) {const [tableState, setTableState] = useState<PeekTableState>({filters: [],sorting: undefined,@@ -33,7 +40,10 @@ export function PeekTableStateProvider({ children }: { children: ReactNode }) {search: { query: null, type: ["id"] },});- const value = useMemo(() => ({ tableState, setTableState }), [tableState]);+ const value = useMemo(+ () => ({ tableState, setTableState, getPanelWidthPx }),+ [tableState, getPanelWidthPx],+ );return (<PeekTableStateContext.Provider value={value}>diff --git a/web/src/components/table/peek/store/peekPanelStore.clienttest.ts b/web/src/components/table/peek/store/peekPanelStore.clienttest.tsindex 91d1787149..eace7e76e9 100644--- a/web/src/components/table/peek/store/peekPanelStore.clienttest.ts+++ b/web/src/components/table/peek/store/peekPanelStore.clienttest.ts@@ -7,6 +7,7 @@ import {PEEK_MAX_WIDGET_WIDTH_FRACTION,PEEK_MIN_WIDTH_FRACTION,resolveDefaultWidthFraction,+ resolveEffectiveWidthFraction,selectDraftExpanded,selectWidgetWidth,} from "@/src/components/table/peek/store/peekPanelStore";@@ -99,6 +100,116 @@ describe("peekPanelStore", () => {);});+ it("fits a local default without replacing other views' preference, then retains an explicit resize", () => {+ window.localStorage.setItem(STORAGE_KEY, "0.7");+ const localKey = "peek-width-topics";+ const store = createPeekPanelStore({ widthStorageKey: localKey });+ store.getState().actions.setDefaultWidth(0.3);+ expect(selectWidgetWidth(store.getState())).toBe("30vw");+ store.getState().actions.setDefaultWidth(0.96);+ expect(selectWidgetWidth(store.getState())).toBe("96vw");+ store.getState().actions.setDefaultWidth(0.35);+ expect(selectWidgetWidth(store.getState())).toBe("35vw");+ expect(window.localStorage.getItem(STORAGE_KEY)).toBe("0.7");+ expect(window.localStorage.getItem(localKey)).toBeNull();++ store.getState().actions.commitWidth(0.55);+ store.getState().actions.setDefaultWidth(0.32);+ expect(selectWidgetWidth(store.getState())).toBe(pct(0.55));+ expect(window.localStorage.getItem(localKey)).toBe("0.55");+ expect(window.localStorage.getItem(STORAGE_KEY)).toBe("0.7");+ const reopened = createPeekPanelStore({ widthStorageKey: localKey });+ reopened.getState().actions.setDefaultWidth(0.32);+ expect(reopened.getState().widthFraction).toBe(0.55);+ });++ it("sizes a scoped peek's inner layout from its live width instead of the shared preference", () => {+ withViewportWidth(1600, () => {+ window.localStorage.setItem(STORAGE_KEY, "0.4");+ const store = createPeekPanelStore({+ widthStorageKey: "peek-width-topics",+ allowLayoutWidths: true,+ });+ store.getState().actions.setDefaultWidth(1000 / 1600);++ expect(+ resolveEffectiveWidthFraction({+ widgetWidthFraction: store.getState().widthFraction,+ }) * window.innerWidth,+ ).toBe(1000);+ expect(resolveEffectiveWidthFraction() * window.innerWidth).toBe(640);+ });+ });++ it("caps widget and expanded layout widths at the sidebar edge", () => {+ withViewportWidth(1600, () => {+ expect(+ resolveEffectiveWidthFraction({+ widgetWidthFraction: 0.96,+ sidebarOffsetPx: 240,+ }) * window.innerWidth,+ ).toBe(1360);+ expect(+ resolveEffectiveWidthFraction({+ widgetWidthFraction: 0.5,+ isExpanded: true,+ sidebarOffsetPx: 240,+ }) * window.innerWidth,+ ).toBe(1360);+ expect(+ resolveEffectiveWidthFraction({+ isExpanded: true,+ sidebarOffsetPx: 1800,+ }),+ ).toBe(0);+ });+ });++ it("returns to a narrow layout width without reversing keyboard or drag resizing", () => {+ const store = createPeekPanelStore({+ widthStorageKey: "peek-width-topics",+ });+ const { actions } = store.getState();+ actions.setDefaultWidth(0.35);+ actions.nudgeWidth("shrink");+ expect(store.getState().widthFraction).toBeCloseTo(0.35);+ actions.nudgeWidth("grow");+ actions.nudgeWidth("shrink");+ expect(store.getState().widthFraction).toBeCloseTo(0.35);+ actions.setDraftFraction(0.36);+ expect(store.getState().draftFraction).toBeCloseTo(0.36);+ actions.commitWidth(0.36);+ expect(store.getState().widthFraction).toBeCloseTo(0.36);+ const reopened = createPeekPanelStore({+ widthStorageKey: "peek-width-topics",+ allowLayoutWidths: true,+ });+ reopened.getState().actions.setDefaultWidth(0.45);+ expect(reopened.getState().widthFraction).toBeCloseTo(0.36);+ reopened.getState().actions.nudgeWidth("shrink");+ expect(reopened.getState().widthFraction).toBeCloseTo(0.36);+ });++ it("does not shrink a wide layout width when asked to grow", () => {+ const store = createPeekPanelStore({+ widthStorageKey: "peek-width-topics",+ });+ const { actions } = store.getState();+ actions.setDefaultWidth(0.96);+ actions.nudgeWidth("grow");+ expect(store.getState().widthFraction).toBeCloseTo(0.96);+ actions.nudgeWidth("shrink");+ expect(store.getState().widthFraction).toBeCloseTo(0.91);+ actions.setDraftFraction(0.93);+ expect(store.getState().draftFraction).toBeCloseTo(0.93);+ actions.commitWidth(0.93);+ const reopened = createPeekPanelStore({+ widthStorageKey: "peek-width-topics",+ allowLayoutWidths: true,+ });+ expect(reopened.getState().widthFraction).toBeCloseTo(0.93);+ });+it("commitWidth clamps, persists, and clears the draft", () => {const store = createPeekPanelStore();store.getState().actions.setDraftExpanded();diff --git a/web/src/components/table/peek/store/peekPanelStore.ts b/web/src/components/table/peek/store/peekPanelStore.tsindex 1d7543d742..c47ab67ef7 100644--- a/web/src/components/table/peek/store/peekPanelStore.ts+++ b/web/src/components/table/peek/store/peekPanelStore.ts@@ -10,7 +10,7 @@ import { createStore, type StoreApi } from "zustand/vanilla";* the URL (`peekView=expanded`, owned by `usePeekNavigation`) so it is shareable* and survives back/forward. This store only owns the widget width and the* transient drag state:- * - **widthFraction** — cross-view persisted widget width (localStorage, a+ * - **widthFraction** — persisted widget width (localStorage, a* resolution-independent viewport fraction).* - **draftFraction / draftExpanded / isResizing** — high-frequency transient* drag state. On pointer-up the drag either commits a widget width or asks the@@ -40,11 +40,11 @@ const KEYBOARD_RESIZE_STEP = 0.05;// the default never lands narrower than the user could drag back to.export const PEEK_MAX_DEFAULT_WIDTH_PX = 1400;-const clampWidthFraction = (fraction: number) =>- Math.min(- PEEK_MAX_WIDGET_WIDTH_FRACTION,- Math.max(PEEK_MIN_WIDTH_FRACTION, fraction),- );+const clampWidthFraction = (+ fraction: number,+ minimum = PEEK_MIN_WIDTH_FRACTION,+ maximum = PEEK_MAX_WIDGET_WIDTH_FRACTION,+) => Math.min(maximum, Math.max(minimum, fraction));// Default width when the user has no saved preference. Viewport-aware: the plain// 50vw fraction, but capped so the resulting px never exceeds@@ -59,37 +59,66 @@ export function resolveDefaultWidthFraction(): number {);}-// The width fraction that will actually be used to open the peek: the saved-// preference (clamped) if present, else the viewport-aware default. SSR-safe-// (returns the plain default when there's no window). Exported so the inner-// tree↔info split can size its default against the real peek width without-// re-measuring the DOM.-export function resolveEffectiveWidthFraction(): number {- if (typeof window === "undefined") return PEEK_DEFAULT_WIDTH_FRACTION;+function readStoredWidthFraction(+ storageKey: string,+ allowLayoutWidths = false,+): number | null {+ if (typeof window === "undefined") return null;try {- const raw = window.localStorage.getItem(STORAGE_KEY);+ const raw = window.localStorage.getItem(storageKey);if (raw !== null) {const parsed = JSON.parse(raw);- if (typeof parsed === "number") return clampWidthFraction(parsed);+ if (typeof parsed === "number" && Number.isFinite(parsed)) {+ if (allowLayoutWidths) return parsed > 0 ? Math.min(1, parsed) : null;+ return clampWidthFraction(parsed);+ }}} catch {// Fall through to the default on any read/parse failure.}- return resolveDefaultWidthFraction();+ return null;+}++/** Resolve the host's visible width; hosts without sizing use the shared preference. */+export function resolveEffectiveWidthFraction({+ widgetWidthFraction,+ isExpanded = false,+ sidebarOffsetPx = 0,+}: {+ widgetWidthFraction?: number;+ isExpanded?: boolean;+ sidebarOffsetPx?: number;+} = {}): number {+ const viewportWidth = typeof window === "undefined" ? 0 : window.innerWidth;+ const maximumFraction =+ viewportWidth > 0+ ? Math.max(0, (viewportWidth - sidebarOffsetPx) / viewportWidth)+ : 1;+ if (isExpanded) return maximumFraction;+ const widgetFraction =+ widgetWidthFraction ??+ readStoredWidthFraction(STORAGE_KEY) ??+ resolveDefaultWidthFraction();+ return Math.min(widgetFraction, maximumFraction);}-function writeStoredWidthFraction(fraction: number): void {+function writeStoredWidthFraction(storageKey: string, fraction: number): void {if (typeof window === "undefined") return;try {- window.localStorage.setItem(STORAGE_KEY, JSON.stringify(fraction));+ window.localStorage.setItem(storageKey, JSON.stringify(fraction));} catch {// Ignore write failures (private mode, quota) — width is a best-effort pref.}}export interface PeekPanelStoreState {- /** Committed widget width (persisted), as a fraction of the viewport. */+ /** Widget width, as a fraction of the viewport. Explicit resizes are persisted. */widthFraction: number;+ /** Resize bounds include a host's layout default and any saved preference. */+ minimumWidthFraction: number;+ maximumWidgetWidthFraction: number;+ /** A saved or explicitly resized width takes precedence over a layout default. */+ hasCustomWidth: boolean;/** Live widget width during a drag; null when not dragging or expanded. */draftFraction: number | null;/** True while a drag is previewing the expanded (max) width. */@@ -97,6 +126,8 @@ export interface PeekPanelStoreState {/** True while the resize handle is being dragged. */isResizing: boolean;actions: {+ /** Fit a host's layout until the user chooses a width. Never persisted. */+ setDefaultWidth: (fraction: number) => void;setResizing: (isResizing: boolean) => void;/** Abandon an in-flight drag without committing (e.g. peek closed mid-drag). */cancelResize: () => void;@@ -113,27 +144,75 @@ export interface PeekPanelStoreState {export type PeekPanelStore = StoreApi<PeekPanelStoreState>;-export function createPeekPanelStore(): PeekPanelStore {+export function createPeekPanelStore({+ widthStorageKey = STORAGE_KEY,+ allowLayoutWidths = false,+}: {+ widthStorageKey?: string;+ /** Retain saved widths outside the shared bounds for a host with layout sizing. */+ allowLayoutWidths?: boolean;+} = {}): PeekPanelStore {+ const storedWidth = readStoredWidthFraction(+ widthStorageKey,+ allowLayoutWidths,+ );return createStore<PeekPanelStoreState>((set, get) => ({- widthFraction: resolveEffectiveWidthFraction(),+ widthFraction: storedWidth ?? resolveDefaultWidthFraction(),+ minimumWidthFraction: Math.min(+ PEEK_MIN_WIDTH_FRACTION,+ storedWidth ?? PEEK_MIN_WIDTH_FRACTION,+ ),+ maximumWidgetWidthFraction: Math.max(+ PEEK_MAX_WIDGET_WIDTH_FRACTION,+ storedWidth ?? PEEK_MAX_WIDGET_WIDTH_FRACTION,+ ),+ hasCustomWidth: storedWidth !== null,draftFraction: null,draftExpanded: false,isResizing: false,actions: {+ setDefaultWidth: (fraction) => {+ if (get().isResizing || !Number.isFinite(fraction) || fraction <= 0)+ return;+ const width = Math.min(1, fraction);+ const customWidth = get().hasCustomWidth ? get().widthFraction : width;+ set({+ minimumWidthFraction: Math.min(+ PEEK_MIN_WIDTH_FRACTION,+ width,+ customWidth,+ ),+ maximumWidgetWidthFraction: Math.max(+ PEEK_MAX_WIDGET_WIDTH_FRACTION,+ width,+ customWidth,+ ),+ ...(!get().hasCustomWidth ? { widthFraction: width } : {}),+ });+ },setResizing: (isResizing) => set({ isResizing }),cancelResize: () =>set({ draftFraction: null, draftExpanded: false, isResizing: false }),setDraftFraction: (fraction) =>set({- draftFraction: clampWidthFraction(fraction),+ draftFraction: clampWidthFraction(+ fraction,+ get().minimumWidthFraction,+ get().maximumWidgetWidthFraction,+ ),draftExpanded: false,}),setDraftExpanded: () => set({ draftExpanded: true, draftFraction: null }),commitWidth: (fraction) => {- const clamped = clampWidthFraction(fraction);- writeStoredWidthFraction(clamped);+ const clamped = clampWidthFraction(+ fraction,+ get().minimumWidthFraction,+ get().maximumWidgetWidthFraction,+ );+ writeStoredWidthFraction(widthStorageKey, clamped);set({widthFraction: clamped,+ hasCustomWidth: true,draftFraction: null,draftExpanded: false,});@@ -141,9 +220,18 @@ export function createPeekPanelStore(): PeekPanelStore {nudgeWidth: (direction) => {const delta =direction === "grow" ? KEYBOARD_RESIZE_STEP : -KEYBOARD_RESIZE_STEP;- const next = clampWidthFraction(get().widthFraction + delta);- writeStoredWidthFraction(next);- set({ widthFraction: next, draftFraction: null, draftExpanded: false });+ const next = clampWidthFraction(+ get().widthFraction + delta,+ get().minimumWidthFraction,+ get().maximumWidgetWidthFraction,+ );+ writeStoredWidthFraction(widthStorageKey, next);+ set({+ widthFraction: next,+ hasCustomWidth: true,+ draftFraction: null,+ draftExpanded: false,+ });},},}));@@ -160,4 +248,4 @@ export const selectDraftExpanded = (state: PeekPanelStoreState) =>* computed by the hook, since it depends on the live sidebar offset.*/export const selectWidgetWidth = (state: PeekPanelStoreState): string =>- `${clampWidthFraction(state.draftFraction ?? state.widthFraction) * 100}vw`;+ `${(state.draftFraction ?? state.widthFraction) * 100}vw`;diff --git a/web/src/components/table/peek/usePeekPanelState.clienttest.tsx b/web/src/components/table/peek/usePeekPanelState.clienttest.tsxindex bed728fbd6..0ee2ee9ca6 100644--- a/web/src/components/table/peek/usePeekPanelState.clienttest.tsx+++ b/web/src/components/table/peek/usePeekPanelState.clienttest.tsx@@ -36,7 +36,11 @@ function pressArrow(describe("usePeekPanelState", () => {beforeEach(() => window.localStorage.clear());- afterEach(() => window.localStorage.clear());+ afterEach(() => {+ window.localStorage.clear();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });it("renders the widget width and a stable resize-handle contract", () => {const { result } = setup();@@ -57,6 +61,78 @@ describe("usePeekPanelState", () => {expect(String(result.current.panelStyle.width)).toContain("calc(100vw");});+ it("measures a late layout target, follows its resize, and preserves a user resize", () => {+ window.localStorage.setItem(STORAGE_KEY, "0.8");+ let resized: (() => void) | undefined;+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(callback: () => void) {+ resized = callback;+ }+ observe() {}+ disconnect() {}+ },+ );+ let targetWidth = window.innerWidth * 0.32;+ const target = document.createElement("section");+ vi.spyOn(target, "getBoundingClientRect").mockImplementation(+ () => ({ width: targetWidth }) as DOMRect,+ );+ const { result, rerender } = renderHook(+ ({ target }: { target: HTMLElement | null }) =>+ usePeekPanelState({+ isOpen: true,+ isExpanded: false,+ onExpandedChange: vi.fn(),+ defaultWidthTarget: target,+ widthStorageKey: "peek-width-topics",+ }),+ { initialProps: { target: null as HTMLElement | null } },+ );+ rerender({ target });+ expect(widthFraction(result.current.panelStyle)).toBeCloseTo(0.32);++ targetWidth = window.innerWidth * 0.45;+ act(() => resized?.());+ expect(widthFraction(result.current.panelStyle)).toBeCloseTo(0.45);++ pressArrow(result, "ArrowLeft");+ targetWidth = window.innerWidth * 0.35;+ act(() => window.dispatchEvent(new Event("resize")));+ expect(widthFraction(result.current.panelStyle)).toBeCloseTo(0.5);+ expect(window.localStorage.getItem(STORAGE_KEY)).toBe("0.8");+ expect(window.localStorage.getItem("peek-width-topics")).toBe("0.5");+ });++ it("restores a narrow layout preference before its target mounts", () => {+ window.localStorage.setItem("peek-width-topics", "0.35");+ const target = document.createElement("section");+ vi.spyOn(target, "getBoundingClientRect").mockReturnValue({+ width: window.innerWidth * 0.45,+ } as DOMRect);+ const { result, rerender } = renderHook(+ ({ target }: { target: HTMLElement | null }) =>+ usePeekPanelState({+ isOpen: true,+ isExpanded: false,+ onExpandedChange: vi.fn(),+ defaultWidthTarget: target,+ widthStorageKey: "peek-width-topics",+ }),+ { initialProps: { target: null as HTMLElement | null } },+ );+ expect(widthFraction(result.current.panelStyle)).toBeCloseTo(0.35);+ rerender({ target });+ expect(widthFraction(result.current.panelStyle)).toBeCloseTo(0.35);+ pressArrow(result, "ArrowRight");+ expect(widthFraction(result.current.panelStyle)).toBeCloseTo(0.35);+ expect(result.current.resizeHandleProps["aria-valuemin"]).toBe(35);+ pressArrow(result, "ArrowLeft");+ pressArrow(result, "ArrowRight");+ expect(widthFraction(result.current.panelStyle)).toBeCloseTo(0.35);+ });+it("toggleExpanded writes the expanded flag (URL) via the callback", () => {const { result, onExpandedChange } = setup(false);act(() => result.current.toggleExpanded());diff --git a/web/src/components/table/peek/usePeekPanelState.ts b/web/src/components/table/peek/usePeekPanelState.tsindex aa5be33008..ee5d0578fb 100644--- a/web/src/components/table/peek/usePeekPanelState.ts+++ b/web/src/components/table/peek/usePeekPanelState.ts@@ -12,6 +12,7 @@ import {createPeekPanelStore,PEEK_EXPAND_ENTER_FRACTION,PEEK_MIN_WIDTH_FRACTION,+ resolveEffectiveWidthFraction,selectDraftExpanded,selectIsResizing,selectWidgetWidth,@@ -29,6 +30,8 @@ export type PeekPanelView = {isResizing: boolean;/** Inline style (width) for the docked panel. */panelStyle: CSSProperties;+ /** Read the host's live width for mount-time layouts without subscribing to drag updates. */+ getPanelWidthPx: () => number;/** Toggle the expanded view (writes the URL via `onExpandedChange`). */toggleExpanded: () => void;/** Props to spread onto the left-edge resize handle. */@@ -71,10 +74,16 @@ export function usePeekPanelState({isExpanded,onExpandedChange,onResized,+ defaultWidthTarget,+ widthStorageKey,}: {isOpen: boolean;isExpanded: boolean;onExpandedChange: (expanded: boolean) => void;+ /** Match a layout panel's width until this host has an explicit width preference. */+ defaultWidthTarget?: HTMLElement | null;+ /** Isolate a host's resize preference from the shared peek width. */+ widthStorageKey?: string;/*** Notified once per user resize gesture that lands on a widget width — a* completed drag, or a burst of keyboard nudges (debounced). The host's@@ -82,11 +91,44 @@ export function usePeekPanelState({*/onResized?: (widthFraction: number, trigger: "drag" | "keyboard") => void;}): PeekPanelView {- const [store] = useState(() => createPeekPanelStore());+ const [store] = useState(() =>+ createPeekPanelStore({+ widthStorageKey,+ allowLayoutWidths: defaultWidthTarget !== undefined,+ }),+ );const isResizing = useStore(store, selectIsResizing);const draftExpanded = useStore(store, selectDraftExpanded);const widgetWidth = useStore(store, selectWidgetWidth);+ const minimumWidthFraction = useStore(+ store,+ (state) => state.minimumWidthFraction,+ );++ useEffect(() => {+ if (!defaultWidthTarget) return;+ const measure = () => {+ if (window.innerWidth > 0)+ store+ .getState()+ .actions.setDefaultWidth(+ defaultWidthTarget.getBoundingClientRect().width /+ window.innerWidth,+ );+ };+ measure();+ window.addEventListener("resize", measure);+ const observer =+ typeof ResizeObserver !== "undefined"+ ? new ResizeObserver(measure)+ : null;+ observer?.observe(defaultWidthTarget);+ return () => {+ window.removeEventListener("resize", measure);+ observer?.disconnect();+ };+ }, [defaultWidthTarget, store, isResizing]);// Keep the latest callback in a ref so drag/keyboard closures never go// stale and the memoized handlers don't churn on a new callback identity.@@ -164,6 +206,17 @@ export function usePeekPanelState({"--peek-max-width": maxWidth,width: effectiveExpanded ? maxWidth : `min(${widgetWidth}, ${maxWidth})`,};+ const getPanelWidthPx = useCallback(() => {+ if (typeof window === "undefined") return 0;+ const { draftFraction, widthFraction } = store.getState();+ return (+ resolveEffectiveWidthFraction({+ widgetWidthFraction: draftFraction ?? widthFraction,+ isExpanded: effectiveExpanded,+ sidebarOffsetPx: sidebarOffset,+ }) * window.innerWidth+ );+ }, [store, effectiveExpanded, sidebarOffset]);// End an in-flight drag (drop listeners, restore body styles, clear drag// state) on unmount and whenever the peek closes — the host outlives@@ -253,12 +306,13 @@ export function usePeekPanelState({isExpanded: effectiveExpanded,isResizing,panelStyle,+ getPanelWidthPx,toggleExpanded,resizeHandleProps: {role: "separator","aria-orientation": "vertical","aria-label": "Resize peek view",- "aria-valuemin": Math.round(PEEK_MIN_WIDTH_FRACTION * 100),+ "aria-valuemin": Math.round(minimumWidthFraction * 100),"aria-valuemax": 100,"aria-valuenow": widthPercent,tabIndex: 0,diff --git a/web/src/features/topics/CurrentTopics.tsx b/web/src/features/topics/CurrentTopics.tsxindex 22f62a99b2..844d185c95 100644--- a/web/src/features/topics/CurrentTopics.tsx+++ b/web/src/features/topics/CurrentTopics.tsx@@ -1,6 +1,7 @@import type { TopicTimeRange } from "@langfuse/shared/topics";import { Alert } from "@/src/components/design-system/Alert/Alert";-import { useState } from "react";+import { useState, type MouseEvent } from "react";+import { useMediaQuery } from "react-responsive";import { cn } from "@/src/utils/tailwind";import { type OnChangeFn, type PaginationState } from "@tanstack/react-table";import { keepPreviousData, useQuery } from "@tanstack/react-query";@@ -13,40 +14,41 @@ import { Button } from "@/src/components/design-system/Button/Button";import { Badge } from "@/src/components/design-system/Badge/Badge";import { Dialog } from "@/src/components/design-system/Dialog/Dialog";import { DialogController } from "@/src/components/design-system/DialogController/DialogController";-import { Tabs } from "@/src/components/design-system/Tabs/Tabs";import { TextLink } from "@/src/components/design-system/TextLink/TextLink";+import { Tabs } from "@/src/components/design-system/Tabs/Tabs";+import { useIsMobile } from "@/src/hooks/use-mobile";import { TopicEmbeddingMap } from "./TopicEmbeddingMap";+import { TopicGroupCard } from "./TopicGroupCard";import { topicColor } from "./topic-map-colors";import { SummaryInspector } from "./SummaryInspector";+import { isValidTopicTimeRange } from "./time-range";type Facet = RouterOutputs["topics"]["currentResults"][number];export function CurrentTopics({projectId,- running,- refreshAfter,timeRange,+ result,+ selectedFacetId,+ tracePanelRef,}: {projectId: string;- running: boolean;- refreshAfter: number;timeRange: TopicTimeRange;+ result: ReturnType<typeof useCurrentTopics>;+ selectedFacetId: string | undefined;+ tracePanelRef?: (element: HTMLElement | null) => void;}) {- const [selectedFacetId, setSelectedFacetId] = useState<string>();- const result = useCurrentTopics({- projectId,- running,- refreshAfter,- timeRange,- });- const selectedFacet = result.data?.some(+ const selectedFacet = result.data?.find((facet) => facet.facetId === selectedFacetId,- )- ? selectedFacetId- : result.data?.[0]?.facetId;+ );const empty = !result.isLoading && !result.error && result.data?.length === 0;return (- <section className={cn("flex min-w-0 flex-col gap-5", empty && "hidden")}>+ <section+ className={cn(+ "flex min-h-0 min-w-0 flex-1 flex-col gap-2 overflow-hidden",+ empty && "hidden",+ )}+ >{result.error && (<Alert variant="destructive" size="sm"><Alert.Description>@@ -56,28 +58,13 @@ export function CurrentTopics({)}{result.isLoading && <p className="text-sm">Loading topics…</p>}{selectedFacet && (- <Tabs value={selectedFacet} onValueChange={setSelectedFacetId}>- <div className="mb-4 shrink-0 overflow-x-auto">- <Tabs.List aria-label="Facets" variant="underline">- {result.data?.map((facet) => (- <Tabs.Trigger- key={facet.facetId}- value={facet.facetId}- label={facet.name}- />- ))}- </Tabs.List>- </div>- {result.data?.map((facet) => (- <Tabs.Content key={facet.facetId} value={facet.facetId}>- <CurrentFacet- projectId={projectId}- facet={facet}- timeRange={timeRange}- />- </Tabs.Content>- ))}- </Tabs>+ <CurrentFacet+ key={selectedFacet.facetId}+ projectId={projectId}+ facet={selectedFacet}+ timeRange={timeRange}+ tracePanelRef={tracePanelRef}+ />)}</section>);@@ -87,13 +74,17 @@ function CurrentFacet({projectId,facet,timeRange,+ tracePanelRef,}: {projectId: string;facet: Facet;timeRange: TopicTimeRange;+ tracePanelRef?: (element: HTMLElement | null) => void;}) {const [selection, setSelection] = useState<string | null>(null);const [selectedTraceId, setSelectedTraceId] = useState<string | null>(null);+ const isNarrow = useMediaQuery({ query: "(max-width: 1023px)" });+ const [mobilePanel, setMobilePanel] = useState("traces");const [pagination, setPagination] = useState<PaginationState>({pageIndex: 0,pageSize: 20,@@ -103,11 +94,24 @@ function CurrentFacet({setSelectedTraceId(null);setPagination((current) => ({ ...current, pageIndex: 0 }));}+ function selectAllTraces() {+ selectTopic(null);+ }+ function selectOutliers() {+ selectTopic("outliers");+ }+ function selectNoTopic() {+ selectTopic("no_topic");+ }+ function selectAwaitingMap() {+ selectTopic("awaiting_map");+ }const selected =selection === "outliers" ||selection === "no_topic" ||selection === "awaiting_map" ||- facet.topics.some((topic) => topic.id === selection)+ facet.topics.some((topic) => topic.id === selection) ||+ facet.map?.topics.some((topic) => topic.id === selection)? selection: null;const visible = facet.rows.filter((row) => {@@ -135,107 +139,157 @@ function CurrentFacet({]: facet.topics;const counts = (- <p className="text-muted-foreground text-sm">+ <p className="text-muted-foreground text-xs">{facet.rows.length.toLocaleString()} traces · {facet.topics.length} topics{facet.awaitingCount > 0 &&` · ${facet.awaitingCount.toLocaleString()} awaiting a map or updated assignment`}</p>);- return (- <div className="flex min-w-0 flex-col gap-3">- {!facet.map && counts}- {!facet.map && (- <p className="text-muted-foreground text-sm">- {facet.usableCount.toLocaleString()} usable summaries collected for v- {facet.facetVersion ?? 1}. Run Update topics to cluster stored- summaries. You can configure the minimum there.- </p>+ const mapPanel = (+ <section+ aria-label="Topic map"+ className="flex min-h-0 min-w-0 flex-col overflow-hidden"+ >+ {facet.map ? (+ <TopicEmbeddingMap+ timeRange={timeRange}+ projectId={projectId}+ runId={facet.map.runId}+ topics={facet.map.topics}+ selectedTopic={selected}+ onSelectTopic={selectTopic}+ onSelectTrace={setSelectedTraceId}+ selectedTraceId={selectedTraceId}+ fillContainer+ />+ ) : (+ <div className="flex flex-col gap-1 rounded-md border p-2">+ {counts}+ <p className="text-muted-foreground text-xs">+ {facet.usableCount.toLocaleString()} usable summaries collected for+ v{facet.facetVersion ?? 1}. Run Update topics to cluster stored+ summaries. You can configure the minimum there.+ </p>+ </div>)}- <div className="grid min-w-0 gap-3">- {facet.map && (- <div className="flex min-w-0 flex-col gap-3">- <TopicEmbeddingMap- timeRange={timeRange}- projectId={projectId}- runId={facet.map.runId}- topics={facet.map.topics}- selectedTopic={selected}- onSelectTopic={selectTopic}- onSelectTrace={setSelectedTraceId}- selectedTraceId={selectedTraceId}- headerStats={counts}- />- </div>- )}- <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">+ </section>+ );+ const groupsPanel = (+ <section+ aria-label="Topic groups"+ className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-md border"+ >+ <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2">+ <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-1 xl:grid-cols-2">{facet.topics.map((topic) => (- <button+ <TopicGroupCardkey={topic.id}- onClick={() => selectTopic(topic.id)}- className={`hover:bg-muted/50 flex flex-col gap-2 rounded-lg border p-4 text-left ${selected === topic.id ? "border-primary bg-muted/30" : ""}`}- >- <div className="flex w-full items-start justify-between gap-2">- <h4 className="font-bold">- <span- className="mr-2 inline-block h-2.5 w-2.5 rounded-full"- style={{- backgroundColor: topicColor(- topics.findIndex((item) => item.id === topic.id),- ),- }}- />- {topic.name}- </h4>- <Badge text={topic.count.toLocaleString()} />- </div>- <p className="text-muted-foreground text-sm">- {topic.description}- </p>- </button>+ topic={topic}+ isSelected={selected === topic.id}+ color={topicColor(+ topics.findIndex((item) => item.id === topic.id),+ )}+ onSelect={selectTopic}+ />))}</div>- <div className="flex min-w-0 flex-col gap-3">- <div className="flex flex-wrap gap-2">- <Button- text={`All traces (${facet.rows.length.toLocaleString()})`}- size="sm"- variant={selected === null ? "secondary" : "ghost"}- onClick={() => selectTopic(null)}- />- {outliers > 0 && (- <Button- text={`Outliers (${outliers.toLocaleString()})`}- size="sm"- variant={selected === "outliers" ? "secondary" : "ghost"}- onClick={() => selectTopic("outliers")}- />- )}- {noTopic > 0 && (- <Button- text={`No topic (${noTopic.toLocaleString()})`}- size="sm"- variant={selected === "no_topic" ? "secondary" : "ghost"}- onClick={() => selectTopic("no_topic")}- />- )}- {facet.awaitingCount > 0 && (- <Button- text={`Awaiting update (${facet.awaitingCount.toLocaleString()})`}- size="sm"- variant={selected === "awaiting_map" ? "secondary" : "ghost"}- onClick={() => selectTopic("awaiting_map")}- />- )}- </div>- <CurrentTraceTable- projectId={projectId}- facetId={facet.facetId}- rows={visible}- pagination={pagination}- onPaginationChange={setPagination}+ {facet.topics.length === 0 && (+ <p className="text-muted-foreground text-xs">+ No topics yet. Inspect the collected summaries or update topics to+ find recurring groups.+ </p>+ )}+ </div>+ </section>+ );+ const tracesPanel = (+ <section+ aria-label="Topic traces"+ ref={isNarrow ? undefined : tracePanelRef}+ className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-md border lg:col-start-2 lg:row-span-2 lg:row-start-1"+ >+ <div className="flex shrink-0 flex-wrap items-center gap-1 px-2 py-1.5">+ <Button+ text={`All traces (${facet.rows.length.toLocaleString()})`}+ size="sm"+ variant={selected === null ? "secondary" : "ghost"}+ onClick={selectAllTraces}+ />+ {outliers > 0 && (+ <Button+ text={`Outliers (${outliers.toLocaleString()})`}+ size="sm"+ variant={selected === "outliers" ? "secondary" : "ghost"}+ onClick={selectOutliers}/>- </div>+ )}+ {noTopic > 0 && (+ <Button+ text={`No topic (${noTopic.toLocaleString()})`}+ size="sm"+ variant={selected === "no_topic" ? "secondary" : "ghost"}+ onClick={selectNoTopic}+ />+ )}+ {facet.awaitingCount > 0 && (+ <Button+ text={`Awaiting update (${facet.awaitingCount.toLocaleString()})`}+ size="sm"+ variant={selected === "awaiting_map" ? "secondary" : "ghost"}+ onClick={selectAwaitingMap}+ />+ )}</div>+ <CurrentTraceTable+ projectId={projectId}+ facetId={facet.facetId}+ rows={visible}+ pagination={pagination}+ onPaginationChange={setPagination}+ />+ </section>+ );+ return (+ <div+ className={cn(+ "grid min-h-0 min-w-0 flex-1 gap-2 overflow-hidden lg:grid-cols-2",+ facet.map+ ? "grid-rows-[minmax(0,9fr)_minmax(0,11fr)] lg:grid-rows-[minmax(0,3fr)_minmax(0,2fr)]"+ : "grid-rows-[auto_minmax(0,1fr)]",+ )}+ >+ {mapPanel}+ {isNarrow ? (+ <Tabs+ value={mobilePanel}+ onValueChange={setMobilePanel}+ layout="fill"+ ref={tracePanelRef}+ >+ <div className="mb-2 shrink-0">+ <Tabs.List+ variant="inset"+ size="sm"+ layout="full"+ aria-label="Topics panels"+ >+ <Tabs.Trigger value="topics" label="Topics" />+ <Tabs.Trigger value="traces" label="Traces" />+ </Tabs.List>+ </div>+ <Tabs.Content value="topics" layout="fill">+ {groupsPanel}+ </Tabs.Content>+ <Tabs.Content value="traces" layout="fill">+ {tracesPanel}+ </Tabs.Content>+ </Tabs>+ ) : (+ <>+ {groupsPanel}+ {tracesPanel}+ </>+ )}</div>);}@@ -253,6 +307,7 @@ function CurrentTraceTable({pagination: PaginationState;onPaginationChange: OnChangeFn<PaginationState>;}) {+ const isMobile = useIsMobile();const peekNavigation = usePeekNavigation({tableName: "topics-traces",isV4: false,@@ -274,19 +329,26 @@ function CurrentTraceTable({{accessorKey: "traceId",header: "Trace ID",- size: 220,- cell: ({ row }) => (- <TextLink- path={`/project/${projectId}/traces/${encodeURIComponent(row.original.traceId)}`}- value={row.original.traceId}- onClick={() => peekNavigation.openPeek(row.original.traceId)}- />- ),+ size: 132,+ minSize: 100,+ cell: ({ row }) => {+ function openTrace() {+ peekNavigation.openPeek(row.original.traceId);+ }+ return (+ <TextLink+ path={`/project/${projectId}/traces/${encodeURIComponent(row.original.traceId)}`}+ value={row.original.traceId}+ onClick={openTrace}+ />+ );+ },},{accessorKey: "topicName",header: "Topic",- size: 260,+ size: 148,+ minSize: 100,cell: ({ row }) => (<Badgetext={@@ -298,27 +360,51 @@ function CurrentTraceTable({{accessorKey: "summary",header: "Summary",- size: 600,- cell: ({ row }) => (- <div className="flex flex-col items-start gap-2">- <p className="break-words whitespace-pre-wrap">- {row.original.summary || "No applicable summary."}- </p>- <Button- text="Inspect transcript"- variant="ghost"- size="sm"- onClick={(event) => {- event.stopPropagation();- openInspector({- traceId: row.original.traceId,- facetVersion: row.original.facetVersion,- unitStartTime: row.original.unitStartTime,- });- }}- />- </div>- ),+ size: 300,+ minSize: 180,+ isFlexWidth: true,+ cell: ({ row }) => {+ function openTrace() {+ peekNavigation.openPeek(row.original.traceId);+ }+ function inspectTranscript(event: MouseEvent) {+ event.stopPropagation();+ openInspector({+ traceId: row.original.traceId,+ facetVersion: row.original.facetVersion,+ unitStartTime: row.original.unitStartTime,+ });+ }+ return (+ <div className="flex flex-col items-start gap-1 py-1">+ {isMobile && (+ <div className="flex w-full min-w-0 items-center justify-between gap-2">+ <Badge+ text={+ row.original.topicName ??+ row.original.outcome.replaceAll("_", " ")+ }+ size="sm"+ />+ <TextLink+ path={`/project/${projectId}/traces/${encodeURIComponent(row.original.traceId)}`}+ value="Open trace"+ onClick={openTrace}+ />+ </div>+ )}+ <p className="break-words whitespace-pre-wrap">+ {row.original.summary || "No applicable summary."}+ </p>+ <Button+ text="Inspect transcript"+ variant="ghost"+ size="sm"+ onClick={inspectTranscript}+ />+ </div>+ );+ },},];return (@@ -343,10 +429,11 @@ function CurrentTraceTable({)}>{({ openDialog }) => (- <div className="min-h-0 min-w-0 overflow-auto">+ <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden"><DataTabletableName="topics-current-traces"columns={columns(openDialog)}+ columnVisibility={{ traceId: !isMobile, topicName: !isMobile }}data={{isLoading: false,isError: false,@@ -364,7 +451,8 @@ function CurrentTraceTable({options: [20, 50, 100],}}topAlignCells- cellPadding="comfortable"+ className="min-h-0 overscroll-contain"+ cellPadding="compact"noResultsMessage="No traces in this selection."peekView={peekConfig}/>@@ -374,7 +462,7 @@ function CurrentTraceTable({);}-function useCurrentTopics({+export function useCurrentTopics({projectId,running,refreshAfter,@@ -400,6 +488,7 @@ function useCurrentTopics({client.topics.currentResults.query({ projectId, timeRange }, { signal }),placeholderData: keepPreviousData,refetchInterval: running ? 3000 : false,+ enabled: isValidTopicTimeRange(timeRange),});}diff --git a/web/src/features/topics/EmbeddingMapView.stories.tsx b/web/src/features/topics/EmbeddingMapView.stories.tsxindex 4fb3b3ddea..df48731f11 100644--- a/web/src/features/topics/EmbeddingMapView.stories.tsx+++ b/web/src/features/topics/EmbeddingMapView.stories.tsx@@ -1,7 +1,16 @@-import type { ComponentProps } from "react";-import { fn } from "storybook/test";+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: [@@ -26,6 +35,275 @@ const data = {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: {@@ -50,6 +328,578 @@ 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 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(),+ onOpenTrace: 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(args.onOpenTrace).toHaveBeenCalledWith(trace.traceId);+ 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,+ selectedTopic: null,+ selectedTraceId: null,+ onSelectTrace: fn(),+ onOpenTrace: 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),+ );+ 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 expect(args.onOpenTrace).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;+ }+ },});diff --git a/web/src/features/topics/EmbeddingMapView.tsx b/web/src/features/topics/EmbeddingMapView.tsxindex 225ac8f2f5..63469448db 100644--- a/web/src/features/topics/EmbeddingMapView.tsx+++ b/web/src/features/topics/EmbeddingMapView.tsx@@ -1,265 +1,4 @@-import { type ReactNode, useState } from "react";-import { Button } from "@/src/components/design-system/Button/Button";-import { TextLink } from "@/src/components/design-system/TextLink/TextLink";-import { useElementSize } from "@/src/hooks/useElementSize";-import type { RouterOutputs } from "@/src/utils/api";-import { topicColor } from "./topic-map-colors";--type Topic = Pick<- RouterOutputs["topics"]["currentResults"][number]["topics"][number],- "id" | "name"->;-type MapData = Pick<- RouterOutputs["topics"]["map"],- "points" | "missingSummaryCount" | "unpositionedCount"->;-const pointGroup = (point: MapData["points"][number]) =>- point.outcome === "unassigned" ? "unassigned" : (point.topicId ?? "outliers");--function fitMapPoints(- points: MapData["points"],- cohort: MapData["points"],- width: number,- height: number,-) {- const count = Math.max(cohort.length, 1);- const centerX = cohort.reduce((sum, point) => sum + point.x, 0) / count;- const centerY = cohort.reduce((sum, point) => sum + point.y, 0) / count;- let varianceX = 0,- varianceY = 0,- covariance = 0;- for (const point of cohort) {- const dx = point.x - centerX,- dy = point.y - centerY;- varianceX += dx * dx;- varianceY += dy * dy;- covariance += dx * dy;- }- // Align the cohort's principal axis horizontally without changing distances.- // Keep this orientation when zooming into a topic.- const angle = Math.atan2(2 * covariance, varianceX - varianceY) / 2;- const cosine = Math.cos(angle),- sine = Math.sin(angle);- const rotated = points.map((point) => ({- ...point,- x: (point.x - centerX) * cosine + (point.y - centerY) * sine,- y: -(point.x - centerX) * sine + (point.y - centerY) * cosine,- }));- const bounds = rotated.reduce(- (result, point) => ({- minX: Math.min(result.minX, point.x),- maxX: Math.max(result.maxX, point.x),- minY: Math.min(result.minY, point.y),- maxY: Math.max(result.maxY, point.y),- }),- { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity },- );- const { minX, maxX, minY, maxY } = rotated.length- ? bounds- : { minX: 0, maxX: 0, minY: 0, maxY: 0 };- const scale = Math.min(- Math.max(width - 48, 1) / Math.max(maxX - minX, 0.01),- Math.max(height - 48, 1) / Math.max(maxY - minY, 0.01),- );- return rotated.map((point) => ({- ...point,- x: width / 2 + (point.x - (maxX + minX) / 2) * scale,- y: height / 2 - (point.y - (maxY + minY) / 2) * scale,- }));-}--export function EmbeddingMapView({- projectId,- data,- topics,- selectedTopic,- onSelectTopic,- headerStats,- onSelectTrace,- selectedTraceId,- onOpenTrace,-}: {- projectId: string;- data: MapData;- topics: Topic[];- selectedTopic: string | null;- onSelectTopic: (id: string | null) => void;- headerStats?: ReactNode;- onSelectTrace: (traceId: string | null) => void;- selectedTraceId: string | null;- onOpenTrace: (traceId: string) => void;-}) {- const [plotRef, plotSize] = useElementSize<HTMLDivElement>();- const width = plotSize?.width || 960;- const height = plotSize?.height || 320;- const plotted =- selectedTopic === null- ? data.points- : data.points.filter((point) => pointGroup(point) === selectedTopic);- const [hoveredId, setHoveredId] = useState<string | null>(null);- const [focusedId, setFocusedId] = useState<string | null>(null);- const tabStopId = plotted.some((point) => point.traceId === focusedId)- ? focusedId- : plotted[0]?.traceId;- const active =- plotted.find((point) => point.traceId === selectedTraceId) ??- plotted.find((point) => point.traceId === hoveredId);- const groups = [- ...topics.map((topic, index) => ({- id: topic.id,- name: topic.name,- color: topicColor(index),- })),- { id: "outliers", name: "Outliers", color: topicColor(-1) },- { id: "unassigned", name: "Assignment unavailable", color: topicColor(-1) },- ];- const positioned = fitMapPoints(plotted, data.points, width, height);- const activeGroup = active- ? groups.find((group) => group.id === pointGroup(active))- : null;- return (- <section- className="ph-no-capture overflow-hidden rounded-lg border"- aria-label="Embedding map"- >- <div className="flex flex-wrap items-start justify-between gap-3 border-b p-4">- <div>- <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">- <h4 className="font-bold">Embedding map</h4>- {headerStats}- </div>- </div>- <Button- text="All topics"- size="sm"- variant={selectedTopic === null ? "secondary" : "ghost"}- onClick={() => onSelectTopic(null)}- />- </div>- <div ref={plotRef} className="h-48 w-full sm:h-72 lg:h-80">- <svg- viewBox={`0 0 ${width} ${height}`}- className="h-full w-full"- role="group"- aria-label="Two-dimensional UMAP projection of summary embeddings"- >- {plotted.length === 0 && (- <text- x={width / 2}- y={height / 2}- textAnchor="middle"- className="fill-muted-foreground text-sm"- >- No plotted summaries in this selection.- </text>- )}- {positioned.map((point) => {- const color = topicColor(- topics.findIndex((topic) => topic.id === point.topicId),- );- const isActive = active?.traceId === point.traceId;- const select = () => {- onSelectTrace(- selectedTraceId === point.traceId ? null : point.traceId,- );- };- return (- <circle- key={point.traceId}- cx={point.x}- cy={point.y}- r={isActive ? 7 : 4.5}- fill={color}- fillOpacity={0.8}- stroke={isActive ? "currentColor" : color}- strokeWidth={isActive ? 2 : 0.8}- strokeOpacity={1}- role="button"- tabIndex={point.traceId === tabStopId ? 0 : -1}- aria-label={`${point.traceId}: ${point.summary}`}- aria-pressed={selectedTraceId === point.traceId}- className="cursor-pointer focus:outline-2 focus:outline-offset-4"- onClick={select}- onKeyDown={(event) => {- if (event.key === "Enter" || event.key === " ") {- event.preventDefault();- select();- } else if (- [- "ArrowRight",- "ArrowDown",- "ArrowLeft",- "ArrowUp",- "Home",- "End",- ].includes(event.key)- ) {- event.preventDefault();- const dots = Array.from(- event.currentTarget.ownerSVGElement?.querySelectorAll(- "circle",- ) ?? [],- );- const index = dots.indexOf(event.currentTarget);- const direction = ["ArrowRight", "ArrowDown"].includes(- event.key,- )- ? 1- : -1;- let next = (index + direction + dots.length) % dots.length;- if (event.key === "Home") next = 0;- else if (event.key === "End") next = dots.length - 1;- dots[next]?.focus();- }- }}- onMouseEnter={() => setHoveredId(point.traceId)}- onMouseLeave={() => setHoveredId(null)}- onFocus={() => {- setHoveredId(point.traceId);- setFocusedId(point.traceId);- }}- onBlur={() => setHoveredId(null)}- >- <title>- {point.traceId}: {point.summary}- </title>- </circle>- );- })}- </svg>- </div>- <div- className="bg-muted/20 h-32 overflow-y-auto border-t px-4 py-3"- aria-live="polite"- >- {active ? (- <>- <div className="mb-2 flex flex-wrap items-center justify-between gap-2 text-xs">- <span className="font-bold" style={{ color: activeGroup?.color }}>- {activeGroup?.name ?? "Unassigned"}- </span>- <TextLink- path={`/project/${projectId}/traces/${encodeURIComponent(active.traceId)}`}- value={active.traceId}- onClick={() => onOpenTrace(active.traceId)}- />- </div>- <p className="text-sm">{active.summary}</p>- </>- ) : null}- </div>- {(data.unpositionedCount > 0 || data.missingSummaryCount > 0) && (- <p className="text-muted-foreground border-t px-4 py-3 text-xs">- {data.unpositionedCount > 0- ? ` ${data.unpositionedCount} current summaries have no coordinates in this map; they remain in the list below.`- : ""}- {data.missingSummaryCount > 0- ? ` ${data.missingSummaryCount} original summaries are no longer available.`- : ""}- </p>- )}- </section>- );-}--export const __test = { fitMapPoints };+export {+ TopicMapExplorer as EmbeddingMapView,+ __test,+} from "./map/TopicMapExplorer";diff --git a/web/src/features/topics/README.md b/web/src/features/topics/README.mdindex c0c7d59d4f..e856443de0 100644--- a/web/src/features/topics/README.md+++ b/web/src/features/topics/README.md@@ -5,8 +5,16 @@ Topics**. Only platform administrators see or change this personal flag. Thesidebar, direct page, and Topics API also require deployment enablement andproject permissions. Processing additionally requires the project allowlist.-- `TopicsPage.tsx` owns facet configuration and the execution history drawer.- `CurrentTopics.tsx` remains mounted as the only results workspace, including+- `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` presents the selected+ facet in independently scrolling panels: map and groups on the left, traces on+ the right. Narrow views keep the 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.+ 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, errorsand retry controls in the drawer; returning to the run list or closing thedrawer removes only that parameter. Historical map comparison is not exposed.@@ -66,22 +74,53 @@ project permissions. Processing additionally requires the project allowlist.open. It uses the same deterministic transcript loader as the worker, doesnot run inference, and explains when the source is unavailable or may differfrom the original input. Transcript content is marked `ph-no-capture`.-- `TopicEmbeddingMap.tsx` loads the published map by run ID and supplies trace- navigation to the isolated `EmbeddingMapView.tsx`, whose states are shown- in Storybook. A pure geometry unit test protects distance ratios.- The view renders its saved 2D UMAP- coordinates. Clicking a point pins its summary until another selection. Trace IDs- in the map summary open the shared trace peek. The summary area collapses when- inactive and fits its content up to a scrollable maximum height. Cards own- topic filtering, with All topics in the map header to reset it. Topic selection is- shared with the cards and list and fits the plot to that topic's points, making- overlapping groups easier to inspect. Arrow keys navigate a single roving tab- stop; Enter or Space keeps a point selected. The plot uses the measured viewport- and rotates the cohort's principal axis horizontally, then applies one uniform- scale to preserve all relative 2D distances. Topic zoom retains the cohort's- orientation. The shared element-size hook owns the ResizeObserver lifecycle;- geometry is derived during render. Saved coordinates and clustering are unchanged.- Missing-coordinate warnings remain visible below the map.+- `TopicEmbeddingMap.tsx` loads the published map and supplies trace navigation.+ `EmbeddingMapView.tsx` preserves the controlled selection contract as a drop-in+ adapter to `map/TopicMapExplorer.tsx`. The renderer owns no queries or clustering.+ `map/prepare-topic-map.ts` prepares topic zones, colors, mapped-cohort counts,+ camera geometry and collision-bounded node footprints. Saved coordinates are+ the fixed world centers at every zoom; fitting and camera movement use one+ uniform scale. Zones represent existing topics, not a new clustering hierarchy;+ halos and deterministic depth are decorative, not density, severity or quality+ measures. Subtle pointer parallax fades as detail grows; it does not change+ stored positions, topic membership or the spatial arrangement.+ The bird's-eye cloud keeps group labels hidden. Only individual traces show+ hover hints; group context comes from the in-space labels. Each trace grows around+ its fixed center, retaining a filled abstract shape until its actual footprint+ allows summary text. Text starts small, increases with available space and+ fades in as the shape becomes a rounded card. Neighbor+ clearance constrains expansion, including foreign and offscreen neighbors.+ Dense or coincident points keep their hover and trace-table paths. Zoom can reach+ 128 times the fitted overview so dense regions can reveal detail without packing+ points into a grid. Background text contains only existing group names and+ descriptions, including Outliers, with one label per group. Labels follow fixed+ zone centers and stay within the visible part of each zone as users pan and+ zoom. Overlapping labels fade instead of searching for new positions.+ Hover hints fade and scale gently while summaries lack inline space. These+ translucent hints always ignore pointer events, so moving across them targets+ the underlying map. Inline trace content remains selectable. Camera movement+ clears hover until fresh physical pointer movement, and the same painted frame+ supplies Canvas, inline content and hit testing. Zone selection uses a slow+ eased camera flight, including selection from the group panel. Hover never+ changes the map layout. Clicking a trace opens peek directly; trace-table links+ also expose dense and coincident points without mounting thousands of focusable+ dots.+ `map/TopicMapCanvas.tsx` interpolates camera, pointer parallax and hover emphasis+ via a frame-batched subscription to a per-mount vanilla store. Inline summaries,+ background text and animated hover hints subscribe to its shared presentation.+ The measured stage fills its container and expands with native browser fullscreen,+ retaining the camera. Opening a trace exits fullscreen before using the peek panel.+ `usePanZoomGestures` shares wheel input with the timeline: scroll pans, pinch or+ Ctrl/Command-scroll zooms at the pointer, and two touch contacts pinch and pan.+ Drag capture starts after a threshold so clicks remain clicks. Arrow keys pan,+ +/- zoom and 0/Home return to the full map. Zoom, fit and fullscreen controls+ overlay the chart without reserving a header row. OS reduced motion disables focus+ flights, presentation interpolation and pointer parallax, with immediate hints.+ Unpositioned summaries remain available in the trace table. The compact mapped-count+ tooltip reports points without summaries and summaries without coordinates, without+ reserving a footer row. This internal PoC adds no+ analytics events for camera/hover/fullscreen; the entire renderer is blocked+ from session replay. Browser fullscreen denial is expected UI state.- `server/currentResults.ts` joins latest per-trace/facet assignments to theirexact topic versions, including assignments from older maps. Summary statesidentify terminal no-topic results. An assignment applies only when its stored@@ -107,10 +146,9 @@ project permissions. Processing additionally requires the project allowlist.The plot is an approximate 2D view, separate from clustering and classification.It always shows the original discovery cohort. Later assignment batches keep-their results in the list; they are explicitly reported as unpositioned because-the PoC does not retain a UMAP transform. Missing coordinates show an explanation-instead of fabricated points. Missing source summaries do not change the-remaining points' coordinates.+their results in the trace table because the PoC does not retain a UMAP+transform. The map only renders saved coordinates; missing source summaries do+not change the remaining points' coordinates.Runtime and numerical pipeline:[`worker/src/features/topics/README.md`](../../../../worker/src/features/topics/README.md).diff --git a/web/src/features/topics/TopicEmbeddingMap.tsx b/web/src/features/topics/TopicEmbeddingMap.tsxindex 91f6689848..3e93d33820 100644--- a/web/src/features/topics/TopicEmbeddingMap.tsx+++ b/web/src/features/topics/TopicEmbeddingMap.tsx@@ -1,6 +1,5 @@import type { TopicTimeRange } from "@langfuse/shared/topics";import { Alert } from "@/src/components/design-system/Alert/Alert";-import { type ReactNode } from "react";import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";import { api, type RouterOutputs } from "@/src/utils/api";import { EmbeddingMapView } from "./EmbeddingMapView";@@ -8,7 +7,7 @@ import { EmbeddingMapView } from "./EmbeddingMapView";type Topic = Pick<RouterOutputs["topics"]["currentResults"][number]["topics"][number],"id" | "name"->;+> & { description?: string };export function TopicEmbeddingMap({projectId,@@ -17,9 +16,9 @@ export function TopicEmbeddingMap({topics,selectedTopic,onSelectTopic,- headerStats,onSelectTrace,selectedTraceId,+ fillContainer = false,}: {projectId: string;runId: string;@@ -27,9 +26,9 @@ export function TopicEmbeddingMap({topics: Topic[];selectedTopic: string | null;onSelectTopic: (id: string | null) => void;- headerStats?: ReactNode;onSelectTrace: (traceId: string | null) => void;selectedTraceId: string | null;+ fillContainer?: boolean;}) {const { openPeek } = usePeekNavigation({tableName: "topics-traces",@@ -72,9 +71,9 @@ export function TopicEmbeddingMap({topics={topics}selectedTopic={selectedTopic}onSelectTopic={onSelectTopic}- headerStats={headerStats}onSelectTrace={onSelectTrace}selectedTraceId={selectedTraceId}+ fillContainer={fillContainer}/>);}diff --git a/web/src/features/topics/TopicGroupCard.tsx b/web/src/features/topics/TopicGroupCard.tsxnew file mode 100644index 0000000000..47d6de3159--- /dev/null+++ b/web/src/features/topics/TopicGroupCard.tsx@@ -0,0 +1,44 @@+import { Badge } from "@/src/components/design-system/Badge/Badge";+import { cn } from "@/src/utils/tailwind";++export function TopicGroupCard({+ topic,+ color,+ isSelected,+ onSelect,+}: TopicGroupCardProps) {+ function selectTopic() {+ onSelect(topic.id);+ }+ return (+ <button+ onClick={selectTopic}+ aria-pressed={isSelected}+ className={cn(+ "ph-no-capture hover:bg-muted/50 flex flex-col gap-1 rounded-md border p-2 text-left",+ isSelected && "border-primary bg-muted/30",+ )}+ >+ <div className="flex w-full items-start justify-between gap-2">+ <h4 className="flex min-w-0 items-start gap-1.5 text-xs font-bold">+ <span+ className="mt-1 inline-block h-2 w-2 shrink-0 rounded-full"+ style={{ backgroundColor: color }}+ />+ {topic.name}+ </h4>+ <Badge text={topic.count.toLocaleString()} size="sm" />+ </div>+ <p className="text-muted-foreground text-xs leading-relaxed">+ {topic.description}+ </p>+ </button>+ );+}++type TopicGroupCardProps = {+ topic: { id: string; name: string; count: number; description: string };+ color: string;+ isSelected: boolean;+ onSelect: (topicId: string) => void;+};diff --git a/web/src/features/topics/TopicPipelineForm.tsx b/web/src/features/topics/TopicPipelineForm.tsxindex 2322b8c54c..0649ecac72 100644--- a/web/src/features/topics/TopicPipelineForm.tsx+++ b/web/src/features/topics/TopicPipelineForm.tsx@@ -41,6 +41,12 @@ export function useTopicPipelineForm({timeRange: TopicTimeRange | null;}) {const [configurationOpen, setConfigurationOpen] = useState(false);+ function openConfiguration() {+ setConfigurationOpen(true);+ }+ function closeConfiguration() {+ setConfigurationOpen(false);+ }const [operation, setOperation] = useState<TopicOperation>("process");const [reuseExistingSummaries, setReuseExistingSummaries] = useState(false);const rules = api.topics.rules.useQuery(@@ -60,7 +66,7 @@ export function useTopicPipelineForm({projectId,enabled: facets.length > 0 && operation === "process",filterOptionsEnabled: configurationOpen,- onOpenTrace: () => setConfigurationOpen(false),+ onOpenTrace: closeConfiguration,});const [selectedFacetIds, setSelectedFacetIds] = useState<string[]>(() =>facets@@ -161,7 +167,8 @@ export function useTopicPipelineForm({async function submit() {setError(null);try {- if (!selectedFacets.length) throw new Error("Select at least one facet.");+ if (selectedFacets.length === 0)+ throw new Error("Select at least one facet.");const base = {projectId,facets: selectedFacets,@@ -292,41 +299,29 @@ export function useTopicPipelineForm({actionLabel = selection?.count? `Process ${selection.count.toLocaleString()} traces`: "Process traces";- const actions = (- <>- <Button- text="Configure topics"- variant="secondary"- size="sm"- onClick={() => setConfigurationOpen(true)}- />-- <Button- text={trigger.isPending ? "Starting…" : actionLabel}- size="sm"- disabled={- !canWrite ||- !embeddingConfig.success ||- (operation === "update" &&- (!timeRange || !minimumTraceCountResult.success)) ||- trigger.isPending ||- !selectedFacets.length ||- (operation === "update"- ? summaryCounts.isFetching ||- !!summaryCounts.error ||- !hasStoredSummaries- : !selection?.count)- }- onClick={submit}- />- {error && (- <Alert variant="destructive" size="sm">- <Alert.Description>- <p className="break-words">{error}</p>- </Alert.Description>- </Alert>- )}- </>+ const triggerAction = {+ label: trigger.isPending ? "Starting…" : actionLabel,+ disabled:+ !canWrite ||+ !embeddingConfig.success ||+ (operation === "update" &&+ (!timeRange || !minimumTraceCountResult.success)) ||+ trigger.isPending ||+ selectedFacets.length === 0 ||+ (operation === "update"+ ? summaryCounts.isFetching ||+ !!summaryCounts.error ||+ !hasStoredSummaries+ : !selection?.count),+ onSelect: submit,+ };+ const primaryAction = (+ <Button+ text={triggerAction.label}+ size="sm"+ disabled={triggerAction.disabled}+ onClick={triggerAction.onSelect}+ />);const configuration = (<DialogPrimitive.Root@@ -408,7 +403,7 @@ export function useTopicPipelineForm({disabled={!canWrite ||!ruleName.trim() ||- !activeFacetIds.length ||+ activeFacetIds.length === 0 ||saveRule.isPending}onClick={() =>@@ -535,14 +530,17 @@ export function useTopicPipelineForm({<Buttontext="Done"variant="secondary"- onClick={() => setConfigurationOpen(false)}+ onClick={closeConfiguration}/></div></Dialog></DialogPrimitive.Root>);return {- actions: facets.length ? actions : null,- configuration: facets.length ? configuration : null,+ primaryAction: facets.length > 0 ? primaryAction : null,+ triggerAction: facets.length > 0 ? triggerAction : null,+ openConfiguration,+ error: facets.length > 0 ? error : null,+ configuration: facets.length > 0 ? configuration : null,};}diff --git a/web/src/features/topics/TopicsActionsMenu.tsx b/web/src/features/topics/TopicsActionsMenu.tsxnew file mode 100644index 0000000000..c5e1455ba0--- /dev/null+++ b/web/src/features/topics/TopicsActionsMenu.tsx@@ -0,0 +1,74 @@+import { type ReactNode } from "react";+import { History, Play, RefreshCw, Settings2 } from "lucide-react";+import { HeaderActionMenuRow } from "@/src/components/HeaderActionMenuRow";++export function TopicsActionsMenu({+ children,+ hasFacets,+ triggerAction,+ closeMenu,+ onOpenConfiguration,+ onOpenHistory,+ onRefresh,+}: TopicsActionsMenuProps) {+ function processTraces() {+ closeMenu();+ triggerAction?.onSelect();+ }+ function configureTopics() {+ closeMenu({ handoffFocus: true });+ onOpenConfiguration();+ }+ function openHistory() {+ closeMenu({ handoffFocus: true });+ onOpenHistory();+ }+ function refreshResults() {+ closeMenu();+ onRefresh();+ }+ return (+ <>+ {children}+ {triggerAction && (+ <HeaderActionMenuRow+ label={triggerAction.label}+ icon={<Play className="icon-base text-icon-foreground" />}+ disabled={triggerAction.disabled}+ onClick={processTraces}+ />+ )}+ {hasFacets && (+ <HeaderActionMenuRow+ label="Configure topics"+ icon={<Settings2 className="icon-base text-icon-foreground" />}+ onClick={configureTopics}+ />+ )}+ <HeaderActionMenuRow+ label="History"+ icon={<History className="icon-base text-icon-foreground" />}+ onClick={openHistory}+ />+ <HeaderActionMenuRow+ label="Refresh results"+ icon={<RefreshCw className="icon-base text-icon-foreground" />}+ onClick={refreshResults}+ />+ </>+ );+}++type TopicsActionsMenuProps = {+ children: ReactNode;+ hasFacets: boolean;+ triggerAction: {+ label: string;+ disabled: boolean;+ onSelect: () => void;+ } | null;+ closeMenu: (options?: { handoffFocus?: boolean }) => void;+ onOpenConfiguration: () => void;+ onOpenHistory: () => void;+ onRefresh: () => void;+};diff --git a/web/src/features/topics/TopicsFilters.stories.tsx b/web/src/features/topics/TopicsFilters.stories.tsxnew file mode 100644index 0000000000..d2f29b8099--- /dev/null+++ b/web/src/features/topics/TopicsFilters.stories.tsx@@ -0,0 +1,107 @@+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: "issues", name: "Issues" },+ ],+ selectedFacetId: undefined,+ timeWindow: "7",+ onSelectFacet: fn(),+ onSelectTimeWindow: fn(),+};++const meta = preview.meta({ component: TopicsFilters });++export const Header = meta.story({+ args: { ...filterArgs, layout: "header" },+});++export const Menu = meta.story({+ args: { ...filterArgs, layout: "menu" },+});++export const RetainsSelectionThroughRefresh = meta.story({+ name: "(Test) Retains selection through refresh and falls back after removal",+ args: { ...filterArgs, layout: "header" },+ 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 body = within(canvasElement.ownerDocument.body);+ const picker = canvas.getByRole("combobox", { name: "Topics facet" });+ await expect(picker).toHaveTextContent("Intent");+ await userEvent.click(picker);+ await userEvent.click(body.getByRole("option", { name: "Issues" }));+ await expect(args.onSelectFacet).toHaveBeenCalledWith("issues");+ await expect(picker).toHaveTextContent("Issues");+ await userEvent.click(+ canvas.getByRole("button", { name: "Refresh facets" }),+ );+ await expect(picker).toHaveTextContent("Issues");+ await userEvent.click(+ canvas.getByRole("button", { name: "Remove selected facet" }),+ );+ await expect(picker).toHaveTextContent("Intent");+ },+});++export const MenuTimeRangeSelection = meta.story({+ name: "(Test) Selects time range from menu controls",+ args: { ...filterArgs, layout: "menu" },+ render: (args) => {+ const [timeWindow, setTimeWindow] = useState(args.timeWindow);+ function selectTimeWindow(value: string) {+ setTimeWindow(value);+ args.onSelectTimeWindow(value);+ }+ return (+ <TopicsFilters+ {...args}+ timeWindow={timeWindow}+ onSelectTimeWindow={selectTimeWindow}+ />+ );+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const body = within(canvasElement.ownerDocument.body);+ const picker = canvas.getByRole("combobox", { name: "Topics time range" });+ await userEvent.click(picker);+ await userEvent.click(body.getByRole("option", { name: "Last 30 days" }));+ await expect(args.onSelectTimeWindow).toHaveBeenCalledWith("30");+ await expect(picker).toHaveTextContent("Last 30 days");+ },+});diff --git a/web/src/features/topics/TopicsFilters.tsx b/web/src/features/topics/TopicsFilters.tsxnew file mode 100644index 0000000000..d7e9918d98--- /dev/null+++ b/web/src/features/topics/TopicsFilters.tsx@@ -0,0 +1,79 @@+import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { resolveTopicFacetId } from "./topic-facet-selection";+import { topicTimeRangePresets } from "./time-range";++const layouts = {+ header: {+ root: "ph-no-capture flex min-w-0 flex-wrap items-center gap-2",+ facet: "w-44",+ range: "w-36",+ },+ menu: {+ root: "ph-no-capture flex flex-col gap-3 p-1",+ facet: "flex w-full flex-col gap-1",+ range: "flex w-full flex-col gap-1",+ },+};++export function TopicsFilters({+ layout,+ facets,+ selectedFacetId,+ timeWindow,+ onSelectFacet,+ onSelectTimeWindow,+}: TopicsFiltersProps) {+ const selectedFacet = resolveTopicFacetId(facets, selectedFacetId);+ const classes = layouts[layout];+ return (+ <div className={classes.root}>+ {facets.length > 0 && selectedFacet && (+ <div className={classes.facet}>+ {layout === "menu" && (+ <span className="text-muted-foreground text-xs">Facet</span>+ )}+ <Select value={selectedFacet} onValueChange={onSelectFacet}>+ <SelectTrigger aria-label="Topics facet" className="h-8">+ <SelectValue placeholder="Facet" />+ </SelectTrigger>+ <SelectContent className="ph-no-capture">+ {facets.map((facet) => (+ <SelectItem key={facet.facetId} value={facet.facetId}>+ {facet.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}+ <div className={classes.range}>+ {layout === "menu" && (+ <span className="text-muted-foreground text-xs">Time range</span>+ )}+ <SelectInput+ aria-label="Topics time range"+ placeholder="Topics time range"+ value={timeWindow}+ options={topicTimeRangePresets}+ onValueChange={onSelectTimeWindow}+ />+ </div>+ </div>+ );+}++type TopicsFiltersProps = {+ layout: "header" | "menu";+ facets: readonly { facetId: string; name: string }[];+ selectedFacetId: string | undefined;+ timeWindow: string;+ onSelectFacet: (facetId: string) => void;+ onSelectTimeWindow: (value: string) => void;+};diff --git a/web/src/features/topics/TopicsPage.clienttest.tsx b/web/src/features/topics/TopicsPage.clienttest.tsxindex 27ac3d055e..edc0ba8f0a 100644--- a/web/src/features/topics/TopicsPage.clienttest.tsx+++ b/web/src/features/topics/TopicsPage.clienttest.tsx@@ -32,27 +32,36 @@ vi.mock("@/src/features/feature-flags/hooks/useIsFeatureEnabled", () => ({default: () => true,}));vi.mock("./TopicPipelineForm", () => ({- useTopicPipelineForm: () => ({ actions: null, configuration: null }),+ useTopicPipelineForm: () => ({+ primaryAction: null,+ openConfiguration: vi.fn(),+ configuration: null,+ }),}));vi.mock("./CurrentTopics", () => ({- CurrentTopics: ({+ useCurrentTopics: ({running,refreshAfter,}: {running: boolean;refreshAfter: number;+ }) => ({ running, refreshAfter, data: [] }),+ CurrentTopics: ({+ result,+ }: {+ result: { running: boolean; refreshAfter: number };}) => (<divdata-testid="current-topics"- data-running={running}- data-refresh-after={refreshAfter}+ data-running={result.running}+ data-refresh-after={result.refreshAfter}/>),}));vi.mock("@/src/utils/api", () => ({api: {topics: {- facets: { useQuery: () => ({ data: [] }) },+ facets: { useQuery: () => ({ data: [], isLoading: false }) },executions: { useQuery: () => ({ data: [] }) },initialize: { useMutation: () => ({}) },execution: {@@ -106,6 +115,7 @@ beforeEach(() => {state.executionUpdatedAt = 110;state.updatedAt = "2026-09-23T12:00:00Z";});+afterEach(() => vi.unstubAllGlobals());it("refreshes current results through retry and completion for a selected run outside history", () => {diff --git a/web/src/features/topics/TopicsPage.tsx b/web/src/features/topics/TopicsPage.tsxindex 9b59f8cff7..96c093b728 100644--- a/web/src/features/topics/TopicsPage.tsx+++ b/web/src/features/topics/TopicsPage.tsx@@ -1,5 +1,6 @@import { useState } from "react";import { format } from "date-fns";+import { MoreHorizontal } from "lucide-react";import { type UseQueryResult } from "@tanstack/react-query";import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";import { TablePeekViewTraceDetail } from "@/src/components/table/peek/peek-trace-detail";@@ -18,10 +19,11 @@ import {SheetDescription,} from "@/src/components/ui/sheet";import { Input } from "@/src/components/design-system/Input/Input";-import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";+import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";import { DateRangeInput } from "@/src/features/evals/v2/components/Evaluators/EvaluatorBackfillSettings/components/DateRangeInput/DateRangeInput";import { Textarea } from "@/src/components/ui/textarea";-import { PopoverClose, PopoverController } from "@/src/components/ui/popover";+import { PopoverController } from "@/src/components/ui/popover";import { Badge } from "@/src/components/design-system/Badge/Badge";import {Select,@@ -40,13 +42,16 @@ import {type TopicOperation,} from "@langfuse/shared/topics";import { useTopicPipelineForm } from "./TopicPipelineForm";-import { CurrentTopics } from "./CurrentTopics";+import { CurrentTopics, useCurrentTopics } from "./CurrentTopics";+import { TopicsFilters } from "./TopicsFilters";+import { TopicsActionsMenu } from "./TopicsActionsMenu";+import { TopicsWorkspaceGate } from "./TopicsWorkspaceGate";+import { resolveTopicFacetId } from "./topic-facet-selection";import {isValidTopicTimeRange,relativeTopicTimeRange,topicCalendarDates,topicCalendarRange,- topicTimeRangePresets,} from "./time-range";const operationLabels: Record<TopicOperation, string> = {@@ -79,6 +84,11 @@ const facetOutcomeLabels: Record<TopicFacetOutcome, string> = {no_topics: "No topics found",failed: "Facet failed",};+const loadingPage = (+ <Page headerProps={{ title: "Topics" }} withPadding>+ <p>Loading topics…</p>+ </Page>+);export default function TopicsPage() {const router = useRouter();@@ -93,20 +103,20 @@ export default function TopicsPage() {return projectId ? (<TopicsWorkspace key={projectId} projectId={projectId} />) : (- <Page headerProps={{ title: "Topics" }} withPadding>- <p>Loading topics…</p>- </Page>+ loadingPage);}function TopicsWorkspace({ projectId }: { projectId: string }) {const facets = api.topics.facets.useQuery({ projectId });return (- <TopicsWorkspaceView- key={facets.data?.length ? "configured" : "empty"}- projectId={projectId}- facets={facets}- />+ <TopicsWorkspaceGate isLoading={facets.isLoading} fallback={loadingPage}>+ <TopicsWorkspaceView+ key={(facets.data?.length ?? 0) > 0 ? "configured" : "empty"}+ projectId={projectId}+ facets={facets}+ />+ </TopicsWorkspaceGate>);}@@ -120,6 +130,8 @@ function TopicsWorkspaceView({const [historyOpen, setHistoryOpen] = useState(false);const [timeWindow, setTimeWindow] = useState("7");const [timeRange, setTimeRange] = useState(() => relativeTopicTimeRange(7));+ const [selectedFacetId, setSelectedFacetId] = useState<string>();+ const [tracePanel, setTracePanel] = useState<HTMLElement | null>(null);const validTimeRange = isValidTopicTimeRange(timeRange);const peekNavigation = usePeekNavigation({tableName: "topics-traces",@@ -168,6 +180,19 @@ function TopicsWorkspaceView({timeWindow === "custom" || !Number.isFinite(rangeEnd)? timeRange: relativeTopicTimeRange(Number(timeWindow), new Date(rangeEnd));+ const running =+ Boolean(executions.data?.some((execution) => busy(execution.status))) ||+ busy(selectedExecution.data?.status ?? "");+ const results = useCurrentTopics({+ projectId,+ running,+ refreshAfter: completedAt,+ timeRange: currentTimeRange,+ });+ const selectedFacet = resolveTopicFacetId(+ results.data ?? [],+ selectedFacetId,+ );const refreshResults = () => {if (timeWindow !== "custom")setTimeRange(relativeTopicTimeRange(Number(timeWindow)));@@ -193,32 +218,86 @@ function TopicsWorkspaceView({shallow: true,});};- const { actions: pipelineActions, configuration } = useTopicPipelineForm({+ function openHistory() {+ setHistoryOpen(true);+ }+ function selectTimeWindow(value: string) {+ setTimeWindow(value);+ setTimeRange(+ value === "custom"+ ? topicCalendarRange(topicCalendarDates(currentTimeRange))+ : relativeTopicTimeRange(Number(value)),+ );+ }+ function selectCalendarRange(+ value: Parameters<typeof topicCalendarRange>[0],+ ) {+ setTimeRange(topicCalendarRange(value));+ }+ const {+ primaryAction,+ triggerAction,+ openConfiguration,+ configuration,+ error,+ } = useTopicPipelineForm({projectId,facets: facets.data ?? [],canWrite,onTriggered: openExecution,timeRange: validTimeRange ? currentTimeRange : null,facetEditor:- canWrite && facets.data?.length ? (- <FacetEditor projectId={projectId} facets={facets.data} />+ canWrite && (facets.data?.length ?? 0) > 0 ? (+ <FacetEditor projectId={projectId} facets={facets.data ?? []} />) : null,});+ const filterProps = {+ facets: results.data ?? [],+ selectedFacetId,+ timeWindow,+ onSelectFacet: setSelectedFacetId,+ onSelectTimeWindow: selectTimeWindow,+ };const actions = (- <div className="ph-no-capture flex flex-wrap items-center justify-end gap-2">- {pipelineActions}- <Button- text="History"- variant="ghost"- size="sm"- onClick={() => setHistoryOpen(true)}- />- <Button- text="Refresh results"- variant="ghost"- size="sm"- onClick={refreshResults}- />+ <div className="ph-no-capture flex items-center justify-end gap-1">+ {primaryAction}+ <DropdownMenu+ ariaLabel="Topics actions"+ placement="bottom-end"+ items={[+ ...((facets.data?.length ?? 0) > 0+ ? [+ {+ id: "configure",+ type: "item" as const,+ title: "Configure topics",+ onClick: openConfiguration,+ },+ ]+ : []),+ {+ id: "history",+ type: "item",+ title: "History",+ onClick: openHistory,+ },+ {+ id: "refresh",+ type: "item",+ title: "Refresh results",+ onClick: refreshResults,+ },+ ]}+ >+ {({ getTriggerProps }) => (+ <IconButton+ {...getTriggerProps()}+ icon={MoreHorizontal}+ label="Topics actions"+ size="sm"+ />+ )}+ </DropdownMenu></div>);return (@@ -230,153 +309,145 @@ function TopicsWorkspaceView({"Explore recurring themes across traces, one facet at a time.",},actionButtonsRight: actions,- actionButtonsMenu: <PopoverClose asChild>{actions}</PopoverClose>,+ actionButtonsLeft: <TopicsFilters {...filterProps} layout="header" />,+ actionButtonsMenu: ({ closeMenu }) => (+ <TopicsActionsMenu+ hasFacets={(facets.data?.length ?? 0) > 0}+ triggerAction={triggerAction}+ closeMenu={closeMenu}+ onOpenConfiguration={openConfiguration}+ onOpenHistory={openHistory}+ onRefresh={refreshResults}+ >+ <TopicsFilters {...filterProps} layout="menu" />+ </TopicsActionsMenu>+ ),}}- scrollable={Boolean(facets.data?.length)}- withPadding>- <div className="ph-no-capture mb-6 flex flex-wrap items-end gap-3">- <label className="flex w-48 flex-col gap-1 text-sm">- Topics time range- <SelectInput- aria-label="Topics time range"- placeholder="Topics time range"- value={timeWindow}- options={topicTimeRangePresets}- onValueChange={(value) => {- setTimeWindow(value);- setTimeRange(- value === "custom"- ? topicCalendarRange(topicCalendarDates(currentTimeRange))- : relativeTopicTimeRange(Number(value)),- );- }}- />- </label>+ <div className="ph-no-capture flex min-h-0 flex-1 flex-col gap-2 overflow-hidden p-2">{timeWindow === "custom" && (- <DateRangeInput- value={topicCalendarDates(timeRange)}- max={format(new Date(), "yyyy-MM-dd")}- fromAriaLabel="Topics start date"- toAriaLabel="Topics end date"- onValueChange={(value) => setTimeRange(topicCalendarRange(value))}- />+ <div className="flex shrink-0 flex-wrap items-center gap-2">+ <DateRangeInput+ value={topicCalendarDates(timeRange)}+ max={format(new Date(), "yyyy-MM-dd")}+ fromAriaLabel="Topics start date"+ toAriaLabel="Topics end date"+ onValueChange={selectCalendarRange}+ />+ </div>)}- <p className="text-muted-foreground text-sm">- Trace start time for results and Update topics.- </p>- </div>- {!validTimeRange && (- <ErrorMessage message="Select a time range of at most 93 days." />- )}- {configuration}- <Sheet- open={historyOpen || executionId !== null}- onOpenChange={showExecutionList}- >- <SheetContent className="ph-no-capture flex w-full flex-col gap-4 sm:max-w-xl">- <SheetHeader>- <SheetTitle>- {executionId ? "Run status" : "Past executions"}- </SheetTitle>- <SheetDescription>- Review progress, errors, and retry interrupted runs.- </SheetDescription>- </SheetHeader>- <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto">- {executionId ? (- <>- <div className="self-start">- <Button- text="All runs"- variant="ghost"- size="sm"- onClick={() => showExecutionList(true)}- />- </div>- <ExecutionPanel- key={executionId}- projectId={projectId}- executionId={executionId}- query={selectedExecution}- facets={facets.data ?? []}- canWrite={canWrite}- />- </>- ) : (- <>- <div className="self-end">- <Button- text="Refresh"- size="sm"- variant="ghost"- onClick={() => executions.refetch()}+ {!validTimeRange && (+ <ErrorMessage message="Select a time range of at most 93 days." />+ )}+ {error && <ErrorMessage message={error} />}+ {configuration}+ <Sheet+ open={historyOpen || executionId !== null}+ onOpenChange={showExecutionList}+ >+ <SheetContent className="ph-no-capture flex w-full flex-col gap-4 sm:max-w-xl">+ <SheetHeader>+ <SheetTitle>+ {executionId ? "Run status" : "Past executions"}+ </SheetTitle>+ <SheetDescription>+ Review progress, errors, and retry interrupted runs.+ </SheetDescription>+ </SheetHeader>+ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto">+ {executionId ? (+ <>+ <div className="self-start">+ <Button+ text="All runs"+ variant="ghost"+ size="sm"+ onClick={() => showExecutionList(true)}+ />+ </div>+ <ExecutionPanel+ key={executionId}+ projectId={projectId}+ executionId={executionId}+ query={selectedExecution}+ facets={facets.data ?? []}+ canWrite={canWrite}/>- </div>- {executions.error && (- <ErrorMessage message={executions.error.message} />- )}- {!executions.data?.length && (- <p className="text-muted-foreground text-sm">- Your triggered batches will appear here.- </p>- )}- {executions.data?.map((execution) => (- <button- key={execution.id}- onClick={() => openExecution(execution.id)}- className="hover:bg-muted/50 flex flex-wrap items-center justify-between gap-2 rounded-md border p-3 text-left text-sm"- >- <span className="capitalize">- {operationLabels[execution.input.operation]} ·{" "}- {new Date(execution.createdAt).toLocaleString()}- </span>- <span>{execution.facets.length} facets</span>- <Badge text={executionLabels[execution.status]} />- </button>- ))}- </>- )}- </div>- </SheetContent>- </Sheet>- <div className="ph-no-capture flex w-full min-w-0 flex-col gap-6 pb-12">- <TablePeekViewTraceDetail- {...peekNavigation}- itemType="TRACE"- projectId={projectId}- />- {validTimeRange && (- <CurrentTopics+ </>+ ) : (+ <>+ <div className="self-end">+ <Button+ text="Refresh"+ size="sm"+ variant="ghost"+ onClick={() => executions.refetch()}+ />+ </div>+ {executions.error && (+ <ErrorMessage message={executions.error.message} />+ )}+ {!executions.data?.length && (+ <p className="text-muted-foreground text-sm">+ Your triggered batches will appear here.+ </p>+ )}+ {executions.data?.map((execution) => (+ <button+ key={execution.id}+ onClick={() => openExecution(execution.id)}+ className="hover:bg-muted/50 flex flex-wrap items-center justify-between gap-2 rounded-md border p-3 text-left text-sm"+ >+ <span className="capitalize">+ {operationLabels[execution.input.operation]} ·{" "}+ {new Date(execution.createdAt).toLocaleString()}+ </span>+ <span>{execution.facets.length} facets</span>+ <Badge text={executionLabels[execution.status]} />+ </button>+ ))}+ </>+ )}+ </div>+ </SheetContent>+ </Sheet>+ <div className="flex min-h-0 w-full min-w-0 flex-1 flex-col gap-2 overflow-hidden">+ <TablePeekViewTraceDetail+ {...peekNavigation}+ itemType="TRACE"projectId={projectId}- timeRange={currentTimeRange}- refreshAfter={completedAt}- running={- Boolean(- executions.data?.some((execution) => busy(execution.status)),- ) || busy(selectedExecution.data?.status ?? "")- }+ defaultWidthTarget={tracePanel}+ widthStorageKey="topicsPeekViewWidthFraction"/>- )}- {facets.isLoading && <p>Loading facets…</p>}- {facets.error && <ErrorMessage message={facets.error.message} />}- {facets.data?.length === 0 && (- <section className="flex flex-col items-start gap-3">- <h2 className="font-bold">Start with a question</h2>- <p className="text-muted-foreground text-sm">- Create built-in facets for intent, outcome, and issues, then add- custom facets for your own questions.- </p>- <Button- text="Create starter facets"- disabled={!canWrite || initialize.isPending}- onClick={() => initialize.mutate({ projectId })}+ {validTimeRange && (+ <CurrentTopics+ projectId={projectId}+ timeRange={currentTimeRange}+ result={results}+ selectedFacetId={selectedFacet}+ tracePanelRef={setTracePanel}/>- {initialize.error && (- <ErrorMessage message={initialize.error.message} />- )}- </section>- )}+ )}+ {facets.isLoading && <p>Loading facets…</p>}+ {facets.error && <ErrorMessage message={facets.error.message} />}+ {facets.data?.length === 0 && (+ <section className="flex flex-col items-start gap-3">+ <h2 className="font-bold">Start with a question</h2>+ <p className="text-muted-foreground text-sm">+ Create built-in facets for intent, outcome, and issues, then add+ custom facets for your own questions.+ </p>+ <Button+ text="Create starter facets"+ disabled={!canWrite || initialize.isPending}+ onClick={() => initialize.mutate({ projectId })}+ />+ {initialize.error && (+ <ErrorMessage message={initialize.error.message} />+ )}+ </section>+ )}+ </div></div></Page>);diff --git a/web/src/features/topics/TopicsWorkspaceGate.stories.tsx b/web/src/features/topics/TopicsWorkspaceGate.stories.tsxnew file mode 100644index 0000000000..4d238debbf--- /dev/null+++ b/web/src/features/topics/TopicsWorkspaceGate.stories.tsx@@ -0,0 +1,70 @@+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 { TopicsWorkspaceGate } from "./TopicsWorkspaceGate";++const controls = (+ <TopicsFilters+ layout="header"+ facets={[{ facetId: "intent", name: "Intent" }]}+ selectedFacetId="intent"+ timeWindow="7"+ onSelectFacet={fn()}+ onSelectTimeWindow={fn()}+ />+);++const meta = preview.meta({ component: TopicsWorkspaceGate });++export const Loading = meta.story({+ args: {+ isLoading: true,+ fallback: <p>Loading topics…</p>,+ children: controls,+ },+});++export const Loaded = meta.story({+ args: {+ isLoading: false,+ fallback: <p>Loading topics…</p>,+ children: controls,+ },+});++export const WaitsForInitialFacets = meta.story({+ name: "(Test) Waits for initial facets before mounting controls",+ args: {+ isLoading: true,+ fallback: <p>Loading topics…</p>,+ children: controls,+ },+ render: (args) => {+ const [isLoading, setIsLoading] = useState(args.isLoading);+ function completeLoading() {+ setIsLoading(false);+ }+ return (+ <div className="flex flex-col items-start gap-2">+ <TopicsWorkspaceGate {...args} isLoading={isLoading} />+ <Button text="Finish loading" onClick={completeLoading} />+ </div>+ );+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.getByText("Loading topics…")).toBeVisible();+ await expect(+ canvas.queryByRole("combobox", { name: "Topics facet" }),+ ).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole("button", { name: "Finish loading" }),+ );+ await expect(canvas.queryByText("Loading topics…")).not.toBeInTheDocument();+ await expect(+ canvas.getByRole("combobox", { name: "Topics facet" }),+ ).toHaveTextContent("Intent");+ },+});diff --git a/web/src/features/topics/TopicsWorkspaceGate.tsx b/web/src/features/topics/TopicsWorkspaceGate.tsxnew file mode 100644index 0000000000..ea3c04d64a--- /dev/null+++ b/web/src/features/topics/TopicsWorkspaceGate.tsx@@ -0,0 +1,16 @@+import { type ReactNode } from "react";++export function TopicsWorkspaceGate({+ isLoading,+ fallback,+ children,+}: TopicsWorkspaceGateProps) {+ if (isLoading) return fallback;+ return children;+}++type TopicsWorkspaceGateProps = {+ isLoading: boolean;+ fallback: ReactNode;+ children: ReactNode;+};diff --git a/web/src/features/topics/map/TopicMapCanvas.tsx b/web/src/features/topics/map/TopicMapCanvas.tsxnew file mode 100644index 0000000000..63a5bceb57--- /dev/null+++ b/web/src/features/topics/map/TopicMapCanvas.tsx@@ -0,0 +1,280 @@+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,+}: 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,+ );+ 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,+ ]);+ 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, readingTopic } = 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.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 =+ readingTopic && point.groupId !== readingTopic+ ? 0.22 + active * 0.78+ : 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();+ context.globalAlpha = node.backgroundOpacity * Math.min(1, opacity + 0.2);+ context.fillStyle = surface;+ context.fill();+ 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;+};++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.tsxnew file mode 100644index 0000000000..ecd520191b--- /dev/null+++ b/web/src/features/topics/map/TopicMapExplorer.tsx@@ -0,0 +1,767 @@+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 "lucide-react";+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,+ onOpenTrace,+ 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();+ 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 openTrace = async (id: string) => {+ clearTopicMapHover(store);+ try {+ if (document.fullscreenElement === sectionRef.current)+ await document.exitFullscreen();+ onOpenTrace(id);+ } catch {+ store.setState({ fullscreenError: true });+ }+ };+ 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.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+ ? hitMapNode(frame, {+ x: event.clientX - rect.left,+ y: event.clientY - rect.top,+ })+ : null;+ onSelectTrace(point?.traceId ?? null);+ if (point) openTrace(point.traceId);+ };+ 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();+ };+ const handleSelectTrace = (id: string) => {+ onSelectTrace(id);+ openTrace(id);+ };+ 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}+ />+ <MapLabels+ model={model}+ size={size}+ store={store}+ selectedTopic={selectedTopic}+ selectedTraceId={selectedTraceId}+ onSelectTrace={handleSelectTrace}+ />+ {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={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,+ onSelectTrace,+}: {+ model: TopicMapModel;+ size: Size;+ store: TopicMapStore;+ selectedTopic: string | null;+ selectedTraceId: string | null;+ onSelectTrace: (id: string) => void;+}) {+ 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;+ 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;+ 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: ${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.y,+ width: rect.width,+ height: rect.height,+ borderLeftColor: trace?.point.color ?? zone!.color,+ borderLeftWidth: 2,+ }}+ >+ {trace ? (+ <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;+ onOpenTrace: (traceId: string) => void;+ fillContainer?: boolean;+};++type LayoutReadoutProps = {+ store: TopicMapStore;+ initialCamera: Camera;+ scope: string | null;+ population: string;+ missingSummaryCount: number;+ unpositionedCount: number;+};++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.tsnew file mode 100644index 0000000000..29d1ca5f57--- /dev/null+++ b/web/src/features/topics/map/prepare-topic-map.ts@@ -0,0 +1,691 @@+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;+ 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;+ 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,+): 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 growth = readingTopic && point.groupId !== readingTopic ? 0 : blend;+ 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,+ 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,+ 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,+ 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 } = 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;+ 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),+ 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),+ };+}++function hoverRectangle(+ anchor: MapRectangle,+ size: Size,+ desired: Size,+): MapRectangle | 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,+ ): MapRectangle => ({+ x: Math.min(Math.max(margin, left), size.width - w - margin),+ y: Math.min(Math.max(margin, top), size.height - h - margin),+ width: w,+ height: h,+ });+ 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: margin,+ width: size.width - margin - anchor.x - anchor.width - 12,+ height: size.height - margin * 2,+ },+ {+ x: margin,+ y: margin,+ 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: margin,+ 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;+ node: TopicMapNode;+ position: MapPosition;+ card: MapRectangle;+ excerpt: string;+ reading: boolean;+};+type ZoneHover = MapZone & {+ position: MapPosition;+ label: MapRectangle;+ 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: 144,+ });+ return {+ traces: card+ ? [+ {+ point: node.point,+ 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.tsnew file mode 100644index 0000000000..060dad0468--- /dev/null+++ b/web/src/features/topics/map/topic-map-store.ts@@ -0,0 +1,146 @@+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+ );+}++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.cssnew file mode 100644index 0000000000..ebf656aa10--- /dev/null+++ b/web/src/features/topics/map/topic-map.module.css@@ -0,0 +1,47 @@+.hoverCard {+ pointer-events: none;+ transform-origin: center;+ opacity: 0;+ transform: translateY(4px) scale(0.94);+ transition:+ opacity 180ms cubic-bezier(0.2, 0.8, 0.2, 1),+ transform 180ms cubic-bezier(0.2, 0.8, 0.2, 1);+}++.enter {+ opacity: 0.96;+ transform: translateY(0) scale(1);+}++.exit {+ pointer-events: none;+ transform: translateY(3px) scale(0.96);+ transition-duration: 130ms;+}++.backgroundLabel {+ animation: labelEnter 180ms ease-out;+ transition: opacity 180ms ease-out;+}++@keyframes labelEnter {+ from {+ opacity: 0;+ }+}++@starting-style {+ .enter {+ opacity: 0;+ transform: translateY(4px) scale(0.94);+ }+}++@media (prefers-reduced-motion: reduce) {+ .enter,+ .exit,+ .backgroundLabel {+ animation-duration: 1ms;+ transition-duration: 1ms;+ }+}diff --git a/web/src/features/topics/server/currentResults.ts b/web/src/features/topics/server/currentResults.tsindex 53cf1f61b4..bb873cdabb 100644--- a/web/src/features/topics/server/currentResults.ts+++ b/web/src/features/topics/server/currentResults.ts@@ -145,6 +145,7 @@ export async function currentTopicResults(topics: run.topics.map((topic) => ({id: topic.topicId,name: topic.name,+ description: topic.description,})),}: null,diff --git a/web/src/features/topics/topic-facet-selection.clienttest.ts b/web/src/features/topics/topic-facet-selection.clienttest.tsnew file mode 100644index 0000000000..d790a715d8--- /dev/null+++ b/web/src/features/topics/topic-facet-selection.clienttest.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest";+import { resolveTopicFacetId } from "./topic-facet-selection";++describe("resolveTopicFacetId", () => {+ const facets = [{ facetId: "intent" }, { facetId: "issues" }];++ it("retains user intent when refreshed results contain the same facet", () => {+ expect(resolveTopicFacetId(facets, "issues")).toBe("issues");+ expect(+ resolveTopicFacetId(+ facets.map((facet) => ({ ...facet })),+ "issues",+ ),+ ).toBe("issues");+ });++ it("uses the first available facet when no choice exists or a choice disappears", () => {+ expect(resolveTopicFacetId(facets, undefined)).toBe("intent");+ expect(resolveTopicFacetId([{ facetId: "intent" }], "issues")).toBe(+ "intent",+ );+ expect(resolveTopicFacetId([], "issues")).toBeUndefined();+ });+});diff --git a/web/src/features/topics/topic-facet-selection.ts b/web/src/features/topics/topic-facet-selection.tsnew file mode 100644index 0000000000..f7b5e4ef97--- /dev/null+++ b/web/src/features/topics/topic-facet-selection.ts@@ -0,0 +1,7 @@+export function resolveTopicFacetId(+ facets: readonly { facetId: string }[],+ requestedId: string | undefined,+): string | undefined {+ if (facets.some((facet) => facet.facetId === requestedId)) return requestedId;+ return facets[0]?.facetId;+}diff --git a/web/src/features/topics/topic-map-geometry.clienttest.ts b/web/src/features/topics/topic-map-geometry.clienttest.tsindex 9d9fc7d6aa..559fc2aeb5 100644--- a/web/src/features/topics/topic-map-geometry.clienttest.ts+++ b/web/src/features/topics/topic-map-geometry.clienttest.ts@@ -1,6 +1,126 @@-import { expect, it } from "vitest";+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],@@ -35,3 +155,634 @@ it("fits a tall cohort across the landscape plot while preserving pairwise dista}}});++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);+ });+});diff --git a/web/src/features/traces/components/TraceLayoutDesktop.tsx b/web/src/features/traces/components/TraceLayoutDesktop.tsxindex 839b475686..62ddad86da 100644--- a/web/src/features/traces/components/TraceLayoutDesktop.tsx+++ b/web/src/features/traces/components/TraceLayoutDesktop.tsx@@ -28,6 +28,7 @@ import { TraceReviewLayout } from "./TraceReviewLayout";import { useInternalFeaturesEnabled } from "@/src/features/feature-flags";import { useReadPath } from "@/src/features/events";import { resolveEffectiveWidthFraction } from "@/src/components/table/peek/store/peekPanelStore";+import { usePeekTableState } from "@/src/components/table/peek/contexts/PeekTableStateContext";const RESIZABLE_PANEL_HANDLE_ID = "trace-layout-handle";const RESIZABLE_PANEL_NAVIGATION_ID = "trace-layout-panel-navigation";@@ -221,23 +222,17 @@ function TraceNavigationDetailLayout({// Peek sizing depends on the drawer width; persistence scope is caller-owned.const { isPeekMode } = useViewPreferences();- // The width the trace container actually opens at, driving the computed- // default split. Peek: the drawer width — when expanded (a shared/reloaded- // `?peekView=expanded` link) the panel renders at ~viewport width, NOT the- // widget fraction — so we must size the split against that, or a first-open- // expanded peek on a big screen re-creates the wide-tree bug. Full-page: the- // viewport. Sidebar offsets are ignored in both (the nav is width-capped at- // these sizes, so the small overestimate only makes the tree slightly- // narrower, still within its comfortable band). 0 during SSR. Mount-time- // default only (a saved layout wins after the first resize), so it doesn't- // track viewport changes.+ /** Mount-time defaults use the host width; saved inner splits take precedence. */+ const getPanelWidthPx = usePeekTableState()?.getPanelWidthPx;const [peekView] = useQueryParam("peekView", StringParam);const isPeekExpanded = isPeekMode && peekView === "expanded";const containerWidthPx = useMemo(() => {if (typeof window === "undefined") return 0;- if (!isPeekMode || isPeekExpanded) return window.innerWidth;+ if (!isPeekMode) return window.innerWidth;+ if (getPanelWidthPx) return getPanelWidthPx();+ if (isPeekExpanded) return window.innerWidth;return resolveEffectiveWidthFraction() * window.innerWidth;- }, [isPeekMode, isPeekExpanded]);+ }, [isPeekMode, isPeekExpanded, getPanelWidthPx]);// Deterministic default split, computed from `containerWidthPx`. Only used on// first open (no saved layout); memoized so the Group sees a stable prop.diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsxindex c4773167b7..963b40941b 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx@@ -24,7 +24,7 @@* grows only the rows — the whole duration stays on screen until the names* come back — and after that both axes move together. Zoom is exponential in* a zoom level and deltas accumulate per frame, as in mapping libraries — see- * the rate constants below.+ * the shared gesture adapter's rate constants.* - Drag pans both axes too, and drag draws a box to zoom into — the one* gesture where the user has stated the window on both axes, so it goes* straight there. There are no scrollbars by design: a map has none, and the@@ -57,6 +57,7 @@ import {type ReactNode,} from "react";import { useTheme } from "next-themes";+import { usePanZoomGestures } from "@/src/hooks/usePanZoomGestures";import { Scan, Minus, Plus, UnfoldVertical } from "lucide-react";import {ItemTypeIcon,@@ -182,18 +183,6 @@ const TOOLBAR_HEIGHT = 22;const AXIS_HEIGHT = 16;const READOUT_HEIGHT = 18;const FRAME_BORDER = 1;-/**- * Zoom is exponential in a zoom LEVEL — one level doubles the scale — and input- * deltas accumulate into level deltas, which is how every mapping library does- * it. The rate has to depend on the input device, and mapping libraries ship two- * constants for exactly this reason: macOS sends pinch deltas of only a few- * units while a mouse notch is ~100, so one divisor cannot serve both. A single- * linear factor per event with a /100 divisor moved ~1% per pinch event, which- * is why it felt like a lot of touching to get anywhere.- */-const PINCH_ZOOM_RATE = 1 / 40;-/** A line, for the browsers that report wheel deltas in lines rather than pixels. */-const WHEEL_LINE_PX = 16;/** Step for the toolbar buttons and the keyboard, in zoom levels. */const BUTTON_ZOOM_LEVELS = 0.6;const DRAG_THRESHOLD_PX = 3;@@ -939,86 +928,56 @@ export function TimelineDense({pending.current.frame = requestAnimationFrame(flushGesture);}, [flushGesture, releaseOverride, cancelTween]);- /**- * Wheel and trackpad pinch on a non-passive listener, so the page never takes- * the gesture. A Mac pinch arrives as wheel + ctrlKey and needs no special- * case; shift or a horizontal wheel pans instead. Pinch-zoom grows only the- * rows while labels are hidden, then both axes once they fit.- */+ // Shared with spatial explorers: device input is independent of row layout.+ // The timeline keeps its own pointer path because mouse drag draws a marquee.+ usePanZoomGestures({+ target: surfaceRef,+ pointerPan: false,+ onInteractionStart: () => {+ cancelTween();+ releaseOverride();+ },+ canPan: (dxPx, dyPx) => {+ const { limits: live, laneWidth: width } = layoutRef.current;+ return !viewportsEqual(+ panViewport(viewportRef.current, live, { dxPx, dyPx, boxWidth: width }),+ viewportRef.current,+ );+ },+ onPan: (dxPx, dyPx) => {+ const { limits: live, laneWidth: width } = layoutRef.current;+ const next = panViewport(viewportRef.current, live, {+ dxPx,+ dyPx,+ boxWidth: width,+ });+ viewportRef.current = next;+ setViewport(next);+ notifyHoverRef.current(next);+ },+ onZoom: (levels, anchor) => {+ const { railWidth: rail, laneWidth: width } = layoutRef.current;+ const surfaceWidth =+ surfaceRef.current?.getBoundingClientRect().width ?? width + rail;+ const next = zoomAndAnchorRef.current(viewportRef.current, {+ factor: 2 ** levels,+ xRatio:+ (anchor.x * surfaceWidth - rail) / Math.max(surfaceWidth - rail, 1),+ yRatio: anchor.y,+ });+ viewportRef.current = next;+ setViewport(next);+ notifyHoverRef.current(next);+ },+ });+const attachSurface = useCallback((element: HTMLDivElement | null) => {surfaceRef.current = element;if (!element) return;-- const onWheel = (event: WheelEvent) => {- const rect = element.getBoundingClientRect();- const queued = pending.current;- const rail = layoutRef.current.railWidth;- // Deltas arrive in pixels, lines or pages depending on the browser and- // the device, so normalize before anything reads them: a line-mode wheel- // reports 3, and panning 3px per notch reads as stuck.- const unit = (() => {- if (event.deltaMode === 1) {- return WHEEL_LINE_PX;- }- if (event.deltaMode === 2) {- return Math.max(rect.height, 1);- }- return 1;- })();- const deltaX = event.deltaX * unit;- const deltaY = event.deltaY * unit;- // A macOS pinch is the ONLY wheel event that carries ctrlKey. Holding- // ⌘/ctrl is the same intent by hand, and it is how you zoom with a mouse.- const pinch = event.ctrlKey || event.metaKey;-- if (pinch) {- queued.xRatio =- rect.width > 0- ? (event.clientX - rect.left - rail) /- Math.max(rect.width - rail, 1)- : 0.5;- queued.yRatio =- rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0.5;- queued.levels += -deltaY * PINCH_ZOOM_RATE;- event.preventDefault();- scheduleGesture();- return;- }-- // EVERY other wheel pans, whatever the device. Sniffing a "mouse notch"- // out of a big delta and zooming on it was wrong twice over: a fast- // two-finger flick on a Mac trackpad sends deltas far past any such- // threshold, so a quick scroll down zoomed OUT to the fitted view and- // the timeline looked like it kept snapping back to the top — and it- // swallowed the event either way, so there was no scrolling down at all.- // Zoom keeps the gestures that say zoom and nothing else: pinch,- // ⌘/ctrl + wheel, the toolbar buttons, double-click to focus.- const dxPx = event.shiftKey ? -deltaY : -deltaX;- const dyPx = event.shiftKey ? 0 : -deltaY;- const wouldMove = panViewport(- viewportRef.current,- layoutRef.current.limits,- { dxPx, dyPx, boxWidth: layoutRef.current.laneWidth },- );- // Only swallow the gesture if it actually moves us; at a clamp the page- // keeps its scroll instead of being trapped.- if (viewportsEqual(wouldMove, viewportRef.current)) return;- event.preventDefault();- queued.dxPx += dxPx;- queued.dyPx += dyPx;- scheduleGesture();- };-- element.addEventListener("wheel", onWheel, { passive: false });- return () => {- cancelTween();- element.removeEventListener("wheel", onWheel);- };+ return cancelTween;},- // Stable: everything live is read from layoutRef, so the listener attaches- // once and an animation is never cancelled by a re-attach.- [scheduleGesture, cancelTween],+ [cancelTween],);const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {@@ -1120,8 +1079,8 @@ export function TimelineDense({// Two fingers: pinch to zoom BOTH axes about the midpoint, and pan by// however far that midpoint travelled — the two happen together on a map,// and separating them makes a pinch feel like it fights the drag. Both go- // through the same per-frame accumulator the wheel uses, so they inherit its- // zoom-then-reanchor and its cancelling of a focus flight.+ // through a per-frame accumulator, with the same zoom-then-reanchor and+ // cancelling of a focus flight as wheel input.const active = touches.current;// Self-heal the other way too: no contact for this pointer means it is not// down, whatever we were told.diff --git a/web/src/hooks/usePanZoomGestures.clienttest.tsx b/web/src/hooks/usePanZoomGestures.clienttest.tsxnew file mode 100644index 0000000000..8a77734a6b--- /dev/null+++ b/web/src/hooks/usePanZoomGestures.clienttest.tsx@@ -0,0 +1,379 @@+import { act, cleanup, renderHook } from "@testing-library/react";+import { type PointerEvent as ReactPointerEvent } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ classifyPanZoomWheel,+ panZoomAnchor,+} from "@/src/utils/panZoomGestures";+import { usePanZoomGestures } from "./usePanZoomGestures";++const bounds = new DOMRect(20, 40, 400, 200);+let frames: Map<number, FrameRequestCallback>;+let nextFrame: number;++beforeEach(() => {+ frames = new Map();+ nextFrame = 1;+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ const id = nextFrame++;+ frames.set(id, callback);+ return id;+ });+ vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));+});+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+});++function flushFrame() {+ act(() => {+ const callbacks = [...frames.values()];+ frames.clear();+ callbacks.forEach((callback) => callback(16));+ });+}++function surface() {+ const element = document.createElement("div");+ element.getBoundingClientRect = () => bounds;+ element.setPointerCapture = vi.fn();+ element.releasePointerCapture = vi.fn();+ element.hasPointerCapture = vi.fn(() => false);+ return element;+}++function pointer(+ element: HTMLElement,+ pointerId: number,+ x: number,+ y: number,+ options: { isPrimary?: boolean; pointerType?: string; buttons?: number } = {},+): ReactPointerEvent<HTMLElement> {+ return {+ currentTarget: element,+ pointerId,+ clientX: x,+ clientY: y,+ pointerType: options.pointerType ?? "touch",+ isPrimary: options.isPrimary ?? false,+ button: 0,+ buttons: options.buttons ?? 1,+ preventDefault: vi.fn(),+ } as unknown as ReactPointerEvent<HTMLElement>;+}++describe("pan and zoom device input", () => {+ it("keeps a fast unmodified scroll as pan and normalizes line/page units", () => {+ expect(+ classifyPanZoomWheel(new WheelEvent("wheel", { deltaY: 400 }), bounds),+ ).toEqual({ kind: "pan", dxPx: -0, dyPx: -400 });+ expect(+ classifyPanZoomWheel(+ new WheelEvent("wheel", { deltaX: 2, deltaY: 3, deltaMode: 1 }),+ bounds,+ ),+ ).toEqual({ kind: "pan", dxPx: -32, dyPx: -48 });+ expect(+ classifyPanZoomWheel(+ new WheelEvent("wheel", { deltaY: 1, deltaMode: 2, shiftKey: true }),+ bounds,+ ),+ ).toEqual({ kind: "pan", dxPx: -200, dyPx: 0 });+ });++ it("anchors to the measured surface and clamps an off-surface pointer", () => {+ expect(panZoomAnchor({ x: 320, y: 90 }, bounds)).toEqual({+ x: 0.75,+ y: 0.25,+ });+ expect(panZoomAnchor({ x: -100, y: 300 }, bounds)).toEqual({ x: 0, y: 1 });+ expect(panZoomAnchor({ x: 20, y: 40 }, new DOMRect(20, 40, 0, 0))).toEqual({+ x: 0.5,+ y: 0.5,+ });+ });++ it("accumulates pinch zoom in scale levels once per frame at the cursor", () => {+ const element = surface();+ const onZoom = vi.fn();+ renderHook(() =>+ usePanZoomGestures({+ target: { current: element },+ onPan: vi.fn(),+ onZoom,+ }),+ );+ const wheel = () =>+ new WheelEvent("wheel", {+ deltaY: -4,+ ctrlKey: true,+ clientX: 320,+ clientY: 90,+ cancelable: true,+ });+ const first = wheel();+ element.dispatchEvent(first);+ element.dispatchEvent(wheel());+ expect(first.defaultPrevented).toBe(true);+ expect(onZoom).not.toHaveBeenCalled();+ expect(frames.size).toBe(1);+ flushFrame();+ expect(onZoom).toHaveBeenCalledExactlyOnceWith(0.2, { x: 0.75, y: 0.25 });+ });++ it("hands page scrolling back at the camera boundary", () => {+ const element = surface();+ const onPan = vi.fn();+ renderHook(() =>+ usePanZoomGestures({+ target: { current: element },+ onPan,+ onZoom: vi.fn(),+ canPan: () => false,+ }),+ );+ const event = new WheelEvent("wheel", { deltaY: 100, cancelable: true });+ element.dispatchEvent(event);+ flushFrame();+ expect(event.defaultPrevented).toBe(false);+ expect(onPan).not.toHaveBeenCalled();+ });++ it("delays pointer capture until dragging and preserves ordinary clicks", () => {+ const element = surface();+ const onPan = vi.fn();+ const click = vi.fn();+ const parent = document.createElement("div");+ parent.append(element);+ parent.addEventListener("click", click);+ const target = { current: element };+ const { result } = renderHook(() =>+ usePanZoomGestures({ target, onPan, onZoom: vi.fn() }),+ );+ act(() => {+ result.current.pointerHandlers.onPointerDown(+ pointer(element, 1, 100, 100, {+ isPrimary: true,+ pointerType: "mouse",+ }),+ );+ result.current.pointerHandlers.onPointerMove(+ pointer(element, 1, 102, 100, { pointerType: "mouse" }),+ );+ });+ expect(element.setPointerCapture).not.toHaveBeenCalled();+ act(() => {+ result.current.pointerHandlers.onPointerUp(pointer(element, 1, 102, 100));+ });+ element.dispatchEvent(+ new MouseEvent("click", { cancelable: true, bubbles: true }),+ );+ expect(click).toHaveBeenCalledOnce();++ act(() => {+ result.current.pointerHandlers.onPointerDown(+ pointer(element, 2, 100, 100, {+ isPrimary: true,+ pointerType: "mouse",+ }),+ );+ result.current.pointerHandlers.onPointerMove(+ pointer(element, 2, 110, 120),+ );+ });+ expect(element.setPointerCapture).toHaveBeenCalledExactlyOnceWith(2);+ flushFrame();+ expect(onPan).toHaveBeenCalledExactlyOnceWith(10, 20);+ act(() => {+ result.current.pointerHandlers.onPointerUp(pointer(element, 2, 110, 120));+ });+ const draggedClick = new MouseEvent("click", {+ cancelable: true,+ bubbles: true,+ detail: 1,+ });+ element.dispatchEvent(draggedClick);+ expect(draggedClick.defaultPrevented).toBe(true);+ expect(click).toHaveBeenCalledOnce();+ });++ it("combines a touch pinch with midpoint pan and reanchors the surviving finger", () => {+ const element = surface();+ const onZoom = vi.fn();+ const onPan = vi.fn();+ const target = { current: element };+ const { result } = renderHook(() =>+ usePanZoomGestures({ target, onPan, onZoom }),+ );+ act(() => {+ result.current.pointerHandlers.onPointerDown(+ pointer(element, 1, 120, 140, { isPrimary: true }),+ );+ result.current.pointerHandlers.onPointerDown(+ pointer(element, 2, 220, 140),+ );+ result.current.pointerHandlers.onPointerMove(+ pointer(element, 2, 320, 140),+ );+ result.current.pointerHandlers.onPointerMove(+ pointer(element, 1, 140, 140),+ );+ });+ flushFrame();+ // 100px → 180px; anchor is the original midpoint, then 60px translation.+ expect(onZoom).toHaveBeenCalledExactlyOnceWith(Math.log2(1.8), {+ x: 0.375,+ y: 0.5,+ });+ expect(onPan).toHaveBeenCalledExactlyOnceWith(60, 0);+ act(() => {+ result.current.pointerHandlers.onPointerUp(pointer(element, 2, 320, 140));+ result.current.pointerHandlers.onPointerMove(+ pointer(element, 1, 150, 140),+ );+ });+ flushFrame();+ expect(onPan).toHaveBeenLastCalledWith(10, 0);+ expect(onZoom).toHaveBeenCalledOnce();+ });++ it("continues pinching when three contacts become a different pair", () => {+ const element = surface();+ const onZoom = vi.fn();+ const onPan = vi.fn();+ const target = { current: element };+ const { result } = renderHook(() =>+ usePanZoomGestures({ target, onPan, onZoom }),+ );+ act(() => {+ result.current.pointerHandlers.onPointerDown(+ pointer(element, 1, 120, 140, { isPrimary: true }),+ );+ result.current.pointerHandlers.onPointerDown(+ pointer(element, 2, 220, 140),+ );+ result.current.pointerHandlers.onPointerDown(+ pointer(element, 3, 320, 140),+ );+ result.current.pointerHandlers.onPointerUp(pointer(element, 1, 120, 140));+ result.current.pointerHandlers.onPointerMove(+ pointer(element, 3, 420, 140),+ );+ });+ flushFrame();+ expect(onZoom).toHaveBeenCalledExactlyOnceWith(1, { x: 0.625, y: 0.5 });+ expect(onPan).toHaveBeenCalledExactlyOnceWith(50, 0);+ expect(result.current.isDragging).toBe(true);+ });++ it("preserves the first toolbar tap after a pinch without allowing the pinch's click", () => {+ const element = surface();+ const button = document.createElement("button");+ element.append(button);+ button.addEventListener("pointerdown", (event) => event.stopPropagation());+ const click = vi.fn();+ button.addEventListener("click", click);+ const target = { current: element };+ const { result } = renderHook(() =>+ usePanZoomGestures({ target, onPan: vi.fn(), onZoom: vi.fn() }),+ );+ const pinch = () =>+ act(() => {+ result.current.pointerHandlers.onPointerDown(+ pointer(element, 1, 120, 140, { isPrimary: true }),+ );+ result.current.pointerHandlers.onPointerDown(+ pointer(element, 2, 220, 140),+ );+ result.current.pointerHandlers.onPointerUp(+ pointer(element, 2, 220, 140),+ );+ result.current.pointerHandlers.onPointerUp(+ pointer(element, 1, 120, 140),+ );+ });++ // Touch pinches need not produce a click; a toolbar owns the next press.+ pinch();+ button.dispatchEvent(new Event("pointerdown", { bubbles: true }));+ const tap = new MouseEvent("click", {+ cancelable: true,+ bubbles: true,+ detail: 1,+ });+ button.dispatchEvent(tap);+ expect(tap.defaultPrevented).toBe(false);+ expect(click).toHaveBeenCalledOnce();++ pinch();+ const pinchClick = new MouseEvent("click", {+ cancelable: true,+ bubbles: true,+ detail: 1,+ });+ element.dispatchEvent(pinchClick);+ expect(pinchClick.defaultPrevented).toBe(true);+ expect(click).toHaveBeenCalledOnce();++ pinch();+ const keyboardClick = new MouseEvent("click", {+ cancelable: true,+ bubbles: true,+ detail: 0,+ });+ button.dispatchEvent(keyboardClick);+ expect(keyboardClick.defaultPrevented).toBe(false);+ expect(click).toHaveBeenCalledTimes(2);+ });++ it("forgets a mouse press released outside the surface before capture", () => {+ const element = surface();+ const onPan = vi.fn();+ const target = { current: element };+ const { result } = renderHook(() =>+ usePanZoomGestures({ target, onPan, onZoom: vi.fn() }),+ );+ act(() => {+ result.current.pointerHandlers.onPointerDown(+ pointer(element, 1, 21, 100, {+ isPrimary: true,+ pointerType: "mouse",+ }),+ );+ result.current.pointerHandlers.onPointerMove(+ pointer(element, 1, 20, 100, { pointerType: "mouse" }),+ );+ // The release happens outside, so the next event is an unpressed hover.+ result.current.pointerHandlers.onPointerMove(+ pointer(element, 1, 100, 100, { pointerType: "mouse", buttons: 0 }),+ );+ });+ flushFrame();+ expect(element.setPointerCapture).not.toHaveBeenCalled();+ expect(onPan).not.toHaveBeenCalled();+ expect(result.current.isDragging).toBe(false);+ });++ it("uses the latest camera callbacks for a pending frame and cancels on unmount", () => {+ const element = surface();+ const target = { current: element };+ const oldPan = vi.fn();+ const nextPan = vi.fn();+ const { rerender, unmount } = renderHook(+ ({ onPan }) => usePanZoomGestures({ target, onPan, onZoom: vi.fn() }),+ { initialProps: { onPan: oldPan } },+ );+ element.dispatchEvent(new WheelEvent("wheel", { deltaY: 20 }));+ rerender({ onPan: nextPan });+ flushFrame();+ expect(oldPan).not.toHaveBeenCalled();+ expect(nextPan).toHaveBeenCalledExactlyOnceWith(0, -20);+ element.dispatchEvent(new WheelEvent("wheel", { deltaY: 20 }));+ unmount();+ expect(frames.size).toBe(0);+ flushFrame();+ expect(nextPan).toHaveBeenCalledOnce();+ });+});diff --git a/web/src/hooks/usePanZoomGestures.ts b/web/src/hooks/usePanZoomGestures.tsnew file mode 100644index 0000000000..ace529a4d5--- /dev/null+++ b/web/src/hooks/usePanZoomGestures.ts@@ -0,0 +1,283 @@+import {+ useEffect,+ useRef,+ useState,+ type PointerEvent as ReactPointerEvent,+ type RefObject,+} from "react";+import {+ classifyPanZoomWheel,+ panZoomAnchor,+ type PanZoomAnchor,+} from "@/src/utils/panZoomGestures";++const DRAG_THRESHOLD_PX = 3;+const WHEEL_END_MS = 120;++/**+ * Device input only: callers own viewport math and rendering. Browser listeners,+ * pointer capture and animation-frame batching share one mount/cleanup lifecycle.+ */+export function usePanZoomGestures(options: Options) {+ const { target, enabled = true, pointerPan = true } = options;+ const live = useRef(options);+ live.current = options;+ const [isDragging, setIsDragging] = useState(false);+ const pending = useRef({+ levels: 0,+ dxPx: 0,+ dyPx: 0,+ anchor: { x: 0.5, y: 0.5 },+ frame: 0,+ });+ const wheelEnd = useRef<ReturnType<typeof setTimeout> | null>(null);+ const contacts = useRef(new Map<number, Point>());+ const pinch = useRef<{ distance: number; midpoint: Point } | null>(null);+ const press = useRef<{+ pointerId: number;+ origin: Point;+ last: Point;+ dragged: boolean;+ } | null>(null);+ const suppressClick = useRef(false);++ const flush = () => {+ const queued = pending.current;+ queued.frame = 0;+ const { levels, dxPx, dyPx, anchor } = queued;+ queued.levels = 0;+ queued.dxPx = 0;+ queued.dyPx = 0;+ // Zoom about the previous midpoint, then translate to the new one. Both+ // callbacks read the caller's current camera, including the prior callback.+ if (levels !== 0) live.current.onZoom(levels, anchor);+ if (dxPx !== 0 || dyPx !== 0) live.current.onPan(dxPx, dyPx);+ };+ const flushRef = useRef(flush);+ flushRef.current = flush;++ const schedule = () => {+ live.current.onInteractionStart?.();+ if (!pending.current.frame) {+ pending.current.frame = requestAnimationFrame(() => flushRef.current());+ }+ };+ const finish = () => {+ if (pending.current.frame) {+ cancelAnimationFrame(pending.current.frame);+ flushRef.current();+ }+ live.current.onInteractionEnd?.();+ };++ useEffect(() => {+ const element = target.current;+ if (!element || !enabled) return;+ const activeContacts = contacts.current;+ const onWheel = (event: WheelEvent) => {+ const input = classifyPanZoomWheel(+ event,+ element.getBoundingClientRect(),+ );+ const queued = pending.current;+ if (input.kind === "zoom") {+ queued.levels += input.levels;+ queued.anchor = input.anchor;+ } else {+ if (live.current.canPan?.(input.dxPx, input.dyPx) === false) return;+ queued.dxPx += input.dxPx;+ queued.dyPx += input.dyPx;+ }+ event.preventDefault();+ live.current.onInteractionStart?.();+ if (!queued.frame) {+ queued.frame = requestAnimationFrame(() => flushRef.current());+ }+ if (wheelEnd.current) clearTimeout(wheelEnd.current);+ wheelEnd.current = setTimeout(() => {+ wheelEnd.current = null;+ if (pending.current.frame) {+ cancelAnimationFrame(pending.current.frame);+ flushRef.current();+ }+ live.current.onInteractionEnd?.();+ }, WHEEL_END_MS);+ };+ const onClick = (event: MouseEvent) => {+ if (!suppressClick.current || event.detail === 0) return;+ suppressClick.current = false;+ event.preventDefault();+ event.stopPropagation();+ };+ // A new press may belong to a child control that stops pointer bubbling.+ const onPress = () => {+ suppressClick.current = false;+ };+ element.addEventListener("wheel", onWheel, { passive: false });+ element.addEventListener("pointerdown", onPress, { capture: true });+ element.addEventListener("click", onClick, { capture: true });+ return () => {+ element.removeEventListener("wheel", onWheel);+ element.removeEventListener("pointerdown", onPress, { capture: true });+ element.removeEventListener("click", onClick, { capture: true });+ if (pending.current.frame) cancelAnimationFrame(pending.current.frame);+ if (wheelEnd.current) clearTimeout(wheelEnd.current);+ pending.current = {+ levels: 0,+ dxPx: 0,+ dyPx: 0,+ anchor: { x: 0.5, y: 0.5 },+ frame: 0,+ };+ activeContacts.clear();+ press.current = null;+ pinch.current = null;+ };+ }, [target, enabled]);++ const onPointerDown = (event: ReactPointerEvent<HTMLElement>) => {+ if (!enabled || !pointerPan) return;+ if (event.pointerType !== "touch" && event.button !== 0) return;+ if (event.isPrimary) {+ contacts.current.clear();+ pinch.current = null;+ setIsDragging(false);+ }+ suppressClick.current = false;+ const point = { x: event.clientX, y: event.clientY };+ contacts.current.set(event.pointerId, point);+ if (contacts.current.size >= 2) {+ const [a, b] = [...contacts.current.values()];+ pinch.current = {+ distance: Math.hypot(b.x - a.x, b.y - a.y),+ midpoint: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 },+ };+ press.current = null;+ suppressClick.current = true;+ setIsDragging(true);+ for (const pointerId of contacts.current.keys()) {+ capture(event.currentTarget, pointerId);+ }+ live.current.onInteractionStart?.();+ return;+ }+ press.current = {+ pointerId: event.pointerId,+ origin: point,+ last: point,+ dragged: false,+ };+ };++ const onPointerMove = (event: ReactPointerEvent<HTMLElement>) => {+ if (!enabled || !pointerPan || !contacts.current.has(event.pointerId))+ return;+ // An uncaptured press can release outside the surface without a pointerup.+ if (event.pointerType === "mouse" && event.buttons === 0) {+ releasePointer(event);+ suppressClick.current = false;+ return;+ }+ const point = { x: event.clientX, y: event.clientY };+ contacts.current.set(event.pointerId, point);+ const previous = pinch.current;+ if (contacts.current.size >= 2 && previous) {+ const [a, b] = [...contacts.current.values()];+ const distance = Math.hypot(b.x - a.x, b.y - a.y);+ const midpoint = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };+ const queued = pending.current;+ if (previous.distance > 0 && distance > 0) {+ queued.levels += Math.log2(distance / previous.distance);+ if (!queued.frame) {+ queued.anchor = panZoomAnchor(+ previous.midpoint,+ event.currentTarget.getBoundingClientRect(),+ );+ }+ }+ queued.dxPx += midpoint.x - previous.midpoint.x;+ queued.dyPx += midpoint.y - previous.midpoint.y;+ pinch.current = { distance, midpoint };+ event.preventDefault();+ schedule();+ return;+ }+ const current = press.current;+ if (!current || current.pointerId !== event.pointerId) return;+ if (!current.dragged) {+ const distance = Math.hypot(+ point.x - current.origin.x,+ point.y - current.origin.y,+ );+ if (distance < DRAG_THRESHOLD_PX) return;+ current.dragged = true;+ suppressClick.current = true;+ setIsDragging(true);+ capture(event.currentTarget, event.pointerId);+ }+ pending.current.dxPx += point.x - current.last.x;+ pending.current.dyPx += point.y - current.last.y;+ current.last = point;+ event.preventDefault();+ schedule();+ };++ const releasePointer = (event: ReactPointerEvent<HTMLElement>) => {+ if (!enabled || !pointerPan) return;+ if (!contacts.current.has(event.pointerId)) return;+ contacts.current.delete(event.pointerId);+ pinch.current = null;+ if (contacts.current.size >= 2) {+ const [a, b] = [...contacts.current.values()];+ pinch.current = {+ distance: Math.hypot(b.x - a.x, b.y - a.y),+ midpoint: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 },+ };+ press.current = null;+ } else if (contacts.current.size === 1) {+ const [pointerId, point] = [...contacts.current.entries()][0];+ press.current = {+ pointerId,+ origin: point,+ last: point,+ dragged: false,+ };+ } else if (contacts.current.size === 0) {+ press.current = null;+ setIsDragging(false);+ finish();+ }+ if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {+ event.currentTarget.releasePointerCapture(event.pointerId);+ }+ };++ const capture = (element: HTMLElement, pointerId: number) => {+ element.setPointerCapture?.(pointerId);+ };++ return {+ isDragging: enabled && isDragging,+ pointerHandlers: {+ onPointerDown,+ onPointerMove,+ onPointerUp: releasePointer,+ onPointerCancel: releasePointer,+ onLostPointerCapture: releasePointer,+ },+ };+}++type Point = { x: number; y: number };+type Options = {+ target: RefObject<HTMLElement | null>;+ onPan: (dxPx: number, dyPx: number) => void;+ /** One level doubles scale; anchor coordinates are fractions of the surface. */+ onZoom: (levels: number, anchor: PanZoomAnchor) => void;+ canPan?: (dxPx: number, dyPx: number) => boolean;+ onInteractionStart?: () => void;+ onInteractionEnd?: () => void;+ enabled?: boolean;+ /** A surface with its own marquee gestures can reuse just the wheel adapter. */+ pointerPan?: boolean;+};diff --git a/web/src/utils/panZoomGestures.ts b/web/src/utils/panZoomGestures.tsnew file mode 100644index 0000000000..9e53a46c5f--- /dev/null+++ b/web/src/utils/panZoomGestures.ts@@ -0,0 +1,66 @@+const PINCH_ZOOM_RATE = 1 / 40;+const WHEEL_LINE_PX = 16;++/** Scroll pans; only pinch or an explicit modifier asks for zoom. */+export function classifyPanZoomWheel(+ event: WheelInput,+ bounds: SurfaceBounds,+):+ | { kind: "pan"; dxPx: number; dyPx: number }+ | { kind: "zoom"; levels: number; anchor: PanZoomAnchor } {+ const unit = wheelUnit(event.deltaMode, bounds.height);+ const deltaX = finite(event.deltaX) * unit;+ const deltaY = finite(event.deltaY) * unit;+ if (event.ctrlKey || event.metaKey) {+ return {+ kind: "zoom",+ levels: -deltaY * PINCH_ZOOM_RATE,+ anchor: panZoomAnchor({ x: event.clientX, y: event.clientY }, bounds),+ };+ }+ return {+ kind: "pan",+ dxPx: event.shiftKey ? -deltaY : -deltaX,+ dyPx: event.shiftKey ? 0 : -deltaY,+ };+}++/** Fractions of the measured surface; off-surface contacts stay at its edge. */+export function panZoomAnchor(+ point: { x: number; y: number },+ bounds: SurfaceBounds,+): PanZoomAnchor {+ return {+ x: ratio(point.x - bounds.left, bounds.width),+ y: ratio(point.y - bounds.top, bounds.height),+ };+}++function wheelUnit(deltaMode: number, height: number) {+ if (deltaMode === 1) return WHEEL_LINE_PX;+ if (deltaMode === 2) return Math.max(height, 1);+ return 1;+}++function ratio(value: number, extent: number) {+ return extent > 0 ? Math.min(Math.max(finite(value) / extent, 0), 1) : 0.5;+}++function finite(value: number) {+ return Number.isFinite(value) ? value : 0;+}++export type PanZoomAnchor = { x: number; y: number };++type SurfaceBounds = Pick<DOMRect, "left" | "top" | "width" | "height">;+type WheelInput = Pick<+ WheelEvent,+ | "deltaX"+ | "deltaY"+ | "deltaMode"+ | "ctrlKey"+ | "metaKey"+ | "shiftKey"+ | "clientX"+ | "clientY"+>;