🪢 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 run history groups runs by day and explains failed runs (#19288)
Trang Nguyen7506b4ddf77c
diff --git a/web/src/features/topics/README.md b/web/src/features/topics/README.mdindex 900df68222..3a72f70285 100644--- a/web/src/features/topics/README.md+++ b/web/src/features/topics/README.md@@ -70,7 +70,7 @@ project permissions. Processing additionally requires the project allowlist.limit custom ranges to 90 days, matching the Topics header.All steps start expanded; model details and reuse settings live in review.Preview trace clicks open a new tab, preserving the run dialog and selection.- Without a compatible map, summaries wait for an explicit Update topics run.+ Without a compatible map, summaries wait for an explicit Regenerate topics run.Generate topics defaults to compatible summaries from the past seven days,with its picker limited to a maximum thirty-day range. Its own time-rangepicker uses the same frozen range for counts and submission, independently ofdiff --git a/web/src/features/topics/TopicRunDetails.stories.tsx b/web/src/features/topics/TopicRunDetails.stories.tsxnew file mode 100644index 0000000000..e32ae4f6d5--- /dev/null+++ b/web/src/features/topics/TopicRunDetails.stories.tsx@@ -0,0 +1,336 @@+import { expect, fn, userEvent, within } from "storybook/test";+import preview from "../../../.storybook/preview";+import { type RouterOutputs } from "@/src/utils/api";+import { TopicRunDetails } from "./TopicRunDetails";++type Run = RouterOutputs["topics"]["execution"];+type FacetProgress = Run["facets"][number];++const facets = [+ { id: "intent", name: "Intent" },+ { id: "sentiment", name: "Sentiment" },+ { id: "outcome", name: "Outcome" },+ { id: "issues", name: "Issues" },+];+const facetRefs = facets.map((facet) => ({ facetId: facet.id, version: 1 }));++function facetProgress(+ facetId: string,+ overrides: Partial<Omit<FacetProgress, "counts">> & {+ counts?: Partial<FacetProgress["counts"]>;+ } = {},+): FacetProgress {+ const { counts, ...rest } = overrides;+ return {+ facetId,+ facetVersion: 1,+ outcome: "published",+ runId: `run-${facetId}`,+ error: null,+ ...rest,+ counts: {+ requested: 500,+ complete: 500,+ nonApplicable: 0,+ insufficientInput: 0,+ failed: 0,+ assigned: 480,+ outlier: 20,+ ...counts,+ },+ };+}++function processRun(overrides: Partial<Run>): Run {+ return {+ id: "run-process",+ projectId: "project",+ status: "completed",+ phase: "completed",+ createdAt: "2026-10-23T09:12:00Z",+ updatedAt: "2026-10-23T09:40:00Z",+ error: null,+ estimatedCost: 1.62,+ facets: facetRefs.map(({ facetId }) => facetProgress(facetId)),+ input: {+ operation: "process",+ projectId: "project",+ requestId: "request-process",+ facets: facetRefs,+ embeddingConfig: { embeddingDimensions: 1024 },+ reuseExistingSummaries: false,+ processingConfig: { maxInputTokens: 120_000, maxOutputTokens: 512 },+ },+ ...overrides,+ };+}++const traceErrorsClosed = {+ open: false,+ onOpenChange: fn(),+ isPending: false,+};++const retryIdle = { isPending: false, onRetry: fn() };++const doneWithIssues: Run = {+ id: "run-update",+ projectId: "project",+ status: "completed_with_errors",+ phase: "assigning",+ createdAt: "2026-10-22T17:05:00Z",+ updatedAt: "2026-10-22T17:48:00Z",+ error: null,+ estimatedCost: 0,+ facets: [+ facetProgress("intent", {+ counts: {+ requested: 1_240,+ complete: 1_240,+ assigned: 1_193,+ outlier: 47,+ },+ }),+ facetProgress("sentiment", {+ outcome: "awaiting_topics",+ runId: null,+ counts: {+ requested: 1_240,+ complete: 1_240,+ assigned: 0,+ outlier: 0,+ },+ }),+ facetProgress("outcome", {+ outcome: "insufficient_data",+ runId: null,+ counts: {+ requested: 64,+ complete: 64,+ insufficientInput: 12,+ assigned: 0,+ outlier: 0,+ },+ }),+ facetProgress("issues", {+ outcome: "no_topics",+ runId: null,+ counts: {+ requested: 1_240,+ complete: 1_240,+ nonApplicable: 900,+ assigned: 0,+ outlier: 0,+ },+ }),+ ],+ input: {+ operation: "update",+ projectId: "project",+ requestId: "request-update",+ facets: facetRefs,+ embeddingConfig: { embeddingDimensions: 1024 },+ timeRange: {+ from: new Date("2026-09-23T00:00:00Z"),+ to: new Date("2026-10-23T00:00:00Z"),+ },+ exploratory: false,+ minimumTraceCount: 100,+ },+};++const failedRun = processRun({+ id: "run-failed",+ status: "failed",+ phase: "summarizing",+ error: "Summary model returned 429 Too Many Requests for 3 batches.",+ estimatedCost: 0.62,+ facets: facetRefs.map(({ facetId }) =>+ facetProgress(facetId, {+ outcome: "failed",+ runId: null,+ error: "Summary model returned 429 Too Many Requests for 3 batches.",+ counts: { complete: 310, failed: 3, assigned: 0, outlier: 0 },+ }),+ ),+});++const failedTraceErrors = {+ open: true,+ onOpenChange: fn(),+ isPending: false,+ data: {+ expired: false,+ errors: [+ {+ traceId: "7f3a9c2e1b8d4f6a",+ error: "Input exceeds 120,000 tokens after truncation.",+ },+ {+ traceId: "c41d8e7a9b2f3056",+ error: "Summary model returned 429 Too Many Requests.",+ },+ {+ traceId: "e92b7f1c3d5a8604",+ error: "Trace has no observations with text content.",+ },+ ],+ },+};++const meta = preview.meta({+ component: TopicRunDetails,+ args: {+ facets,+ projectId: "project",+ canWrite: true,+ onBack: fn(),+ },+});++export const Running = meta.story({+ args: {+ execution: processRun({+ status: "running",+ phase: "summarizing",+ facets: facetRefs.map(({ facetId }) =>+ facetProgress(facetId, {+ outcome: "pending",+ runId: null,+ counts: { complete: 180, assigned: 0, outlier: 0 },+ }),+ ),+ }),+ traceErrors: traceErrorsClosed,+ retry: retryIdle,+ },+});++export const DoneWithIssues = meta.story({+ args: {+ execution: doneWithIssues,+ traceErrors: traceErrorsClosed,+ retry: retryIdle,+ },+});++export const Failed = meta.story({+ args: {+ execution: failedRun,+ traceErrors: failedTraceErrors,+ retry: retryIdle,+ },+});++export const ExpiredTraceErrors = meta.story({+ args: {+ execution: processRun({+ id: "run-expired",+ status: "completed_with_errors",+ phase: "completed",+ createdAt: "2026-09-02T09:12:00Z",+ updatedAt: "2026-09-02T09:55:00Z",+ estimatedCost: 2.31,+ facets: facetRefs.map(({ facetId }) =>+ facetProgress(facetId, {+ counts: { complete: 488, failed: 12, assigned: 470, outlier: 18 },+ }),+ ),+ }),+ traceErrors: {+ open: true,+ onOpenChange: fn(),+ isPending: false,+ data: { expired: true, errors: [] },+ },+ retry: retryIdle,+ },+});++export const Complete = meta.story({+ args: {+ execution: processRun({+ facets: facetRefs.map(({ facetId }) =>+ facetProgress(facetId, {+ counts: { complete: 488, failed: 12, assigned: 470, outlier: 18 },+ }),+ ),+ }),+ traceErrors: traceErrorsClosed,+ retry: retryIdle,+ },+});++export const FailedRunResumes = meta.story({+ name: "(Test) Failed run shows the error once and resumes",+ args: {+ execution: failedRun,+ traceErrors: failedTraceErrors,+ retry: retryIdle,+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const banner = canvas.getByRole("alert");+ await expect(banner).toHaveTextContent("Run stopped");+ await expect(banner).toHaveTextContent(+ "Summary model returned 429 Too Many Requests for 3 batches.",+ );+ await expect(banner).toHaveTextContent(+ "310 traces are already summarized and will be kept.",+ );+ await expect(+ canvas.getAllByText(+ "Summary model returned 429 Too Many Requests for 3 batches.",+ ),+ ).toHaveLength(1);+ await expect(+ canvas.getAllByText("310 of 500 summarized · 190 left"),+ ).toHaveLength(4);+ await expect(canvas.getAllByText("Stopped")).toHaveLength(4);+ await expect(+ canvas.getByText("Summarized before it stopped"),+ ).toBeVisible();+ await expect(canvas.getByText("Est. cost")).toBeVisible();+ await expect(+ canvas.getByRole("link", { name: "7f3a9c2e1b8d4f6a" }),+ ).toHaveAttribute("href", "/project/project/traces/7f3a9c2e1b8d4f6a");+ await userEvent.click(canvas.getByRole("button", { name: "Resume run" }));+ await expect(args.retry.onRetry).toHaveBeenCalledOnce();+ await userEvent.click(canvas.getByRole("button", { name: "All runs" }));+ await expect(args.onBack).toHaveBeenCalledOnce();+ },+});++export const QuestionStatusesExplainThemselves = meta.story({+ name: "(Test) Done with issues maps question outcomes and notes",+ args: {+ execution: doneWithIssues,+ traceErrors: traceErrorsClosed,+ retry: retryIdle,+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.queryByRole("alert")).toBeNull();+ await expect(canvas.queryByText("Est. cost")).toBeNull();+ await expect(canvas.getByText("Done with issues")).toBeVisible();+ await expect(+ canvas.getByText("1,193 in topics · 47 didn’t fit a topic"),+ ).toBeVisible();+ await expect(canvas.getByText("Waiting")).toBeVisible();+ await expect(canvas.getByText("Needs more traces")).toBeVisible();+ await expect(+ canvas.getByText("64 summarized · 12 had too little text"),+ ).toBeVisible();+ await expect(+ canvas.getByText(+ "Grouping needs at least 100 summaries. Run on more traces, or lower the minimum.",+ ),+ ).toBeVisible();+ await expect(canvas.getByText("No topics found")).toBeVisible();+ await expect(+ canvas.getByText(+ "The other 340 didn’t form clear groups. Try a larger, more varied set of traces.",+ ),+ ).toBeVisible();+ },+});diff --git a/web/src/features/topics/TopicRunDetails.tsx b/web/src/features/topics/TopicRunDetails.tsxnew file mode 100644index 0000000000..6e3c32d546--- /dev/null+++ b/web/src/features/topics/TopicRunDetails.tsx@@ -0,0 +1,407 @@+import { TextLink } from "@/src/components/design-system/TextLink/TextLink";+import { format } from "date-fns";+import {+ ChevronDown,+ ChevronLeft,+ ChevronRight,+ CircleAlert,+} from "@langfuse/icons";+import { Alert } from "@/src/components/design-system/Alert/Alert";+import { Button } from "@/src/components/design-system/Button/Button";+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";+import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";+import { type RouterOutputs } from "@/src/utils/api";+import { costFormatter } from "@/src/utils/numbers";+import { cn } from "@/src/utils/tailwind";+import {+ type TopicFacet,+ type TopicFacetOutcome,+} from "@langfuse/shared/topics";+import { TopicsErrorMessage } from "./TopicsErrorMessage";+import {+ busy,+ executionBadgeTypes,+ executionLabels,+ operationLabels,+} from "./topic-run-labels";++type Run = RouterOutputs["topics"]["execution"];+type FacetProgress = Run["facets"][number];++type TopicRunDetailsProps = {+ execution: Run;+ facets: Pick<TopicFacet, "id" | "name">[];+ projectId: string;+ canWrite: boolean;+ traceErrors: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ isPending: boolean;+ errorMessage?: string;+ data?: RouterOutputs["topics"]["traceErrors"];+ };+ retry: {+ isPending: boolean;+ errorMessage?: string;+ onRetry: () => void;+ };+ onBack: () => void;+};++const phaseLabels: Record<string, string> = {+ queued: "Waiting for a worker",+ resuming: "Resuming",+ summarizing: "Summarizing traces",+ clustering: "Clustering summaries",+ naming: "Naming topics",+ assigning: "Assigning traces to topics",+ processing: "Processing questions",+};++const questionStatuses: Record<+ TopicFacetOutcome,+ { label: string; dot: string }+> = {+ published: { label: "Topics ready", dot: "bg-dark-green" },+ assigned: { label: "Topics ready", dot: "bg-dark-green" },+ pending: { label: "Waiting", dot: "bg-muted-foreground" },+ awaiting_topics: { label: "Waiting", dot: "bg-muted-foreground" },+ insufficient_data: { label: "Needs more traces", dot: "bg-dark-yellow" },+ no_topics: { label: "No topics found", dot: "bg-muted-foreground" },+ no_applicable_summaries: {+ label: "No topics found",+ dot: "bg-muted-foreground",+ },+ failed: { label: "Stopped", dot: "bg-dark-red" },+};++function formatCount(count: number) {+ return count.toLocaleString("en-US");+}++function canResume(execution: Run) {+ return (+ execution.status === "failed" ||+ (execution.status === "completed_with_errors" &&+ execution.facets.some(+ (facet) => facet.outcome === "pending" || facet.outcome === "failed",+ ))+ );+}++function questionStats(progress: FacetProgress, runStatus: Run["status"]) {+ const c = progress.counts;+ if (busy(runStatus))+ return `${formatCount(c.complete)} of ${formatCount(c.requested)} summarized`;+ if (runStatus === "failed")+ return `${formatCount(c.complete)} of ${formatCount(c.requested)} summarized · ${formatCount(Math.max(0, c.requested - c.complete))} left`;+ const parts = [+ c.assigned > 0+ ? `${formatCount(c.assigned)} in topics`+ : `${formatCount(c.complete)} summarized`,+ ];+ if (c.outlier > 0) parts.push(`${formatCount(c.outlier)} didn’t fit a topic`);+ if (c.insufficientInput > 0)+ parts.push(`${formatCount(c.insufficientInput)} had too little text`);+ if (c.nonApplicable > 0)+ parts.push(`${formatCount(c.nonApplicable)} had no issue`);+ if (c.failed > 0) parts.push(`${formatCount(c.failed)} failed`);+ return parts.join(" · ");+}++function questionNote(progress: FacetProgress, minimum: number | null) {+ const c = progress.counts;+ if (progress.outcome === "insufficient_data" && minimum !== null)+ return `Grouping needs at least ${formatCount(minimum)} summaries. Run on more traces, or lower the minimum.`;+ if (progress.outcome === "no_topics") {+ const unclustered = c.complete - c.nonApplicable;+ if (unclustered <= 0)+ return "No clear groups formed. Try a larger, more varied set of traces.";+ return c.nonApplicable > 0+ ? `The other ${formatCount(unclustered)} didn’t form clear groups. Try a larger, more varied set of traces.`+ : `${formatCount(unclustered)} summaries didn’t form clear groups. Try a larger, more varied set of traces.`;+ }+ if (progress.outcome === "awaiting_topics")+ return `${formatCount(c.complete)} summaries are ready. Run Regenerate topics to group them.`;+ return null;+}++function StatusLabel({ label, dot }: { label: string; dot: string }) {+ return (+ <span className="flex shrink-0 items-center gap-2 text-sm whitespace-nowrap">+ <span className={cn("size-2 rounded-full", dot)} aria-hidden />+ {label}+ </span>+ );+}++function QuestionRow({+ progress,+ name,+ execution,+ minimum,+}: {+ progress: FacetProgress;+ name: string;+ execution: Run;+ minimum: number | null;+}) {+ const status = questionStatuses[progress.outcome] ?? {+ label: progress.outcome,+ dot: "bg-muted-foreground",+ };+ const note = questionNote(progress, minimum);+ const facetError =+ progress.error && progress.error !== execution.error+ ? progress.error+ : null;+ return (+ <div className="flex flex-col gap-1 px-4 py-3">+ <div className="flex items-center justify-between gap-2.5">+ <h4 className="truncate text-sm font-bold" title={name}>+ {name}+ </h4>+ <StatusLabel label={status.label} dot={status.dot} />+ </div>+ <p className="text-muted-foreground text-xs">+ {questionStats(progress, execution.status)}+ </p>+ {note && (+ <p className="text-foreground-secondary text-sm text-pretty">{note}</p>+ )}+ {facetError && (+ <p className="text-foreground-secondary text-sm break-words">+ {facetError}+ </p>+ )}+ </div>+ );+}++export function TopicRunDetails({+ execution,+ facets,+ projectId,+ canWrite,+ traceErrors,+ retry,+ onBack,+}: TopicRunDetailsProps) {+ const isUpdate = execution.input.operation === "update";+ const counts = execution.facets.map((facet) => facet.counts);+ const total = isUpdate+ ? counts.reduce((sum, c) => sum + c.requested, 0)+ : Math.max(0, ...counts.map((c) => c.requested));+ const complete = isUpdate+ ? counts.reduce((sum, c) => sum + c.complete, 0)+ : Math.min(total, ...counts.map((c) => c.complete));+ const isBusy = busy(execution.status);+ const failed = execution.status === "failed";+ const resumable = canWrite && !isBusy && canResume(execution);+ const traceErrorCount = Math.max(0, ...counts.map((c) => c.failed));+ const minimum =+ execution.input.operation === "update"+ ? (execution.input.minimumTraceCount ??+ (execution.input.exploratory ? 10 : 100))+ : null;+ const name = operationLabels[execution.input.operation];+ const meta = [+ format(new Date(execution.createdAt), "MMM d, HH:mm"),+ isUpdate+ ? `${formatCount(total)} summaries`+ : `${formatCount(total)} traces`,+ ...(execution.input.operation === "update" && execution.input.exploratory+ ? ["small sample"]+ : []),+ ].join(" · ");+ const showBar = !isUpdate && total > 0 && (isBusy || failed);+ const summaryLabel = (() => {+ if (isBusy)+ return (+ phaseLabels[execution.phase] ?? execution.phase.replaceAll("_", " ")+ );+ if (failed) return isUpdate ? "Summaries" : "Summarized before it stopped";+ return isUpdate ? "Summaries" : "Summarized";+ })();+ const summaryValue = (() => {+ if (isUpdate) return formatCount(total);+ return total > 0+ ? `${formatCount(complete)} / ${formatCount(total)}`+ : null;+ })();++ return (+ <section className="flex w-full min-w-0 flex-col">+ <header className="flex items-center justify-between gap-2.5 border-b py-3.5 pr-12 pl-3">+ <div className="flex min-w-0 items-center gap-2">+ <IconButton+ icon={ChevronLeft}+ label="All runs"+ variant="ghost"+ size="sm"+ onClick={onBack}+ />+ <div className="flex min-w-0 flex-col">+ <h2 className="truncate text-base font-bold" title={name}>+ {name}+ </h2>+ <span className="text-muted-foreground font-mono text-xs">+ {meta}+ </span>+ </div>+ </div>+ <StatusBadge+ type={executionBadgeTypes[execution.status]}+ showText={false}+ >+ {executionLabels[execution.status]}+ </StatusBadge>+ </header>+ {(failed || resumable) && (+ <div className="px-4 pt-4">+ <Alert variant="destructive" icon={CircleAlert}>+ <Alert.Title>Run stopped</Alert.Title>+ <Alert.Description>+ <div className="text-foreground-secondary flex flex-col gap-0.5">+ {execution.error && (+ <p className="break-words">{execution.error}</p>+ )}+ {!isUpdate && complete > 0 && (+ <p>+ {formatCount(complete)} traces are already summarized and+ will be kept.+ </p>+ )}+ </div>+ {resumable && (+ <div className="pt-2.5">+ <Button+ text="Resume run"+ size="sm"+ loading={retry.isPending}+ onClick={() => retry.onRetry()}+ />+ </div>+ )}+ </Alert.Description>+ </Alert>+ </div>+ )}+ {retry.errorMessage && (+ <div className="px-4 pt-4">+ <TopicsErrorMessage message={retry.errorMessage} />+ </div>+ )}+ <div+ className="flex flex-col gap-2.5 border-b p-4"+ role={isBusy ? "status" : undefined}+ >+ {showBar && (+ <div className="bg-muted h-1.5 overflow-hidden rounded-sm">+ <div+ className={cn(+ "h-full rounded-sm",+ failed ? "bg-dark-red" : "bg-foreground",+ )}+ style={{ width: `${(complete / total) * 100}%` }}+ />+ </div>+ )}+ <div className="flex items-center justify-between gap-2.5">+ <span className="text-muted-foreground text-xs">{summaryLabel}</span>+ {summaryValue && (+ <span className="font-mono text-xs">{summaryValue}</span>+ )}+ </div>+ {!isBusy && !isUpdate && execution.estimatedCost != null && (+ <div className="flex items-center justify-between gap-2.5">+ <span className="text-muted-foreground text-xs">Est. cost</span>+ <span className="font-mono text-xs">+ ~{costFormatter(execution.estimatedCost)}+ </span>+ </div>+ )}+ </div>+ <div className="flex flex-col">+ <h3 className="text-muted-foreground px-4 pt-3.5 pb-0.5 text-xs font-bold">+ Questions+ </h3>+ <div className="divide-y">+ {execution.facets.map((progress) => (+ <QuestionRow+ key={`${progress.facetId}:${progress.facetVersion}`}+ progress={progress}+ name={+ facets.find((item) => item.id === progress.facetId)?.name ??+ "Question"+ }+ execution={execution}+ minimum={minimum}+ />+ ))}+ </div>+ </div>+ {traceErrorCount > 0 && (+ <div className="ph-no-capture flex flex-col gap-2 border-t px-4 py-3 text-sm">+ <button+ type="button"+ aria-expanded={traceErrors.open}+ onClick={() => traceErrors.onOpenChange(!traceErrors.open)}+ className="flex items-center gap-1.5 self-start font-bold"+ >+ {traceErrors.open ? (+ <ChevronDown size="base" color="muted" aria-hidden />+ ) : (+ <ChevronRight size="base" color="muted" aria-hidden />+ )}+ Trace errors+ <span className="text-muted-foreground font-mono font-normal">+ {formatCount(traceErrorCount)}+ </span>+ </button>+ {traceErrors.open && (+ <div className="flex flex-col gap-2 pl-5">+ {traceErrors.isPending && (+ <p className="text-muted-foreground text-xs">+ Loading trace errors…+ </p>+ )}+ {traceErrors.errorMessage && (+ <TopicsErrorMessage message={traceErrors.errorMessage} />+ )}+ {traceErrors.data?.expired && (+ <p className="text-muted-foreground text-xs">+ Trace error details have expired. The run counts are still+ available.+ </p>+ )}+ {traceErrors.data?.errors.map((item) => (+ <div+ key={`${item.traceId}:${item.error}`}+ className="flex items-start gap-2.5"+ >+ <span className="w-28 shrink-0 font-mono">+ <TextLink+ path={`/project/${projectId}/traces/${encodeURIComponent(item.traceId)}`}+ value={item.traceId}+ />+ </span>+ <span className="text-foreground-secondary min-w-0 text-xs break-words">+ {item.error}+ </span>+ </div>+ ))}+ {traceErrors.data &&+ !traceErrors.data.expired &&+ traceErrors.data.errors.length === 0 && (+ <p className="text-muted-foreground text-xs">+ No trace-level errors were recorded.+ </p>+ )}+ </div>+ )}+ </div>+ )}+ </section>+ );+}diff --git a/web/src/features/topics/TopicRunHistoryList.stories.tsx b/web/src/features/topics/TopicRunHistoryList.stories.tsxnew file mode 100644index 0000000000..703c5cadfd--- /dev/null+++ b/web/src/features/topics/TopicRunHistoryList.stories.tsx@@ -0,0 +1,256 @@+import { expect, fn, userEvent, within } from "storybook/test";+import { format, setHours, startOfDay, subDays } from "date-fns";+import preview from "../../../.storybook/preview";+import { type RouterOutputs } from "@/src/utils/api";+import { TopicRunHistoryList } from "./TopicRunHistoryList";++type Run = RouterOutputs["topics"]["executions"][number];+type Counts = Partial<Run["facets"][number]["counts"]>;++const facetRefs = [+ { facetId: "intent", version: 1 },+ { facetId: "sentiment", version: 1 },+ { facetId: "outcome", version: 2 },+];++const hoursAgo = (hours: number) =>+ new Date(Date.now() - hours * 3_600_000).toISOString();+const atDaysAgo = (days: number, hour: number) =>+ setHours(subDays(startOfDay(new Date()), days), hour).toISOString();+const dayLabel = (days: number) => {+ const date = subDays(startOfDay(new Date()), days);+ return format(+ date,+ date.getFullYear() === new Date().getFullYear() ? "MMM d" : "MMM d, yyyy",+ );+};++function facetProgress(+ facetId: string,+ version: number,+ counts: Counts,+ error: string | null = null,+): Run["facets"][number] {+ const requested = counts.requested ?? 500;+ return {+ facetId,+ facetVersion: version,+ outcome: error ? "failed" : "published",+ runId: `run-${facetId}`,+ error,+ counts: {+ requested,+ complete: requested,+ nonApplicable: 0,+ insufficientInput: 0,+ failed: 0,+ assigned: requested - 20,+ outlier: 20,+ ...counts,+ },+ };+}++function processRun(+ id: string,+ status: Run["status"],+ createdAt: string,+ estimatedCost: number,+ counts: Counts = {},+ error: string | null = null,+): Run {+ return {+ id,+ projectId: "project",+ status,+ phase: status === "running" ? "summarizing" : status,+ createdAt,+ updatedAt: createdAt,+ error,+ estimatedCost,+ facets: facetRefs.map(({ facetId, version }) =>+ facetProgress(facetId, version, counts),+ ),+ input: {+ operation: "process",+ projectId: "project",+ requestId: `request-${id}`,+ facets: facetRefs,+ embeddingConfig: { embeddingDimensions: 1024 },+ reuseExistingSummaries: false,+ processingConfig: { maxInputTokens: 120_000, maxOutputTokens: 512 },+ },+ };+}++function updateRun(+ id: string,+ status: Run["status"],+ createdAt: string,+ error: string | null = null,+): Run {+ return {+ id,+ projectId: "project",+ status,+ phase: status === "queued" ? "queued" : "clustering",+ createdAt,+ updatedAt: createdAt,+ error,+ estimatedCost: 0,+ facets: facetRefs+ .slice(0, 2)+ .map(({ facetId, version }) =>+ facetProgress(facetId, version, { requested: 1_200 }),+ ),+ input: {+ operation: "update",+ projectId: "project",+ requestId: `request-${id}`,+ facets: facetRefs.slice(0, 2),+ embeddingConfig: { embeddingDimensions: 1024 },+ timeRange: {+ from: new Date("2026-09-23T00:00:00Z"),+ to: new Date("2026-10-23T00:00:00Z"),+ },+ exploratory: false,+ },+ };+}++const runs: Run[] = [+ processRun("run-9", "running", hoursAgo(0.4), 1.84, {+ requested: 1_280,+ complete: 640,+ }),+ updateRun("run-8", "queued", hoursAgo(0.3)),+ processRun("run-7", "completed", hoursAgo(17), 4.2, { requested: 1_412 }),+ processRun("run-6", "completed_with_errors", hoursAgo(46), 3.95, {+ requested: 1_330,+ complete: 1_318,+ failed: 12,+ }),+ updateRun("run-5", "failed", hoursAgo(67), "Embedding model returned 429."),+ processRun("run-4", "completed", hoursAgo(97), 0.97, { requested: 326 }),+ updateRun("run-3", "completed", hoursAgo(98)),+ processRun("run-2", "completed", hoursAgo(118), 3.3, {+ requested: 1_105,+ }),+ processRun("run-1", "completed", hoursAgo(148), 2.9, { requested: 980 }),+ updateRun("run-0", "completed", hoursAgo(152)),+];++const meta = preview.meta({+ component: TopicRunHistoryList,+ args: {+ onOpen: fn(),+ onRetry: fn(),+ },+});++export const Default = meta.story({+ args: { executions: runs },+});++export const Empty = meta.story({+ args: { executions: [] },+});++export const LoadError = meta.story({+ args: {+ executions: [],+ errorMessage: "Request timed out.",+ },+});++export const PinsRunningAndGroupsByDay = meta.story({+ name: "(Test) Pins the running run and groups past runs by day",+ args: {+ executions: [+ updateRun("regenerate-done", "completed", atDaysAgo(4, 10)),+ processRun("analyze-running", "running", atDaysAgo(0, 9), 1.84, {+ requested: 1_280,+ complete: 640,+ }),+ processRun("analyze-done", "completed", atDaysAgo(1, 10), 4.2, {+ requested: 1_412,+ }),+ processRun(+ "analyze-issues",+ "completed_with_errors",+ atDaysAgo(2, 10),+ 3.95,+ { requested: 1_330, complete: 1_318, failed: 12 },+ ),+ updateRun(+ "regenerate-failed",+ "failed",+ atDaysAgo(3, 10),+ "Embedding model returned 429.",+ ),+ ],+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ const active = canvas.getByRole("status");+ await expect(active).toHaveTextContent("Analyze traces");+ await expect(active).toHaveTextContent("640 / 1,280");+ await expect(+ within(active).getByRole("img", { name: "Running" }),+ ).toBeVisible();++ await expect(+ canvas.getAllByRole("heading", { level: 3 }).map((h) => h.textContent),+ ).toEqual(["Yesterday", dayLabel(2), dayLabel(3), dayLabel(4)]);++ await userEvent.click(+ within(active).getByRole("button", { name: /Analyze traces/ }),+ );+ await expect(args.onOpen).toHaveBeenCalledWith("analyze-running");++ const rows = canvas+ .getAllByRole("button")+ .filter((row) => !active.contains(row));+ await expect(rows.map((row) => row.textContent)).toEqual([+ expect.stringContaining("Analyze traces1,412 traces · $4.20"),+ expect.stringContaining("Analyze traces12 traces failed"),+ expect.stringContaining("Regenerate topicsEmbedding model returned 429."),+ expect.stringMatching(/Regenerate topicsComplete$/),+ ]);+ await expect(within(rows[1]).getByText("Done with issues")).toBeVisible();+ await expect(within(rows[2]).getByText("Failed")).toBeVisible();++ await userEvent.click(rows[1]);+ await expect(args.onOpen).toHaveBeenCalledWith("analyze-issues");+ },+});++export const ShowsRefetchErrorAboveRuns = meta.story({+ name: "(Test) A refetch error shows above the cached runs",+ args: {+ executions: runs.slice(2, 4),+ errorMessage: "Request timed out.",+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.getByRole("alert")).toHaveTextContent(+ "Request timed out.",+ );+ await expect(canvas.getAllByRole("button")).toHaveLength(2);+ },+});++export const RetriesAfterLoadError = meta.story({+ name: "(Test) Load error offers a retry",+ args: {+ executions: [],+ errorMessage: "Request timed out.",+ },+ play: async ({ args, canvasElement }) => {+ const canvas = within(canvasElement);+ await expect(canvas.getByText("Couldn’t load run history")).toBeVisible();+ await expect(canvas.getByText("Request timed out.")).toBeVisible();+ await userEvent.click(canvas.getByRole("button", { name: "Try again" }));+ await expect(args.onRetry).toHaveBeenCalledOnce();+ },+});diff --git a/web/src/features/topics/TopicRunHistoryList.tsx b/web/src/features/topics/TopicRunHistoryList.tsxnew file mode 100644index 0000000000..afc85704a2--- /dev/null+++ b/web/src/features/topics/TopicRunHistoryList.tsx@@ -0,0 +1,297 @@+import { type ReactNode } from "react";+import { format, isToday, isYesterday } from "date-fns";+import { CircleAlert, History } from "@langfuse/icons";+import { Button } from "@/src/components/design-system/Button/Button";+import { Tooltip } from "@/src/components/design-system/Tooltip/Tooltip";+import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";+import { type RouterOutputs } from "@/src/utils/api";+import { costFormatter } from "@/src/utils/numbers";+import { cn } from "@/src/utils/tailwind";+import {+ busy,+ executionBadgeTypes,+ executionLabels,+ operationLabels,+} from "./topic-run-labels";+import { TopicsErrorMessage } from "./TopicsErrorMessage";++type Run = RouterOutputs["topics"]["executions"][number];++type TopicRunHistoryListProps = {+ executions: Run[];+ errorMessage?: string;+ onOpen: (executionId: string) => void;+ onRetry: () => void;+};++function formatCount(count: number) {+ return count.toLocaleString("en-US");+}++function plural(count: number) {+ return count === 1 ? "trace" : "traces";+}++function traceCount(run: Run) {+ return Math.max(0, ...run.facets.map((facet) => facet.counts.requested));+}++function dayLabel(date: Date, now: Date) {+ if (isToday(date)) return "Today";+ if (isYesterday(date)) return "Yesterday";+ return format(+ date,+ date.getFullYear() === now.getFullYear() ? "MMM d" : "MMM d, yyyy",+ );+}++function groupByDay(runs: Run[]) {+ const now = new Date();+ const groups: { label: string; runs: Run[] }[] = [];+ for (const run of runs) {+ const label = dayLabel(new Date(run.createdAt), now);+ const last = groups.at(-1);+ if (last?.label === label) last.runs.push(run);+ else groups.push({ label, runs: [run] });+ }+ return groups;+}++function problemReason(run: Run) {+ const failed = Math.max(0, ...run.facets.map((f) => f.counts.failed));+ if (failed > 0) return `${formatCount(failed)} ${plural(failed)} failed`;+ const skipped = Math.max(+ 0,+ ...run.facets.map((f) => f.counts.insufficientInput),+ );+ if (skipped > 0)+ return `${formatCount(skipped)} ${plural(skipped)} skipped: not enough input`;+ return run.error ?? run.facets.find((f) => f.error)?.error ?? null;+}++function runDetail(run: Run): { text: string; problem: boolean } | null {+ if (run.status === "failed" || run.status === "completed_with_errors") {+ const reason = problemReason(run);+ if (reason) return { text: reason, problem: true };+ }+ if (run.input.operation !== "process") return null;+ const parts = [`${formatCount(traceCount(run))} traces`];+ if (run.estimatedCost != null)+ parts.push(+ `${busy(run.status) ? "~" : ""}${costFormatter(run.estimatedCost)}`,+ );+ return { text: parts.join(" · "), problem: false };+}++function CenteredState({+ icon,+ title,+ body,+ children,+}: {+ icon: ReactNode;+ title: string;+ body: string;+ children?: ReactNode;+}) {+ return (+ <div className="flex flex-1 items-center justify-center p-6 pb-44">+ <div className="flex max-w-xs flex-col items-center gap-3 text-center">+ {icon}+ <div className="flex flex-col gap-1">+ <p className="text-sm font-bold">{title}</p>+ <p className="text-muted-foreground text-sm text-balance break-words">+ {body}+ </p>+ </div>+ {children}+ </div>+ </div>+ );+}++/** Live runs only: StatusBadge draws a dot for running and queued, not for finished runs. */+function StatusDot({ status }: { status: Run["status"] }) {+ const label = executionLabels[status];+ return (+ <Tooltip label={label} hoverableContent={false}>+ {({ getTriggerProps }) => (+ <span+ {...getTriggerProps()}+ role="img"+ aria-label={label}+ className="inline-flex shrink-0"+ >+ <StatusBadge+ type={executionBadgeTypes[status]}+ variant="transparent"+ showText={false}+ />+ </span>+ )}+ </Tooltip>+ );+}++function ActiveRun({+ run,+ onOpen,+}: {+ run: Run;+ onOpen: (id: string) => void;+}) {+ const total = traceCount(run);+ const processed = Math.min(+ total,+ ...run.facets.map((facet) => facet.counts.complete),+ );+ const showProgress = run.input.operation === "process" && total > 0;+ return (+ <div+ role="status"+ className="bg-muted/40 flex flex-col gap-2 border-b px-4 py-3.5"+ >+ <button+ type="button"+ onClick={() => onOpen(run.id)}+ className="flex items-center justify-between gap-3 text-left hover:underline"+ >+ <span className="flex min-w-0 items-center gap-2 text-sm font-bold">+ <StatusDot status={run.status} />+ <span+ className="truncate"+ title={operationLabels[run.input.operation]}+ >+ {operationLabels[run.input.operation]}+ </span>+ </span>+ <span className="text-muted-foreground font-mono text-xs">+ {format(new Date(run.createdAt), "HH:mm")}+ </span>+ </button>+ {showProgress && (+ <div className="bg-muted h-1.5 overflow-hidden rounded-sm">+ <div+ className="bg-foreground h-full rounded-sm"+ style={{ width: `${(processed / total) * 100}%` }}+ />+ </div>+ )}+ {showProgress && (+ <div className="flex justify-end text-xs">+ <span className="font-mono">+ {formatCount(processed)} / {formatCount(total)}+ </span>+ </div>+ )}+ </div>+ );+}++function RunRow({ run, onOpen }: { run: Run; onOpen: (id: string) => void }) {+ const name = operationLabels[run.input.operation];+ const detail = runDetail(run);+ return (+ <button+ type="button"+ onClick={() => onOpen(run.id)}+ className="hover:bg-muted flex w-full items-start gap-2.5 rounded-md px-2 py-1.5 text-left"+ >+ <span className="text-muted-foreground w-11 shrink-0 pt-0.5 font-mono text-xs">+ {format(new Date(run.createdAt), "HH:mm")}+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="truncate text-sm" title={name}>+ {name}+ </span>+ {detail && (+ <span+ className={cn(+ "text-xs",+ detail.problem+ ? "text-foreground-secondary"+ : "text-muted-foreground",+ )}+ >+ {detail.text}+ </span>+ )}+ </span>+ <span className="shrink-0">+ <StatusBadge type={executionBadgeTypes[run.status]} showText={false}>+ {executionLabels[run.status]}+ </StatusBadge>+ </span>+ </button>+ );+}++function Empty() {+ return (+ <CenteredState+ icon={<History size="lg" color="muted" />}+ title="No runs yet"+ body="Runs show up here as Topics processes your traces."+ />+ );+}++function LoadError({+ message,+ onRetry,+}: {+ message: string;+ onRetry: () => void;+}) {+ return (+ <CenteredState+ icon={<CircleAlert size="lg" color="destructive" />}+ title="Couldn’t load run history"+ body={message}+ >+ <Button+ text="Try again"+ variant="secondary"+ size="sm"+ onClick={onRetry}+ />+ </CenteredState>+ );+}++export function TopicRunHistoryList({+ executions,+ errorMessage,+ onOpen,+ onRetry,+}: TopicRunHistoryListProps) {+ if (errorMessage && executions.length === 0) {+ return <LoadError message={errorMessage} onRetry={onRetry} />;+ }+ if (executions.length === 0) return <Empty />;+ const runs = [...executions].sort(+ (a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt),+ );+ const active = runs.find((run) => run.status === "running") ?? null;+ const past = runs.filter((run) => run !== active);+ return (+ <div className="flex flex-col">+ {errorMessage && (+ <div className="px-4 pt-4">+ <TopicsErrorMessage message={errorMessage} />+ </div>+ )}+ {active && <ActiveRun run={active} onOpen={onOpen} />}+ {groupByDay(past).map((group) => (+ <section key={group.runs[0].id} className="px-2 pt-2.5 pb-1">+ <h3 className="text-muted-foreground px-2 text-xs font-bold">+ {group.label}+ </h3>+ {group.runs.map((run) => (+ <RunRow key={run.id} run={run} onOpen={onOpen} />+ ))}+ </section>+ ))}+ </div>+ );+}diff --git a/web/src/features/topics/TopicsErrorMessage.tsx b/web/src/features/topics/TopicsErrorMessage.tsxnew file mode 100644index 0000000000..6ebe20b8bc--- /dev/null+++ b/web/src/features/topics/TopicsErrorMessage.tsx@@ -0,0 +1,15 @@+import { Alert } from "@/src/components/design-system/Alert/Alert";++export function TopicsErrorMessage({ message }: TopicsErrorMessageProps) {+ return (+ <Alert variant="destructive">+ <Alert.Description>+ <p className="break-words">{message}</p>+ </Alert.Description>+ </Alert>+ );+}++type TopicsErrorMessageProps = {+ message: string;+};diff --git a/web/src/features/topics/TopicsPage.clienttest.tsx b/web/src/features/topics/TopicsPage.clienttest.tsxindex 501d8cc66a..eabb7d7f16 100644--- a/web/src/features/topics/TopicsPage.clienttest.tsx+++ b/web/src/features/topics/TopicsPage.clienttest.tsx@@ -543,10 +543,8 @@ it.each([it("refreshes current results through retry and completion for a selected run outside history", () => {state.executionId = "execution";const view = render(<TopicsPage />);- const status = screen.getByRole("dialog", { name: "Run status" });- fireEvent.click(- within(status).getByRole("button", { name: "Resume interrupted stages" }),- );+ const status = screen.getByRole("dialog", { name: "Analyze traces" });+ fireEvent.click(within(status).getByRole("button", { name: "Resume run" }));expect(state.retry).toHaveBeenCalledWith({projectId: "project",executionId: "execution",diff --git a/web/src/features/topics/TopicsPage.tsx b/web/src/features/topics/TopicsPage.tsxindex 971e71ddcf..35a10909e9 100644--- a/web/src/features/topics/TopicsPage.tsx+++ b/web/src/features/topics/TopicsPage.tsx@@ -1,10 +1,10 @@/* eslint-disable react/no-unstable-nested-components, @typescript-eslint/no-use-before-define */import { 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";import { TablePeekViewTraceDetail } from "@/src/components/table/peek/TablePeekViewTraceDetail";import { useRouter } from "next/router";-import { TextLink } from "@/src/components/design-system/TextLink/TextLink";import Page from "@/src/components/layouts/Page";import { PageHeaderControlsPortal } from "@/src/components/layouts/page-header-controls-slot";import { TimeRangePicker } from "@/src/components/date-picker";@@ -16,26 +16,17 @@ import {type TimeRange,} from "@/src/utils/date-range-utils";import { ErrorPage } from "@/src/components/error-page";-import { Button } from "@/src/components/design-system/Button/Button";-import { Button as PopoverButton } from "@/src/components/ui/button";-import { Alert } from "@/src/components/design-system/Alert/Alert";import {Sheet,SheetContent,SheetHeader,SheetTitle,- SheetDescription,} from "@/src/components/ui/sheet";-import { PopoverController } from "@/src/components/ui/popover";-import { Badge } from "@/src/components/design-system/Badge/Badge";import { api, type RouterOutputs } from "@/src/utils/api";-import { costFormatter } from "@/src/utils/numbers";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { useCanViewTopics } from "@/src/features/topics/topicsAccess";import {type TopicFacet,- type TopicExecutionStatus,- type TopicFacetOutcome,type TopicOperation,type TopicTimeRange,} from "@langfuse/shared/topics";@@ -52,6 +43,7 @@ import {useTopicsResultsView,} from "./TopicsResultsViewSelect";import { DialogController } from "@/src/components/design-system/DialogController/DialogController";+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";import { useRegenerateTopics } from "./useRegenerateTopics";import { useTopicModelSettings } from "./TopicModelSettings";import { AutomaticProcessingDialogController } from "./AutomaticProcessingDialogController";@@ -66,6 +58,10 @@ import { prepareTopicsActions } from "./prepare-topics-actions";import { TopicsWorkspaceGate } from "./TopicsWorkspaceGate";import { isValidTopicTimeRange } from "./time-range";import { useTopicTraceFilters } from "./useTopicTraceFilters";+import { TopicRunDetails } from "./TopicRunDetails";+import { TopicRunHistoryList } from "./TopicRunHistoryList";+import { TopicsErrorMessage } from "./TopicsErrorMessage";+import { busy, operationLabels } from "./topic-run-labels";const maxTimeRangeMs = TIME_RANGES.last90Days.minutes * 60_000;const sharedTimeRangePresets = [@@ -75,36 +71,6 @@ const topicsTimeRangePresets = sharedTimeRangePresets.filter((range) => TIME_RANGES[range].minutes * 60_000 <= maxTimeRangeMs,);-const operationLabels: Record<TopicOperation, string> = {- process: "Process traces",- update: "Update topics",-};-const busy = (status: string) => status === "queued" || status === "running";-const executionLabels: Record<TopicExecutionStatus, string> = {- queued: "Run queued",- running: "Run in progress",- completed: "Run complete",- completed_with_errors: "Run finished with issues",- failed: "Run failed",-};-const executionPhaseLabels: Record<string, string> = {- queued: "Waiting for a worker",- summarizing: "Preparing summaries and embeddings",- clustering: "Clustering summaries",- naming: "Naming topics",- assigning: "Assigning traces to topics",- processing: "Processing facets",-};-const facetOutcomeLabels: Record<TopicFacetOutcome, string> = {- pending: "Waiting for results",- published: "Topics ready",- assigned: "Traces assigned",- awaiting_topics: "Awaiting topics",- insufficient_data: "More traces needed",- no_applicable_summaries: "No applicable traces",- no_topics: "No topics found",- failed: "Facet failed",-};const loadingPage = (<Page headerProps={{ title: "Topics" }}><Spinner message="Loading topics" />@@ -313,10 +279,16 @@ function TopicsWorkspaceContent({{ projectId, executionId: executionId ?? "" },{enabled: executionId !== null,+ // The list already has this run, so the panel renders without a loading flash.+ placeholderData: () =>+ executions.data?.find((execution) => execution.id === executionId),refetchInterval: (query) =>!query.state.data || busy(query.state.data.status) ? 1500 : false,},);+ const selectedRunTitle = selectedExecution.data+ ? operationLabels[selectedExecution.data.input.operation]+ : "Run";const completedAt = Math.max(0,...[...(executions.data ?? []), selectedExecution.data].flatMap(@@ -384,7 +356,6 @@ function TopicsWorkspaceContent({utils.topics.currentResults.invalidate({ projectId });};const openExecution = (id: string) => {- setHistoryOpen(false);router.push({pathname: router.pathname,@@ -572,7 +543,7 @@ function TopicsWorkspaceContent({</p>)}{!validTimeRange && (- <ErrorMessage message="Select a time range of at most 90 days." />+ <TopicsErrorMessage message="Select a time range of at most 90 days." />)}<TopicSetupNoticenotice={modelSettings.notice}@@ -633,77 +604,37 @@ function TopicsWorkspaceContent({open={historyOpen || executionId !== null}onOpenChange={showExecutionList}>- <SheetContent className="ph-no-capture flex w-full flex-col gap-4 sm:max-w-xl">- <SheetHeader>- <SheetTitle>- {executionId ? "Run status" : "Past executions"}+ <SheetContent+ className="ph-no-capture flex w-full flex-col gap-0 p-0 sm:max-w-lg"+ aria-describedby={undefined}+ >+ {executionId ? (+ <SheetTitle className="sr-only">+ {selectedRunTitle}</SheetTitle>- <SheetDescription>- Review progress, costs, errors, and retry interrupted- runs.- </SheetDescription>- </SheetHeader>- <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto">+ ) : (+ <SheetHeader className="border-b px-5 py-4">+ <SheetTitle>Run history</SheetTitle>+ </SheetHeader>+ )}+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">{executionId ? (- <>- <div className="self-start">- <Button- text="All runs"- variant="ghost"- size="sm"- onClick={() => showExecutionList(true)}- />- </div>- <ExecutionPanel- key={executionId}- projectId={projectId}- executionId={executionId}- query={selectedExecution}- facets={facets.data ?? []}- canWrite={canWrite}- />- </>+ <ExecutionPanel+ key={executionId}+ projectId={projectId}+ executionId={executionId}+ query={selectedExecution}+ facets={facets.data ?? []}+ canWrite={canWrite}+ onBack={() => showExecutionList(true)}+ />) : (- <>- <div className="self-end">- <Button- text="Refresh"- size="sm"- variant="ghost"- onClick={() => executions.refetch()}- />- </div>- {executions.error && (- <ErrorMessage message={executions.error.message} />- )}- {!executions.data?.length && (- <p className="text-muted-foreground text-sm">- Your triggered batches will appear here.- </p>- )}- {executions.data?.map((execution) => (- <button- key={execution.id}- onClick={() => openExecution(execution.id)}- className="hover:bg-muted/50 flex flex-wrap items-center justify-between gap-2 rounded-md border p-3 text-left text-sm"- >- <span className="capitalize">- {operationLabels[execution.input.operation]} ·{" "}- {new Date(execution.createdAt).toLocaleString()}- </span>- <span>{execution.facets.length} facets</span>- <Badge text={executionLabels[execution.status]} />- {execution.input.operation === "process" && (- <span className="text-muted-foreground w-full tabular-nums">- Estimated cost:{" "}- {estimatedExecutionCost(- execution.estimatedCost,- )}- </span>- )}- </button>- ))}- </>+ <TopicRunHistoryList+ executions={executions.data ?? []}+ errorMessage={executions.error?.message}+ onOpen={openExecution}+ onRetry={() => executions.refetch()}+ />)}</div></SheetContent>@@ -739,7 +670,7 @@ function TopicsWorkspaceContent({)}{facets.isLoading && <p>Loading facets…</p>}{facets.error && (- <ErrorMessage message={facets.error.message} />+ <TopicsErrorMessage message={facets.error.message} />)}</div></div>@@ -756,6 +687,7 @@ function ExecutionPanel({query,facets,canWrite,+ onBack,}: {projectId: string;executionId: string;@@ -765,6 +697,7 @@ function ExecutionPanel({>;facets: TopicFacet[];canWrite: boolean;+ onBack: () => void;}) {const utils = api.useUtils();const retry = api.topics.retry.useMutation({@@ -774,271 +707,61 @@ function ExecutionPanel({utils.topics.executions.invalidate({ projectId }),]),});- const [traceErrorsOpen, setTraceErrorsOpen] = useState(false);+ // Trace errors start expanded for failed runs until the user toggles them.+ const [traceErrorsToggled, setTraceErrorsToggled] = useState<boolean | null>(+ null,+ );+ const execution = query.data;+ const traceErrorsOpen =+ traceErrorsToggled ??+ (execution?.status === "failed" &&+ execution.facets.some((facet) => facet.counts.failed > 0));const traceErrors = api.topics.traceErrors.useQuery({ projectId, executionId },{ enabled: traceErrorsOpen },);- const execution = query.data;- if (query.error) return <ErrorMessage message={query.error.message} />;- if (!execution) return <p>Loading execution…</p>;- const isUpdate = execution.input.operation === "update";- const selectionDescription = isUpdate- ? `${execution.facets.reduce((count, facet) => count + facet.counts.requested, 0).toLocaleString()} stored facet summaries`- : `${Math.max(0, ...execution.facets.map((facet) => facet.counts.requested)).toLocaleString()} selected traces`;- const facetCount = execution.facets.length;- const operationLabel = operationLabels[execution.input.operation];- const modeLabel = (() => {- if (execution.input.operation !== "update")- return "Assign to current topics";- return execution.input.exploratory ? "Small sample" : "Standard";- })();- const selectionPrefix = (() => {- if (execution.status === "running") return "Running on ";- if (execution.status === "queued") return "Queued for ";- return "Run selection: ";- })();- return (- <section className="flex w-full min-w-0 flex-col gap-4">- <div className="flex flex-wrap items-center justify-between gap-3">- <div className="flex flex-wrap items-center gap-3">- <Badge text={executionLabels[execution.status]} />- {execution.input.operation === "update" &&- execution.input.exploratory && (- <Badge text="Small sample · provisional" />- )}- </div>- <PopoverController- align="end"- contentClassName="w-80 max-w-[calc(100vw-2rem)]"- disabled={false}- modal={false}- renderContent={() => (- <div className="ph-no-capture flex flex-col gap-3 text-sm">- <h3 className="font-bold">Run details</h3>- <dl className="grid grid-cols-2 gap-x-4 gap-y-2">- <dt className="text-muted-foreground">Triggered</dt>- <dd>{new Date(execution.createdAt).toLocaleString()}</dd>- <dt className="text-muted-foreground">Operation</dt>- <dd>{operationLabel}</dd>- <dt className="text-muted-foreground">Mode</dt>- <dd>{modeLabel}</dd>- <dt className="text-muted-foreground">Last step</dt>- <dd className="capitalize">- {execution.phase.replaceAll("_", " ")}- </dd>- <dt className="text-muted-foreground">Embedding dimensions</dt>- <dd>{execution.input.embeddingConfig.embeddingDimensions}</dd>- {execution.input.operation === "update" && (- <>- <dt className="text-muted-foreground">- Minimum traces for clustering- </dt>- <dd>- {execution.input.minimumTraceCount ??- (execution.input.exploratory ? 10 : 100)}- </dd>- </>- )}- </dl>- </div>- )}- >- {({ Trigger }) => (- <Trigger asChild>- <PopoverButton variant="ghost" size="sm">- Run details- </PopoverButton>- </Trigger>- )}- </PopoverController>- </div>- <div- className="flex flex-col gap-1"- role={busy(execution.status) ? "status" : undefined}- >- <p className="text-sm">- {operationLabel} · {selectionPrefix}- {selectionDescription} across {facetCount.toLocaleString()}{" "}- {facetCount === 1 ? "facet" : "facets"}.- </p>- {busy(execution.status) && (- <p className="text-muted-foreground text-sm">- {executionPhaseLabels[execution.phase] ??- execution.phase.replaceAll("_", " ")}- . Counts update after each processing batch. You can leave this page- and reopen the run.- </p>- )}- </div>- {!isUpdate && (- <section className="flex flex-col gap-2 rounded-md border p-3 text-sm">- <p className="flex items-center justify-between gap-3">- <span className="font-bold">Estimated cost</span>- <span className="tabular-nums">- {estimatedExecutionCost(execution.estimatedCost)}- </span>- </p>- <p className="text-muted-foreground text-xs">- Estimated cost for this run’s currently stored summaries and- embeddings. Costs may decrease when summaries are reused,- reprocessed, or deleted.- </p>- </section>- )}- {execution.error && <ErrorMessage message={execution.error} />}- {execution.facets.some((facet) => facet.counts.failed > 0) && (- <details- className="ph-no-capture text-sm"- onToggle={(event) => setTraceErrorsOpen(event.currentTarget.open)}- >- <summary className="cursor-pointer">Trace errors</summary>- {traceErrorsOpen && (- <div className="flex flex-col gap-2 pt-2">- {traceErrors.isPending && <p>Loading trace errors…</p>}- {traceErrors.error && (- <ErrorMessage message={traceErrors.error.message} />- )}- {traceErrors.data?.expired && (- <p>- Trace error details have expired. The run counts are still- available.- </p>- )}- {traceErrors.data?.errors.map((item) => (- <p- key={`${item.traceId}:${item.error}`}- className="break-words"- >- <TextLink- path={`/project/${projectId}/traces/${encodeURIComponent(item.traceId)}`}- value={item.traceId}- />- : {item.error}- </p>- ))}- {traceErrors.data &&- !traceErrors.data.expired &&- traceErrors.data.errors.length === 0 && (- <p>No trace-level errors were recorded.</p>- )}- </div>- )}- </details>- )}- {canWrite &&- !busy(execution.status) &&- (execution.status === "failed" ||- (execution.status === "completed_with_errors" &&- execution.facets.some(- (facet) =>- facet.outcome === "pending" || facet.outcome === "failed",- ))) && (- <div className="self-start">- <Button- text="Resume interrupted stages"- disabled={retry.isPending}- onClick={() => retry.mutate({ projectId, executionId })}- />- </div>- )}- {retry.error && <ErrorMessage message={retry.error.message} />}- {execution.facets.map((progress) => {- const facet = facets.find((item) => item.id === progress.facetId);- return (- <div- key={`${progress.facetId}:${progress.facetVersion}`}- className="flex flex-col gap-3 border-t pt-4"- >- <div className="flex flex-wrap items-center gap-2">- <h3 className="font-bold">{facet?.name ?? "Facet"}</h3>- <Badge text={facetOutcomeLabels[progress.outcome]} />- </div>- <p className="text-muted-foreground text-sm">- {[- `${progress.counts.complete.toLocaleString()} / ${progress.counts.requested.toLocaleString()} traces have summaries and embeddings ready`,- ...(progress.runId- ? [- `${progress.counts.assigned.toLocaleString()} assigned`,- `${progress.counts.outlier.toLocaleString()} outliers`,- ]- : []),- ...(progress.counts.nonApplicable- ? [- `${progress.counts.nonApplicable.toLocaleString()} not applicable`,- ]- : []),- ...(progress.counts.insufficientInput- ? [- `${progress.counts.insufficientInput.toLocaleString()} insufficient input`,- ]- : []),- `${progress.counts.failed.toLocaleString()} failed`,- ].join(" · ")}- </p>- {progress.outcome === "awaiting_topics" && (- <p className="text-sm">- {progress.counts.complete.toLocaleString()} summaries are ready.- Run Update topics to create topics for this facet and embedding- configuration.- </p>- )}- {progress.error &&- (progress.outcome === "published" ? (- <Alert variant="warning">- <Alert.Description>{progress.error}</Alert.Description>- </Alert>- ) : (- <ErrorMessage message={progress.error} />- ))}- {progress.outcome === "insufficient_data" &&- execution.input.operation === "update" && (- <p className="text-sm">- Clustering needs at least{" "}- {execution.input.minimumTraceCount ??- (execution.input.exploratory ? 10 : 100)}{" "}- compatible stored summaries for this facet. Process more- traces or lower the minimum when starting a new update.- </p>- )}- {progress.outcome === "no_topics" && (- <p className="text-sm">- No stable groups found. Inspect the summaries, adjust the facet,- or try a larger and more varied batch.- </p>- )}- </div>- );- })}- {!busy(execution.status) && (- <div className="self-start">- <Button- text="Refresh status"+ if (query.error || !execution) {+ return (+ <>+ <header className="flex items-center border-b py-3.5 pr-12 pl-3">+ <IconButton+ icon={ChevronLeft}+ label="All runs"variant="ghost"- onClick={() => {- query.refetch();- utils.topics.currentResults.invalidate({ projectId });- utils.topics.executions.invalidate({ projectId });- utils.topics.summaryCounts.invalidate({ projectId });- }}+ size="sm"+ onClick={onBack}/>- </div>- )}- </section>- );-}--function estimatedExecutionCost(cost: number | null) {- return cost != null ? `~${costFormatter(cost)}` : "Unavailable";-}--function ErrorMessage({ message }: { message: string }) {+ </header>+ {query.error ? (+ <div className="p-4">+ <TopicsErrorMessage message={query.error.message} />+ </div>+ ) : (+ <p className="p-4 text-sm">Loading execution…</p>+ )}+ </>+ );+ }return (- <Alert variant="destructive">- <Alert.Description>- <p className="break-words">{message}</p>- </Alert.Description>- </Alert>+ <TopicRunDetails+ execution={execution}+ facets={facets}+ projectId={projectId}+ canWrite={canWrite}+ traceErrors={{+ open: traceErrorsOpen,+ onOpenChange: setTraceErrorsToggled,+ isPending: traceErrors.isPending,+ errorMessage: traceErrors.error?.message,+ data: traceErrors.data,+ }}+ retry={{+ isPending: retry.isPending,+ errorMessage: retry.error?.message,+ onRetry: () => retry.mutate({ projectId, executionId }),+ }}+ onBack={onBack}+ />);}diff --git a/web/src/features/topics/topic-run-labels.ts b/web/src/features/topics/topic-run-labels.tsnew file mode 100644index 0000000000..126ba961a7--- /dev/null+++ b/web/src/features/topics/topic-run-labels.ts@@ -0,0 +1,30 @@+import { type Status } from "@/src/components/ui/StatusBadge/StatusBadge";+import {+ type TopicExecutionStatus,+ type TopicOperation,+} from "@langfuse/shared/topics";++export const operationLabels: Record<TopicOperation, string> = {+ process: "Analyze traces",+ update: "Regenerate topics",+};++export const executionLabels: Record<TopicExecutionStatus, string> = {+ queued: "Queued",+ running: "Running",+ completed: "Complete",+ completed_with_errors: "Done with issues",+ failed: "Failed",+};++/** StatusBadge types, so run statuses share the app-wide status colours. */+export const executionBadgeTypes: Record<TopicExecutionStatus, Status> = {+ queued: "queued",+ running: "running",+ completed: "completed",+ completed_with_errors: "partial",+ failed: "failed",+};++export const busy = (status: string) =>+ status === "queued" || status === "running";