Skip to content

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

feat(topics): make it work well on mobile (#19364)

Nimar0e024ca8eae1
diff --git a/web/src/features/topics/AutomaticProcessingControl.stories.tsx b/web/src/features/topics/AutomaticProcessingControl.stories.tsx
index aa8d0f9b26..e96ebe821c 100644
--- a/web/src/features/topics/AutomaticProcessingControl.stories.tsx
+++ b/web/src/features/topics/AutomaticProcessingControl.stories.tsx
@@ -1,34 +1,63 @@
import { expect, fn, userEvent, within } from "storybook/test";
-
import preview from "../../../.storybook/preview";
import { AutomaticProcessingControl } from "./AutomaticProcessingControl";
+import {
+ prepareAutomaticProcessingAction,
+ type AutomaticProcessingState,
+} from "./prepare-topics-actions";
const meta = preview.meta({
component: AutomaticProcessingControl,
parameters: { layout: "centered" },
- args: { canWrite: true, onOpen: fn() },
});
-export default meta;
+const states: AutomaticProcessingState[] = [
+ { status: "unconfigured" },
+ { status: "off" },
+ { status: "on" },
+ { status: "paused", shortLabel: "LLM connection missing" },
+];
-export const Unconfigured = meta.story({
- args: { state: { status: "unconfigured" } },
+export const VariantMatrix = meta.story({
+ render: () => (
+ <div className="flex flex-col items-end gap-4">
+ {states.map((state) => (
+ <AutomaticProcessingControl
+ key={state.status}
+ action={prepareAutomaticProcessingAction({
+ state,
+ canWrite: true,
+ saving: false,
+ onSelect: fn(),
+ })}
+ />
+ ))}
+ </div>
+ ),
});
-export const Off = meta.story({
- name: "(Test) Opens the dialog to turn on",
- args: { state: { status: "off" } },
- play: async ({ args }) => {
- const body = within(document.body);
- await userEvent.click(
- body.getByRole("button", { name: /Automatic processing/ }),
+export const ReadOnlyPaused = meta.story({
+ name: "(Test) Read-only users can see the pause reason",
+ args: {
+ action: prepareAutomaticProcessingAction({
+ state: { status: "paused", shortLabel: "LLM connection missing" },
+ canWrite: false,
+ saving: false,
+ onSelect: fn(),
+ }),
+ },
+ play: async ({ canvasElement }) => {
+ const button = within(canvasElement).getByRole("button", {
+ name: "Automatic processing",
+ });
+ await expect(button).toBeDisabled();
+ await userEvent.hover(button.parentElement!);
+ const tooltip = await within(canvasElement.ownerDocument.body).findByRole(
+ "tooltip",
+ );
+ await expect(tooltip).toHaveTextContent("LLM connection missing");
+ await expect(tooltip).toHaveTextContent(
+ "You need permission to edit Topics.",
);
- await expect(args.onOpen).toHaveBeenCalledOnce();
},
});
-
-export const On = meta.story({ args: { state: { status: "on" } } });
-
-export const Paused = meta.story({
- args: { state: { status: "paused", shortLabel: "LLM connection missing" } },
-});
diff --git a/web/src/features/topics/AutomaticProcessingControl.tsx b/web/src/features/topics/AutomaticProcessingControl.tsx
index 6ac395716c..66b9dc7a5d 100644
--- a/web/src/features/topics/AutomaticProcessingControl.tsx
+++ b/web/src/features/topics/AutomaticProcessingControl.tsx
@@ -1,46 +1,32 @@
-/* eslint-disable @typescript-eslint/no-use-before-define */
import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";
import { Button } from "@/src/components/design-system/Button/Button";
-import {
- StatusBadge,
- type Status,
-} from "@/src/components/ui/StatusBadge/StatusBadge";
+import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";
+import { type AutomaticProcessingAction } from "./prepare-topics-actions";
-/**
- * Topics header status for automatic processing. Turning it on or off and the
- * sampling rate happen in the dialog it opens, next to the models that run.
- */
+/** Status and dialog trigger for the automatic-processing action. */
export function AutomaticProcessingControl({
- canWrite,
- onOpen,
- state,
-}: AutomaticProcessingControlProps) {
- const reason = disabledReason(state, canWrite);
+ action,
+}: {
+ action: AutomaticProcessingAction;
+}) {
const button = (
<Button
- text="Automatic processing"
+ text={action.label}
size="sm"
- variant={
- state.status === "off" || state.status === "paused"
- ? "primary"
- : "secondary"
- }
- disabled={reason !== null}
- onClick={onOpen}
+ variant={action.variant}
+ disabled={Boolean(action.disabledReason)}
+ onClick={action.onSelect}
/>
);
return (
<div className="flex shrink-0 items-center gap-1">
- <div
- role="status"
- aria-label={`Automatic processing: ${statusLabel(state)}`}
- >
- <StatusBadge type={badgeStatus(state)} showText={false}>
- {statusLabel(state)}
+ <div role="status" aria-label={`${action.label}: ${action.badge}`}>
+ <StatusBadge type={action.badgeStatus} showText={false}>
+ {action.badge}
</StatusBadge>
</div>
- {reason ? (
- <Tooltip label={state.status === "paused" ? state.shortLabel : reason}>
+ {action.disabledReason ? (
+ <Tooltip label={action.disabledReason}>
{({ getTriggerProps }) => (
<span {...getTriggerProps()}>{button}</span>
)}
@@ -51,33 +37,3 @@ export function AutomaticProcessingControl({
</div>
);
}
-
-function badgeStatus(state: AutomaticProcessingState): Status {
- if (state.status === "on") return "active";
- if (state.status === "paused") return "paused";
- return "inactive";
-}
-
-function statusLabel(state: AutomaticProcessingState) {
- if (state.status === "on") return "On";
- if (state.status === "paused") return "Paused";
- return "Off";
-}
-
-function disabledReason(state: AutomaticProcessingState, canWrite: boolean) {
- if (state.status === "unconfigured") return "Configure Topics first.";
- if (!canWrite) return "You need permission to edit Topics.";
- return null;
-}
-
-export type AutomaticProcessingState =
- | { status: "unconfigured" }
- | { status: "off" }
- | { status: "on" }
- | { status: "paused"; shortLabel: string };
-
-type AutomaticProcessingControlProps = {
- state: AutomaticProcessingState;
- canWrite: boolean;
- onOpen: () => void;
-};
diff --git a/web/src/features/topics/ConfigureTopicsDialog.tsx b/web/src/features/topics/ConfigureTopicsDialog.tsx
index 71ffed39c6..29af8b36b4 100644
--- a/web/src/features/topics/ConfigureTopicsDialog.tsx
+++ b/web/src/features/topics/ConfigureTopicsDialog.tsx
@@ -322,7 +322,7 @@ export function ConfigureTopicsDialog(props: ConfigureTopicsDialogProps) {
compactBottomSpacing
>
<div className="flex items-center gap-2">
- <div className="w-24">
+ <div className="w-24 shrink-0">
<Input
aria-label="Seconds to wait after the last observation"
type="number"
@@ -420,11 +420,11 @@ function ModelSlot({
);
return (
- <div className="flex items-start gap-2">
- <p className="flex h-8 w-36 shrink-0 items-center text-sm font-bold">
+ <div className="flex flex-col items-start gap-2 sm:flex-row">
+ <p className="flex shrink-0 items-center text-sm font-bold sm:h-8 sm:w-36">
{copy.label}
</p>
- <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <div className="flex w-full min-w-0 flex-1 flex-col gap-1">
{locked ? (
<Tooltip>
<TooltipTrigger asChild>{fields}</TooltipTrigger>
diff --git a/web/src/features/topics/CurrentTopics.tsx b/web/src/features/topics/CurrentTopics.tsx
index 8b9cd84831..b4addb3e02 100644
--- a/web/src/features/topics/CurrentTopics.tsx
+++ b/web/src/features/topics/CurrentTopics.tsx
@@ -12,6 +12,10 @@ import { TopicGridView } from "./TopicGridView";
import { TopicTreemapView } from "./TopicTreemapView";
import { type TopicsResultsView } from "./TopicsResultsViewSelect";
import type { useTopicTraceFilters } from "./useTopicTraceFilters";
+import { useIsHandheld } from "@/src/hooks/use-mobile";
+import useSessionStorage from "@/src/components/useSessionStorage";
+import { useReadPath } from "@/src/features/events/hooks/useReadPath";
+import { MobileTopicsView } from "./MobileTopicsView";
export function CurrentTopics({
projectId,
@@ -46,7 +50,7 @@ export function CurrentTopics({
{result.isLoading && <p className="text-sm">Loading topics…</p>}
{selectedFacet && (
<CurrentFacet
- key={JSON.stringify([projectId, selectedFacet.facetId])}
+ key={projectId}
projectId={projectId}
facet={selectedFacet}
timeRange={timeRange}
@@ -71,6 +75,7 @@ function CurrentFacet({
onGenerateTopics,
canGenerateTopics,
}: CurrentFacetProps) {
+ const isHandheld = useIsHandheld();
const mapResult = useCurrentTopicMap(
projectId,
view === "treemap" ? undefined : facet.map?.runId,
@@ -82,9 +87,23 @@ function CurrentFacet({
queryParams: ["observation", "display", "timestamp", "traceId"],
});
const peekView = { itemType: "TRACE" as const, ...peekNavigation };
+ if (isHandheld)
+ return (
+ <MobileTopics
+ projectId={projectId}
+ facet={facet}
+ view={view}
+ mapResult={mapResult}
+ traceFilters={traceFilters}
+ onGenerateTopics={onGenerateTopics}
+ canGenerateTopics={canGenerateTopics}
+ onOpenTrace={peekNavigation.openPeek}
+ />
+ );
if (view === "treemap")
return (
<TopicTreemapView
+ key={facet.facetId}
projectId={projectId}
facet={facet}
onGenerateTopics={onGenerateTopics}
@@ -95,6 +114,7 @@ function CurrentFacet({
if (view === "map")
return (
<CurrentTopicsView
+ key={facet.facetId}
projectId={projectId}
facet={facet}
mapResult={mapResult}
@@ -108,6 +128,7 @@ function CurrentFacet({
);
return (
<TopicGridView
+ key={facet.facetId}
projectId={projectId}
facet={facet}
mapResult={mapResult}
@@ -120,6 +141,51 @@ function CurrentFacet({
);
}
+function MobileTopics({
+ projectId,
+ facet,
+ view,
+ mapResult,
+ traceFilters,
+ onGenerateTopics,
+ canGenerateTopics,
+ onOpenTrace,
+}: Pick<
+ CurrentFacetProps,
+ | "projectId"
+ | "facet"
+ | "view"
+ | "traceFilters"
+ | "onGenerateTopics"
+ | "canGenerateTopics"
+> & {
+ mapResult: ReturnType<typeof useCurrentTopicMap>;
+ onOpenTrace: (traceId: string) => void;
+}) {
+ const { isV4 } = useReadPath();
+ const [selectedTraceId, setSelectedTraceId] = useSessionStorage<
+ string | null
+ >(`topics-selected-trace:${projectId}`, null);
+ return (
+ <MobileTopicsView
+ projectId={projectId}
+ facet={facet}
+ view={view}
+ mapResult={mapResult}
+ filters={traceFilters.filters}
+ searchQuery={traceFilters.searchQuery}
+ onFiltersChange={traceFilters.setFilters}
+ onSearchQueryChange={traceFilters.setSearchQuery}
+ selectedTraceId={selectedTraceId}
+ onSelectTrace={setSelectedTraceId}
+ onOpenTrace={onOpenTrace}
+ onGenerateTopics={onGenerateTopics}
+ canGenerateTopics={canGenerateTopics}
+ isV4={isV4}
+ />
+ );
+}
+
export function useCurrentTopics({
projectId,
running,
diff --git a/web/src/features/topics/CurrentTopicsView.tsx b/web/src/features/topics/CurrentTopicsView.tsx
index c2b1968e7b..cdf6ec310f 100644
--- a/web/src/features/topics/CurrentTopicsView.tsx
+++ b/web/src/features/topics/CurrentTopicsView.tsx
@@ -147,7 +147,6 @@ export function CurrentTopicsView({
<TopicEmbeddingMap
key={facet.map.runId}
query={mapResult}
- projectId={projectId}
topics={facet.map.topics}
selectedTopic={null}
matchingTraceIds={matchingTraceIds}
@@ -263,11 +262,13 @@ export function CurrentTopicsView({
);
return (
- <TopicsWorkspaceSplit
- isNarrow={isNarrow}
- overviewPanel={overviewPanel}
- tracesPanel={tracesPanel}
- />
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col p-2">
+ <TopicsWorkspaceSplit
+ isNarrow={isNarrow}
+ overviewPanel={overviewPanel}
+ tracesPanel={tracesPanel}
+ />
+ </div>
);
}
diff --git a/web/src/features/topics/EmbeddingMapView.stories.tsx b/web/src/features/topics/EmbeddingMapView.stories.tsx
index ace0cb8034..a295ea89c6 100644
--- a/web/src/features/topics/EmbeddingMapView.stories.tsx
+++ b/web/src/features/topics/EmbeddingMapView.stories.tsx
@@ -307,7 +307,6 @@ async function hoverInlineNode(canvasElement: HTMLElement) {
const meta = preview.meta({
component: EmbeddingMapView,
args: {
- projectId: "storybook-project",
topics: [{ id: "billing", name: "Billing" }],
data,
selectedTopic: null,
diff --git a/web/src/features/topics/MobileTopicVisualization.tsx b/web/src/features/topics/MobileTopicVisualization.tsx
new file mode 100644
index 0000000000..8f65dfa7f4
--- /dev/null
+++ b/web/src/features/topics/MobileTopicVisualization.tsx
@@ -0,0 +1,107 @@
+import { type ComponentProps } from "react";
+import { type Facet } from "./facet-topics";
+import { type TopicDisplay } from "./prepare-topic-display";
+import { TopicEmbeddingMap } from "./TopicEmbeddingMap";
+import { TopicGrid } from "./TopicGrid";
+import { TopicTreemap } from "./TopicTreemap";
+import { prepareTopicGrid } from "./prepare-topic-grid";
+import { type TopicsResultsView } from "./TopicsResultsViewSelect";
+
+type MobileTopicVisualizationProps = {
+ view: TopicsResultsView;
+ facet: Facet;
+ treemapTopics: TopicDisplay[];
+ mapResult: ComponentProps<typeof TopicEmbeddingMap>["query"];
+ selectedTopicId: string | null;
+ selectedTraceId: string | null;
+ matchingTraceIds?: ReadonlySet<string>;
+ onSelectTopic: (topicId: string | null) => void;
+ onSelectTrace: (traceId: string | null) => void;
+};
+
+function gridMessage(query: MobileTopicVisualizationProps["mapResult"]) {
+ if (query.error) return `Grid could not load: ${query.error.message}`;
+ if (!query.data) return "Loading grid…";
+ return query.data.reason ?? "This run has no saved embedding projection.";
+}
+
+export function MobileTopicVisualization({
+ view,
+ facet,
+ treemapTopics,
+ mapResult,
+ selectedTopicId,
+ selectedTraceId,
+ matchingTraceIds,
+ onSelectTopic,
+ onSelectTrace,
+}: MobileTopicVisualizationProps) {
+ function selectMapTopic(topicId: string | null) {
+ // Fitting the camera leaves the trace filters and active panel intact.
+ if (topicId !== null) onSelectTopic(topicId);
+ }
+ if (view === "treemap") {
+ return treemapTopics.length > 0 ? (
+ <div className="flex min-h-0 flex-1 p-4">
+ <TopicTreemap
+ key={facet.facetId}
+ total={facet.rows.length}
+ topics={treemapTopics}
+ selectedTopicId={selectedTopicId}
+ onSelectTopic={onSelectTopic}
+ previewOnSelect
+ />
+ </div>
+ ) : (
+ <p className="text-muted-foreground p-4 text-sm">
+ No topics in this time range. Browse traces to read their summaries.
+ </p>
+ );
+ }
+ if (!facet.map) {
+ return (
+ <p className="text-muted-foreground p-4 text-sm">
+ No map published for this facet. Browse topics or traces instead.
+ </p>
+ );
+ }
+ if (view === "map") {
+ return (
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col p-2">
+ <TopicEmbeddingMap
+ key={facet.map.runId}
+ query={mapResult}
+ topics={facet.map.topics}
+ selectedTopic={null}
+ selectedTraceId={selectedTraceId}
+ matchingTraceIds={matchingTraceIds}
+ onSelectTopic={selectMapTopic}
+ onSelectTrace={onSelectTrace}
+ previewOnSelect
+ fillContainer
+ />
+ </div>
+ );
+ }
+ if (mapResult.error || !mapResult.data || mapResult.data.status !== "ready") {
+ return (
+ <p className="text-muted-foreground p-4 text-sm">
+ {gridMessage(mapResult)}
+ </p>
+ );
+ }
+ const grid = prepareTopicGrid(facet, mapResult.data);
+ const selectedIndex = grid.topics.findIndex(
+ (topic) => topic.id === selectedTopicId,
+ );
+ return (
+ <TopicGrid
+ key={facet.map.runId}
+ {...grid}
+ selectedIndex={selectedIndex < 0 ? null : selectedIndex}
+ onSelectTopic={onSelectTopic}
+ onSelectTrace={onSelectTrace}
+ previewOnSelect
+ />
+ );
+}
diff --git a/web/src/features/topics/MobileTopicsView.stories.tsx b/web/src/features/topics/MobileTopicsView.stories.tsx
new file mode 100644
index 0000000000..c3392919b0
--- /dev/null
+++ b/web/src/features/topics/MobileTopicsView.stories.tsx
@@ -0,0 +1,434 @@
+import { useState, type ComponentProps } from "react";
+import { type FilterState } from "@langfuse/shared";
+import { expect, fn, userEvent, waitFor, within } from "storybook/test";
+import { Button } from "@/src/components/design-system/Button/Button";
+import preview from "../../../.storybook/preview";
+import { MobileTopicsView } from "./MobileTopicsView";
+import { TopicsMobileControls } from "./TopicsMobileControls";
+
+const topics = [
+ {
+ id: "billing",
+ name: "Billing and subscription questions",
+ description: "Requests about invoices, refunds, and plan changes.",
+ count: 21,
+ versionId: "v1",
+ runId: "run",
+ },
+ {
+ id: "access",
+ name: "Recovering access after changing a company email address",
+ description: "Sign-in and account recovery.",
+ count: 1,
+ versionId: "v2",
+ runId: "run",
+ },
+];
+const rows = [
+ ...topics.flatMap((topic) =>
+ Array.from({ length: topic.count }, (_, index) => ({
+ traceId: `${topic.id}-${index}`,
+ topicId: topic.id,
+ topicName: topic.name,
+ summary:
+ topic.id === "access"
+ ? "The user changed their work email and cannot sign in. They need to recover their workspace without losing their project history."
+ : `Invoice question ${index + 1}: the customer needs help understanding a charge and switching their subscription to annual billing.`,
+ outcome: "assigned" as const,
+ facetVersion: 1,
+ unitStartTime: "2026-10-20T12:00:00.000Z",
+ })),
+ ),
+ {
+ traceId: "unassigned",
+ topicId: null,
+ topicName: null,
+ summary: "A new request that has not been classified yet.",
+ outcome: "awaiting_map" as const,
+ facetVersion: 1,
+ unitStartTime: "2026-10-20T12:00:00.000Z",
+ },
+];
+const facet: ComponentProps<typeof MobileTopicsView>["facet"] = {
+ facetId: "intent",
+ name: "Intent",
+ facetVersion: 1,
+ topics,
+ rows,
+ map: { runId: "run", topics },
+ awaitingCount: 1,
+ usableCount: rows.length,
+};
+const mapResult = {
+ error: null,
+ data: {
+ status: "ready" as const,
+ reason: null,
+ missingSummaryCount: 0,
+ unpositionedCount: 0,
+ points: rows.map((row, index) => ({
+ ...row,
+ outcome: row.topicId ? ("assigned" as const) : ("unassigned" as const),
+ x: index % 5,
+ y: Math.floor(index / 5),
+ })),
+ },
+};
+
+function MobileExample(args: ComponentProps<typeof MobileTopicsView>) {
+ const [view, setView] = useState(args.view);
+ const [facetId, setFacetId] = useState(args.facet.facetId);
+ const facets = [
+ args.facet,
+ {
+ ...args.facet,
+ facetId: "issues",
+ name: "Unresolved customer support issues",
+ map: args.facet.map && { ...args.facet.map, runId: "other-map" },
+ },
+ ];
+ const facet = facets.find((facet) => facet.facetId === facetId)!;
+ const [filters, setFilters] = useState<FilterState>(args.filters);
+ const [searchQuery, setSearchQuery] = useState<string | null>(
+ args.searchQuery,
+ );
+ const [selectedTraceId, setSelectedTraceId] = useState(args.selectedTraceId);
+ return (
+ <div className="flex h-[min(720px,100dvh)] w-full max-w-[390px] flex-col border">
+ <div className="shrink-0 border-b p-2">
+ <TopicsMobileControls
+ facets={facets}
+ selectedFacet={facetId}
+ onSelectFacet={setFacetId}
+ view={view}
+ onSelectView={setView}
+ />
+ </div>
+ <MobileTopicsView
+ {...args}
+ facet={facet}
+ view={view}
+ filters={filters}
+ searchQuery={searchQuery}
+ onFiltersChange={setFilters}
+ onSearchQueryChange={setSearchQuery}
+ selectedTraceId={selectedTraceId}
+ onSelectTrace={(traceId) => {
+ args.onSelectTrace(traceId);
+ setSelectedTraceId(traceId);
+ }}
+ />
+ </div>
+ );
+}
+
+const defaultArgs: ComponentProps<typeof MobileTopicsView> = {
+ projectId: "storybook-topics",
+ facet,
+ view: "treemap",
+ mapResult,
+ filters: [],
+ searchQuery: null,
+ selectedTraceId: null,
+ isV4: false,
+ onFiltersChange: fn(),
+ onSearchQueryChange: fn(),
+ onSelectTrace: fn(),
+ onOpenTrace: fn(),
+ onGenerateTopics: fn(),
+ canGenerateTopics: true,
+};
+
+const meta = preview.meta({
+ component: MobileTopicsView,
+ parameters: { layout: "fullscreen" },
+ args: defaultArgs,
+ render: (args) => <MobileExample {...args} />,
+});
+
+export const Default = meta.story({});
+export const AwaitingTopics = meta.story({
+ args: {
+ facet: {
+ ...facet,
+ topics: [],
+ rows: rows.filter((row) => row.topicId === null),
+ map: null,
+ },
+ },
+});
+export const BrowseAndOpenTrace = meta.story({
+ name: "(Test) Reveal selection and browse topics, traces, and pages",
+ args: {
+ selectedTraceId: "billing-19",
+ filters: [
+ {
+ column: "topicId",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["billing"],
+ },
+ ],
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const selected = canvas.getByRole("button", {
+ name: "Open trace billing-19",
+ });
+ await waitFor(() => {
+ const card = selected.getBoundingClientRect();
+ const panel = canvas
+ .getByRole("region", { name: "Topic traces" })
+ .getBoundingClientRect();
+ expect(card.top).toBeGreaterThanOrEqual(panel.top);
+ expect(card.bottom).toBeLessThanOrEqual(panel.bottom);
+ });
+ await userEvent.click(canvas.getByRole("tab", { name: "Topics" }));
+ await userEvent.click(
+ canvas.getByRole("button", { name: `${topics[1].name}, 1 traces` }),
+ );
+ await expect(canvas.getByRole("tab", { name: "Traces" })).toHaveAttribute(
+ "data-state",
+ "active",
+ );
+ const trace = canvas.getByRole("button", { name: "Open trace access-0" });
+ await expect(within(trace).getByText(rows[21].summary!)).toBeVisible();
+ await userEvent.click(trace);
+ await expect(args.onOpenTrace).toHaveBeenCalledWith("access-0");
+ await userEvent.click(canvas.getByRole("tab", { name: "Topics" }));
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Unassigned, 1 traces" }),
+ );
+ await expect(
+ canvas.getByRole("button", { name: "Open trace unassigned" }),
+ ).toBeVisible();
+ await expect(
+ canvas.queryByRole("button", { name: "Open trace access-0" }),
+ ).not.toBeInTheDocument();
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Show all traces" }),
+ );
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Go to next page" }),
+ );
+ await expect(
+ canvas.getByRole("button", { name: "Open trace billing-20" }),
+ ).toBeVisible();
+ const pagination = within(
+ canvas.getByRole("navigation", { name: "Trace pagination" }),
+ );
+ await userEvent.click(pagination.getByRole("combobox"));
+ await userEvent.click(
+ within(canvasElement.ownerDocument.body).getByRole("option", {
+ name: "50",
+ }),
+ );
+ await expect(
+ canvas.getAllByRole("button", { name: /^Open trace / }),
+ ).toHaveLength(rows.length);
+ await expect(pagination.getByRole("combobox")).toBeVisible();
+ const search = canvas.getByRole("combobox", { name: "Search" });
+ await userEvent.click(search);
+ await userEvent.type(search, "no-match");
+ await userEvent.keyboard("{Enter}");
+ await expect(
+ await canvas.findByText("No matches. Adjust or clear your filters."),
+ ).toBeVisible();
+ await expect(search).toHaveFocus();
+ },
+});
+
+export const FitFilteredMap = meta.story({
+ name: "(Test) Fit and refresh preserve map preview and Unassigned results",
+ render: function RefreshableMap(args) {
+ const [facet, setFacet] = useState(args.facet);
+ return (
+ <>
+ <Button
+ text="Refresh results"
+ onClick={() => setFacet({ ...facet, rows: [...facet.rows] })}
+ />
+ <MobileExample {...args} facet={facet} />
+ </>
+ );
+ },
+ args: {
+ view: "map",
+ filters: [
+ {
+ column: "assignment",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["assigned"],
+ },
+ ],
+ mapResult: {
+ ...mapResult,
+ data: {
+ ...mapResult.data,
+ points: [
+ { ...mapResult.data.points[0], x: -10, y: -10 },
+ { ...mapResult.data.points[21], x: 10, y: 10 },
+ { ...mapResult.data.points[22], x: 0, y: 0 },
+ ],
+ },
+ },
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByRole("tab", { name: "Visualize" }));
+ await userEvent.click(canvas.getByRole("button", { name: "Fit map (0)" }));
+ await expect(
+ canvas.getByRole("tab", { name: "Visualize" }),
+ ).toHaveAttribute("data-state", "active");
+ for (
+ let attempt = 0;
+ attempt < 12 &&
+ canvas.queryAllByRole("button", { name: /^Select trace:/ }).length === 0;
+ attempt++
+ ) {
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Zoom in (+)" }),
+ );
+ await new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ );
+ }
+ const trace = await canvas.findByRole("button", { name: /^Select trace:/ });
+ await userEvent.click(trace);
+ await expect(
+ canvas.getByRole("tab", { name: "Visualize" }),
+ ).toHaveAttribute("data-state", "active");
+ await waitFor(() =>
+ expect(
+ canvas.getByRole("tooltip", { name: /^Trace summary:/ }),
+ ).toBeVisible(),
+ );
+ await expect(args.onSelectTrace).not.toHaveBeenCalled();
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Refresh results" }),
+ );
+ await new Promise<void>((resolve) =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ );
+ await expect(
+ canvas.getByRole("tooltip", { name: /^Trace summary:/ }),
+ ).toBeVisible();
+ await userEvent.click(trace);
+ await expect(
+ canvas.getByRole("button", { name: "Open trace unassigned" }),
+ ).toBeVisible();
+ await expect(
+ canvas.queryByRole("button", { name: "Open trace billing-0" }),
+ ).not.toBeInTheDocument();
+ await expect(args.onOpenTrace).not.toHaveBeenCalled();
+ },
+});
+
+export const PreviewTreemap = meta.story({
+ name: "(Test) Tap a topic to preview, tap again to browse its traces",
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByRole("tab", { name: "Visualize" }));
+ const billing = canvas.getByRole("button", {
+ name: `${topics[0].name}, 21 traces`,
+ });
+ const access = canvas.getByRole("button", {
+ name: `${topics[1].name}, 1 traces`,
+ });
+ await userEvent.click(billing);
+ await expect(
+ canvas.getByRole("tab", { name: "Visualize" }),
+ ).toHaveAttribute("data-state", "active");
+ await expect(canvas.getByRole("tooltip")).toHaveTextContent(
+ topics[0].description,
+ );
+ await userEvent.click(access);
+ await expect(canvas.getByRole("tooltip")).toHaveTextContent(topics[1].name);
+ await userEvent.click(access);
+ const trace = canvas.getByRole("button", { name: "Open trace access-0" });
+ await expect(trace).toBeVisible();
+ await expect(args.onOpenTrace).not.toHaveBeenCalled();
+ },
+});
+
+export const PreviewGrid = meta.story({
+ name: "(Test) Preview grid items, select traces, and clear topics",
+ args: {
+ filters: [
+ {
+ column: "topicId",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["billing"],
+ },
+ ],
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(
+ canvas.getByRole("combobox", { name: "Topics view" }),
+ );
+ await userEvent.click(
+ within(canvasElement.ownerDocument.body).getByRole("option", {
+ name: "Grid",
+ }),
+ );
+ const grid = await canvas.findByRole("img", { name: /^Topic grid/ });
+ const dot = grid.querySelector('[data-trace-id="access-0"]')!;
+ await userEvent.click(dot);
+ await expect(canvas.getByRole("tooltip")).toHaveTextContent(
+ rows[21].summary!,
+ );
+ await expect(
+ canvas.getByRole("tab", { name: "Visualize" }),
+ ).toHaveAttribute("data-state", "active");
+ await expect(args.onSelectTrace).not.toHaveBeenCalled();
+ await userEvent.click(dot);
+ const trace = canvas.getByRole("button", { name: "Open trace access-0" });
+ await expect(trace).toHaveAttribute("aria-current", "true");
+ await userEvent.click(canvas.getByRole("tab", { name: "Visualize" }));
+ const topic = canvas.getByRole("button", {
+ name: /Billing and subscription questions/,
+ });
+ await userEvent.click(topic);
+ await expect(canvas.getByRole("tooltip")).toHaveTextContent(
+ topics[0].description,
+ );
+ await userEvent.click(topic);
+ await userEvent.click(canvas.getByRole("tab", { name: "Visualize" }));
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Show all topics" }),
+ );
+ await expect(
+ canvas.getByRole("tab", { name: "Visualize" }),
+ ).toHaveAttribute("data-state", "active");
+ await expect(
+ canvas.getByRole("button", { name: "Show all topics" }),
+ ).toBeDisabled();
+ await expect(args.onOpenTrace).not.toHaveBeenCalled();
+ },
+});
+
+export const SwitchPublishedMap = meta.story({
+ name: "(Test) Switching facet maps resets the camera and keeps Visualize open",
+ args: { view: "map" },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByRole("tab", { name: "Visualize" }));
+ await userEvent.click(canvas.getByRole("button", { name: "Zoom in (+)" }));
+ await expect(canvas.queryByText("100%")).not.toBeInTheDocument();
+ await userEvent.click(
+ canvas.getByRole("combobox", { name: "Topics facet" }),
+ );
+ await userEvent.click(
+ within(canvasElement.ownerDocument.body).getByRole("option", {
+ name: "Unresolved customer support issues",
+ }),
+ );
+ await expect(await canvas.findByText("100%")).toBeVisible();
+ await expect(
+ canvas.getByRole("tab", { name: "Visualize" }),
+ ).toHaveAttribute("data-state", "active");
+ },
+});
diff --git a/web/src/features/topics/MobileTopicsView.tsx b/web/src/features/topics/MobileTopicsView.tsx
new file mode 100644
index 0000000000..8bd1b7eaad
--- /dev/null
+++ b/web/src/features/topics/MobileTopicsView.tsx
@@ -0,0 +1,215 @@
+import { useMemo, useState, type ComponentProps } from "react";
+import { type FilterState } from "@langfuse/shared";
+import { Button } from "@/src/components/design-system/Button/Button";
+import { Tabs } from "@/src/components/design-system/Tabs/Tabs";
+import {
+ type Facet,
+ orderedFacetTopics,
+ topicTracesHref,
+} from "./facet-topics";
+import { selectTopicTraceFilters } from "./topic-trace-filters";
+import { TopicMobileList } from "./TopicMobileList";
+import { TopicMobileTraceList } from "./TopicMobileTraceList";
+import { MobileTopicVisualization } from "./MobileTopicVisualization";
+import { TopicsTraceToolbar } from "./TopicsTraceToolbar";
+import { prepareMobileTopics } from "./prepare-mobile-topics";
+import { UNASSIGNED_TOPIC_ID } from "./prepare-topic-display";
+
+type MobileTopicsViewProps = {
+ projectId: string;
+ facet: Facet;
+ view: ComponentProps<typeof MobileTopicVisualization>["view"];
+ mapResult: ComponentProps<typeof MobileTopicVisualization>["mapResult"];
+ filters: FilterState;
+ searchQuery: string | null;
+ onFiltersChange: (filters: FilterState) => void;
+ onSearchQueryChange: (query: string | null) => void;
+ selectedTraceId: string | null;
+ onSelectTrace: (traceId: string | null) => void;
+ onOpenTrace: (traceId: string) => void;
+ onGenerateTopics: () => void;
+ canGenerateTopics: boolean;
+ isV4: boolean;
+};
+
+/** Local navigation only; query data and persisted filters stay with the caller. */
+export function MobileTopicsView({
+ projectId,
+ facet,
+ view,
+ mapResult,
+ filters,
+ searchQuery,
+ onFiltersChange,
+ onSearchQueryChange,
+ selectedTraceId,
+ onSelectTrace,
+ onOpenTrace,
+ onGenerateTopics,
+ canGenerateTopics,
+ isV4,
+}: MobileTopicsViewProps) {
+ const [navigation, setNavigation] = useState({
+ view,
+ panel: filters.length > 0 || searchQuery ? "traces" : "topics",
+ });
+ if (navigation.view !== view) {
+ setNavigation({ view, panel: "visualization" });
+ }
+ function showPanel(panel: string) {
+ setNavigation({ view, panel });
+ }
+ const { topics, selectedTopicId, selectedTopic, visible } =
+ prepareMobileTopics(facet, view, filters, searchQuery);
+ const matchingTraceKey =
+ filters.length > 0 || searchQuery?.trim()
+ ? JSON.stringify([...new Set(visible.map((row) => row.traceId))].sort())
+ : null;
+ // Map frame identity follows matching IDs, preserving tap previews across refreshes.
+ const matchingTraceIds = useMemo(
+ () =>
+ matchingTraceKey === null
+ ? undefined
+ : new Set<string>(JSON.parse(matchingTraceKey)),
+ [matchingTraceKey],
+ );
+ const tracingHref = topicTracesHref(projectId, visible, isV4);
+
+ function showAllTraces() {
+ onFiltersChange([]);
+ onSearchQueryChange(null);
+ showPanel("traces");
+ }
+ function selectTopic(topicId: string | null) {
+ if (topicId === null) {
+ onFiltersChange([]);
+ onSearchQueryChange(null);
+ return;
+ }
+ onFiltersChange(
+ topicId === UNASSIGNED_TOPIC_ID
+ ? [
+ {
+ column: "assignment",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["assigned"],
+ },
+ ]
+ : selectTopicTraceFilters([], topicId),
+ );
+ onSearchQueryChange(null);
+ showPanel("traces");
+ }
+ function selectTrace(traceId: string | null) {
+ if (traceId !== null && !visible.some((row) => row.traceId === traceId)) {
+ onFiltersChange([]);
+ onSearchQueryChange(null);
+ }
+ onSelectTrace(traceId);
+ if (traceId !== null) showPanel("traces");
+ }
+ function openTrace(traceId: string) {
+ onSelectTrace(traceId);
+ onOpenTrace(traceId);
+ }
+
+ return (
+ <div className="ph-no-capture flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
+ <Tabs value={navigation.panel} onValueChange={showPanel} layout="fill">
+ <Tabs.List variant="underline" layout="full" aria-label="Topics panels">
+ <Tabs.Trigger value="topics" label="Topics" />
+ <Tabs.Trigger value="traces" label="Traces" />
+ <Tabs.Trigger value="visualization" label="Visualize" />
+ </Tabs.List>
+ <Tabs.Content value="topics" layout="fill">
+ <TopicMobileList
+ topics={topics}
+ totalCount={facet.rows.length}
+ selectedTopicId={selectedTopicId}
+ onSelectTopic={selectTopic}
+ onShowAllTraces={showAllTraces}
+ />
+ {facet.topics.length === 0 && canGenerateTopics && (
+ <div className="shrink-0 border-t p-3">
+ <Button text="Generate topics" onClick={onGenerateTopics} />
+ </div>
+ )}
+ </Tabs.Content>
+ <Tabs.Content value="traces" layout="fill">
+ <section
+ aria-label="Topic traces"
+ className="flex min-h-0 flex-1 flex-col overflow-hidden"
+ >
+ <TopicMobileTraceList
+ key={facet.facetId}
+ filterKey={JSON.stringify([filters, searchQuery])}
+ rows={visible}
+ selectedTraceId={selectedTraceId}
+ onOpenTrace={openTrace}
+ >
+ <div className="shrink-0 border-b px-4 py-3">
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <h3 className="min-w-0 flex-1 text-sm font-bold [overflow-wrap:anywhere]">
+ {selectedTopic?.name ?? "Trace summaries"}
+ </h3>
+ <span className="text-muted-foreground text-xs tabular-nums">
+ {visible.length.toLocaleString()} traces
+ </span>
+ </div>
+ {selectedTopic?.description && (
+ <p className="text-muted-foreground mt-1 line-clamp-3 text-sm [overflow-wrap:anywhere]">
+ {selectedTopic.description}
+ </p>
+ )}
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ {(filters.length > 0 || searchQuery) && (
+ <Button
+ text="Show all traces"
+ variant="ghost"
+ size="sm"
+ onClick={showAllTraces}
+ />
+ )}
+ {tracingHref && (
+ <Button
+ text="Open in Tracing"
+ href={tracingHref}
+ variant="secondary"
+ size="sm"
+ />
+ )}
+ </div>
+ </div>
+ <TopicsTraceToolbar
+ projectId={projectId}
+ topics={orderedFacetTopics(facet)}
+ filters={filters}
+ onFiltersChange={onFiltersChange}
+ searchQuery={searchQuery}
+ onSearchQueryChange={onSearchQueryChange}
+ />
+ </TopicMobileTraceList>
+ </section>
+ </Tabs.Content>
+ <Tabs.Content value="visualization" layout="fill">
+ <MobileTopicVisualization
+ facet={facet}
+ treemapTopics={topics}
+ view={view}
+ mapResult={mapResult}
+ selectedTopicId={selectedTopicId}
+ selectedTraceId={
+ visible.some((row) => row.traceId === selectedTraceId)
+ ? selectedTraceId
+ : null
+ }
+ matchingTraceIds={matchingTraceIds}
+ onSelectTopic={selectTopic}
+ onSelectTrace={selectTrace}
+ />
+ </Tabs.Content>
+ </Tabs>
+ </div>
+ );
+}
diff --git a/web/src/features/topics/README.md b/web/src/features/topics/README.md
index 6a400883e3..900df68222 100644
--- a/web/src/features/topics/README.md
+++ b/web/src/features/topics/README.md
@@ -5,6 +5,8 @@ Topics**. Only platform administrators see or change this personal flag. The
sidebar, direct page, and Topics API also require deployment enablement and
project permissions. Processing additionally requires the project allowlist.
+- On phones (including touch-screen landscape), `CurrentTopics.tsx` renders `MobileTopicsView`: full-height Topics, Traces, and Visualize panels instead of concurrent split panes. `TopicsMobileControls` keeps facet/view selection in the page; the mobile menu includes automatic processing. Selecting a topic opens its traces; changing visualization opens Visualize. All traces and Unassigned remain reachable without selecting tiny chart marks. Filters stay in `useTopicTraceFilters`, trace selection in project session storage, and panel navigation stays local to the mounted project. No mirrored query state or additional store is needed for these low-frequency interactions. `prepare-topic-display.ts` owns display topics, Unassigned counts, and colors shared with desktop Treemap. `prepare-mobile-topics.ts` adds selection and matching rows; `TopicMobileList` and `TopicMobileTraceList` render explicit props. Trace cards wrap full summaries and use design-system pagination, initially 20 per page. Facet/view controls use the compact design-system SelectInput. Their header and search scroll with the cards so short screens retain access to every row. `MobileTopicVisualization` composes the same `TopicTreemap`, `TopicGrid`, and `TopicEmbeddingMap` renderers as desktop. `prepare-topic-grid.ts` owns the shared grid preparation; parents own chart dimensions. Mobile renderers use `previewOnSelect`: first tap shows persistent hover details, a second tap on the same item selects it and opens Traces. Tapping a different item replaces the preview; tapping empty space dismisses it. Only a trace-list tap opens peek. Map pan/zoom invalidates the preview. Storybook composes the mobile explorer with its facet/view controls; desktop charts retain their stories. The mobile flow shares one page shell across visualizations; chart insets belong inside their visualization, never around the page controls or panel navigation. The flow uses existing view-selection analytics and the same replay-blocked content boundaries; it adds no events for local panel navigation.
+- `prepare-topics-actions.ts` defines labels, processing status, availability, and callbacks once for the inline header and both overflow menus. The view adapters own menu dismissal and presentation; the page owns dialog lifetimes.
- `TopicsPage.tsx` owns facet configuration, the execution history drawer,
the current-results query and facet selection. The header shows the facet
tabs, then "Visualize as" (`TopicsResultsViewSelect.tsx`) with Treemap
diff --git a/web/src/features/topics/TopicEmbeddingMap.tsx b/web/src/features/topics/TopicEmbeddingMap.tsx
index 9ace910afc..39ddd611ce 100644
--- a/web/src/features/topics/TopicEmbeddingMap.tsx
+++ b/web/src/features/topics/TopicEmbeddingMap.tsx
@@ -4,7 +4,6 @@ import { EmbeddingMapView } from "./EmbeddingMapView";
import { TopicMapLoading } from "./TopicMapLoading";
export function TopicEmbeddingMap({
- projectId,
query,
topics,
selectedTopic,
@@ -13,6 +12,7 @@ export function TopicEmbeddingMap({
selectedTraceId,
matchingTraceIds,
fillContainer = false,
+ previewOnSelect = false,
}: TopicEmbeddingMapProps) {
if (query.error)
return (
@@ -33,7 +33,6 @@ export function TopicEmbeddingMap({
);
return (
<EmbeddingMapView
- projectId={projectId}
data={query.data}
topics={topics}
selectedTopic={selectedTopic}
@@ -42,12 +41,12 @@ export function TopicEmbeddingMap({
selectedTraceId={selectedTraceId}
matchingTraceIds={matchingTraceIds}
fillContainer={fillContainer}
+ previewOnSelect={previewOnSelect}
/>
);
}
type TopicEmbeddingMapProps = {
- projectId: string;
query: {
data?: RouterOutputs["topics"]["map"];
error: { message: string } | null;
@@ -59,6 +58,7 @@ type TopicEmbeddingMapProps = {
selectedTraceId: string | null;
matchingTraceIds?: ReadonlySet<string>;
fillContainer?: boolean;
+ previewOnSelect?: boolean;
};
type Topic = Pick<
diff --git a/web/src/features/topics/TopicGrid.tsx b/web/src/features/topics/TopicGrid.tsx
new file mode 100644
index 0000000000..a730cbc615
--- /dev/null
+++ b/web/src/features/topics/TopicGrid.tsx
@@ -0,0 +1,527 @@
+import {
+ useMemo,
+ useState,
+ type MouseEvent,
+ type PointerEvent,
+ type ReactNode,
+} from "react";
+import { Minus, Plus } from "@langfuse/icons";
+import { Button } from "@/src/components/design-system/Button/Button";
+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";
+import { useElementSize } from "@/src/hooks/useElementSize";
+import { formatCompactRelativeTime } from "@/src/utils/dates";
+import { cn } from "@/src/utils/tailwind";
+import { type FacetRow } from "./facet-topics";
+import { type prepareTopicGrid } from "./prepare-topic-grid";
+import { topicColor } from "./topic-map-colors";
+import { TopicPreviewCard } from "./TopicPreviewCard";
+import {
+ layoutTopicGrid,
+ type GridCell,
+ type GridPoint,
+} from "./topic-grid-layout";
+
+type TopicGridProps = {
+ points: GridPoint[];
+ perDot: number;
+ topics: GridTopic[];
+ rowsById: Map<string, FacetRow>;
+ selectedIndex: number | null;
+ onSelectTopic: (topicId: string | null) => void;
+ onSelectTrace: (traceId: string) => void;
+ previewOnSelect?: boolean;
+};
+
+type GridHoverCardProps = {
+ cell: GridCell;
+ topicName: string;
+ count: number;
+ row: FacetRow | undefined;
+ cellSize: number;
+ grid: { cols: number; rows: number };
+ members: FacetRow[];
+ color: string;
+ previewOnSelect: boolean;
+};
+
+type GridTopic = ReturnType<typeof prepareTopicGrid>["topics"][number];
+type GridHoverTarget = { kind: "trace" | "topic"; id: string } | null;
+
+type GridLegendProps = {
+ children: ReactNode;
+ topics: TopicGridProps["topics"];
+ selectedIndex: number | null;
+ onSelectTopic: (topicId: string | null) => void;
+ onHoverTopic: (topicId: string | null) => void;
+};
+
+const ZOOM_MIN = -3;
+const ZOOM_MAX = 6;
+const ZOOM_STEP = 1.25;
+const CELL_MIN = 3;
+const CELL_MAX = 28;
+const PAD_X = 16;
+const PAD_Y = 16;
+const CARD_OFFSET = 8;
+
+function squareOpacity(
+ topicIndex: number,
+ selectedIndex: number | null,
+ hoveredIndex: number | null,
+ isHovered: boolean,
+) {
+ if (isHovered) return 1;
+ const hasSelection = selectedIndex !== null;
+ let opacity: number;
+ if (topicIndex < 0) opacity = hasSelection ? 0.1 : 0.2;
+ else if (!hasSelection) opacity = 0.35;
+ else opacity = topicIndex === selectedIndex ? 1 : 0.12;
+ if (topicIndex >= 0 && topicIndex === hoveredIndex) {
+ opacity = Math.max(opacity, 0.7);
+ }
+ return opacity;
+}
+
+function colorAt(topics: GridTopic[], topicIndex: number) {
+ return topics[topicIndex]?.color ?? topicColor(-1);
+}
+
+function clamp(value: number, min: number, max: number) {
+ return Math.min(max, Math.max(min, value));
+}
+
+function GridHoverCard({
+ cell,
+ topicName,
+ count,
+ row,
+ cellSize,
+ grid,
+ members,
+ color,
+ previewOnSelect,
+}: GridHoverCardProps) {
+ // Card sits above/below the dot, growing toward the grid center, so it never covers it.
+ const toLeft = cell.col >= grid.cols / 2;
+ const below = cell.row < grid.rows / 2;
+ const left = (cell.col + (toLeft ? 1 : 0)) * cellSize;
+ const top = below
+ ? (cell.row + 1) * cellSize + CARD_OFFSET
+ : cell.row * cellSize - CARD_OFFSET;
+ const shortId = cell.id.length > 8 ? `${cell.id.slice(0, 8)}…` : cell.id;
+ const started = row
+ ? formatCompactRelativeTime(new Date(row.unitStartTime))
+ : null;
+ return (
+ <div
+ role="tooltip"
+ className={cn(
+ "bg-popover text-popover-foreground pointer-events-none absolute rounded-md border p-2 shadow-md",
+ previewOnSelect ? "right-2 bottom-2 left-2" : "w-64",
+ )}
+ style={
+ previewOnSelect
+ ? undefined
+ : {
+ left,
+ top,
+ translate: `${toLeft ? "-100%" : "0"} ${below ? "0" : "-100%"}`,
+ }
+ }
+ >
+ <div className="flex items-center gap-1.5 text-xs">
+ <span
+ aria-hidden
+ className="size-2.5 shrink-0 rounded-xs"
+ style={{ backgroundColor: color }}
+ />
+ <span
+ className={cn(
+ "min-w-0 font-bold",
+ previewOnSelect ? "line-clamp-2" : "truncate",
+ )}
+ title={topicName}
+ >
+ {topicName}
+ </span>
+ <span className="text-muted-foreground text-2xs ml-auto shrink-0 font-mono">
+ {count.toLocaleString()} traces
+ </span>
+ </div>
+ {members.length > 1 ? (
+ <>
+ <ul className="mt-1 flex flex-col gap-0.5 text-xs">
+ {members.slice(0, 3).map((member) => (
+ <li key={member.traceId} className="line-clamp-1">
+ {member.summary || "No applicable summary."}
+ </li>
+ ))}
+ </ul>
+ <p className="text-muted-foreground text-2xs mt-1 font-mono">
+ {[
+ `${members.length.toLocaleString()} traces in this dot`,
+ members.length > 3
+ ? `+${(members.length - 3).toLocaleString()} more`
+ : null,
+ !previewOnSelect && "click to open the first",
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </p>
+ </>
+ ) : (
+ <>
+ <p
+ className={cn(
+ "mt-1 text-xs",
+ previewOnSelect ? "line-clamp-4" : "line-clamp-2",
+ )}
+ >
+ {row?.summary || "No applicable summary."}
+ </p>
+ <p
+ className="text-muted-foreground text-2xs mt-1 truncate font-mono"
+ title={cell.id}
+ >
+ {[shortId, started, !previewOnSelect && "click to open"]
+ .filter(Boolean)
+ .join(" · ")}
+ </p>
+ </>
+ )}
+ {previewOnSelect && (
+ <p className="text-muted-foreground mt-2 text-xs">
+ Tap again to view {members.length > 1 ? "the first trace" : "trace"}
+ </p>
+ )}
+ </div>
+ );
+}
+
+function GridLegend({
+ topics,
+ selectedIndex,
+ onSelectTopic,
+ onHoverTopic,
+ children,
+}: GridLegendProps) {
+ const entries = topics
+ .map((topic, topicIndex) => ({ topic, topicIndex }))
+ .filter(({ topic }) => topic.count > 0)
+ .sort((a, b) => b.topic.count - a.topic.count);
+ function clearHover() {
+ onHoverTopic(null);
+ }
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden border-t">
+ <ul
+ aria-label="Topics"
+ className="grid min-h-0 grid-cols-2 gap-x-4 gap-y-0.5 overflow-y-auto p-2"
+ >
+ {entries.map((entry) => {
+ const { topic } = entry;
+ const isSelected = entry.topicIndex === selectedIndex;
+ function select() {
+ onSelectTopic(topic.id);
+ }
+ function hover() {
+ onHoverTopic(topic.id);
+ }
+ return (
+ <li key={topic.id} className="min-w-0">
+ <button
+ type="button"
+ aria-pressed={isSelected}
+ onClick={select}
+ onPointerEnter={hover}
+ onPointerLeave={clearHover}
+ onFocus={hover}
+ onBlur={clearHover}
+ className={cn(
+ "hover:bg-accent focus-visible:ring-ring flex w-full min-w-0 items-center gap-2 rounded-sm px-1.5 py-1 text-left text-sm focus-visible:ring-2 focus-visible:outline-hidden",
+ isSelected && "bg-accent font-bold",
+ selectedIndex !== null &&
+ !isSelected &&
+ "text-muted-foreground",
+ )}
+ >
+ <span
+ aria-hidden
+ className="size-2.5 shrink-0 rounded-xs"
+ style={{ backgroundColor: colorAt(topics, entry.topicIndex) }}
+ />
+ <span className="min-w-0 flex-1 truncate" title={topic.name}>
+ {topic.name}
+ </span>
+ <span className="text-muted-foreground shrink-0 font-mono text-xs">
+ {topic.count.toLocaleString()}
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ <div className="text-muted-foreground flex shrink-0 items-center gap-2 px-3.5 pb-2 text-xs">
+ {children}
+ </div>
+ </div>
+ );
+}
+
+export function TopicGrid({
+ points,
+ perDot,
+ topics,
+ rowsById,
+ selectedIndex,
+ onSelectTopic,
+ onSelectTrace,
+ previewOnSelect = false,
+}: TopicGridProps) {
+ const [zoom, setZoom] = useState(0);
+ const [hoverTarget, setHoverTarget] = useState<GridHoverTarget>(null);
+ const [containerRef, size] = useElementSize<HTMLDivElement>();
+ const innerWidth = size ? Math.max(1, size.width - 2 * PAD_X) : 0;
+ const innerHeight = size ? Math.max(1, size.height - 2 * PAD_Y) : 0;
+ const aspect = size ? Math.round((innerWidth / innerHeight) * 4) / 4 : 1;
+ const layout = useMemo(
+ () => layoutTopicGrid(points, aspect),
+ [points, aspect],
+ );
+ const cellById = useMemo(
+ () => new Map(layout.cells.map((cell) => [cell.id, cell])),
+ [layout],
+ );
+ const countByIndex = useMemo(() => {
+ const counts = new Map<number, number>();
+ for (const cell of layout.cells) {
+ counts.set(cell.topicIndex, (counts.get(cell.topicIndex) ?? 0) + 1);
+ }
+ return counts;
+ }, [layout]);
+
+ const selectedId =
+ selectedIndex === null ? null : (topics[selectedIndex]?.id ?? null);
+ const hoveredId = hoverTarget?.kind === "trace" ? hoverTarget.id : null;
+ const hoveredLabelIndex =
+ hoverTarget?.kind === "topic"
+ ? topics.findIndex((topic) => topic.id === hoverTarget.id)
+ : -1;
+ const hoveredCell = hoveredId ? (cellById.get(hoveredId) ?? null) : null;
+ const hoveredIndex =
+ hoveredCell?.topicIndex ??
+ (hoveredLabelIndex < 0 ? null : hoveredLabelIndex);
+ const fit = size
+ ? Math.min(innerWidth / layout.cols, innerHeight / layout.rows)
+ : 0;
+ // Zoom from the displayed size, so steps take effect even when fit exceeds the cap.
+ const baseCell = clamp(fit, CELL_MIN, CELL_MAX);
+ const cell = clamp(baseCell * ZOOM_STEP ** zoom, CELL_MIN, CELL_MAX);
+ const gap = Math.max(0.5, cell * 0.16);
+ const radius = cell * 0.18;
+ const gridWidth = layout.cols * cell;
+ const gridHeight = layout.rows * cell;
+
+ function traceIdAt(event: PointerEvent<SVGElement> | MouseEvent<SVGElement>) {
+ const target = event.target as Element;
+ return target.getAttribute("data-trace-id");
+ }
+ function handlePointerMove(event: PointerEvent<SVGSVGElement>) {
+ if (previewOnSelect) return;
+ const id = traceIdAt(event);
+ if (id !== hoveredId) setHoverTarget(id ? { kind: "trace", id } : null);
+ }
+ function handlePointerLeave() {
+ if (previewOnSelect) return;
+ setHoverTarget(null);
+ }
+ function handleClick(event: MouseEvent<SVGSVGElement>) {
+ const id = traceIdAt(event);
+ if (previewOnSelect && id !== hoveredId) {
+ setHoverTarget(id ? { kind: "trace", id } : null);
+ return;
+ }
+ setHoverTarget(null);
+ if (id) onSelectTrace(id);
+ }
+ function selectTopic(id: string | null) {
+ if (
+ previewOnSelect &&
+ id !== null &&
+ (hoverTarget?.kind !== "topic" || hoverTarget.id !== id)
+ ) {
+ setHoverTarget({ kind: "topic", id });
+ return;
+ }
+ setHoverTarget(null);
+ onSelectTopic(!previewOnSelect && id === selectedId ? null : id);
+ }
+ function hoverTopic(id: string | null) {
+ if (!previewOnSelect) setHoverTarget(id ? { kind: "topic", id } : null);
+ }
+ function dismissPreview(event: MouseEvent<HTMLDivElement>) {
+ if (
+ event.target instanceof Element &&
+ !event.target.closest("[data-trace-id], button")
+ ) {
+ setHoverTarget(null);
+ }
+ }
+ function showAllTopics() {
+ setHoverTarget(null);
+ onSelectTopic(null);
+ }
+ function zoomIn() {
+ setHoverTarget(null);
+ setZoom((current) => Math.min(ZOOM_MAX, current + 1));
+ }
+ function zoomOut() {
+ setHoverTarget(null);
+ setZoom((current) => Math.max(ZOOM_MIN, current - 1));
+ }
+
+ const squares = hoveredCell
+ ? [...layout.cells.filter((item) => item.id !== hoveredId), hoveredCell]
+ : layout.cells;
+ const hoverCard = hoveredCell && (
+ <GridHoverCard
+ cell={hoveredCell}
+ topicName={topics[hoveredCell.topicIndex]?.name ?? "No topic"}
+ count={
+ topics[hoveredCell.topicIndex]?.count ??
+ (countByIndex.get(hoveredCell.topicIndex) ?? 0) * perDot
+ }
+ row={rowsById.get(hoveredCell.id)}
+ members={(hoveredCell.memberIds ?? [hoveredCell.id]).flatMap((id) => {
+ const member = rowsById.get(id);
+ return member ? [member] : [];
+ })}
+ color={colorAt(topics, hoveredCell.topicIndex)}
+ cellSize={cell}
+ grid={layout}
+ previewOnSelect={previewOnSelect}
+ />
+ );
+
+ return (
+ <>
+ <div className="flex h-12 shrink-0 items-center justify-end gap-2 px-4">
+ <div className="flex items-center gap-0.5">
+ <IconButton
+ icon={Minus}
+ label="Zoom out (−)"
+ size="sm"
+ disabled={zoom <= ZOOM_MIN || cell <= CELL_MIN}
+ onClick={zoomOut}
+ />
+ <IconButton
+ icon={Plus}
+ label="Zoom in (+)"
+ size="sm"
+ disabled={zoom >= ZOOM_MAX || cell >= CELL_MAX}
+ onClick={zoomIn}
+ />
+ </div>
+ </div>
+ <div
+ className="relative flex min-h-0 flex-1 flex-col border-t"
+ onClick={dismissPreview}
+ >
+ <div
+ ref={containerRef}
+ className="relative flex min-h-0 flex-[2] overflow-auto overscroll-contain"
+ >
+ {points.length === 0 ? (
+ <p className="text-muted-foreground p-4 text-sm">
+ No positioned traces in this time range.
+ </p>
+ ) : (
+ size && (
+ <div
+ className="m-auto shrink-0"
+ style={{ padding: `${PAD_Y}px ${PAD_X}px` }}
+ >
+ <div
+ className="relative"
+ style={{ width: gridWidth, height: gridHeight }}
+ >
+ <svg
+ width={gridWidth}
+ height={gridHeight}
+ role="img"
+ aria-label={`Topic grid, ${points.length.toLocaleString()} traces`}
+ className="block"
+ onPointerMove={handlePointerMove}
+ onPointerLeave={handlePointerLeave}
+ onClick={handleClick}
+ >
+ {squares.map((square) => {
+ const isHovered = square.id === hoveredId;
+ const grow = isHovered ? gap / 2 : 0;
+ return (
+ <rect
+ key={square.id}
+ data-trace-id={square.id}
+ className="cursor-pointer"
+ x={square.col * cell + gap / 2 - grow}
+ y={square.row * cell + gap / 2 - grow}
+ width={cell - gap + grow * 2}
+ height={cell - gap + grow * 2}
+ rx={radius}
+ fill={colorAt(topics, square.topicIndex)}
+ fillOpacity={squareOpacity(
+ square.topicIndex,
+ selectedIndex,
+ hoveredIndex,
+ isHovered,
+ )}
+ stroke={isHovered ? "hsl(var(--foreground))" : "none"}
+ strokeWidth={1.5}
+ />
+ );
+ })}
+ </svg>
+ {!previewOnSelect && hoverCard}
+ </div>
+ </div>
+ )
+ )}
+ </div>
+ <GridLegend
+ topics={topics}
+ selectedIndex={
+ previewOnSelect && hoveredLabelIndex >= 0
+ ? hoveredLabelIndex
+ : selectedIndex
+ }
+ onSelectTopic={selectTopic}
+ onHoverTopic={hoverTopic}
+ >
+ <span>
+ {perDot > 1
+ ? `1 dot ≈ ${perDot.toLocaleString()} traces`
+ : "1 dot = 1 trace"}
+ </span>
+ <Button
+ text="Show all topics"
+ variant="ghost"
+ size="sm"
+ disabled={selectedId === null}
+ onClick={showAllTopics}
+ />
+ </GridLegend>
+ {previewOnSelect && hoverCard}
+ {previewOnSelect &&
+ hoveredLabelIndex >= 0 &&
+ topics[hoveredLabelIndex] && (
+ <div className="pointer-events-none absolute right-2 bottom-2 left-2">
+ <TopicPreviewCard
+ topic={topics[hoveredLabelIndex]}
+ total={rowsById.size}
+ />
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
diff --git a/web/src/features/topics/TopicGridView.tsx b/web/src/features/topics/TopicGridView.tsx
index 8a4c555783..493041b6c4 100644
--- a/web/src/features/topics/TopicGridView.tsx
+++ b/web/src/features/topics/TopicGridView.tsx
@@ -1,43 +1,36 @@
-/* eslint-disable @typescript-eslint/no-use-before-define */
import { type RouterOutputs } from "@/src/utils/api";
-import {
- useMemo,
- useState,
- type MouseEvent,
- type PointerEvent,
- type ReactNode,
-} from "react";
-import { Minus, Plus } from "@langfuse/icons";
-import { Button } from "@/src/components/design-system/Button/Button";
-import { IconButton } from "@/src/components/design-system/IconButton/IconButton";
+import { useMemo, useState } from "react";
import { type DataTablePeekViewProps } from "@/src/components/table/peek";
-import { useElementSize } from "@/src/hooks/useElementSize";
-import { formatCompactRelativeTime } from "@/src/utils/dates";
-import { cn } from "@/src/utils/tailwind";
import { TopicsEmptyState } from "./TopicsEmptyState";
-import {
- type Facet,
- type FacetRow,
- allTopicsLabel,
- orderedFacetTopics,
-} from "./facet-topics";
-import { topicColor } from "./topic-map-colors";
-import {
- layoutTopicGrid,
- sampleGridPoints,
- type GridCell,
- type GridPoint,
-} from "./topic-grid-layout";
+import { type Facet, allTopicsLabel } from "./facet-topics";
+import { prepareTopicGrid } from "./prepare-topic-grid";
+import { TopicGrid } from "./TopicGrid";
import { TopicTraceList } from "./TopicTraceList";
-const ZOOM_MIN = -3;
-const ZOOM_MAX = 6;
-const ZOOM_STEP = 1.25;
-const CELL_MIN = 3;
-const CELL_MAX = 28;
-const PAD_X = 16;
-const PAD_Y = 16;
-const CARD_OFFSET = 8;
+type TopicGridViewProps = {
+ projectId: string;
+ facet: Facet;
+ mapResult: {
+ data?: RouterOutputs["topics"]["map"];
+ error: { message: string } | null;
+ };
+ onOpenTrace: (traceId: string) => void;
+ peekView: DataTablePeekViewProps;
+ tracePanelRef?: (element: HTMLElement | null) => void;
+ onGenerateTopics: () => void;
+ canGenerateTopics: boolean;
+};
+
+function gridMessage(mapResult: TopicGridViewProps["mapResult"]) {
+ if (mapResult.error) return `Grid could not load: ${mapResult.error.message}`;
+ if (!mapResult.data) return "Loading grid…";
+ if (mapResult.data.status !== "ready") {
+ return (
+ mapResult.data.reason ?? "This run has no saved embedding projection."
+ );
+ }
+ return null;
+}
export function TopicGridView({
projectId,
@@ -50,35 +43,12 @@ export function TopicGridView({
canGenerateTopics,
}: TopicGridViewProps) {
const [selectedTopicId, setSelectedTopicId] = useState<string | null>(null);
- const counts = new Map(facet.topics.map((topic) => [topic.id, topic.count]));
- const topics = orderedFacetTopics(facet).map((topic, index) => ({
- ...topic,
- count: counts.get(topic.id) ?? 0,
- color: topicColor(index),
- }));
+ const { topics, points, perDot, rowsById } = useMemo(
+ () => prepareTopicGrid(facet, mapResult.data),
+ [facet, mapResult.data],
+ );
const selectedTopic =
topics.find((topic) => topic.id === selectedTopicId) ?? null;
- const rowsById = useMemo(
- () => new Map(facet.rows.map((row) => [row.traceId, row])),
- [facet.rows],
- );
- const mapData = mapResult.data;
- const { points, perDot } = useMemo(() => {
- if (mapData?.status !== "ready") return { points: [], perDot: 1 };
- const indexById = new Map(
- orderedFacetTopics(facet).map((topic, index) => [topic.id, index]),
- );
- return sampleGridPoints(
- mapData.points.map(
- (point): GridPoint => ({
- id: point.traceId,
- x: point.x,
- y: point.y,
- topicIndex: point.topicId ? (indexById.get(point.topicId) ?? -1) : -1,
- }),
- ),
- );
- }, [mapData, facet]);
if (topics.length === 0) {
return (
<TopicsEmptyState
@@ -104,7 +74,7 @@ export function TopicGridView({
className="flex min-h-48 min-w-0 shrink-0 basis-1/2 flex-col overflow-hidden lg:shrink lg:basis-3/5"
>
{message ? (
- <GridMessage>{message}</GridMessage>
+ <p className="text-muted-foreground p-4 text-sm">{message}</p>
) : (
<TopicGrid
points={points}
@@ -113,7 +83,7 @@ export function TopicGridView({
rowsById={rowsById}
selectedIndex={selectedIndex}
onSelectTopic={setSelectedTopicId}
- onOpenTrace={onOpenTrace}
+ onSelectTrace={onOpenTrace}
/>
)}
</section>
@@ -132,446 +102,3 @@ export function TopicGridView({
</div>
);
}
-
-function GridMessage({ children }: { children: ReactNode }) {
- return <p className="text-muted-foreground p-4 text-sm">{children}</p>;
-}
-
-function TopicGrid({
- points,
- perDot,
- topics,
- rowsById,
- selectedIndex,
- onSelectTopic,
- onOpenTrace,
-}: TopicGridProps) {
- const [zoom, setZoom] = useState(0);
- const [hoveredId, setHoveredId] = useState<string | null>(null);
- const [hoveredLabelIndex, setHoveredLabelIndex] = useState<number | null>(
- null,
- );
- const [containerRef, size] = useElementSize<HTMLDivElement>();
- const innerWidth = size ? Math.max(1, size.width - 2 * PAD_X) : 0;
- const innerHeight = size ? Math.max(1, size.height - 2 * PAD_Y) : 0;
- const aspect = size ? Math.round((innerWidth / innerHeight) * 4) / 4 : 1;
- const layout = useMemo(
- () => layoutTopicGrid(points, aspect),
- [points, aspect],
- );
- const cellById = useMemo(
- () => new Map(layout.cells.map((cell) => [cell.id, cell])),
- [layout],
- );
- const countByIndex = useMemo(() => {
- const counts = new Map<number, number>();
- for (const cell of layout.cells) {
- counts.set(cell.topicIndex, (counts.get(cell.topicIndex) ?? 0) + 1);
- }
- return counts;
- }, [layout]);
-
- const selectedId =
- selectedIndex === null ? null : (topics[selectedIndex]?.id ?? null);
- const hoveredCell = hoveredId ? (cellById.get(hoveredId) ?? null) : null;
- const hoveredIndex = hoveredCell ? hoveredCell.topicIndex : hoveredLabelIndex;
- const fit = size
- ? Math.min(innerWidth / layout.cols, innerHeight / layout.rows)
- : 0;
- // Zoom from the displayed size, so steps take effect even when fit exceeds the cap.
- const baseCell = clamp(fit, CELL_MIN, CELL_MAX);
- const cell = clamp(baseCell * ZOOM_STEP ** zoom, CELL_MIN, CELL_MAX);
- const gap = Math.max(0.5, cell * 0.16);
- const radius = cell * 0.18;
- const gridWidth = layout.cols * cell;
- const gridHeight = layout.rows * cell;
-
- function traceIdAt(event: PointerEvent<SVGElement> | MouseEvent<SVGElement>) {
- const target = event.target as Element;
- return target.getAttribute("data-trace-id");
- }
- function handlePointerMove(event: PointerEvent<SVGSVGElement>) {
- const id = traceIdAt(event);
- if (id !== hoveredId) setHoveredId(id);
- }
- function handlePointerLeave() {
- setHoveredId(null);
- }
- function handleClick(event: MouseEvent<SVGSVGElement>) {
- const id = traceIdAt(event);
- if (id) onOpenTrace(id);
- }
- function showAllTopics() {
- onSelectTopic(null);
- }
- function zoomIn() {
- setZoom((current) => Math.min(ZOOM_MAX, current + 1));
- }
- function zoomOut() {
- setZoom((current) => Math.max(ZOOM_MIN, current - 1));
- }
-
- const squares = hoveredCell
- ? [...layout.cells.filter((item) => item.id !== hoveredId), hoveredCell]
- : layout.cells;
-
- return (
- <>
- <div className="flex h-12 shrink-0 items-center justify-end gap-2 px-4">
- <div className="flex items-center gap-0.5">
- <IconButton
- icon={Minus}
- label="Zoom out (−)"
- size="sm"
- disabled={zoom <= ZOOM_MIN || cell <= CELL_MIN}
- onClick={zoomOut}
- />
- <IconButton
- icon={Plus}
- label="Zoom in (+)"
- size="sm"
- disabled={zoom >= ZOOM_MAX || cell >= CELL_MAX}
- onClick={zoomIn}
- />
- </div>
- </div>
- <div className="flex min-h-0 flex-1 flex-col border-t">
- <div
- ref={containerRef}
- className="relative flex min-h-0 flex-[2] overflow-auto overscroll-contain"
- >
- {points.length === 0 ? (
- <GridMessage>No positioned traces in this time range.</GridMessage>
- ) : (
- size && (
- <div
- className="m-auto shrink-0"
- style={{ padding: `${PAD_Y}px ${PAD_X}px` }}
- >
- <div
- className="relative"
- style={{ width: gridWidth, height: gridHeight }}
- >
- <svg
- width={gridWidth}
- height={gridHeight}
- role="img"
- aria-label={`Topic grid, ${points.length.toLocaleString()} traces`}
- className="block"
- onPointerMove={handlePointerMove}
- onPointerLeave={handlePointerLeave}
- onClick={handleClick}
- >
- {squares.map((square) => {
- const isHovered = square.id === hoveredId;
- const grow = isHovered ? gap / 2 : 0;
- return (
- <rect
- key={square.id}
- data-trace-id={square.id}
- className="cursor-pointer"
- x={square.col * cell + gap / 2 - grow}
- y={square.row * cell + gap / 2 - grow}
- width={cell - gap + grow * 2}
- height={cell - gap + grow * 2}
- rx={radius}
- fill={colorAt(topics, square.topicIndex)}
- fillOpacity={squareOpacity(
- square.topicIndex,
- selectedIndex,
- hoveredIndex,
- isHovered,
- )}
- stroke={isHovered ? "hsl(var(--foreground))" : "none"}
- strokeWidth={1.5}
- />
- );
- })}
- </svg>
- {hoveredCell && (
- <GridHoverCard
- cell={hoveredCell}
- topicName={
- topics[hoveredCell.topicIndex]?.name ?? "No topic"
- }
- count={
- topics[hoveredCell.topicIndex]?.count ??
- (countByIndex.get(hoveredCell.topicIndex) ?? 0) * perDot
- }
- row={rowsById.get(hoveredCell.id)}
- members={(
- hoveredCell.memberIds ?? [hoveredCell.id]
- ).flatMap((id) => {
- const member = rowsById.get(id);
- return member ? [member] : [];
- })}
- color={colorAt(topics, hoveredCell.topicIndex)}
- cellSize={cell}
- grid={layout}
- />
- )}
- </div>
- </div>
- )
- )}
- </div>
- <GridLegend
- topics={topics}
- selectedIndex={selectedIndex}
- onSelectTopic={onSelectTopic}
- onHoverTopic={setHoveredLabelIndex}
- >
- <span>
- {perDot > 1
- ? `1 dot ≈ ${perDot.toLocaleString()} traces`
- : "1 dot = 1 trace"}
- </span>
- <Button
- text="Show all topics"
- variant="ghost"
- size="sm"
- disabled={selectedId === null}
- onClick={showAllTopics}
- />
- </GridLegend>
- </div>
- </>
- );
-}
-
-function GridLegend({
- topics,
- selectedIndex,
- onSelectTopic,
- onHoverTopic,
- children,
-}: GridLegendProps) {
- const entries = topics
- .map((topic, topicIndex) => ({ topic, topicIndex }))
- .filter(({ topic }) => topic.count > 0)
- .sort((a, b) => b.topic.count - a.topic.count);
- function clearHover() {
- onHoverTopic(null);
- }
- return (
- <div className="flex min-h-0 flex-1 flex-col overflow-hidden border-t">
- <ul
- aria-label="Topics"
- className="grid min-h-0 grid-cols-2 gap-x-4 gap-y-0.5 overflow-y-auto p-2"
- >
- {entries.map((entry) => {
- const { topic } = entry;
- const isSelected = entry.topicIndex === selectedIndex;
- function select() {
- onSelectTopic(isSelected ? null : topic.id);
- }
- function hover() {
- onHoverTopic(entry.topicIndex);
- }
- return (
- <li key={topic.id} className="min-w-0">
- <button
- type="button"
- aria-pressed={isSelected}
- onClick={select}
- onPointerEnter={hover}
- onPointerLeave={clearHover}
- onFocus={hover}
- onBlur={clearHover}
- className={cn(
- "hover:bg-accent focus-visible:ring-ring flex w-full min-w-0 items-center gap-2 rounded-sm px-1.5 py-1 text-left text-sm focus-visible:ring-2 focus-visible:outline-hidden",
- isSelected && "bg-accent font-bold",
- selectedIndex !== null &&
- !isSelected &&
- "text-muted-foreground",
- )}
- >
- <span
- aria-hidden
- className="size-2.5 shrink-0 rounded-xs"
- style={{ backgroundColor: colorAt(topics, entry.topicIndex) }}
- />
- <span className="min-w-0 flex-1 truncate" title={topic.name}>
- {topic.name}
- </span>
- <span className="text-muted-foreground shrink-0 font-mono text-xs">
- {topic.count.toLocaleString()}
- </span>
- </button>
- </li>
- );
- })}
- </ul>
- <div className="text-muted-foreground flex shrink-0 items-center gap-2 px-3.5 pb-2 text-xs">
- {children}
- </div>
- </div>
- );
-}
-
-function GridHoverCard({
- cell,
- topicName,
- count,
- row,
- cellSize,
- grid,
- members,
- color,
-}: GridHoverCardProps) {
- // Card sits above/below the dot, growing toward the grid center, so it never covers it.
- const toLeft = cell.col >= grid.cols / 2;
- const below = cell.row < grid.rows / 2;
- const left = (cell.col + (toLeft ? 1 : 0)) * cellSize;
- const top = below
- ? (cell.row + 1) * cellSize + CARD_OFFSET
- : cell.row * cellSize - CARD_OFFSET;
- const shortId = cell.id.length > 8 ? `${cell.id.slice(0, 8)}…` : cell.id;
- const started = row
- ? formatCompactRelativeTime(new Date(row.unitStartTime))
- : null;
- return (
- <div
- role="tooltip"
- className="bg-popover text-popover-foreground pointer-events-none absolute w-64 rounded-md border p-2 shadow-md"
- style={{
- left,
- top,
- translate: `${toLeft ? "-100%" : "0"} ${below ? "0" : "-100%"}`,
- }}
- >
- <div className="flex items-center gap-1.5 text-xs">
- <span
- aria-hidden
- className="size-2.5 shrink-0 rounded-xs"
- style={{ backgroundColor: color }}
- />
- <span className="min-w-0 truncate font-bold" title={topicName}>
- {topicName}
- </span>
- <span className="text-muted-foreground text-2xs ml-auto shrink-0 font-mono">
- {count.toLocaleString()} traces
- </span>
- </div>
- {members.length > 1 ? (
- <>
- <ul className="mt-1 flex flex-col gap-0.5 text-xs">
- {members.slice(0, 3).map((member) => (
- <li key={member.traceId} className="line-clamp-1">
- {member.summary || "No applicable summary."}
- </li>
- ))}
- </ul>
- <p className="text-muted-foreground text-2xs mt-1 font-mono">
- {[
- `${members.length.toLocaleString()} traces in this dot`,
- members.length > 3
- ? `+${(members.length - 3).toLocaleString()} more`
- : null,
- "click to open the first",
- ]
- .filter(Boolean)
- .join(" · ")}
- </p>
- </>
- ) : (
- <>
- <p className="mt-1 line-clamp-2 text-xs">
- {row?.summary || "No applicable summary."}
- </p>
- <p
- className="text-muted-foreground text-2xs mt-1 truncate font-mono"
- title={cell.id}
- >
- {[shortId, started, "click to open"].filter(Boolean).join(" · ")}
- </p>
- </>
- )}
- </div>
- );
-}
-
-function gridMessage(mapResult: TopicGridViewProps["mapResult"]) {
- if (mapResult.error) return `Grid could not load: ${mapResult.error.message}`;
- if (!mapResult.data) return "Loading grid…";
- if (mapResult.data.status !== "ready") {
- return (
- mapResult.data.reason ?? "This run has no saved embedding projection."
- );
- }
- return null;
-}
-
-function squareOpacity(
- topicIndex: number,
- selectedIndex: number | null,
- hoveredIndex: number | null,
- isHovered: boolean,
-) {
- if (isHovered) return 1;
- const hasSelection = selectedIndex !== null;
- let opacity: number;
- if (topicIndex < 0) opacity = hasSelection ? 0.1 : 0.2;
- else if (!hasSelection) opacity = 0.35;
- else opacity = topicIndex === selectedIndex ? 1 : 0.12;
- if (topicIndex >= 0 && topicIndex === hoveredIndex) {
- opacity = Math.max(opacity, 0.7);
- }
- return opacity;
-}
-
-function colorAt(topics: GridTopic[], topicIndex: number) {
- return topics[topicIndex]?.color ?? topicColor(-1);
-}
-
-function clamp(value: number, min: number, max: number) {
- return Math.min(max, Math.max(min, value));
-}
-
-type TopicGridViewProps = {
- projectId: string;
- facet: Facet;
- mapResult: {
- data?: RouterOutputs["topics"]["map"];
- error: { message: string } | null;
- };
- onOpenTrace: (traceId: string) => void;
- peekView: DataTablePeekViewProps;
- tracePanelRef?: (element: HTMLElement | null) => void;
- onGenerateTopics: () => void;
- canGenerateTopics: boolean;
-};
-
-type TopicGridProps = {
- points: GridPoint[];
- perDot: number;
- topics: GridTopic[];
- rowsById: Map<string, FacetRow>;
- selectedIndex: number | null;
- onSelectTopic: (topicId: string | null) => void;
- onOpenTrace: (traceId: string) => void;
-};
-
-type GridHoverCardProps = {
- cell: GridCell;
- topicName: string;
- count: number;
- row: FacetRow | undefined;
- cellSize: number;
- grid: { cols: number; rows: number };
- members: FacetRow[];
- color: string;
-};
-
-type GridTopic = ReturnType<typeof orderedFacetTopics>[number] & {
- count: number;
- color: string;
-};
-
-type GridLegendProps = {
- children: ReactNode;
- topics: TopicGridProps["topics"];
- selectedIndex: number | null;
- onSelectTopic: (topicId: string | null) => void;
- onHoverTopic: (topicIndex: number | null) => void;
-};
diff --git a/web/src/features/topics/TopicMapLoading.stories.tsx b/web/src/features/topics/TopicMapLoading.stories.tsx
index 30c1bb5907..1b02eb0712 100644
--- a/web/src/features/topics/TopicMapLoading.stories.tsx
+++ b/web/src/features/topics/TopicMapLoading.stories.tsx
@@ -12,7 +12,6 @@ const meta = preview.meta({
</div>
<div className="flex h-[680px] min-h-0 flex-col">
<EmbeddingMapView
- projectId="project"
data={{ points: [], missingSummaryCount: 0, unpositionedCount: 0 }}
topics={[]}
selectedTopic={null}
diff --git a/web/src/features/topics/TopicMobileList.tsx b/web/src/features/topics/TopicMobileList.tsx
new file mode 100644
index 0000000000..e84b8c569c
--- /dev/null
+++ b/web/src/features/topics/TopicMobileList.tsx
@@ -0,0 +1,81 @@
+import { ChevronRight } from "@langfuse/icons";
+import { cn } from "@/src/utils/tailwind";
+import { type TopicDisplay } from "./prepare-topic-display";
+
+type TopicMobileListProps = {
+ topics: Pick<
+ TopicDisplay,
+ "id" | "name" | "description" | "count" | "color"
+ >[];
+ totalCount: number;
+ selectedTopicId: string | null;
+ onSelectTopic: (id: string) => void;
+ onShowAllTraces: () => void;
+};
+
+/** Every topic has a readable label and a touch target independent of its size. */
+export function TopicMobileList({
+ topics,
+ totalCount,
+ selectedTopicId,
+ onSelectTopic,
+ onShowAllTraces,
+}: TopicMobileListProps) {
+ return (
+ <div className="ph-no-capture flex min-h-0 flex-1 flex-col overflow-y-auto overscroll-contain">
+ <button
+ type="button"
+ onClick={onShowAllTraces}
+ className="hover:bg-accent focus-visible:ring-ring flex min-h-12 items-center justify-between gap-3 border-b px-4 py-3 text-left text-sm focus-visible:ring-2 focus-visible:ring-inset"
+ >
+ <span className="font-bold">All traces</span>
+ <span className="text-muted-foreground flex items-center gap-2 tabular-nums">
+ {totalCount.toLocaleString()}
+ <ChevronRight size="base" aria-hidden />
+ </span>
+ </button>
+ <ul className="divide-y">
+ {topics.map((topic) => (
+ <li key={topic.id}>
+ <button
+ type="button"
+ aria-label={`${topic.name}, ${topic.count} traces`}
+ aria-pressed={selectedTopicId === topic.id}
+ onClick={() => onSelectTopic(topic.id)}
+ className={cn(
+ "hover:bg-accent focus-visible:ring-ring flex min-h-14 w-full items-start gap-3 px-4 py-3 text-left text-sm focus-visible:ring-2 focus-visible:ring-inset",
+ selectedTopicId === topic.id && "bg-accent",
+ )}
+ >
+ <span
+ aria-hidden
+ className="mt-1.5 size-2.5 shrink-0 rounded-xs"
+ style={{ backgroundColor: topic.color }}
+ />
+ <span className="flex min-w-0 flex-1 flex-col gap-1">
+ <span className="font-bold [overflow-wrap:anywhere]">
+ {topic.name}
+ </span>
+ {topic.description && (
+ <span className="text-muted-foreground line-clamp-2 [overflow-wrap:anywhere]">
+ {topic.description}
+ </span>
+ )}
+ </span>
+ <span className="text-muted-foreground flex shrink-0 items-center gap-2 tabular-nums">
+ {topic.count.toLocaleString()}
+ <ChevronRight size="base" aria-hidden />
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ {topics.length === 0 && (
+ <p className="text-muted-foreground p-4 text-sm">
+ No topics in this time range. You can still browse all trace
+ summaries.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/features/topics/TopicMobileTraceList.tsx b/web/src/features/topics/TopicMobileTraceList.tsx
new file mode 100644
index 0000000000..7d5c7ebdf1
--- /dev/null
+++ b/web/src/features/topics/TopicMobileTraceList.tsx
@@ -0,0 +1,121 @@
+import { useEffect, useRef, useState, type ReactNode } from "react";
+import { ChevronRight } from "@langfuse/icons";
+import {
+ PaginationBar,
+ type PaginationBarState,
+} from "@/src/components/design-system/PaginationBar/PaginationBar";
+import { formatCompactRelativeTime } from "@/src/utils/dates";
+import { cn } from "@/src/utils/tailwind";
+import { type FacetRow } from "./facet-topics";
+
+const PAGE_SIZE = 20;
+
+type TopicMobileTraceListProps = {
+ children: ReactNode;
+ filterKey: string;
+ rows: FacetRow[];
+ selectedTraceId: string | null;
+ onOpenTrace: (traceId: string) => void;
+};
+
+export function TopicMobileTraceList({
+ children,
+ filterKey,
+ rows,
+ selectedTraceId,
+ onOpenTrace,
+}: TopicMobileTraceListProps) {
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const selectedRef = useRef<HTMLButtonElement>(null);
+ const [pageRequest, setPageRequest] = useState(() => ({
+ filterKey,
+ pageSize: PAGE_SIZE,
+ pageIndex: Math.max(
+ 0,
+ Math.floor(
+ rows.findIndex((row) => row.traceId === selectedTraceId) / PAGE_SIZE,
+ ),
+ ),
+ }));
+ if (pageRequest.filterKey !== filterKey) {
+ setPageRequest({ ...pageRequest, filterKey, pageIndex: 0 });
+ }
+ // The DOM scroll position follows map selection without moving keyboard focus.
+ useEffect(() => {
+ selectedRef.current?.scrollIntoView({ block: "nearest" });
+ }, [selectedTraceId]);
+ const { pageSize } = pageRequest;
+ const pageCount = Math.max(1, Math.ceil(rows.length / pageSize));
+ const pageIndex = Math.min(pageRequest.pageIndex, pageCount - 1);
+ const pageRows = rows.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize);
+ function changePage(pagination: PaginationBarState) {
+ setPageRequest({ filterKey, ...pagination });
+ scrollRef.current?.scrollTo({ top: 0 });
+ }
+
+ return (
+ <div className="ph-no-capture flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
+ <div
+ ref={scrollRef}
+ className="min-h-0 flex-1 overflow-y-auto overscroll-contain"
+ >
+ {children}
+ <ul className="divide-y">
+ {pageRows.map((row) => (
+ <li key={row.traceId}>
+ <button
+ ref={row.traceId === selectedTraceId ? selectedRef : undefined}
+ type="button"
+ aria-label={`Open trace ${row.traceId}`}
+ aria-current={
+ row.traceId === selectedTraceId ? "true" : undefined
+ }
+ onClick={() => onOpenTrace(row.traceId)}
+ className={cn(
+ "hover:bg-accent focus-visible:ring-ring flex w-full flex-col gap-2 p-4 text-left text-sm focus-visible:ring-2 focus-visible:ring-inset",
+ row.traceId === selectedTraceId && "bg-accent",
+ )}
+ >
+ <span className="text-muted-foreground flex w-full min-w-0 items-start justify-between gap-3 text-xs">
+ <span className="[overflow-wrap:anywhere]">
+ {row.topicName ?? row.outcome.replaceAll("_", " ")}
+ </span>
+ <time className="shrink-0" dateTime={row.unitStartTime}>
+ {formatCompactRelativeTime(new Date(row.unitStartTime))}
+ </time>
+ </span>
+ <span className="[overflow-wrap:anywhere] whitespace-pre-wrap">
+ {row.summary || "No applicable summary."}
+ </span>
+ <span className="text-muted-foreground flex w-full min-w-0 items-center justify-between gap-2 text-xs">
+ <span className="truncate font-mono" title={row.traceId}>
+ {row.traceId}
+ </span>
+ <span className="text-link flex shrink-0 items-center gap-1">
+ Open trace{" "}
+ <ChevronRight size="base" color="inherit" aria-hidden />
+ </span>
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ {rows.length === 0 && (
+ <p className="text-muted-foreground p-4 text-sm">
+ No matches. Adjust or clear your filters.
+ </p>
+ )}
+ </div>
+ {rows.length > 0 && (
+ <nav aria-label="Trace pagination" className="shrink-0">
+ <PaginationBar
+ mode="offset"
+ totalCount={rows.length}
+ state={{ pageIndex, pageSize }}
+ onChange={changePage}
+ />
+ </nav>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/features/topics/TopicPreviewCard.tsx b/web/src/features/topics/TopicPreviewCard.tsx
new file mode 100644
index 0000000000..5e17a9d547
--- /dev/null
+++ b/web/src/features/topics/TopicPreviewCard.tsx
@@ -0,0 +1,27 @@
+import { type TopicDisplay } from "./prepare-topic-display";
+
+/** Persistent touch counterpart to a topic's hover details. */
+export function TopicPreviewCard({
+ topic,
+ total,
+}: {
+ topic: Pick<TopicDisplay, "name" | "description" | "count">;
+ total: number;
+}) {
+ return (
+ <div
+ role="tooltip"
+ className="ph-no-capture bg-popover text-popover-foreground pointer-events-none rounded-md border p-3 text-xs shadow-md"
+ >
+ <p className="font-bold">{topic.name}</p>
+ <p className="text-muted-foreground mt-1">
+ {topic.count.toLocaleString()} traces ·{" "}
+ {Math.round((topic.count / Math.max(1, total)) * 100)}% of traces
+ </p>
+ {topic.description && (
+ <p className="mt-1 line-clamp-3">{topic.description}</p>
+ )}
+ <p className="text-muted-foreground mt-2">Tap again to view traces</p>
+ </div>
+ );
+}
diff --git a/web/src/features/topics/TopicSetupFlowDialog.tsx b/web/src/features/topics/TopicSetupFlowDialog.tsx
index 793a48e2e4..cd1733df77 100644
--- a/web/src/features/topics/TopicSetupFlowDialog.tsx
+++ b/web/src/features/topics/TopicSetupFlowDialog.tsx
@@ -179,7 +179,7 @@ export function TopicSetupFlowDialog({
{questions.map((question) => (
<div
key={question.name}
- className="grid grid-cols-[16px_96px_minmax(0,1fr)] items-center gap-2.5 px-3 py-2.5"
+ className="grid grid-cols-[16px_minmax(0,1fr)] items-center gap-x-2.5 gap-y-1 px-3 py-2.5 sm:grid-cols-[16px_96px_minmax(0,1fr)]"
>
<Checkbox
checked={question.enabled}
@@ -190,7 +190,7 @@ export function TopicSetupFlowDialog({
}
/>
<span className="text-sm font-bold">{question.name}</span>
- <span className="text-muted-foreground text-sm">
+ <span className="text-muted-foreground col-start-2 text-sm sm:col-start-auto">
{question.description}
</span>
</div>
@@ -198,7 +198,7 @@ export function TopicSetupFlowDialog({
</div>
</section>
<section className="flex flex-col gap-2">
- <div className="flex items-baseline justify-between gap-3">
+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
<h2 className="text-sm font-bold">
Select models for analysis
</h2>
@@ -237,7 +237,7 @@ export function TopicSetupFlowDialog({
{MODEL_ROWS.map((row) => (
<div
key={row.slot}
- className="grid grid-cols-[140px_minmax(0,1fr)] items-center gap-3 px-3.5 py-2.75"
+ className="grid gap-1 px-3.5 py-2.75 sm:grid-cols-[140px_minmax(0,1fr)] sm:items-center sm:gap-3"
>
<span>{row.label}</span>
<span className="text-muted-foreground">
@@ -441,7 +441,7 @@ export function TopicSetupFlowDialog({
) : null}
</div>
{!viewerBlocked && (
- <div className="flex items-center justify-between border-t px-4 py-3">
+ <div className="flex shrink-0 items-center justify-between border-t px-4 py-3">
{step === "questions" ? (
<span />
) : (
@@ -527,7 +527,7 @@ function ModelRow({
}) {
const [open, setOpen] = useState(false);
return (
- <div className="grid grid-cols-[112px_minmax(0,1fr)] items-center gap-2 py-1.5 pr-1.5 pl-3">
+ <div className="grid gap-1 px-3 py-2 sm:grid-cols-[112px_minmax(0,1fr)] sm:items-center sm:gap-2 sm:py-1.5 sm:pr-1.5">
<span className="text-sm">{label}</span>
<JudgeModelPicker
purpose="decision"
@@ -582,9 +582,9 @@ function ReviewRow({
onEdit: () => void;
}) {
return (
- <div className="grid grid-cols-[120px_minmax(0,1fr)_auto] items-center gap-3 rounded-md border px-3.5 py-3">
+ <div className="flex flex-col items-start gap-2 rounded-md border px-3.5 py-3 sm:grid sm:grid-cols-[120px_minmax(0,1fr)_auto] sm:items-center sm:gap-3">
<span className="text-sm font-bold">{label}</span>
- <div className="flex min-w-0 flex-col gap-1.5">
+ <div className="flex w-full min-w-0 flex-col gap-1.5">
{lines.map((line) => (
<div
key={`${line.key ?? ""}${line.value}`}
@@ -596,7 +596,11 @@ function ReviewRow({
</span>
) : null}
<span
- className={line.mono ? "truncate font-mono text-xs" : "text-sm"}
+ className={
+ line.mono
+ ? "min-w-0 truncate font-mono text-xs"
+ : "min-w-0 text-sm break-words"
+ }
title={line.mono ? line.value : undefined}
>
{line.value}
diff --git a/web/src/features/topics/TopicTreemap.tsx b/web/src/features/topics/TopicTreemap.tsx
new file mode 100644
index 0000000000..28c6a0d368
--- /dev/null
+++ b/web/src/features/topics/TopicTreemap.tsx
@@ -0,0 +1,231 @@
+import { useState, type MouseEvent } from "react";
+import { useElementSize } from "@/src/hooks/useElementSize";
+import { CustomTooltip } from "@/src/components/design-system/CustomTooltip/CustomTooltip";
+import { cn } from "@/src/utils/tailwind";
+import { type TopicDisplay } from "./prepare-topic-display";
+import { layoutTreemap } from "./topic-treemap-layout";
+import { TopicPreviewCard } from "./TopicPreviewCard";
+
+type TopicTreemapProps = {
+ total: number;
+ topics: TopicDisplay[];
+ selectedTopicId: string | null;
+ onSelectTopic: (topicId: string) => void;
+ previewOnSelect?: boolean;
+};
+
+type TileTier = "large" | "medium" | "small" | "tiny";
+
+type TopicTileProps = {
+ previewOnSelect: boolean;
+ topic: TopicDisplay;
+ share: number;
+ colors: TopicDisplay["tiles"]["small"];
+ isSelected: boolean;
+ onSelect: (topicId: string) => void;
+ rect: { left: number; top: number; width: number; height: number };
+ tier: TileTier;
+};
+
+type TopicTileButtonProps = TopicTileProps & {
+ shareLabel: string;
+ triggerProps?: Record<string, unknown>;
+};
+
+const TILE_GAP = 8;
+/** Tiles above this area (px²) get the stronger resting tint. */
+const BIG_TILE_AREA = 30_000;
+
+const TILE_PADDING: Record<TileTier, string> = {
+ large: "p-3",
+ medium: "p-3",
+ small: "p-2",
+ tiny: "p-0",
+};
+
+/** Vertical padding, name line height and count+share block height (px) for tiers that show a name. */
+const PADDING_Y_PX = 24;
+const NAME_LINE_PX = { large: 28, medium: 20 };
+const FOOTER_PX = { large: 54, medium: 46 };
+const NAME_CLAMP = ["line-clamp-1", "line-clamp-2", "line-clamp-3"];
+
+const COUNT_SIZE: Record<TileTier, string> = {
+ large: "text-3xl",
+ medium: "text-xl",
+ small: "text-sm",
+ tiny: "",
+};
+
+function tileTier(width: number, height: number): TileTier {
+ if (width >= 240 && height >= 160) return "large";
+ if (width >= 112 && height >= 96) return "medium";
+ if (width >= 40 && height >= 32) return "small";
+ return "tiny";
+}
+
+function TopicTileButton({
+ topic,
+ colors,
+ isSelected,
+ onSelect,
+ rect,
+ tier,
+ shareLabel,
+ triggerProps,
+}: TopicTileButtonProps) {
+ function selectTopic() {
+ onSelect(topic.id);
+ }
+ const showName = tier === "large" || tier === "medium";
+ /** Name lines that fit above the count. */
+ const nameLines = showName
+ ? Math.min(
+ 3,
+ Math.max(
+ 1,
+ Math.floor(
+ (rect.height - PADDING_Y_PX - FOOTER_PX[tier]) / NAME_LINE_PX[tier],
+ ),
+ ),
+ )
+ : 0;
+ return (
+ <button
+ {...triggerProps}
+ type="button"
+ onClick={selectTopic}
+ aria-pressed={isSelected}
+ aria-label={`${topic.name}, ${topic.count} traces`}
+ style={rect}
+ className={cn(
+ "absolute flex flex-col justify-between overflow-hidden rounded-md text-left",
+ TILE_PADDING[tier],
+ isSelected
+ ? cn(
+ colors.active,
+ "text-foreground outline-foreground outline-2 outline-offset-2",
+ )
+ : cn(
+ colors.tile,
+ colors.hover,
+ "text-muted-foreground hover:text-foreground",
+ ),
+ )}
+ >
+ {showName && (
+ <span
+ className={cn(
+ NAME_CLAMP[nameLines - 1],
+ "font-bold",
+ tier === "large" ? "text-lg" : "text-sm",
+ )}
+ >
+ {topic.name}
+ </span>
+ )}
+ {tier !== "tiny" && (
+ <span className="flex flex-col gap-0.5">
+ <span className={cn("font-bold tabular-nums", COUNT_SIZE[tier])}>
+ {topic.count.toLocaleString()}
+ </span>
+ {showName && <span className="text-xs opacity-80">{shareLabel}</span>}
+ </span>
+ )}
+ </button>
+ );
+}
+
+function TopicTile(props: TopicTileProps) {
+ const { topic, share, tier, previewOnSelect } = props;
+ const shareLabel = `${Math.round(share * 100)}% of traces`;
+ if (previewOnSelect || tier === "large" || tier === "medium") {
+ return <TopicTileButton {...props} shareLabel={shareLabel} />;
+ }
+ return (
+ <CustomTooltip
+ placement="top"
+ content={
+ <span className="ph-no-capture flex flex-col gap-0.5">
+ <span className="font-bold">{topic.name}</span>
+ <span className="text-muted-foreground text-xs">
+ {topic.count.toLocaleString()} traces · {shareLabel}
+ </span>
+ </span>
+ }
+ >
+ {({ getTriggerProps }) => (
+ <TopicTileButton
+ {...props}
+ shareLabel={shareLabel}
+ triggerProps={getTriggerProps()}
+ />
+ )}
+ </CustomTooltip>
+ );
+}
+
+export function TopicTreemap({
+ total,
+ topics,
+ selectedTopicId,
+ onSelectTopic,
+ previewOnSelect = false,
+}: TopicTreemapProps) {
+ const [previewedId, setPreviewedId] = useState<string | null>(null);
+ const [ref, size] = useElementSize<HTMLDivElement>();
+ const tiles = size
+ ? layoutTreemap(topics, size.width, size.height, TILE_GAP)
+ : [];
+ const previewedTopic = topics.find((topic) => topic.id === previewedId);
+ const previewedTile = tiles.find((tile) => tile.item.id === previewedId);
+ const previewAnchor = previewedTile
+ ? previewedTile.y + previewedTile.height / 2
+ : 0;
+ function selectTopic(topicId: string) {
+ if (previewOnSelect && previewedId !== topicId) {
+ setPreviewedId(topicId);
+ return;
+ }
+ setPreviewedId(null);
+ onSelectTopic(topicId);
+ }
+ function dismissPreview(event: MouseEvent<HTMLElement>) {
+ if (event.target === event.currentTarget) setPreviewedId(null);
+ }
+ return (
+ <section
+ aria-label="Topics"
+ ref={ref}
+ className="relative h-full min-h-0 min-w-0 flex-1"
+ onClick={dismissPreview}
+ >
+ {tiles.map(({ item, x, y, width, height }) => (
+ <TopicTile
+ key={item.id}
+ topic={item}
+ share={total > 0 ? item.count / total : 0}
+ colors={
+ width * height > BIG_TILE_AREA ? item.tiles.big : item.tiles.small
+ }
+ isSelected={item.id === (previewedId ?? selectedTopicId)}
+ onSelect={selectTopic}
+ rect={{ left: x, top: y, width, height }}
+ tier={tileTier(width, height)}
+ previewOnSelect={previewOnSelect}
+ />
+ ))}
+ {previewedTopic && (
+ <div
+ className="pointer-events-none absolute right-2 left-2"
+ style={
+ size && previewAnchor > size.height / 2
+ ? { bottom: size.height - previewAnchor }
+ : { top: previewAnchor }
+ }
+ >
+ <TopicPreviewCard topic={previewedTopic} total={total} />
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/web/src/features/topics/TopicTreemapView.tsx b/web/src/features/topics/TopicTreemapView.tsx
index 89a1007daf..785fccaf30 100644
--- a/web/src/features/topics/TopicTreemapView.tsx
+++ b/web/src/features/topics/TopicTreemapView.tsx
@@ -1,43 +1,20 @@
-/* eslint-disable @typescript-eslint/no-use-before-define */
import { useState } from "react";
-import { useElementSize } from "@/src/hooks/useElementSize";
-import { CustomTooltip } from "@/src/components/design-system/CustomTooltip/CustomTooltip";
import { type DataTablePeekViewProps } from "@/src/components/table/peek";
-import { cn } from "@/src/utils/tailwind";
import { TopicsEmptyState } from "./TopicsEmptyState";
-import { type Facet, type FacetTopic } from "./facet-topics";
+import { type Facet } from "./facet-topics";
import {
- treemapSwatchColor,
- treemapTileClasses,
- UNASSIGNED_SWATCH_COLOR,
- unassignedTileClasses,
-} from "./topic-map-colors";
-import { layoutTreemap } from "./topic-treemap-layout";
+ prepareTopicDisplay,
+ UNASSIGNED_TOPIC_ID,
+} from "./prepare-topic-display";
+import { TopicTreemap } from "./TopicTreemap";
import { TopicTraceList } from "./TopicTraceList";
-const TILE_GAP = 8;
-const UNASSIGNED_ID = "__unassigned";
-/** Tiles above this area (px²) get the stronger resting tint. */
-const BIG_TILE_AREA = 30_000;
-
-const TILE_PADDING: Record<TileTier, string> = {
- large: "p-3",
- medium: "p-3",
- small: "p-2",
- tiny: "p-0",
-};
-
-/** Vertical padding, name line height and count+share block height (px) for tiers that show a name. */
-const PADDING_Y_PX = 24;
-const NAME_LINE_PX = { large: 28, medium: 20 };
-const FOOTER_PX = { large: 54, medium: 46 };
-const NAME_CLAMP = ["line-clamp-1", "line-clamp-2", "line-clamp-3"];
-
-const COUNT_SIZE: Record<TileTier, string> = {
- large: "text-3xl",
- medium: "text-xl",
- small: "text-sm",
- tiny: "",
+type TopicTreemapViewProps = {
+ projectId: string;
+ facet: Facet;
+ peekView: DataTablePeekViewProps;
+ onGenerateTopics: () => void;
+ canGenerateTopics: boolean;
};
export function TopicTreemapView({
@@ -56,41 +33,32 @@ export function TopicTreemapView({
/>
);
}
- const unassignedCount = facet.rows.filter((row) => !row.topicId).length;
- const topics: FacetTopic[] =
- unassignedCount > 0
- ? [
- ...facet.topics,
- {
- id: UNASSIGNED_ID,
- versionId: "",
- runId: "",
- name: "Unassigned",
- description: "",
- count: unassignedCount,
- },
- ]
- : facet.topics;
+ const { topics, total } = prepareTopicDisplay(facet, "treemap");
const selected =
topics.find((topic) => topic.id === selectedTopicId) ?? topics[0];
- const selectedRowTopicId = selected.id === UNASSIGNED_ID ? null : selected.id;
+ const selectedRowTopicId =
+ selected.id === UNASSIGNED_TOPIC_ID ? null : selected.id;
const rows = facet.rows.filter(
(row) => (row.topicId ?? null) === selectedRowTopicId,
);
return (
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">
- <TopicTreemap
- facet={facet}
- topics={topics}
- selectedTopicId={selected.id}
- onSelectTopic={setSelectedTopicId}
- />
+ <div className="m-4 flex min-h-48 shrink-0 basis-1/2">
+ <TopicTreemap
+ total={total}
+ topics={topics}
+ selectedTopicId={selected.id}
+ onSelectTopic={setSelectedTopicId}
+ />
+ </div>
<TopicTraceList
key={selected.id}
projectId={projectId}
title={selected.name}
- description={selected.description}
- swatchColor={swatchFor(facet, selected.id)}
+ description={
+ selected.id === UNASSIGNED_TOPIC_ID ? undefined : selected.description
+ }
+ swatchColor={selected.color}
rows={rows}
peekView={peekView}
divider="top"
@@ -98,190 +66,3 @@ export function TopicTreemapView({
</div>
);
}
-
-function TopicTreemap({
- facet,
- topics,
- selectedTopicId,
- onSelectTopic,
-}: TopicTreemapProps) {
- const [ref, size] = useElementSize<HTMLDivElement>();
- const total = facet.rows.length;
- function tileColors(topicId: string, big: boolean) {
- if (topicId === UNASSIGNED_ID) return unassignedTileClasses;
- return treemapTileClasses(
- facet.topics.findIndex((topic) => topic.id === topicId),
- big,
- );
- }
- const tiles = size
- ? layoutTreemap(topics, size.width, size.height, TILE_GAP)
- : [];
- return (
- <section
- aria-label="Topics"
- ref={ref}
- className="relative m-4 min-h-48 min-w-0 shrink-0 basis-1/2"
- >
- {tiles.map(({ item, x, y, width, height }) => (
- <TopicTile
- key={item.id}
- topic={item}
- share={total > 0 ? item.count / total : 0}
- colors={tileColors(item.id, width * height > BIG_TILE_AREA)}
- isSelected={item.id === selectedTopicId}
- onSelect={onSelectTopic}
- rect={{ left: x, top: y, width, height }}
- tier={tileTier(width, height)}
- />
- ))}
- </section>
- );
-}
-
-function TopicTile(props: TopicTileProps) {
- const { topic, share, tier } = props;
- const shareLabel = `${Math.round(share * 100)}% of traces`;
- if (tier === "large" || tier === "medium") {
- return <TopicTileButton {...props} shareLabel={shareLabel} />;
- }
- return (
- <CustomTooltip
- placement="top"
- content={
- <span className="ph-no-capture flex flex-col gap-0.5">
- <span className="font-bold">{topic.name}</span>
- <span className="text-muted-foreground text-xs">
- {topic.count.toLocaleString()} traces · {shareLabel}
- </span>
- </span>
- }
- >
- {({ getTriggerProps }) => (
- <TopicTileButton
- {...props}
- shareLabel={shareLabel}
- triggerProps={getTriggerProps()}
- />
- )}
- </CustomTooltip>
- );
-}
-
-function TopicTileButton({
- topic,
- colors,
- isSelected,
- onSelect,
- rect,
- tier,
- shareLabel,
- triggerProps,
-}: TopicTileButtonProps) {
- function selectTopic() {
- onSelect(topic.id);
- }
- const showName = tier === "large" || tier === "medium";
- /** Name lines that fit above the count. */
- const nameLines = showName
- ? Math.min(
- 3,
- Math.max(
- 1,
- Math.floor(
- (rect.height - PADDING_Y_PX - FOOTER_PX[tier]) / NAME_LINE_PX[tier],
- ),
- ),
- )
- : 0;
- return (
- <button
- {...triggerProps}
- type="button"
- onClick={selectTopic}
- aria-pressed={isSelected}
- aria-label={`${topic.name}, ${topic.count} traces`}
- style={rect}
- className={cn(
- "absolute flex flex-col justify-between overflow-hidden rounded-md text-left",
- TILE_PADDING[tier],
- isSelected
- ? cn(
- colors.active,
- "text-foreground outline-foreground outline-2 outline-offset-2",
- )
- : cn(
- colors.tile,
- colors.hover,
- "text-muted-foreground hover:text-foreground",
- ),
- )}
- >
- {showName && (
- <span
- className={cn(
- NAME_CLAMP[nameLines - 1],
- "font-bold",
- tier === "large" ? "text-lg" : "text-sm",
- )}
- >
- {topic.name}
- </span>
- )}
- {tier !== "tiny" && (
- <span className="flex flex-col gap-0.5">
- <span className={cn("font-bold tabular-nums", COUNT_SIZE[tier])}>
- {topic.count.toLocaleString()}
- </span>
- {showName && <span className="text-xs opacity-80">{shareLabel}</span>}
- </span>
- )}
- </button>
- );
-}
-
-function tileTier(width: number, height: number): TileTier {
- if (width >= 240 && height >= 160) return "large";
- if (width >= 112 && height >= 96) return "medium";
- if (width >= 40 && height >= 32) return "small";
- return "tiny";
-}
-
-function swatchFor(facet: Facet, topicId: string) {
- if (topicId === UNASSIGNED_ID) return UNASSIGNED_SWATCH_COLOR;
- return treemapSwatchColor(
- facet.topics.findIndex((topic) => topic.id === topicId),
- );
-}
-
-type TopicTreemapViewProps = {
- projectId: string;
- facet: Facet;
- peekView: DataTablePeekViewProps;
- onGenerateTopics: () => void;
- canGenerateTopics: boolean;
-};
-
-type TopicTreemapProps = {
- facet: Facet;
- topics: FacetTopic[];
- selectedTopicId: string;
- onSelectTopic: (topicId: string) => void;
-};
-
-type TileTier = "large" | "medium" | "small" | "tiny";
-
-type TopicTileProps = {
- topic: FacetTopic;
- share: number;
- colors: { tile: string; active: string; hover: string };
- isSelected: boolean;
- onSelect: (topicId: string) => void;
- rect: { left: number; top: number; width: number; height: number };
- tier: TileTier;
-};
-
-type TopicTileButtonProps = TopicTileProps & {
- shareLabel: string;
- triggerProps?: Record<string, unknown>;
-};
diff --git a/web/src/features/topics/TopicsActionsMenu.tsx b/web/src/features/topics/TopicsActionsMenu.tsx
index 6d3e206989..2bf7fe6ce3 100644
--- a/web/src/features/topics/TopicsActionsMenu.tsx
+++ b/web/src/features/topics/TopicsActionsMenu.tsx
@@ -1,59 +1,32 @@
-import { type ReactNode } from "react";
-import { History, Play, RefreshCw } from "@langfuse/icons";
import { HeaderActionMenuRow } from "@/src/components/HeaderActionMenuRow";
+import { Badge } from "@/src/components/design-system/Badge/Badge";
+import { type TopicsActions } from "./prepare-topics-actions";
export function TopicsActionsMenu({
- children,
- triggerAction,
+ actions,
closeMenu,
- onOpenHistory,
- onRefresh,
-}: TopicsActionsMenuProps) {
- function processTraces() {
- closeMenu();
- triggerAction?.onSelect();
- }
- function openHistory() {
- closeMenu({ handoffFocus: true });
- onOpenHistory();
- }
- function refreshResults() {
- closeMenu();
- onRefresh();
- }
- return (
- <>
- {children}
- {triggerAction && (
- <HeaderActionMenuRow
- label={triggerAction.label}
- icon={<Play size="base" color="default" />}
- disabled={triggerAction.disabled}
- onClick={processTraces}
- />
- )}
- <HeaderActionMenuRow
- label="History"
- icon={<History size="base" color="default" />}
- onClick={openHistory}
- />
+}: {
+ actions: TopicsActions;
+ closeMenu: (options?: { handoffFocus?: boolean }) => void;
+}) {
+ return actions.menu.map((action) => {
+ const Icon = action.icon;
+ function select() {
+ closeMenu({ handoffFocus: action.id === "history" });
+ action.onSelect();
+ }
+ return (
<HeaderActionMenuRow
- label="Refresh results"
- icon={<RefreshCw size="base" color="default" />}
- onClick={refreshResults}
+ key={action.id}
+ label={action.label}
+ icon={<Icon size="base" color="default" />}
+ badge={
+ action.badge ? <Badge text={action.badge} size="sm" /> : undefined
+ }
+ disabled={Boolean(action.disabledReason)}
+ disabledReason={action.disabledReason}
+ onClick={select}
/>
- </>
- );
+ );
+ });
}
-
-type TopicsActionsMenuProps = {
- children?: ReactNode;
- triggerAction: {
- label: string;
- disabled: boolean;
- onSelect: () => void;
- } | null;
- closeMenu: (options?: { handoffFocus?: boolean }) => void;
- onOpenHistory: () => void;
- onRefresh: () => void;
-};
diff --git a/web/src/features/topics/TopicsHeaderActions.stories.tsx b/web/src/features/topics/TopicsHeaderActions.stories.tsx
new file mode 100644
index 0000000000..7df591267f
--- /dev/null
+++ b/web/src/features/topics/TopicsHeaderActions.stories.tsx
@@ -0,0 +1,66 @@
+import { expect, fn, userEvent, waitFor, within } from "storybook/test";
+import { type ComponentProps } from "react";
+import preview from "../../../.storybook/preview";
+import { TopicsHeaderActions } from "./TopicsHeaderActions";
+import { prepareTopicsActions } from "./prepare-topics-actions";
+
+const defaultArgs: ComponentProps<typeof TopicsHeaderActions> = {
+ actions: prepareTopicsActions({
+ automaticProcessing: { state: { status: "off" }, saving: false },
+ configureAvailable: true,
+ configureVariant: "secondary",
+ configured: true,
+ canWrite: true,
+ manualAvailable: true,
+ menuOnly: false,
+ onManualProcessing: fn(),
+ onAutomaticProcessing: fn(),
+ onConfigure: fn(),
+ onHistory: fn(),
+ onRefresh: fn(),
+ }),
+};
+
+const meta = preview.meta({
+ component: TopicsHeaderActions,
+ parameters: { layout: "fullscreen" },
+ args: defaultArgs,
+});
+
+export const Wide = meta.story({
+ render: (args) => (
+ <div className="@container/topics-header w-full p-3">
+ <TopicsHeaderActions {...args} />
+ </div>
+ ),
+});
+
+export const Compact = meta.story({
+ name: "(Test) Compact processing actions remain reachable",
+ render: (args) => (
+ <div className="@container/topics-header w-80 p-3">
+ <TopicsHeaderActions {...args} />
+ </div>
+ ),
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(
+ canvas.queryByRole("button", { name: "Automatic processing" }),
+ ).not.toBeInTheDocument();
+ await expect(
+ canvas.queryByRole("button", { name: "Manual processing" }),
+ ).not.toBeInTheDocument();
+ await userEvent.click(
+ canvas.getByRole("button", { name: "Topics actions" }),
+ );
+ const body = within(canvasElement.ownerDocument.body);
+ await waitFor(() =>
+ expect(
+ body.getByRole("menuitem", { name: "Manual processing" }),
+ ).toBeVisible(),
+ );
+ await expect(
+ body.getByRole("menuitem", { name: /Automatic processing/ }),
+ ).toBeVisible();
+ },
+});
diff --git a/web/src/features/topics/TopicsHeaderActions.tsx b/web/src/features/topics/TopicsHeaderActions.tsx
index a8b08c4d21..8634842aa2 100644
--- a/web/src/features/topics/TopicsHeaderActions.tsx
+++ b/web/src/features/topics/TopicsHeaderActions.tsx
@@ -1,77 +1,45 @@
-import { MoreHorizontal, Settings } from "@langfuse/icons";
+import { MoreHorizontal } from "@langfuse/icons";
import { Button } from "@/src/components/design-system/Button/Button";
+import { Badge } from "@/src/components/design-system/Badge/Badge";
import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";
import { IconButton } from "@/src/components/design-system/IconButton/IconButton";
import { AutomaticProcessingControl } from "./AutomaticProcessingControl";
-import { type useTopicModelSettings } from "./TopicModelSettings";
+import { type TopicsActions } from "./prepare-topics-actions";
-export function TopicsHeaderActions({
- automaticProcessing,
- configure,
- configured,
- canWrite,
- manualAvailable,
- openManual,
- onAutomaticProcessing,
- onConfigure,
- onHistory,
- onRefresh,
- menuOnly = false,
-}: TopicsHeaderActionsProps) {
+export function TopicsHeaderActions({ actions }: { actions: TopicsActions }) {
return (
- <div className="ph-no-capture flex items-center justify-end gap-1">
- {!menuOnly && (
- <AutomaticProcessingControl
- state={automaticProcessing.state}
- canWrite={canWrite && !automaticProcessing.saving}
- onOpen={onAutomaticProcessing}
- />
- )}
- {!menuOnly && !configured ? (
- <Button
- text="Configure Topics"
- variant={configure.triggerVariant}
- size="sm"
- disabled={!configure.settings}
- onClick={onConfigure}
- />
- ) : null}
- {!menuOnly && manualAvailable ? (
- <Button
- text="Manual processing"
- variant="secondary"
- size="sm"
- onClick={openManual}
- />
- ) : null}
+ <div className="ph-no-capture flex shrink-0 items-center justify-end gap-1">
+ <div className="hidden items-center gap-1 @5xl/topics-header:flex">
+ {actions.automatic && (
+ <AutomaticProcessingControl action={actions.automatic} />
+ )}
+ {actions.inline.map((action) => (
+ <Button
+ key={action.id}
+ text={action.label}
+ variant={action.variant}
+ size="sm"
+ disabled={Boolean(action.disabledReason)}
+ onClick={action.onSelect}
+ />
+ ))}
+ </div>
<DropdownMenu
ariaLabel="Topics actions"
placement="bottom-end"
- items={[
- ...(configured
- ? [
- {
- id: "configure",
- type: "item" as const,
- title: "Configure Topics",
- icon: Settings,
- onClick: onConfigure,
- },
- ]
- : []),
- {
- id: "history",
- type: "item",
- title: "History",
- onClick: onHistory,
- },
- {
- id: "refresh",
- type: "item",
- title: "Refresh results",
- onClick: onRefresh,
- },
- ]}
+ items={actions.menu.map((action) => ({
+ id: action.id,
+ type: "item",
+ title: action.label,
+ icon: action.icon,
+ badge: action.badge ? (
+ <Badge text={action.badge} size="sm" />
+ ) : undefined,
+ disabled: action.disabledReason
+ ? { reason: action.disabledReason }
+ : undefined,
+ onClick: action.onSelect,
+ }))}
>
{({ getTriggerProps }) => (
<IconButton
@@ -85,22 +53,3 @@ export function TopicsHeaderActions({
</div>
);
}
-
-type ModelSettings = ReturnType<typeof useTopicModelSettings>;
-type TopicsHeaderActionsProps = {
- automaticProcessing: Pick<
- ModelSettings["automaticProcessing"],
- "state" | "saving"
- >;
- configure: Pick<ModelSettings["configure"], "settings" | "triggerVariant">;
- configured: boolean;
- canWrite: boolean;
- manualAvailable: boolean;
- openManual: () => void;
- onAutomaticProcessing: () => void;
- onConfigure: () => void;
- onHistory: () => void;
- onRefresh: () => void;
- /** Before setup only the overflow menu shows. */
- menuOnly?: boolean;
-};
diff --git a/web/src/features/topics/TopicsMobileControls.tsx b/web/src/features/topics/TopicsMobileControls.tsx
new file mode 100644
index 0000000000..cb887a77d8
--- /dev/null
+++ b/web/src/features/topics/TopicsMobileControls.tsx
@@ -0,0 +1,47 @@
+import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";
+import {
+ TOPICS_RESULTS_VIEWS,
+ type TopicsResultsView,
+} from "./TopicsResultsViewSelect";
+
+export function TopicsMobileControls({
+ facets,
+ selectedFacet,
+ onSelectFacet,
+ view,
+ onSelectView,
+}: TopicsMobileControlsProps) {
+ return (
+ <div className="ph-no-capture flex min-w-0 items-center gap-2">
+ <div className="w-40 min-w-0">
+ <SelectInput
+ aria-label="Topics facet"
+ placeholder="Facet"
+ value={selectedFacet}
+ onValueChange={onSelectFacet}
+ options={facets.map((facet) => ({
+ value: facet.facetId,
+ label: facet.name,
+ }))}
+ />
+ </div>
+ <div className="w-28 shrink-0">
+ <SelectInput
+ aria-label="Topics view"
+ placeholder="Visualize as"
+ value={view}
+ onValueChange={onSelectView}
+ options={TOPICS_RESULTS_VIEWS}
+ />
+ </div>
+ </div>
+ );
+}
+
+type TopicsMobileControlsProps = {
+ facets: readonly { facetId: string; name: string }[];
+ selectedFacet: string;
+ onSelectFacet: (facetId: string) => void;
+ view: TopicsResultsView;
+ onSelectView: (view: TopicsResultsView) => void;
+};
diff --git a/web/src/features/topics/TopicsPage.clienttest.tsx b/web/src/features/topics/TopicsPage.clienttest.tsx
index 53738b9fd8..501d8cc66a 100644
--- a/web/src/features/topics/TopicsPage.clienttest.tsx
+++ b/web/src/features/topics/TopicsPage.clienttest.tsx
@@ -26,6 +26,8 @@ const state = vi.hoisted(() => ({
showGenerateCTA: false,
hasStoredSummaries: true,
resultsDataAvailable: true,
+ mobileHeader: false,
+ resultFacets: [] as Array<{ facetId: string; name: string }>,
openAutomaticProcessing: vi.fn(),
picker: vi.fn(),
push: vi.fn(),
@@ -94,10 +96,15 @@ vi.mock("@/src/components/layouts/Page", () => ({
headerProps,
}: {
children: ReactNode;
- headerProps?: { actionButtonsRight?: ReactNode };
+ headerProps?: {
+ actionButtonsRight?: ReactNode;
+ actionButtonsMenu?: (controls: { closeMenu: () => void }) => ReactNode;
+ };
}) => (
<>
- {headerProps?.actionButtonsRight}
+ {state.mobileHeader
+ ? headerProps?.actionButtonsMenu?.({ closeMenu: vi.fn() })
+ : headerProps?.actionButtonsRight}
{children}
</>
),
@@ -166,7 +173,10 @@ vi.mock("./CurrentTopics", () => ({
return {
...input,
data: state.resultsDataAvailable
- ? { hasStoredSummaries: state.hasStoredSummaries, facets: [] }
+ ? {
+ hasStoredSummaries: state.hasStoredSummaries,
+ facets: state.resultFacets,
+ }
: undefined,
isLoading: false,
};
@@ -331,6 +341,8 @@ beforeEach(() => {
state.showGenerateCTA = false;
state.canViewTopics = true;
state.resultsDataAvailable = true;
+ state.mobileHeader = false;
+ state.resultFacets = [];
state.hasStoredSummaries = true;
state.status = "failed";
state.executionUpdatedAt = 110;
@@ -380,6 +392,24 @@ it("shows Not found instead of the workspace when the Topics gate is closed", ()
expect(state.currentTopics).not.toHaveBeenCalled();
});
+it("keeps facet, view, and automatic processing reachable with the mobile header", () => {
+ state.mobileHeader = true;
+ state.resultFacets = [{ facetId: "intent", name: "Intent" }];
+ state.rules = [{ facetIds: ["intent"] }];
+ const view = render(<TopicsPage />);
+ expect(screen.getByRole("combobox", { name: "Topics facet" })).toBeTruthy();
+ expect(screen.getByRole("combobox", { name: "Topics view" })).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: /Automatic processing/ }));
+ expect(state.openAutomaticProcessing).toHaveBeenCalledWith(false);
+ state.canWrite = false;
+ view.rerender(<TopicsPage />);
+ expect(
+ screen
+ .getByRole("button", { name: /Automatic processing/ })
+ .hasAttribute("disabled"),
+ ).toBe(true);
+});
+
it.each([
["30d", 30 * 24 * 60],
["5m", 5],
diff --git a/web/src/features/topics/TopicsPage.tsx b/web/src/features/topics/TopicsPage.tsx
index 30242dda4f..971e71ddcf 100644
--- a/web/src/features/topics/TopicsPage.tsx
+++ b/web/src/features/topics/TopicsPage.tsx
@@ -1,6 +1,5 @@
/* eslint-disable react/no-unstable-nested-components, @typescript-eslint/no-use-before-define */
import { useMemo, useState } from "react";
-import { Settings } from "@langfuse/icons";
import { type UseQueryResult } from "@tanstack/react-query";
import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { TablePeekViewTraceDetail } from "@/src/components/table/peek/TablePeekViewTraceDetail";
@@ -44,6 +43,7 @@ import { useTopicPipelineForm } from "./TopicPipelineForm";
import { ManualTopicsFormContent } from "./ManualTopicsFormContent";
import { cn } from "@/src/utils/tailwind";
import { TopicsFacetTabs } from "./TopicsFacetTabs";
+import { TopicsMobileControls } from "./TopicsMobileControls";
import { resolveTopicFacetId } from "./topic-facet-selection";
import { Spinner } from "@/src/components/layouts/Spinner";
import { TopicsHeaderActions } from "./TopicsHeaderActions";
@@ -52,7 +52,6 @@ import {
useTopicsResultsView,
} from "./TopicsResultsViewSelect";
import { DialogController } from "@/src/components/design-system/DialogController/DialogController";
-import { HeaderActionMenuRow } from "@/src/components/HeaderActionMenuRow";
import { useRegenerateTopics } from "./useRegenerateTopics";
import { useTopicModelSettings } from "./TopicModelSettings";
import { AutomaticProcessingDialogController } from "./AutomaticProcessingDialogController";
@@ -63,6 +62,7 @@ import { topicSetupRun, topicSetupStage } from "./topic-setup-flow";
import { TopicSetupProgressView } from "./TopicSetupProgressView";
import { CurrentTopics, useCurrentTopics } from "./CurrentTopics";
import { TopicsActionsMenu } from "./TopicsActionsMenu";
+import { prepareTopicsActions } from "./prepare-topics-actions";
import { TopicsWorkspaceGate } from "./TopicsWorkspaceGate";
import { isValidTopicTimeRange } from "./time-range";
import { useTopicTraceFilters } from "./useTopicTraceFilters";
@@ -488,10 +488,25 @@ function TopicsWorkspaceContent({
const showOnboarding = showSetupProgress || showLanding;
const landingOnly =
showLanding && !showSetupProgress && !setupBlockedReason;
+ const actions = prepareTopicsActions({
+ automaticProcessing,
+ canWrite,
+ configured,
+ configureAvailable: modelSettings.configure.settings !== null,
+ configureVariant: modelSettings.configure.triggerVariant,
+ manualAvailable: pipeline.available,
+ menuOnly: landingOnly,
+ onAutomaticProcessing: openAutomaticProcessingFromHeader,
+ onConfigure: configured ? openConfigure : openSetup,
+ onManualProcessing: openManualProcessing,
+ onHistory: openHistory,
+ onRefresh: refreshResults,
+ });
return (
<Page
headerProps={{
title: "Topics",
+ className: "@container/topics-header",
actionButtonsLeft: showOnboarding ? null : (
<div className="flex items-center gap-3">
{validTimeRange && headerFacetId && (
@@ -501,7 +516,7 @@ function TopicsWorkspaceContent({
onSelectFacet={traceFilters.selectFacet}
/>
)}
- <span className="text-muted-foreground flex items-center gap-1 text-sm">
+ <span className="text-muted-foreground flex shrink-0 items-center gap-1 text-sm whitespace-nowrap">
Visualize as
<TopicsResultsViewSelect
value={resultsView}
@@ -510,51 +525,10 @@ function TopicsWorkspaceContent({
</span>
</div>
),
- actionButtonsRight: (
- <TopicsHeaderActions
- automaticProcessing={automaticProcessing}
- configure={modelSettings.configure}
- configured={configured}
- canWrite={canWrite}
- manualAvailable={pipeline.available}
- openManual={openManualProcessing}
- onAutomaticProcessing={openAutomaticProcessingFromHeader}
- onConfigure={configured ? openConfigure : openSetup}
- onHistory={openHistory}
- onRefresh={refreshResults}
- menuOnly={landingOnly}
- />
+ actionButtonsRight: <TopicsHeaderActions actions={actions} />,
+ actionButtonsMenu: ({ closeMenu }) => (
+ <TopicsActionsMenu actions={actions} closeMenu={closeMenu} />
),
- actionButtonsMenu: ({ closeMenu }) => {
- function handleConfigureFromMenu() {
- closeMenu();
- openConfigure();
- }
- return (
- <TopicsActionsMenu
- triggerAction={
- pipeline.available && !landingOnly
- ? {
- label: "Manual processing",
- disabled: false,
- onSelect: openManualProcessing,
- }
- : null
- }
- closeMenu={closeMenu}
- onOpenHistory={openHistory}
- onRefresh={refreshResults}
- >
- {configured ? (
- <HeaderActionMenuRow
- label="Configure Topics"
- icon={<Settings size="base" color="default" />}
- onClick={handleConfigureFromMenu}
- />
- ) : null}
- </TopicsActionsMenu>
- );
- },
}}
>
{!showOnboarding && (
@@ -572,9 +546,20 @@ function TopicsWorkspaceContent({
<div
className={cn(
"ph-no-capture flex min-h-0 flex-1 flex-col gap-2 overflow-hidden",
- (showOnboarding || resultsView === "map") && "p-2",
+ showOnboarding && "p-2",
)}
>
+ {!showOnboarding && validTimeRange && headerFacetId && (
+ <div className="shrink-0 px-3 pt-2 md:hidden">
+ <TopicsMobileControls
+ facets={results.data?.facets ?? []}
+ selectedFacet={headerFacetId}
+ onSelectFacet={traceFilters.selectFacet}
+ view={resultsView}
+ onSelectView={setResultsView}
+ />
+ </div>
+ )}
{isTimeRangeCapped && (
<p
role="status"
diff --git a/web/src/features/topics/TopicsResultsViewSelect.tsx b/web/src/features/topics/TopicsResultsViewSelect.tsx
index efe47ea8af..9524fc63a2 100644
--- a/web/src/features/topics/TopicsResultsViewSelect.tsx
+++ b/web/src/features/topics/TopicsResultsViewSelect.tsx
@@ -3,33 +3,29 @@ import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/Dropdo
import useLocalStorage from "@/src/components/useLocalStorage";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-const VIEWS = [
+export const TOPICS_RESULTS_VIEWS = [
{ value: "treemap", label: "Treemap" },
{ value: "grid", label: "Grid" },
{ value: "map", label: "Map" },
] as const;
-export type TopicsResultsView = (typeof VIEWS)[number]["value"];
+export type TopicsResultsView = (typeof TOPICS_RESULTS_VIEWS)[number]["value"];
export function TopicsResultsViewSelect({
value,
onValueChange,
}: TopicsResultsViewSelectProps) {
- const capture = usePostHogClientCapture();
- function changeView(view: TopicsResultsView) {
- if (view === value) return;
- capture("topics:results_view_select", { view, previousView: value });
- onValueChange(view);
- }
- const selected = VIEWS.find((option) => option.value === value);
+ const selected = TOPICS_RESULTS_VIEWS.find(
+ (option) => option.value === value,
+ );
return (
<DropdownMenu
ariaLabel="Topics view"
- items={VIEWS.map((option) => ({
+ items={TOPICS_RESULTS_VIEWS.map((option) => ({
type: "item" as const,
id: option.value,
title: option.label,
- onClick: () => changeView(option.value),
+ onClick: () => onValueChange(option.value),
}))}
>
{({ getTriggerProps }) => (
@@ -48,14 +44,25 @@ export function TopicsResultsViewSelect({
}
export function useTopicsResultsView() {
+ const capture = usePostHogClientCapture();
const [view, setView] = useLocalStorage<TopicsResultsView>(
"topicsResultsView",
"treemap",
);
- return [
- VIEWS.some((option) => option.value === view) ? view : "treemap",
- setView,
- ] as const;
+ const effectiveView = TOPICS_RESULTS_VIEWS.some(
+ (option) => option.value === view,
+ )
+ ? view
+ : "treemap";
+ function selectView(nextView: TopicsResultsView) {
+ if (nextView === effectiveView) return;
+ capture("topics:results_view_select", {
+ view: nextView,
+ previousView: effectiveView,
+ });
+ setView(nextView);
+ }
+ return [effectiveView, selectView] as const;
}
type TopicsResultsViewSelectProps = {
diff --git a/web/src/features/topics/map/TopicMapExplorer.tsx b/web/src/features/topics/map/TopicMapExplorer.tsx
index 0203324ad3..92c2205133 100644
--- a/web/src/features/topics/map/TopicMapExplorer.tsx
+++ b/web/src/features/topics/map/TopicMapExplorer.tsx
@@ -73,6 +73,7 @@ export function TopicMapExplorer({
selectedTraceId,
matchingTraceIds,
fillContainer = false,
+ previewOnSelect = false,
}: TopicMapExplorerProps) {
// Projection preparation is independent of the high-frequency camera store.
const model = useMemo(() => prepareTopicMap(data, topics), [data, topics]);
@@ -219,12 +220,28 @@ export function TopicMapExplorer({
};
const selectTrace = (id: string | null) => {
if (id !== null && matchingTraceIds && !matchingTraceIds.has(id)) return;
+ if (previewOnSelect) {
+ const state = store.getState();
+ if (
+ id !== null &&
+ getTopicMapHover(state, state.frame).hoveredId !== id
+ ) {
+ cancelFlight();
+ if (state.frame) {
+ setCamera(state.frame.camera);
+ store.setState({ isMoving: false });
+ }
+ setTopicMapHover(store, id, null);
+ return;
+ }
+ }
clearTopicMapHover(store);
+ if (previewOnSelect && id === null) return;
onSelectTrace(id);
};
const handlePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
gestures.pointerHandlers.onPointerMove(event);
- if (event.pointerType !== "mouse") return;
+ if (previewOnSelect || event.pointerType !== "mouse") return;
const pointerAt = { x: event.clientX, y: event.clientY };
if (event.buttons !== 0) {
clearTopicMapHover(store);
@@ -298,7 +315,7 @@ export function TopicMapExplorer({
selectTrace(point?.traceId ?? null);
};
const handleStageDoubleClick = (event: ReactMouseEvent<HTMLDivElement>) => {
- if (event.target !== event.currentTarget) return;
+ if (previewOnSelect || event.target !== event.currentTarget) return;
const rect = event.currentTarget.getBoundingClientRect();
cancelFlight();
zoom(1, {
@@ -307,6 +324,7 @@ export function TopicMapExplorer({
});
};
const handlePointerLeave = () => {
+ if (previewOnSelect) return;
setTopicMapHover(store, null, null, { x: 0, y: 0 });
};
const handleStageKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
@@ -437,6 +455,7 @@ export function TopicMapExplorer({
selectedTraceId={selectedTraceId}
matchingTraceIds={matchingTraceIds}
onSelectTrace={selectTrace}
+ previewOnSelect={previewOnSelect}
/>
{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">
@@ -541,6 +560,7 @@ function MapLabels({
selectedTraceId,
matchingTraceIds,
onSelectTrace,
+ previewOnSelect,
}: MapLabelsProps) {
const state = useStore(store);
const frame = state.frame;
@@ -608,7 +628,8 @@ function MapLabels({
(label.kind === "trace"
? hover.hoveredId === label.id
: hover.hoveredZoneId === label.id) &&
- (label.kind !== "trace" ||
+ (previewOnSelect ||
+ label.kind !== "trace" ||
(frame.nodeById.get(label.id)?.textOpacity ?? 1) < 0.65);
const source = active ? frame : label.frame;
if (!source) return null;
@@ -616,6 +637,7 @@ function MapLabels({
source,
label.kind === "trace" ? label.id : null,
label.kind === "zone" ? label.id : null,
+ previewOnSelect,
);
const trace = hints.traces[0];
const zone = hints.zones[0];
@@ -667,6 +689,11 @@ function MapLabels({
</span>
)}
<span className="line-clamp-6">{trace.excerpt}</span>
+ {previewOnSelect && (
+ <span className="text-muted-foreground mt-2 block text-[10px]">
+ Tap again to view trace
+ </span>
+ )}
</>
) : (
<>
@@ -753,7 +780,6 @@ function mapCoverageLabel(
}
export type TopicMapExplorerProps = {
- projectId: string;
data: MapData;
topics: MapTopic[];
selectedTopic: string | null;
@@ -762,6 +788,7 @@ export type TopicMapExplorerProps = {
selectedTraceId: string | null;
matchingTraceIds?: ReadonlySet<string>;
fillContainer?: boolean;
+ previewOnSelect?: boolean;
};
type LayoutReadoutProps = {
@@ -781,6 +808,7 @@ type MapLabelsProps = {
selectedTraceId: string | null;
matchingTraceIds?: ReadonlySet<string>;
onSelectTrace: (id: string) => void;
+ previewOnSelect: boolean;
};
export const __test = { fitMapPoints };
diff --git a/web/src/features/topics/map/prepare-topic-map.ts b/web/src/features/topics/map/prepare-topic-map.ts
index 3a705cc357..fd6c466216 100644
--- a/web/src/features/topics/map/prepare-topic-map.ts
+++ b/web/src/features/topics/map/prepare-topic-map.ts
@@ -663,10 +663,14 @@ export function prepareMapHover(
frame: TopicMapNodeFrame,
hoveredId: string | null,
hoveredZoneId: string | null,
+ showInlineTrace = false,
): { traces: TraceHover[]; zones: ZoneHover[] } {
const node = hoveredId ? frame.nodeById.get(hoveredId) : undefined;
if (node) {
- if (node.textOpacity >= 0.9 || !frame.nodes.includes(node))
+ if (
+ (!showInlineTrace && node.textOpacity >= 0.9) ||
+ !frame.nodes.includes(node)
+ )
return { traces: [], zones: [] };
const card = hoverRectangle(node.rect, frame.size, {
width: 264,
diff --git a/web/src/features/topics/prepare-mobile-topics.ts b/web/src/features/topics/prepare-mobile-topics.ts
new file mode 100644
index 0000000000..cedd6e7c1f
--- /dev/null
+++ b/web/src/features/topics/prepare-mobile-topics.ts
@@ -0,0 +1,41 @@
+import { type FilterState } from "@langfuse/shared";
+import { type Facet } from "./facet-topics";
+import { filterTopicTraces } from "./topic-trace-filters";
+import {
+ prepareTopicDisplay,
+ UNASSIGNED_TOPIC_ID,
+} from "./prepare-topic-display";
+import { type TopicsResultsView } from "./TopicsResultsViewSelect";
+
+function selectedTopicId(filters: FilterState) {
+ const filter = filters.length === 1 ? filters[0] : undefined;
+ if (filter?.type !== "stringOptions" || filter.value.length !== 1)
+ return null;
+ if (filter.column === "topicId" && filter.operator === "any of")
+ return filter.value[0];
+ if (
+ filter.column === "assignment" &&
+ filter.operator === "none of" &&
+ filter.value[0] === "assigned"
+ )
+ return UNASSIGNED_TOPIC_ID;
+ return null;
+}
+
+/** Results remain complete even when a topic is too small to label on a chart. */
+export function prepareMobileTopics(
+ facet: Facet,
+ view: TopicsResultsView,
+ filters: FilterState,
+ searchQuery: string | null,
+) {
+ const { topics } = prepareTopicDisplay(facet, view);
+ const selection = selectedTopicId(filters);
+ const visible = filterTopicTraces(facet.rows, filters, searchQuery);
+ return {
+ topics,
+ selectedTopicId: selection,
+ selectedTopic: topics.find((topic) => topic.id === selection),
+ visible,
+ };
+}
diff --git a/web/src/features/topics/prepare-topic-display.ts b/web/src/features/topics/prepare-topic-display.ts
new file mode 100644
index 0000000000..da3d57fc32
--- /dev/null
+++ b/web/src/features/topics/prepare-topic-display.ts
@@ -0,0 +1,64 @@
+import {
+ type Facet,
+ type FacetTopic,
+ orderedFacetTopics,
+} from "./facet-topics";
+import {
+ topicColor,
+ treemapSwatchColor,
+ treemapTileClasses,
+ UNASSIGNED_SWATCH_COLOR,
+ unassignedTileClasses,
+} from "./topic-map-colors";
+import { type TopicsResultsView } from "./TopicsResultsViewSelect";
+
+export const UNASSIGNED_TOPIC_ID = "__unassigned";
+
+type TileColors = { tile: string; active: string; hover: string };
+
+export type TopicDisplay = Pick<
+ FacetTopic,
+ "id" | "name" | "description" | "count"
+> & {
+ color: string;
+ tiles: {
+ small: TileColors;
+ big: TileColors;
+ };
+};
+
+/** Topic identity, counts, and colors shared by the list and treemap renderers. */
+export function prepareTopicDisplay(facet: Facet, view: TopicsResultsView) {
+ const mapIndices = new Map(
+ orderedFacetTopics(facet).map((topic, index) => [topic.id, index]),
+ );
+ const topics: TopicDisplay[] = facet.topics.map(
+ ({ id, name, description, count }, index) => ({
+ id,
+ name,
+ description,
+ count,
+ color:
+ view === "treemap"
+ ? treemapSwatchColor(index)
+ : topicColor(mapIndices.get(id) ?? -1),
+ tiles: {
+ small: treemapTileClasses(index, false),
+ big: treemapTileClasses(index, true),
+ },
+ }),
+ );
+ const unassignedCount = facet.rows.filter((row) => !row.topicId).length;
+ if (unassignedCount > 0) {
+ topics.push({
+ id: UNASSIGNED_TOPIC_ID,
+ name: "Unassigned",
+ description:
+ "Traces without a topic, including outliers and summaries awaiting classification.",
+ count: unassignedCount,
+ color: UNASSIGNED_SWATCH_COLOR,
+ tiles: { small: unassignedTileClasses, big: unassignedTileClasses },
+ });
+ }
+ return { topics, total: facet.rows.length };
+}
diff --git a/web/src/features/topics/prepare-topic-grid.ts b/web/src/features/topics/prepare-topic-grid.ts
new file mode 100644
index 0000000000..767701b366
--- /dev/null
+++ b/web/src/features/topics/prepare-topic-grid.ts
@@ -0,0 +1,35 @@
+import { type RouterOutputs } from "@/src/utils/api";
+import { type Facet, orderedFacetTopics } from "./facet-topics";
+import { topicColor } from "./topic-map-colors";
+import { sampleGridPoints, type GridPoint } from "./topic-grid-layout";
+
+export function prepareTopicGrid(
+ facet: Facet,
+ mapData: RouterOutputs["topics"]["map"] | undefined,
+) {
+ const counts = new Map(facet.topics.map((topic) => [topic.id, topic.count]));
+ const topics = orderedFacetTopics(facet).map((topic, index) => ({
+ ...topic,
+ count: counts.get(topic.id) ?? 0,
+ color: topicColor(index),
+ }));
+ const rowsById = new Map(facet.rows.map((row) => [row.traceId, row]));
+ const indexById = new Map(topics.map((topic, index) => [topic.id, index]));
+ const { points, perDot } =
+ mapData?.status === "ready"
+ ? sampleGridPoints(
+ mapData.points.map(
+ (point): GridPoint => ({
+ id: point.traceId,
+ x: point.x,
+ y: point.y,
+ topicIndex: point.topicId
+ ? (indexById.get(point.topicId) ?? -1)
+ : -1,
+ }),
+ ),
+ )
+ : { points: [], perDot: 1 };
+
+ return { topics, points, perDot, rowsById };
+}
diff --git a/web/src/features/topics/prepare-topics-actions.ts b/web/src/features/topics/prepare-topics-actions.ts
new file mode 100644
index 0000000000..ceace1416c
--- /dev/null
+++ b/web/src/features/topics/prepare-topics-actions.ts
@@ -0,0 +1,156 @@
+import {
+ History,
+ Play,
+ RefreshCw,
+ Settings,
+ type IconComponent,
+} from "@langfuse/icons";
+import { type Status } from "@/src/components/ui/StatusBadge/StatusBadge";
+
+export type AutomaticProcessingState =
+ | { status: "unconfigured" }
+ | { status: "off" }
+ | { status: "on" }
+ | { status: "paused"; shortLabel: string };
+
+type TopicAction = {
+ id: "automatic" | "manual" | "configure" | "history" | "refresh";
+ label: string;
+ icon: IconComponent;
+ onSelect: () => void;
+ disabledReason?: string;
+ badge?: string;
+ variant: "primary" | "secondary";
+};
+
+export type AutomaticProcessingAction = TopicAction & {
+ badge: string;
+ badgeStatus: Status;
+};
+
+const processingPresentation = {
+ unconfigured: { badge: "Off", badgeStatus: "inactive", variant: "secondary" },
+ off: { badge: "Off", badgeStatus: "inactive", variant: "primary" },
+ on: { badge: "On", badgeStatus: "active", variant: "secondary" },
+ paused: { badge: "Paused", badgeStatus: "paused", variant: "primary" },
+} satisfies Record<
+ AutomaticProcessingState["status"],
+ Pick<AutomaticProcessingAction, "badge" | "badgeStatus" | "variant">
+>;
+
+function processingDisabledReason(
+ state: AutomaticProcessingState,
+ canWrite: boolean,
+ saving: boolean,
+) {
+ if (state.status === "unconfigured") return "Configure Topics first.";
+ if (!canWrite) return "You need permission to edit Topics.";
+ if (saving) return "Saving settings…";
+ return undefined;
+}
+
+export function prepareAutomaticProcessingAction({
+ state,
+ canWrite,
+ saving,
+ onSelect,
+}: {
+ state: AutomaticProcessingState;
+ canWrite: boolean;
+ saving: boolean;
+ onSelect: () => void;
+}): AutomaticProcessingAction {
+ const disabledReason = processingDisabledReason(state, canWrite, saving);
+ return {
+ id: "automatic",
+ label: "Automatic processing",
+ icon: RefreshCw,
+ ...processingPresentation[state.status],
+ disabledReason:
+ disabledReason && state.status === "paused"
+ ? `${state.shortLabel}. ${disabledReason}`
+ : disabledReason,
+ onSelect,
+ };
+}
+
+/** One action policy for inline controls and both overflow-menu presentations. */
+export function prepareTopicsActions({
+ automaticProcessing,
+ canWrite,
+ configured,
+ configureAvailable,
+ configureVariant,
+ manualAvailable,
+ menuOnly,
+ onAutomaticProcessing,
+ onConfigure,
+ onManualProcessing,
+ onHistory,
+ onRefresh,
+}: {
+ automaticProcessing: { state: AutomaticProcessingState; saving: boolean };
+ canWrite: boolean;
+ configured: boolean;
+ configureAvailable: boolean;
+ configureVariant: "primary" | "secondary";
+ manualAvailable: boolean;
+ menuOnly: boolean;
+ onAutomaticProcessing: () => void;
+ onConfigure: () => void;
+ onManualProcessing: () => void;
+ onHistory: () => void;
+ onRefresh: () => void;
+}) {
+ const automatic = menuOnly
+ ? null
+ : prepareAutomaticProcessingAction({
+ ...automaticProcessing,
+ canWrite,
+ onSelect: onAutomaticProcessing,
+ });
+ const configure: TopicAction = {
+ id: "configure",
+ label: "Configure Topics",
+ icon: Settings,
+ variant: configureVariant,
+ onSelect: onConfigure,
+ disabledReason:
+ !configured && !configureAvailable ? "Loading configuration…" : undefined,
+ };
+ const manual: TopicAction = {
+ id: "manual",
+ label: "Manual processing",
+ icon: Play,
+ variant: "secondary",
+ onSelect: onManualProcessing,
+ };
+ const inline: TopicAction[] = [];
+ const menu: TopicAction[] = [];
+ if (automatic) menu.push(automatic);
+ if (!menuOnly && !configured) inline.push(configure);
+ if (!menuOnly && manualAvailable) {
+ inline.push(manual);
+ menu.push(manual);
+ }
+ if (configured || !menuOnly) menu.push(configure);
+ menu.push(
+ {
+ id: "history",
+ label: "History",
+ icon: History,
+ variant: "secondary",
+ onSelect: onHistory,
+ },
+ {
+ id: "refresh",
+ label: "Refresh results",
+ icon: RefreshCw,
+ variant: "secondary",
+ onSelect: onRefresh,
+ },
+ );
+ return { automatic, inline, menu };
+}
+
+export type TopicsActions = ReturnType<typeof prepareTopicsActions>;
diff --git a/web/src/features/topics/useAutomaticProcessing.tsx b/web/src/features/topics/useAutomaticProcessing.tsx
index 32dc154b0d..75939c58c4 100644
--- a/web/src/features/topics/useAutomaticProcessing.tsx
+++ b/web/src/features/topics/useAutomaticProcessing.tsx
@@ -2,7 +2,7 @@
import { getEvaluatorBlockMetadata } from "@langfuse/shared";
import { type TopicRule } from "@langfuse/shared/topics";
import { api, type RouterOutputs } from "@/src/utils/api";
-import { type AutomaticProcessingState } from "./AutomaticProcessingControl";
+import { type AutomaticProcessingState } from "./prepare-topics-actions";
type StoredSettings = RouterOutputs["topics"]["modelSettings"];