🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(web): Topics header shows Analyze or the auto-analyze status (#19290)
Trang Nguyenb410c6998d8c
diff --git a/web/src/features/topics/AnalyzeControl.stories.tsx b/web/src/features/topics/AnalyzeControl.stories.tsxnew file mode 100644index 0000000000..cda243a0e1--- /dev/null+++ b/web/src/features/topics/AnalyzeControl.stories.tsx@@ -0,0 +1,65 @@+import { expect, fn, userEvent, within } from "storybook/test";++import preview from "../../../.storybook/preview";+import { AnalyzeControl } from "./AnalyzeControl";++const meta = preview.meta({+ component: AnalyzeControl,+ parameters: { layout: "centered" },+ args: {+ onClick: fn(),+ },+});++export default meta;++export const On = meta.story({ args: { state: { status: "on" } } });++export const Off = meta.story({ args: { state: { status: "off" } } });++export const Paused = meta.story({+ args: { state: { status: "paused", shortLabel: "LLM connection missing" } },+});++export const Unconfigured = meta.story({+ args: {+ state: { status: "unconfigured" },+ disabledReason: "Configure Topics first.",+ },+});++export const ReadOnly = meta.story({+ args: {+ state: { status: "on" },+ disabledReason: "You need permission to edit Topics.",+ },+});++export const OpensDialog = meta.story({+ name: "(Test) Click opens the Analyze traces dialog",+ args: { state: { status: "on" } },+ play: async ({ args, canvasElement }) => {+ await userEvent.click(+ within(canvasElement).getByRole("button", { name: "Auto-analyze: On" }),+ );+ await expect(args.onClick).toHaveBeenCalledOnce();+ },+});++export const DisabledWithoutSettings = meta.story({+ name: "(Test) Unconfigured is disabled with a reason",+ args: {+ state: { status: "unconfigured" },+ disabledReason: "Configure Topics first.",+ },+ play: async ({ canvasElement }) => {+ const button = within(canvasElement).getByRole("button", {+ name: "Analyze",+ });+ await expect(button).toBeDisabled();+ await expect(button.parentElement).toHaveAttribute(+ "title",+ "Configure Topics first.",+ );+ },+});diff --git a/web/src/features/topics/AnalyzeControl.tsx b/web/src/features/topics/AnalyzeControl.tsxnew file mode 100644index 0000000000..406be7ce66--- /dev/null+++ b/web/src/features/topics/AnalyzeControl.tsx@@ -0,0 +1,50 @@+import { Button } from "@/src/components/design-system/Button/Button";+import { cn } from "@/src/utils/tailwind";+import { type AutomaticProcessingState } from "./prepare-topics-actions";++type AnalyzeControlProps = {+ state: AutomaticProcessingState;+ /** Why the dialog cannot open; absent when it can. */+ disabledReason?: string;+ onClick: () => void;+};++const DOT = { on: "bg-dark-green", paused: "bg-dark-yellow" };++/** Off: an Analyze button. On or paused: the auto-analyze status. Both open the Analyze traces dialog. */+export function AnalyzeControl({+ disabledReason,+ onClick,+ state,+}: AnalyzeControlProps) {+ if (state.status === "off" || state.status === "unconfigured") {+ return (+ <span title={disabledReason} className="inline-flex">+ <Button+ text="Analyze"+ size="sm"+ disabled={Boolean(disabledReason)}+ onClick={onClick}+ />+ </span>+ );+ }+ const title =+ disabledReason ??+ (state.status === "paused" ? state.shortLabel : undefined);+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={Boolean(disabledReason)}+ title={title}+ className="text-muted-foreground hover:bg-accent hover:text-foreground ring-offset-background focus-visible:ring-ring inline-flex h-7 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs whitespace-nowrap focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"+ >+ <span+ aria-hidden+ className={cn("inline-flex size-2 rounded-full", DOT[state.status])}+ />+ {state.status === "on" ? "Auto-analyze: On" : "Auto-analyze: Paused"}+ </button>+ );+}diff --git a/web/src/features/topics/AutomaticProcessingControl.stories.tsx b/web/src/features/topics/AutomaticProcessingControl.stories.tsxdeleted file mode 100644index e96ebe821c..0000000000--- a/web/src/features/topics/AutomaticProcessingControl.stories.tsx+++ /dev/null@@ -1,63 +0,0 @@-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" },-});--const states: AutomaticProcessingState[] = [- { status: "unconfigured" },- { status: "off" },- { status: "on" },- { status: "paused", shortLabel: "LLM connection missing" },-];--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 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.",- );- },-});diff --git a/web/src/features/topics/AutomaticProcessingControl.tsx b/web/src/features/topics/AutomaticProcessingControl.tsxdeleted file mode 100644index 66b9dc7a5d..0000000000--- a/web/src/features/topics/AutomaticProcessingControl.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";-import { Button } from "@/src/components/design-system/Button/Button";-import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";-import { type AutomaticProcessingAction } from "./prepare-topics-actions";--/** Status and dialog trigger for the automatic-processing action. */-export function AutomaticProcessingControl({- action,-}: {- action: AutomaticProcessingAction;-}) {- const button = (- <Button- text={action.label}- size="sm"- 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={`${action.label}: ${action.badge}`}>- <StatusBadge type={action.badgeStatus} showText={false}>- {action.badge}- </StatusBadge>- </div>- {action.disabledReason ? (- <Tooltip label={action.disabledReason}>- {({ getTriggerProps }) => (- <span {...getTriggerProps()}>{button}</span>- )}- </Tooltip>- ) : (- button- )}- </div>- );-}diff --git a/web/src/features/topics/AutomaticProcessingDialog.stories.tsx b/web/src/features/topics/AutomaticProcessingDialog.stories.tsxindex 443cf11a2a..5191d71d68 100644--- a/web/src/features/topics/AutomaticProcessingDialog.stories.tsx+++ b/web/src/features/topics/AutomaticProcessingDialog.stories.tsx@@ -4,12 +4,6 @@ import preview from "../../../.storybook/preview";import { DialogController } from "@/src/components/design-system/DialogController/DialogController";import { AutomaticProcessingDialog } from "./AutomaticProcessingDialog";-const models = {- summary: "us.openai.gpt-6-luna",- embedding: "us.cohere.embed-v4:0",- clustering: "us.openai.gpt-5.6-terra",-};-const meta = preview.meta({component: AutomaticProcessingDialog,parameters: { layout: "fullscreen" },@@ -26,9 +20,8 @@ const meta = preview.meta({args: {initialEnabled: false,initialSampling: 1,- traceIdleMs: 600_000,- models,- paused: null,+ dailyTraces: 180,+ missingModel: false,saving: false,error: null,onSave: fn(),@@ -37,39 +30,37 @@ const meta = preview.meta({export default meta;-export const Enable = meta.story({});+export const Off = meta.story({});-export const EditSampling = meta.story({+export const On = meta.story({args: { initialEnabled: true, initialSampling: 0.25 },});-export const Paused = meta.story({- args: {- paused: {- shortLabel: "LLM connection authentication failed",- message:- 'The facet summaries model us.openai.gpt-6-luna on LLM connection "Amazon Bedrock" failed (HTTP 401). Check the connection\'s credentials, the model ID, and provider availability. Automatic processing was paused. Fix the connection, then turn automatic processing back on.',- },- },+export const CountingTraces = meta.story({+ args: { dailyTraces: null },});export const MissingModel = meta.story({- name: "(Test) A deleted connection blocks turning on",- args: {- models: { ...models, clustering: null },- paused: {- shortLabel: "LLM connection missing",- message:- 'The LLM connection "Amazon Bedrock" was deleted. Choose another connection in Configure Topics, then turn automatic processing back on.',- },- },+ name: "(Test) A missing model blocks turning on",+ args: { missingModel: true },play: async () => {const body = within(document.body);- await expect(await body.findByText("Not set")).toBeInTheDocument();- await userEvent.click(- body.getByRole("switch", { name: "Automatic processing" }),- );+ await userEvent.click(body.getByRole("switch", { name: "Auto-analyze" }));await expect(body.getByRole("button", { name: "Save" })).toBeDisabled();+ await expect(+ body.getByText("Choose every model in Settings before turning this on."),+ ).toBeInTheDocument();+ },+});++export const ShowsEstimate = meta.story({+ name: "(Test) The estimate follows the sample rate",+ args: { initialSampling: 0.25 },+ play: async () => {+ const body = within(document.body);+ await expect(+ body.getByText("~45 new traces a day, based on the last 7 days"),+ ).toBeInTheDocument();},});@@ -78,9 +69,7 @@ export const SubmitsSampling = meta.story({args: { initialSampling: 0.25 },play: async ({ args }) => {const body = within(document.body);- await userEvent.click(- body.getByRole("switch", { name: "Automatic processing" }),- );+ await userEvent.click(body.getByRole("switch", { name: "Auto-analyze" }));await userEvent.click(body.getByRole("button", { name: "Save" }));await expect(args.onSave).toHaveBeenCalledWith({enabled: true,@@ -90,13 +79,11 @@ export const SubmitsSampling = meta.story({});export const TurnsOff = meta.story({- name: "(Test) Turning off saves processing as off",+ name: "(Test) Turning off saves auto-analyze as off",args: { initialEnabled: true, initialSampling: 0.25 },play: async ({ args }) => {const body = within(document.body);- await userEvent.click(- body.getByRole("switch", { name: "Automatic processing" }),- );+ await userEvent.click(body.getByRole("switch", { name: "Auto-analyze" }));await userEvent.click(body.getByRole("button", { name: "Save" }));await expect(args.onSave).toHaveBeenCalledWith({enabled: false,diff --git a/web/src/features/topics/AutomaticProcessingDialog.tsx b/web/src/features/topics/AutomaticProcessingDialog.tsxindex cec034f2d4..c45a48ac34 100644--- a/web/src/features/topics/AutomaticProcessingDialog.tsx+++ b/web/src/features/topics/AutomaticProcessingDialog.tsx@@ -1,166 +1,129 @@-/* eslint-disable @typescript-eslint/no-use-before-define */import { useState } from "react";-import { Info } from "@langfuse/icons";-import { Alert } from "@/src/components/design-system/Alert/Alert";import { Dialog } from "@/src/components/design-system/Dialog/Dialog";-import { SwitchInput } from "@/src/components/design-system/SwitchInput/SwitchInput";-import { RuleSamplingSection } from "@/src/features/evals/v2/components/Rules/RuleSetup/components/RuleSamplingSection";-import { createRuleSetupStore } from "@/src/features/evals/v2/stores/createRuleSetupStore";-import {- TOPICS_MODEL_SLOT_DETAILS,- TOPICS_MODEL_SLOTS,- type TopicsModelSlotName,-} from "@langfuse/shared/topics";--import { type FilterState } from "@langfuse/shared";-import { TopicAutomaticTraceScope } from "./TopicAutomaticTraceScope";+import { Input } from "@/src/components/design-system/Input/Input";+import { Switch } from "@/src/components/design-system/Switch/Switch";+import { Slider } from "@/src/components/ui/Slider";+import { TOPIC_SETUP_BACKFILL_DAYS } from "./topic-setup-flow";type AutomaticProcessingDialogProps = {- projectId?: string;initialEnabled: boolean;+ /** Stored sampling rate, 0 to 1. */initialSampling: number;- traceIdleMs: number;- models: Record<TopicsModelSlotName, string | null>;- paused: { shortLabel: string; message: string } | null;+ /** Finished traces per day over the estimate window; null while unknown. */+ dailyTraces: number | null;+ /** A model slot without a model blocks turning auto-analyze on. */+ missingModel: boolean;saving: boolean;error: string | null;onSave: (input: { enabled: boolean; sampling: number }) => void;};-const COST_NOTE =- "Each sampled trace makes LLM calls on your connections, so cost depends on your trace volume, the selected models, and the sampling rate.";+function dailyEstimate(dailyTraces: number, samplePercent: number) {+ const perDay = (dailyTraces * samplePercent) / 100;+ if (perDay > 0 && perDay < 1) return "<1";+ return Math.round(perDay).toLocaleString("en-US");+}++function samplePercentFromInput(value: string) {+ if (!/^\d+$/.test(value)) return null;+ const percent = Number(value);+ if (percent < 1 || percent > 100) return null;+ return percent;+}++function estimateLine(dailyTraces: number | null, samplePercent: number) {+ if (dailyTraces === null)+ return "Share of new traces analyzed while auto-analyze is on";+ return `~${dailyEstimate(dailyTraces, samplePercent)} new traces a day, based on the last ${TOPIC_SETUP_BACKFILL_DAYS} days`;+}/** Dialog content; render it from `AutomaticProcessingDialogController`. */export function AutomaticProcessingDialog({+ dailyTraces,error,- projectId,initialEnabled,initialSampling,- models,+ missingModel,onSave,- paused,saving,- traceIdleMs,}: AutomaticProcessingDialogProps) {- const [samplingStore] = useState(() =>- createRuleSetupStore({- name: "",- filter: [],- sampling: initialSampling,- assignments: [],- }),- );- const [filters, setFilters] = useState<FilterState>([]);const [enabled, setEnabled] = useState(initialEnabled);- const missingModel = TOPICS_MODEL_SLOTS.some((slot) => !models[slot]);+ const [samplePercent, setSamplePercent] = useState(() =>+ Math.min(100, Math.max(1, Math.round(initialSampling * 100))),+ );+ const blocked = enabled && missingModel;return (<Dialog- title="Automatic processing"- size="lg"+ title="Analyze traces"actions={[{label: "Save",loading: saving,- disabled: saving || (enabled && missingModel),- onClick: () =>- onSave({ enabled, sampling: samplingStore.getState().sampling }),+ disabled: saving || blocked,+ onClick: () => onSave({ enabled, sampling: samplePercent / 100 }),},]}><Dialog.Body><div className="flex flex-col gap-4">- <Alert variant="info" icon={Info}>- <Alert.Description>- Only traces from v4-ready ingestion are processed automatically.- Legacy ingestion is not included.- </Alert.Description>- </Alert>- <p className="text-sm">- New traces are summarized with your saved facets and models once- they have been idle for {idleTimeLabel(traceIdleMs)}. The sampling- rate below applies only to automatic processing. For manual- processing, such as backfills, you set the sampling for each run.- </p>- <p className="text-sm">- Each summarized trace joins the closest existing topic when it is- similar; otherwise it appears under Outliers. A facet without topics- gets its first ones once 100 traces from the last seven days are- summarized. Topics are not refreshed automatically; run{" "}- <em>Regenerate topics</em> to refresh them.- </p>- {paused ? (- <Alert variant="warning">- <Alert.Title>Paused: {paused.shortLabel}</Alert.Title>- <Alert.Description>- <p className="break-words">{paused.message}</p>- </Alert.Description>- </Alert>- ) : null}- <section className="flex flex-col gap-2">- <h3 className="text-sm font-bold">Models</h3>- <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">- {TOPICS_MODEL_SLOTS.map((slot) => (- <ModelRow- key={slot}- label={TOPICS_MODEL_SLOT_DETAILS[slot].label}- model={models[slot]}+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-3">+ <label+ htmlFor="topics-auto-analyze"+ className="text-sm font-bold"+ >+ Auto-analyze+ </label>+ <Switch+ id="topics-auto-analyze"+ checked={enabled}+ onCheckedChange={setEnabled}+ />+ </div>+ {blocked ? (+ <p className="text-destructive text-sm">+ Choose every model in Settings before turning this on.+ </p>+ ) : null}+ </div>+ <div className="flex flex-col gap-2">+ <span className="text-sm font-bold">Sample rate</span>+ <div className="flex items-center gap-3">+ <div className="min-w-0 flex-1">+ <Slider+ min={1}+ max={100}+ step={1}+ value={[samplePercent]}+ aria-label="Sample rate"+ onValueChange={(value) =>+ setSamplePercent(value[0] ?? samplePercent)+ }+ />+ </div>+ <div className="w-20">+ <Input+ type="number"+ min={1}+ max={100}+ inputMode="numeric"+ aria-label="Sample rate percent"+ value={String(samplePercent)}+ onChange={(event) => {+ const percent = samplePercentFromInput(event.target.value);+ if (percent !== null) setSamplePercent(percent);+ }}/>- ))}- </dl>- <p className="text-muted-foreground text-xs">- {modelsHint(paused !== null, missingModel)}+ </div>+ <span className="text-muted-foreground text-sm">%</span>+ </div>+ <p className="text-muted-foreground text-sm">+ {estimateLine(dailyTraces, samplePercent)}</p>- </section>- <RuleSamplingSection- store={samplingStore}- description="The share of new traces Topics summarizes automatically."- tooltip="Topics summarizes this share of new traces. A lower rate costs less. For manual processing, you set the sampling for each run."- />- <TopicAutomaticTraceScope- projectId={projectId}- filters={filters}- onFiltersChange={setFilters}- />- <SwitchInput- id="topics-automatic-processing"- aria-label="Automatic processing"- description={`Summarize new traces automatically. ${COST_NOTE}`}- checked={enabled}- onCheckedChange={setEnabled}- />+ </div>{error ? <p className="text-destructive text-sm">{error}</p> : null}</div></Dialog.Body></Dialog>);}--function ModelRow({ label, model }: { label: string; model: string | null }) {- return (- <>- <dt className="text-muted-foreground">{label}</dt>- {model ? (- <dd className="truncate" title={model}>- {model}- </dd>- ) : (- <dd className="text-destructive">Not set</dd>- )}- </>- );-}--function modelsHint(paused: boolean, missingModel: boolean) {- if (missingModel)- return "Choose every model in Configure Topics before turning this on.";- return paused- ? "Turning this back on tests each model with one call."- : "Change models in Configure Topics.";-}--function idleTimeLabel(traceIdleMs: number) {- const seconds = Math.round(traceIdleMs / 1000);- if (seconds % 60 !== 0) return `${seconds} seconds`;- const minutes = seconds / 60;- return minutes === 1 ? "1 minute" : `${minutes} minutes`;-}diff --git a/web/src/features/topics/AutomaticProcessingDialogController.tsx b/web/src/features/topics/AutomaticProcessingDialogController.tsxindex 9dd5444757..6cbe3bb97e 100644--- a/web/src/features/topics/AutomaticProcessingDialogController.tsx+++ b/web/src/features/topics/AutomaticProcessingDialogController.tsx@@ -1,10 +1,9 @@-/* eslint-disable @typescript-eslint/no-use-before-define */import { useState, type ReactNode } from "react";import { DialogController } from "@/src/components/design-system/DialogController/DialogController";-import { type TopicRule } from "@langfuse/shared/topics";-import { type RouterOutputs } from "@/src/utils/api";+import { TOPICS_MODEL_SLOTS, type TopicRule } from "@langfuse/shared/topics";+import { api, type RouterOutputs } from "@/src/utils/api";import { AutomaticProcessingDialog } from "./AutomaticProcessingDialog";-import { automaticProcessingState } from "./useAutomaticProcessing";+import { TOPIC_SETUP_BACKFILL_DAYS } from "./topic-setup-flow";type StoredSettings = RouterOutputs["topics"]["modelSettings"];@@ -12,7 +11,6 @@ type AutomaticProcessingSettings = {projectId: string;rule: TopicRule | null;stored: StoredSettings | undefined;- traceIdleMs: number | null;/** The write shared with "Keep off", so it outlives a close. */save: (input: { enabled: boolean; sampling: number }) => Promise<unknown>;saving: boolean;@@ -24,27 +22,15 @@ type AutomaticProcessingDialogControllerProps = AutomaticProcessingSettings & {}) => ReactNode;};-/**- * Owns the automatic processing dialog. Wrap the shared parent and pass- * `openDialog` to every opener, e.g. the header control and the paused notice.- */-export function AutomaticProcessingDialogController({- children,- ...settings-}: AutomaticProcessingDialogControllerProps) {- return (- <DialogController<boolean>- renderDialog={({ state, closeDialog }) => (- <AutomaticProcessingDialogContent- {...settings}- initialEnabled={state}- closeDialog={closeDialog}- />- )}- >- {({ openDialog }) => children({ openDialog })}- </DialogController>+/** Finished traces per day over the backfill window; null until counted. */+function useDailyTraceEstimate(projectId: string) {+ const counts = api.topics.setupTraceCounts.useQuery(+ { projectId },+ { retry: false },);+ return counts.data+ ? counts.data.finished7d / TOPIC_SETUP_BACKFILL_DAYS+ : null;}function AutomaticProcessingDialogContent({@@ -55,17 +41,12 @@ function AutomaticProcessingDialogContent({save,saving,stored,- traceIdleMs,}: AutomaticProcessingSettings & {closeDialog: () => void;initialEnabled: boolean;}) {const [error, setError] = useState<string | null>(null);- const state = automaticProcessingState(stored, rule);- const paused =- stored?.blockMessage && state.status === "paused"- ? { shortLabel: state.shortLabel, message: stored.blockMessage }- : null;+ const dailyTraces = useDailyTraceEstimate(projectId);const submit = (input: { enabled: boolean; sampling: number }) => {setError(null);save(input)@@ -74,26 +55,43 @@ function AutomaticProcessingDialogContent({setError(cause instanceof Error? cause.message- : "Could not save automatic processing.",+ : "Could not save auto-analyze.",),);};return (<AutomaticProcessingDialog- projectId={projectId}initialEnabled={initialEnabled}initialSampling={rule?.sampling ?? 1}- traceIdleMs={traceIdleMs ?? 600_000}- models={{- summary: stored?.summary?.model ?? null,- embedding: stored?.embedding?.model ?? null,- clustering: stored?.clustering?.model ?? null,- }}- paused={paused}+ dailyTraces={dailyTraces}+ missingModel={TOPICS_MODEL_SLOTS.some((slot) => !stored?.[slot]?.model)}saving={saving}error={error}onSave={submit}/>);}++/**+ * Owns the Analyze traces dialog. Wrap the shared parent and pass+ * `openDialog` to every opener, e.g. the header control and the paused notice.+ */+export function AutomaticProcessingDialogController({+ children,+ ...settings+}: AutomaticProcessingDialogControllerProps) {+ return (+ <DialogController<boolean>+ renderDialog={({ state, closeDialog }) => (+ <AutomaticProcessingDialogContent+ {...settings}+ initialEnabled={state}+ closeDialog={closeDialog}+ />+ )}+ >+ {({ openDialog }) => children({ openDialog })}+ </DialogController>+ );+}diff --git a/web/src/features/topics/CurrentTopics.tsx b/web/src/features/topics/CurrentTopics.tsxindex 34840f8a61..9e777a443b 100644--- a/web/src/features/topics/CurrentTopics.tsx+++ b/web/src/features/topics/CurrentTopics.tsx@@ -235,7 +235,15 @@ function useCurrentTopicMap() {return api.topics.map.useQuery({ projectId, runId: runId ?? "", timeRange },- { enabled: Boolean(runId) },+ {+ enabled: Boolean(runId),+ // A moved time range keeps the map (and its camera) up; a different run starts fresh.+ placeholderData: (previous, previousQuery) =>+ (previousQuery?.queryKey?.[1] as { input?: { runId?: string } })?.input+ ?.runId === runId+ ? previous+ : undefined,+ },);}diff --git a/web/src/features/topics/README.md b/web/src/features/topics/README.mdindex 3a72f70285..563c75b72d 100644--- a/web/src/features/topics/README.md+++ b/web/src/features/topics/README.md@@ -41,11 +41,7 @@ project permissions. Processing additionally requires the project allowlist.Saving it stores the models, creates the four built-in facets as evaluatorswith a first version, and saves one rule for the filter, idle time, andsampling rate. A project can have only one Topics rule.- Manual processing opens a shared dialog with Summarize traces & embed and- Generate topics tabs. `DialogController` owns the overlay above the page and- the mobile actions menu. Once models are configured, Configure Topics lives- in the overflow menu. `ManualTopicsDialog` is the presentational layout shared- by the app and its isolated `ManualTopicsDialog.stories.tsx` stories.+ The header shows the auto-analyze status (`AnalyzeControl`); clicking it opens the Analyze traces dialog with the auto-analyze toggle and sample rate. The overflow menu holds Regenerate topics, History and Settings. Regenerate topics opens the shared manual dialog on its Generate topics tab; the Summarize traces & embed tab stays reachable there. `DialogController` owns the overlay above the page and the mobile actions menu. `ManualTopicsDialog` is the presentational layout shared by the app and its isolated `ManualTopicsDialog.stories.tsx` stories.`TopicTraceSelectorView` renders the same filters, batch controls and previewtable in both places; stories supply fixture results without private API calls.`ManualTopicsFormContent` owns the draft and uses the real trace selector.diff --git a/web/src/features/topics/TopicAutomaticTraceScope.tsx b/web/src/features/topics/TopicAutomaticTraceScope.tsxdeleted file mode 100644index db09dcb0bd..0000000000--- a/web/src/features/topics/TopicAutomaticTraceScope.tsx+++ /dev/null@@ -1,348 +0,0 @@-/* eslint-disable @typescript-eslint/no-use-before-define */-import { useMemo, useState } from "react";-import { format } from "date-fns";-import { toObservedOptions } from "@/src/features/search-bar";-import { SectionHeader } from "@/src/features/evals/v2/components/Evaluators/Testing/components/SectionHeader/SectionHeader";-import type { EvaluatorFilterExperience } from "@/src/features/evals/v2/types/evaluatorFilterExperience";-import {- eventsEvalFilterColumns,- experimentEvalFilterColsWithOptions,- observationEvalFilterColsWithOptions,- type FilterState,- type TimeFilter,- type TracingSearchType,-} from "@langfuse/shared";-import { useEventsFilterOptions } from "@/src/features/events/hooks/useEventsFilterOptions";-import { api, sendAsPostOption } from "@/src/utils/api";-import { relativeTopicTimeRange } from "./time-range";-import {- TopicTraceFilterSection,- type TopicTraceFilterSectionProps,-} from "./TopicTraceFilterSection";--const SAMPLE_TRACES_IN_SCOPE = [- {- start: "2026-10-08 15:58:44",- type: "GENERATION",- name: "billing-question",- input: '{"role":"user","content":"My subscription invoice..."}',- },- {- start: "2026-10-08 15:58:43",- type: "GENERATION",- name: "weather-question",- input: '{"role":"user","content":"I\'m visiting Lisbon this..."}',- },- {- start: "2026-10-08 15:54:02",- type: "SPAN",- name: "weather-question",- input: '{"role":"user","content":"What is the weather in..."}',- },-];--const BUILDER_OPTION_COLUMNS = [- "environment",- "name",- "traceTags",- "traceName",- "calledToolNames",-] as const;--function authoredTraceFilters(filters: FilterState): FilterState {- return filters.flatMap((filter) => {- if (filter.column === "isRootObservation") return [];- if (filter.column === "tags")- return [{ ...filter, column: "traceTags" as const }];- return [filter];- });-}--function matchCountLabel(count: number | null) {- if (count === null) return null;- const noun = count === 1 ? "match" : "matches";- return `(${count} ${noun})`;-}--function previewStatus(- pending: boolean,- error: string | undefined,- rowCount: number,-) {- if (pending) return "Loading traces…";- if (error) return error;- if (rowCount === 0) return "No traces match this filter in the last 7 days.";- return null;-}--export function TopicAutomaticTraceScope({- projectId,- filters,- onFiltersChange,-}: TopicAutomaticTraceScopeProps) {- if (!projectId)- return (- <SampleTraceScope filters={filters} onFiltersChange={onFiltersChange} />- );- return (- <ProjectTraceScope- projectId={projectId}- filters={filters}- onFiltersChange={onFiltersChange}- />- );-}--function SampleTraceScope({- filters,- onFiltersChange,-}: {- filters: FilterState;- onFiltersChange: (filters: FilterState) => void;-}) {- return (- <TraceScopeFrame- projectId={undefined}- filters={filters}- onFiltersChange={onFiltersChange}- countLabel="Sample"- rows={SAMPLE_TRACES_IN_SCOPE}- />- );-}--function ProjectTraceScope({- projectId,- filters,- onFiltersChange,-}: {- projectId: string;- filters: FilterState;- onFiltersChange: (filters: FilterState) => void;-}) {- const [range] = useState(() => relativeTopicTimeRange(7));- const [mode, setMode] = useState<EvaluatorFilterExperience>("query");- const [searchQuery, setSearchQuery] = useState<string | null>(null);- const [searchType, setSearchType] = useState<TracingSearchType[]>([]);- const startTimeFilter = useMemo<TimeFilter[]>(- () => [- {- column: "startTime",- type: "datetime",- operator: ">=",- value: range.from,- },- {- column: "startTime",- type: "datetime",- operator: "<",- value: range.to,- },- ],- [range],- );- const authored = useMemo(() => authoredTraceFilters(filters), [filters]);- const options = useEventsFilterOptions({- projectId,- startTimeFilter,- refiningFilter: authored,- isRootObservation: true,- includeApproxCount: true,- lazy: mode === "query",- columns: mode === "query" ? undefined : [...BUILDER_OPTION_COLUMNS],- enabled: true,- });- const observed = useMemo(- () =>- toObservedOptions(options.filterOptions, options.isFilterOptionsPending),- [options.filterOptions, options.isFilterOptionsPending],- );- const previewFilters = useMemo<FilterState>(- () => [- ...authored,- {- column: "isRootObservation",- type: "boolean",- operator: "=",- value: true,- },- ...startTimeFilter,- ],- [authored, startTimeFilter],- );- const preview = api.events.listCursor.useQuery({- projectId,- filter: previewFilters,- searchQuery,- searchType,- limit: 10,- });- const observations = preview.data?.observations ?? [];- const ioTargets = observations.flatMap((observation) =>- observation.traceId- ? [{ id: observation.id, traceId: observation.traceId }]- : [],- );- const startTimes = observations.map((observation) =>- observation.startTime.getTime(),- );- const io = api.events.batchIO.useQuery(- {- projectId,- observations: ioTargets,- minStartTime: new Date(- startTimes.length > 0 ? Math.min(...startTimes) : 0,- ),- maxStartTime: new Date(- startTimes.length > 0 ? Math.max(...startTimes) : 0,- ),- },- {- ...sendAsPostOption,- enabled: preview.isSuccess && ioTargets.length > 0,- },- );- const inputById = new Map((io.data ?? []).map((row) => [row.id, row.input]));- const builderColumns = useMemo(- () =>- experimentEvalFilterColsWithOptions(- options.filterOptions,- observationEvalFilterColsWithOptions(- {- ...options.filterOptions,- tags: options.filterOptions?.traceTags,- },- [...eventsEvalFilterColumns],- ),- ).flatMap((column) =>- column.id === "isRootObservation" ? [] : [column],- ),- [options.filterOptions],- );- const rows = observations.map((observation) => ({- id: observation.id,- start: format(observation.startTime, "yyyy-MM-dd HH:mm:ss"),- type: observation.type,- name: observation.name ?? "—",- input: inputById.get(observation.id) ?? (io.isPending ? "…" : ""),- }));- const status = previewStatus(- preview.isPending,- preview.error?.message,- rows.length,- );-- return (- <TraceScopeFrame- projectId={projectId}- mode={mode}- filters={filters}- searchQuery={searchQuery}- observed={observed}- builderColumns={builderColumns}- erroredColumns={options.erroredColumns}- onRequestColumns={options.requestColumns}- countLabel={matchCountLabel(options.approxTotalCount)}- description="Root observations from the last 7 days. Topics summarizes the whole trace."- tooltip="The same filter Topics uses when it selects traces, limited to the last 7 days. Only root observations are shown."- rows={rows}- status={status}- searchType={searchType}- onModeChange={setMode}- onFiltersChange={onFiltersChange}- onSearchQueryChange={setSearchQuery}- onSearchTypeChange={setSearchType}- />- );-}--function TraceScopeFrame({- countLabel,- description,- tooltip,- rows,- status,- ...filterProps-}: Omit<TopicTraceFilterSectionProps, "description"> & {- countLabel?: string | null;- description?: string;- tooltip?: string;- rows: Array<{- id?: string;- start: string;- type: string;- name: string;- input: string;- }>;- status?: string | null;-}) {- return (- <div className="flex flex-col gap-4">- <TopicTraceFilterSection {...filterProps} />- <section className="flex flex-col gap-2">- <SectionHeader- title="Matching traces"- meta={- countLabel ? (- <span className="text-muted-foreground text-sm">- {countLabel}- </span>- ) : null- }- description={- description ?? "A sample of traces this setup would include."- }- tooltip={- tooltip ??- "A fixed sample. The filter is applied when traces are processed, not in this table."- }- trailing={null}- />- <div className="max-h-72 overflow-auto rounded-md border">- <table className="w-full text-left text-sm">- <thead className="text-muted-foreground bg-background sticky top-0">- <tr className="border-b">- <th className="px-3 py-2 font-normal">Start time</th>- <th className="px-3 py-2 font-normal">Type</th>- <th className="px-3 py-2 font-normal">Name</th>- <th className="px-3 py-2 font-normal">Input</th>- </tr>- </thead>- <tbody>- {status ? (- <tr>- <td className="text-muted-foreground px-3 py-2" colSpan={4}>- {status}- </td>- </tr>- ) : (- rows.map((row) => (- <tr- key={row.id ?? `${row.start}-${row.name}`}- className="border-b last:border-b-0"- >- <td className="px-3 py-2 whitespace-nowrap">{row.start}</td>- <td className="px-3 py-2">{row.type}</td>- <td className="px-3 py-2">{row.name}</td>- <td- className="text-muted-foreground max-w-48 truncate px-3 py-2"- title={row.input}- >- {row.input}- </td>- </tr>- ))- )}- </tbody>- </table>- </div>- </section>- </div>- );-}--type TopicAutomaticTraceScopeProps = {- projectId?: string;- filters: FilterState;- onFiltersChange: (filters: FilterState) => void;-};diff --git a/web/src/features/topics/TopicModelSettings.tsx b/web/src/features/topics/TopicModelSettings.tsxindex fbca05f1fa..f1705834b4 100644--- a/web/src/features/topics/TopicModelSettings.tsx+++ b/web/src/features/topics/TopicModelSettings.tsx@@ -90,10 +90,6 @@ export function useTopicModelSettings({error: configurationError? `Could not load Topics configuration: ${configurationError.message} Reload the page to retry.`: null,- triggerVariant:- configureSettings && !configured- ? ("primary" as const)- : ("secondary" as const),},automaticProcessing: {...automaticProcessing,@@ -101,7 +97,6 @@ export function useTopicModelSettings({projectId,rule,stored: settings.data,- traceIdleMs: readinessSettings.data?.traceIdleMs ?? null,save: automaticProcessing.save,saving: automaticProcessing.saving,},diff --git a/web/src/features/topics/TopicSetupProgressView.tsx b/web/src/features/topics/TopicSetupProgressView.tsxindex 5245b61b4b..8380245a79 100644--- a/web/src/features/topics/TopicSetupProgressView.tsx+++ b/web/src/features/topics/TopicSetupProgressView.tsx@@ -68,7 +68,7 @@ export function TopicSetupProgressView({</div>{failed ? (<div className="flex items-center gap-2">- {canRetry && (+ {canRetry && onRetry && (<Button text="Retry" loading={retrying} onClick={onRetry} />)}{onViewDetails && (@@ -135,7 +135,7 @@ function pileFill(slots: number, pileIndex: number, tick: number) {}const NO_RETRY_DETAIL =- "Topics could not start. Use Generate topics in the menu.";+ "Topics could not start. Use Regenerate topics in the menu.";function progressCopy(failed: boolean, waiting: boolean) {if (failed)@@ -163,7 +163,7 @@ type TopicSetupProgressViewProps = {canRetry: boolean;/** Opens the failed run in History. */onViewDetails?: () => void;- onRetry: () => void;+ onRetry?: () => void;/** Automatic processing is on but no trace has been summarized yet. */waiting?: boolean;};diff --git a/web/src/features/topics/TopicTreemap.tsx b/web/src/features/topics/TopicTreemap.tsxindex 41a2800d4b..df85c7b53a 100644--- a/web/src/features/topics/TopicTreemap.tsx+++ b/web/src/features/topics/TopicTreemap.tsx@@ -2,6 +2,7 @@ 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 { compactNumberFormatter } from "@/src/utils/numbers";import {type TopicDisplay,UNASSIGNED_TOPIC_ID,@@ -52,7 +53,7 @@ const TILE_PADDING: Record<TileTier, string> = {const PADDING_PX = { large: 24, medium: 24, small: 16, tiny: 0 };const NAME_LINE_PX = { large: 28, medium: 20, small: 16, tiny: 16 };const NAME_CHAR_PX = { large: 10, medium: 7.6, small: 6.8, tiny: 6.8 };-const COUNT_PX = { large: 36, medium: 28, small: 0, tiny: 0 };+const COUNT_PX = { large: 36, medium: 28, small: 20, tiny: 0 };/** Share caption: text-xs line height, approximate character width and the gap above it. */const SHARE_LINE_PX = 16;const SHARE_CHAR_PX = 6;@@ -76,7 +77,7 @@ const NAME_SIZE: Record<TileTier, string> = {const COUNT_SIZE: Record<TileTier, string> = {large: "text-3xl",medium: "text-xl",- small: "",+ small: "text-sm",tiny: "",};@@ -111,8 +112,7 @@ function tileLabelLayout(COUNT_PX[tier] +(shareLines > 0 ? SHARE_GAP_PX + shareLines * SHARE_LINE_PX : 0);const withCount = lines(footer);- const countFits =- (tier === "large" || tier === "medium") && needed <= withCount;+ const countFits = tier !== "tiny" && needed <= withCount;const available = countFits ? withCount : lines(0);return {showCount: countFits,@@ -150,7 +150,8 @@ function TopicTileButton({function selectTopic() {onSelect(topic.id);}- const showShare = tier === "large" || topic.id === UNASSIGNED_TOPIC_ID;+ const showShare =+ tier === "large" || (tier === "medium" && topic.id === UNASSIGNED_TOPIC_ID);const { showCount, nameLines } = tileLabelLayout(topic.name,rect,@@ -194,7 +195,10 @@ function TopicTileButton({{showCount && (<span className="flex flex-col gap-0.5"><span className={cn("font-bold tabular-nums", COUNT_SIZE[tier])}>- {topic.count.toLocaleString()}+ {compactNumberFormatter(+ topic.count,+ topic.count >= 100_000 ? 0 : 1,+ )}</span>{showShare && (<span className="text-xs opacity-80">{shareLabel}</span>@@ -209,7 +213,8 @@ function TopicTile(props: TopicTileProps) {const { topic, share, tier, previewOnSelect, capped } = props;const percentLabel = `${Math.round(share * 100)}% of traces`;const shareLabel = capped ? `${percentLabel} · shown smaller` : percentLabel;- if ((previewOnSelect || tier === "large" || tier === "medium") && !capped) {+ // Tap-to-preview tiles skip the tooltip; on desktop a capped tile keeps it to explain its size.+ if (previewOnSelect || ((tier === "large" || tier === "medium") && !capped)) {return <TopicTileButton {...props} shareLabel={shareLabel} />;}return (diff --git a/web/src/features/topics/TopicsHeaderActions.stories.tsx b/web/src/features/topics/TopicsHeaderActions.stories.tsxindex 7df591267f..15f344c616 100644--- a/web/src/features/topics/TopicsHeaderActions.stories.tsx+++ b/web/src/features/topics/TopicsHeaderActions.stories.tsx@@ -8,16 +8,13 @@ const defaultArgs: ComponentProps<typeof TopicsHeaderActions> = {actions: prepareTopicsActions({automaticProcessing: { state: { status: "off" }, saving: false },configureAvailable: true,- configureVariant: "secondary",- configured: true,+ regenerateAvailable: true,canWrite: true,- manualAvailable: true,menuOnly: false,- onManualProcessing: fn(),onAutomaticProcessing: fn(),onConfigure: fn(),+ onRegenerate: fn(),onHistory: fn(),- onRefresh: fn(),}),};@@ -36,7 +33,7 @@ export const Wide = meta.story({});export const Compact = meta.story({- name: "(Test) Compact processing actions remain reachable",+ name: "(Test) Compact Analyze stays reachable",render: (args) => (<div className="@container/topics-header w-80 p-3"><TopicsHeaderActions {...args} />@@ -45,22 +42,17 @@ export const Compact = meta.story({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" }),+ canvas.queryByRole("button", { name: "Analyze" }),).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(),+ expect(body.getByRole("menuitem", { name: /Analyze/ })).toBeVisible(),);await expect(- body.getByRole("menuitem", { name: /Automatic processing/ }),+ body.getByRole("menuitem", { name: "Regenerate topics" }),).toBeVisible();},});diff --git a/web/src/features/topics/TopicsHeaderActions.tsx b/web/src/features/topics/TopicsHeaderActions.tsxindex 8634842aa2..d97ed01140 100644--- a/web/src/features/topics/TopicsHeaderActions.tsx+++ b/web/src/features/topics/TopicsHeaderActions.tsx@@ -1,29 +1,22 @@-import { MoreHorizontal } from "@langfuse/icons";-import { Button } from "@/src/components/design-system/Button/Button";+import { EllipsisVertical } from "@langfuse/icons";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 { AnalyzeControl } from "./AnalyzeControl";import { type TopicsActions } from "./prepare-topics-actions";export function TopicsHeaderActions({ actions }: { actions: TopicsActions }) {return (<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}+ {actions.automatic && (+ <div className="hidden items-center gap-1 @5xl/topics-header:flex">+ <AnalyzeControl+ state={actions.automatic.state}+ disabledReason={actions.automatic.disabledReason}+ onClick={actions.automatic.onSelect}/>- ))}- </div>+ </div>+ )}<DropdownMenuariaLabel="Topics actions"placement="bottom-end"@@ -44,7 +37,7 @@ export function TopicsHeaderActions({ actions }: { actions: TopicsActions }) {{({ getTriggerProps }) => (<IconButton{...getTriggerProps()}- icon={MoreHorizontal}+ icon={EllipsisVertical}label="Topics actions"size="sm"/>diff --git a/web/src/features/topics/TopicsPage.clienttest.tsx b/web/src/features/topics/TopicsPage.clienttest.tsxindex eabb7d7f16..f97d6a33a2 100644--- a/web/src/features/topics/TopicsPage.clienttest.tsx+++ b/web/src/features/topics/TopicsPage.clienttest.tsx@@ -8,6 +8,7 @@ import {} from "@testing-library/react";import { afterEach, beforeEach, expect, it, vi } from "vitest";import TopicsPage from "./TopicsPage";+import { LayerProvider } from "@/src/context/LayerContext/LayerContext";import { useGlobalDateRangeStore } from "@/src/features/global-time-range/globalDateRangeStore";import { rangeToString, type TimeRange } from "@/src/utils/date-range-utils";import { type TopicFacet } from "@langfuse/shared/topics";@@ -387,7 +388,7 @@ afterEach(() => {it("shows Not found instead of the workspace when the Topics gate is closed", () => {state.canViewTopics = false;- render(<TopicsPage />);+ render(<TopicsPage />, { wrapper: LayerProvider });expect(screen.getByText("This page is not available.")).toBeTruthy();expect(state.currentTopics).not.toHaveBeenCalled();});@@ -399,14 +400,12 @@ it("keeps facet, view, and automatic processing reachable with the mobile headerconst 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/ }));+ fireEvent.click(screen.getByRole("button", { name: /^Analyze/ }));expect(state.openAutomaticProcessing).toHaveBeenCalledWith(false);state.canWrite = false;view.rerender(<TopicsPage />);expect(- screen- .getByRole("button", { name: /Automatic processing/ })- .hasAttribute("disabled"),+ screen.getByRole("button", { name: /^Analyze/ }).hasAttribute("disabled"),).toBe(true);});@@ -420,7 +419,7 @@ it.each([useGlobalDateRangeStore.getState().actions.setProjectDefault("project", token);- render(<TopicsPage />);+ render(<TopicsPage />, { wrapper: LayerProvider });const { timeRange } = state.currentTopics.mock.lastCall![0];expect(timeRange.to.getTime() - timeRange.from.getTime()).toBe(minutes * 60_000,@@ -443,7 +442,7 @@ it("keeps a URL custom range fixed when an execution completes", () => {};state.dateRange = rangeToString(timeRange);state.status = "running";- const view = render(<TopicsPage />);+ const view = render(<TopicsPage />, { wrapper: LayerProvider });expect(state.currentTopics).toHaveBeenLastCalledWith(expect.objectContaining({ timeRange }),);@@ -462,7 +461,7 @@ it.each(["stored", "URL"])(.getState().actions.setProjectDefault("project", "1y");state.dateRange = source === "URL" ? "1y" : undefined;- render(<TopicsPage />);+ render(<TopicsPage />, { wrapper: LayerProvider });const { timeRange } = state.currentTopics.mock.lastCall![0];expect(timeRange).toEqual({@@ -503,7 +502,7 @@ it("caps a custom range at its original end and preserves its URL through comple};state.dateRange = rangeToString(requested);state.status = "running";- const view = render(<TopicsPage />);+ const view = render(<TopicsPage />, { wrapper: LayerProvider });expect(state.currentTopics).toHaveBeenLastCalledWith(expect.objectContaining({ timeRange: expected }),);@@ -532,7 +531,7 @@ it.each(["leaves an exact 90-day range unchanged: %j",(timeRange) => {state.dateRange = rangeToString(timeRange);- render(<TopicsPage />);+ render(<TopicsPage />, { wrapper: LayerProvider });expect(state.picker).toHaveBeenLastCalledWith(timeRange);expect(screen.queryByRole("status", { name: "" })).not.toBeInTheDocument();expect(state.setQueryParams).not.toHaveBeenCalled();@@ -542,7 +541,7 @@ it.each([it("refreshes current results through retry and completion for a selected run outside history", () => {state.executionId = "execution";- const view = render(<TopicsPage />);+ const view = render(<TopicsPage />, { wrapper: LayerProvider });const status = screen.getByRole("dialog", { name: "Analyze traces" });fireEvent.click(within(status).getByRole("button", { name: "Resume run" }));expect(state.retry).toHaveBeenCalledWith({@@ -573,7 +572,7 @@ it("refreshes current results through retry and completion for a selected run ouit("holds relative bounds between renders and advances them after completion", () => {state.status = "running";- const view = render(<TopicsPage />);+ const view = render(<TopicsPage />, { wrapper: LayerProvider });const initialRange = state.currentTopics.mock.lastCall![0].timeRange;vi.setSystemTime(new Date("2026-10-09T12:01:00Z"));@@ -611,6 +610,18 @@ const execution = (status: string, operation: "process" | "update") => ({input: { operation },facets: [],});+/** Opens the manual dialog from the header menu; "process" switches to its summarize tab. */+async function openManualDialog(operation: "process" | "update" = "update") {+ fireEvent.click(screen.getByRole("button", { name: "Topics actions" }));+ fireEvent.click(+ await screen.findByRole("menuitem", { name: "Regenerate topics" }),+ );+ if (operation === "process")+ fireEvent.mouseDown(+ screen.getByRole("tab", { name: "Summarize traces & embed" }),+ { button: 0, ctrlKey: false },+ );+}function withSummaries() {state.facets = [facet("intent", [2, 1]),@@ -624,6 +635,32 @@ function withSummaries() {];}+it("shows Analyze in the header while auto-analyze is off and keeps Analyze, regenerate, history and settings in the menu", async () => {+ withSummaries();+ render(<TopicsPage />, { wrapper: LayerProvider });+ fireEvent.click(screen.getByRole("button", { name: "Analyze" }));+ expect(state.openAutomaticProcessing).toHaveBeenCalledWith(false);+ fireEvent.click(screen.getByRole("button", { name: "Topics actions" }));+ const items = await screen.findAllByRole("menuitem");+ expect(items.map((item) => item.textContent)).toEqual([+ "AnalyzeOff",+ "Regenerate topics",+ "History",+ "Settings",+ ]);+});++it("shows a paused auto-analyze status with its short reason", () => {+ withSummaries();+ state.settings.blockedAt = "2026-10-09T10:00:00Z";+ state.settings.blockMessage = "Fix the connection.";+ render(<TopicsPage />, { wrapper: LayerProvider });+ const control = screen.getByRole("button", { name: "Auto-analyze: Paused" });+ expect(control).toHaveAttribute("title", "Paused");+ fireEvent.click(control);+ expect(state.openAutomaticProcessing).toHaveBeenCalledWith(false);+});+it.each([{name: "without topics:CUD",@@ -655,11 +692,11 @@ it.each([reason:"No trace summaries in the selected time range yet. Summarize traces first, then regenerate.",},-])("disables Generate topics $name", ({ setup, reason }) => {+])("disables Generate topics $name", async ({ setup, reason }) => {withSummaries();setup();- render(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ render(<TopicsPage />, { wrapper: LayerProvider });+ await openManualDialog();fireEvent.mouseDown(screen.getByRole("tab", { name: "Generate topics" }), {button: 0,ctrlKey: false,@@ -676,8 +713,8 @@ it("requires an eligible selected facet and applies the small-sample threshold b{ facetId: "intent", facetVersion: 2, count: 13 },{ facetId: "outcome", facetVersion: 1, count: 9 },];- render(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ render(<TopicsPage />, { wrapper: LayerProvider });+ await openManualDialog();fireEvent.mouseDown(screen.getByRole("tab", { name: "Generate topics" }), {button: 0,ctrlKey: false,@@ -705,33 +742,32 @@ it("requires an eligible selected facet and applies the small-sample threshold bit("counts summaries only while the open manual dialog is generating topics", async () => {withSummaries();- render(<TopicsPage />);+ render(<TopicsPage />, { wrapper: LayerProvider });const countRequests = () =>state.summaryCountInput.mock.calls.filter(([input]) => typeof input !== "symbol",);expect(countRequests()).toHaveLength(0);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));- expect(countRequests()).toHaveLength(0);- fireEvent.mouseDown(screen.getByRole("tab", { name: "Generate topics" }), {- button: 0,- ctrlKey: false,- });+ await openManualDialog();expect(countRequests().length).toBeGreaterThan(0);+ const generatingRequests = countRequests().length;+ fireEvent.mouseDown(+ screen.getByRole("tab", { name: "Summarize traces & embed" }),+ { button: 0, ctrlKey: false },+ );+ expect(countRequests()).toHaveLength(generatingRequests);fireEvent.click(screen.getByRole("button", { name: "Cancel" }));await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());- const completedRequests = countRequests().length;- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));- expect(countRequests()).toHaveLength(completedRequests);+ expect(countRequests()).toHaveLength(generatingRequests);});-it("keeps summary loading and refetching out of validation warnings", () => {+it("keeps summary loading and refetching out of validation warnings", async () => {withSummaries();state.counts = state.counts.map((count) => ({ ...count, count: 240 }));state.countsPending = true;state.countsFetching = true;- const page = render(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ const page = render(<TopicsPage />, { wrapper: LayerProvider });+ await openManualDialog();fireEvent.mouseDown(screen.getByRole("tab", { name: "Generate topics" }), {button: 0,ctrlKey: false,@@ -767,8 +803,8 @@ it("keeps summary loading and refetching out of validation warnings", () => {it("regenerates the rule's facets that have summaries, at their latest version, over its default seven-day range, then opens the run", async () => {withSummaries();state.executions = [execution("completed", "update")];- render(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ render(<TopicsPage />, { wrapper: LayerProvider });+ await openManualDialog();fireEvent.mouseDown(screen.getByRole("tab", { name: "Generate topics" }), {button: 0,ctrlKey: false,@@ -817,9 +853,9 @@ it("shows a regenerate failure that settles after the dialog was closed and reopstate.trigger.mockImplementationOnce(() => new Promise((_, reject) => (fail = reject)),);- render(<TopicsPage />);- const open = () => {- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ render(<TopicsPage />, { wrapper: LayerProvider });+ const open = async () => {+ await openManualDialog();fireEvent.mouseDown(screen.getByRole("tab", { name: "Generate topics" }), {button: 0,ctrlKey: false,@@ -828,11 +864,11 @@ it("shows a regenerate failure that settles after the dialog was closed and reop};fireEvent.click(- within(open()).getByRole("button", { name: "Generate topics" }),+ within(await open()).getByRole("button", { name: "Generate topics" }),);fireEvent.click(screen.getByRole("button", { name: "Cancel" }));await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());- const reopened = open();+ const reopened = await open();fail(new Error("Clustering connection failed."));expect(@@ -850,8 +886,8 @@ it("shows a regenerate failure that settles after the dialog was closed and reopit("summarizes the frozen trace selection for active facets and opens the progress drawer", async () => {withSummaries();- render(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ render(<TopicsPage />, { wrapper: LayerProvider });+ await openManualDialog("process");const dialog = screen.getByRole("dialog", { name: "Manual processing" });fireEvent.click(within(dialog).getByRole("button", { name: "Summarize & embed" }),@@ -890,8 +926,8 @@ it("summarizes the frozen trace selection for active facets and opens the progreit("hands off from manual processing to Topics model configuration", async () => {withSummaries();- render(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ render(<TopicsPage />, { wrapper: LayerProvider });+ await openManualDialog("process");const dialog = screen.getByRole("dialog", { name: "Manual processing" });fireEvent.click(within(dialog).getByRole("button", { name: "Configure Topics" }),@@ -907,8 +943,8 @@ it("hands off from manual processing to Topics model configuration", async () =>it("freezes an independent generation range for summary counts and submission", async () => {withSummaries();- render(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ render(<TopicsPage />, { wrapper: LayerProvider });+ await openManualDialog();fireEvent.mouseDown(screen.getByRole("tab", { name: "Generate topics" }), {button: 0,ctrlKey: false,@@ -941,8 +977,8 @@ it.each(["relative", "absolute"])(async (rangeKind) => {withSummaries();state.counts = [];- const view = render(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ const view = render(<TopicsPage />, { wrapper: LayerProvider });+ await openManualDialog();if (rangeKind === "absolute") {fireEvent.mouseDown(screen.getByRole("tab", { name: "Generate topics" }),@@ -962,7 +998,7 @@ it.each(["relative", "absolute"])(state.counts = [{ facetId: "intent", facetVersion: 2, count: 120 }];vi.setSystemTime(new Date("2026-10-10T12:00:00Z"));view.rerender(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ await openManualDialog();expect(state.invalidateSummaryCounts).toHaveBeenCalledTimes(2);fireEvent.mouseDown(screen.getByRole("tab", { name: "Generate topics" }), {button: 0,@@ -993,11 +1029,11 @@ it.each(["relative", "absolute"])(it.each(["settings", "readiness", "connections"] as const)("shows a failed %s configuration query and recovers after it succeeds",- (query) => {+ async (query) => {withSummaries();state.configurationFailure = query;- const view = render(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ const view = render(<TopicsPage />, { wrapper: LayerProvider });+ await openManualDialog("process");expect(screen.getByText(/Could not load Topics configuration: Configuration unavailable\./,@@ -1043,8 +1079,8 @@ it.each([if (condition === "loading runs") state.executions = undefined;if (condition === "failed runs")state.executionsError = new Error("Runs unavailable.");- const { rerender } = render(<TopicsPage />);- fireEvent.click(screen.getByRole("button", { name: "Manual processing" }));+ const { rerender } = render(<TopicsPage />, { wrapper: LayerProvider });+ await openManualDialog("process");expect(screen.getByRole("button", { name: "Summarize & embed" }),).toBeDisabled();@@ -1076,11 +1112,9 @@ it.each([it("shows the setup landing until the project's first stored summary exists", () => {state.hasStoredSummaries = false;- const view = render(<TopicsPage />);+ const view = render(<TopicsPage />, { wrapper: LayerProvider });expect(screen.getByRole("button", { name: "Set up topics" })).toBeEnabled();- expect(- screen.queryByRole("button", { name: /^Automatic processing/ }),- ).toBeNull();+ expect(screen.queryByRole("button", { name: /^Analyze/ })).toBeNull();expect(screen.queryByTestId("current-topics")).toBeNull();state.hasStoredSummaries = true;view.rerender(<TopicsPage />);@@ -1091,7 +1125,7 @@ it("shows the setup landing until the project's first stored summary exists", ()it("opens generation directly from the empty topics panel", () => {withSummaries();state.showGenerateCTA = true;- render(<TopicsPage />);+ render(<TopicsPage />, { wrapper: LayerProvider });fireEvent.click(screen.getByRole("button", { name: "Generate topics" }));const dialog = within(screen.getByRole("dialog", { name: "Manual processing" }),@@ -1109,7 +1143,7 @@ it("keeps date controls reachable when a disabled results query has no data", ()from: new Date("2026-10-10T00:00:00Z"),to: new Date("2026-10-09T00:00:00Z"),});- render(<TopicsPage />);+ render(<TopicsPage />, { wrapper: LayerProvider });expect(screen.getByRole("button", { name: "Select last 30 days" }),).toBeVisible();diff --git a/web/src/features/topics/TopicsPage.tsx b/web/src/features/topics/TopicsPage.tsxindex 35a10909e9..0a5b4d2d44 100644--- a/web/src/features/topics/TopicsPage.tsx+++ b/web/src/features/topics/TopicsPage.tsx@@ -1,5 +1,5 @@/* eslint-disable react/no-unstable-nested-components, @typescript-eslint/no-use-before-define */-import { useMemo, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { ChevronLeft } from "@langfuse/icons";import { type UseQueryResult } from "@tanstack/react-query";import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";@@ -211,6 +211,17 @@ function TopicsWorkspaceContent({fallback: "last7Days",});const [refreshedAt, setRefreshedAt] = useState(Date.now);+ // Coming back to the tab moves a relative range forward, so auto-analyzed traces show up.+ useEffect(() => {+ function refreshOnVisible() {+ if (document.visibilityState !== "visible") return;+ const now = Date.now();+ setRefreshedAt((previous) => (now - previous > 60_000 ? now : previous));+ }+ document.addEventListener("visibilitychange", refreshOnVisible);+ return () =>+ document.removeEventListener("visibilitychange", refreshOnVisible);+ }, []);const [tracePanel, setTracePanel] = useState<HTMLElement | null>(null);const peekNavigation = usePeekNavigation({tableName: "topics-traces",@@ -351,10 +362,6 @@ function TopicsWorkspaceContent({results.data?.facets ?? [],);const { selectedFacetId } = traceFilters;- const refreshResults = () => {- setRefreshedAt(Date.now());- utils.topics.currentResults.invalidate({ projectId });- };const openExecution = (id: string) => {router.push({@@ -429,9 +436,6 @@ function TopicsWorkspaceContent({pipeline.clearError();openDialog(operation);};- function openManualProcessing() {- openManual("process");- }function openTopicGeneration() {openManual("update");}@@ -462,16 +466,13 @@ function TopicsWorkspaceContent({const actions = prepareTopicsActions({automaticProcessing,canWrite,- configured,configureAvailable: modelSettings.configure.settings !== null,- configureVariant: modelSettings.configure.triggerVariant,- manualAvailable: pipeline.available,+ regenerateAvailable: pipeline.available,menuOnly: landingOnly,onAutomaticProcessing: openAutomaticProcessingFromHeader,onConfigure: configured ? openConfigure : openSetup,- onManualProcessing: openManualProcessing,+ onRegenerate: openTopicGeneration,onHistory: openHistory,- onRefresh: refreshResults,});return (<Page@@ -567,7 +568,6 @@ function TopicsWorkspaceContent({retrying={false}canRetry={false}onViewDetails={() => openExecution(landingRun.process.id)}- onRetry={refreshResults}/>) : null}{waitingForTraces ? (@@ -577,7 +577,6 @@ function TopicsWorkspaceContent({facets={[]}retrying={false}canRetry={false}- onRetry={refreshResults}/>) : null}{showSetupProgress && setup ? (diff --git a/web/src/features/topics/prepare-topics-actions.ts b/web/src/features/topics/prepare-topics-actions.tsindex ceace1416c..ac448640be 100644--- a/web/src/features/topics/prepare-topics-actions.ts+++ b/web/src/features/topics/prepare-topics-actions.ts@@ -5,7 +5,6 @@ import {Settings,type IconComponent,} from "@langfuse/icons";-import { type Status } from "@/src/components/ui/StatusBadge/StatusBadge";export type AutomaticProcessingState =| { status: "unconfigured" }@@ -14,30 +13,21 @@ export type AutomaticProcessingState =| { status: "paused"; shortLabel: string };type TopicAction = {- id: "automatic" | "manual" | "configure" | "history" | "refresh";+ id: "automatic" | "regenerate" | "configure" | "history";label: string;icon: IconComponent;onSelect: () => void;disabledReason?: string;badge?: string;- variant: "primary" | "secondary";};-export type AutomaticProcessingAction = TopicAction & {- badge: string;- badgeStatus: Status;+const automaticBadge: Record<AutomaticProcessingState["status"], string> = {+ unconfigured: "Off",+ off: "Off",+ on: "On",+ paused: "Paused",};-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,@@ -49,108 +39,79 @@ function processingDisabledReason(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. */+/** One action policy for the inline Analyze control and both overflow-menu presentations. */export function prepareTopicsActions({automaticProcessing,canWrite,- configured,configureAvailable,- configureVariant,- manualAvailable,+ regenerateAvailable,menuOnly,onAutomaticProcessing,onConfigure,- onManualProcessing,+ onRegenerate,onHistory,- onRefresh,}: {automaticProcessing: { state: AutomaticProcessingState; saving: boolean };canWrite: boolean;- configured: boolean;configureAvailable: boolean;- configureVariant: "primary" | "secondary";- manualAvailable: boolean;+ regenerateAvailable: boolean;menuOnly: boolean;onAutomaticProcessing: () => void;onConfigure: () => void;- onManualProcessing: () => void;+ onRegenerate: () => void;onHistory: () => void;- onRefresh: () => void;}) {+ const { state, saving } = automaticProcessing;+ const reason = processingDisabledReason(state, canWrite, saving);+ const disabledReason =+ reason && state.status === "paused"+ ? `${state.shortLabel}. ${reason}`+ : reason;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[] = [];+ : { state, disabledReason, onSelect: onAutomaticProcessing };const menu: TopicAction[] = [];- if (automatic) menu.push(automatic);- if (!menuOnly && !configured) inline.push(configure);- if (!menuOnly && manualAvailable) {- inline.push(manual);- menu.push(manual);+ // Narrow headers hide the inline control, so the menu keeps it reachable.+ if (automatic) {+ menu.push({+ id: "automatic",+ label:+ state.status === "off" || state.status === "unconfigured"+ ? "Analyze"+ : "Auto-analyze",+ icon: Play,+ badge: automaticBadge[state.status],+ disabledReason,+ onSelect: onAutomaticProcessing,+ });}- if (configured || !menuOnly) menu.push(configure);menu.push(+ {+ id: "regenerate",+ label: "Regenerate topics",+ icon: RefreshCw,+ disabledReason: regenerateAvailable+ ? undefined+ : "Configure Topics first.",+ onSelect: onRegenerate,+ },{id: "history",label: "History",icon: History,- variant: "secondary",onSelect: onHistory,},{- id: "refresh",- label: "Refresh results",- icon: RefreshCw,- variant: "secondary",- onSelect: onRefresh,+ id: "configure",+ label: "Settings",+ icon: Settings,+ disabledReason: configureAvailable+ ? undefined+ : "Topics settings are still loading.",+ onSelect: onConfigure,},);- return { automatic, inline, menu };+ return { automatic, menu };}export type TopicsActions = ReturnType<typeof prepareTopicsActions>;diff --git a/web/src/features/topics/useAutomaticProcessing.tsx b/web/src/features/topics/useAutomaticProcessing.tsxindex 75939c58c4..7bed934b5b 100644--- a/web/src/features/topics/useAutomaticProcessing.tsx+++ b/web/src/features/topics/useAutomaticProcessing.tsx@@ -40,7 +40,7 @@ function useSetAutomaticProcessing(projectId: string) {});}-export function automaticProcessingState(+function automaticProcessingState(stored: StoredSettings | undefined,rule: TopicRule | null,): AutomaticProcessingState {