Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(scores): add chart view for the scores table (#16211)

Tobias Wochinger1fd9346ea6db
diff --git a/packages/shared/src/features/query/dataModel.ts b/packages/shared/src/features/query/dataModel.ts
index c095590d6b..232dacd55b 100644
--- a/packages/shared/src/features/query/dataModel.ts
+++ b/packages/shared/src/features/query/dataModel.ts
@@ -4,6 +4,7 @@ import {
type ViewDeclarationType,
type DimensionsDeclarationType,
type views,
+ SCORES_LISTABLE_COUNT_VIEW,
} from "./types";
import { InvalidRequestError } from "../../errors";
import {
@@ -11,6 +12,7 @@ import {
eventsTableTraceNameAggregationSqlForAlias,
eventsTableTraceNameSqlForAlias,
} from "../../eventsTable";
+import { LISTABLE_SCORE_TYPES } from "../../domain/scores";
// The data model defines all available dimensions, measures, and the timeDimension for a given view.
// Make sure to update web/src/features/dashboard/lib/dashboardUiTableToViewMapping.ts if you make changes
@@ -1101,6 +1103,58 @@ export const scoresBooleanViewV2: ViewDeclarationType =
export const scoresCategoricalViewV2: ViewDeclarationType =
scoresCategoricalViewBase("v2");
+/**
+ * Count-only view scoped to every listable score type (see
+ * `LISTABLE_SCORE_TYPES`), unlike `scores-numeric`/`scores-categorical`
+ * which each cover only a subset. Powers `ScoresOutlierStrip`'s "Count"
+ * mode; deliberately has no `value` measure, since categorical/text rows
+ * carry no real numeric value β€” "Value" mode stays a separate query against
+ * the unchanged `scores-numeric` view instead.
+ */
+function scoresListableCountViewBase(
+ version: "v1" | "v2",
+): ViewDeclarationType {
+ const baseDimensions =
+ version === "v1" ? scoreBaseDimensions : scoresV2BaseDimensions;
+ return {
+ name: "scores_listable_count",
+ description:
+ "Internal-only, count-only view scoping to every listable score type. Powers the scores overview strip's Count mode; not part of the public views enum.",
+ dimensions: {
+ ...baseDimensions,
+ ...createScoreSpecificDimensions(
+ "scores_listable_count",
+ version === "v2",
+ ),
+ },
+ measures: {
+ count: {
+ sql: "count(*)",
+ alias: "count",
+ type: "integer",
+ description: "Total number of scores across every listable score type.",
+ unit: "scores",
+ },
+ },
+ tableRelations: createScoreTableRelations(version),
+ segments: [
+ {
+ column: "data_type",
+ operator: "any of" as const,
+ value: [...LISTABLE_SCORE_TYPES],
+ type: "stringOptions" as const,
+ },
+ ],
+ timeDimension: "timestamp",
+ baseCte: `scores scores_listable_count FINAL`,
+ };
+}
+
+export const scoresListableCountView: ViewDeclarationType =
+ scoresListableCountViewBase("v1");
+export const scoresListableCountViewV2: ViewDeclarationType =
+ scoresListableCountViewBase("v2");
+
// Events-Observations View - queries from events table instead of observations table
export const eventsObservationsView: ViewDeclarationType = {
name: "events_observations",
@@ -1515,10 +1569,22 @@ export const viewDeclarations: VersionedViewDeclarations = {
} as const;
// Helper function for view resolution
+const internalViewDeclarations: Record<ViewVersion, ViewDeclarationType> = {
+ v1: scoresListableCountView,
+ v2: scoresListableCountViewV2,
+};
+
export function getViewDeclaration(
- viewName: z.infer<typeof views>,
+ // Widened (not just `z.infer<typeof views>`) so the handful of
+ // server-only callers that know about `SCORES_LISTABLE_COUNT_VIEW` can
+ // resolve it too, without adding it to the public `views` enum.
+ viewName: z.infer<typeof views> | typeof SCORES_LISTABLE_COUNT_VIEW,
version: ViewVersion = "v1",
): ViewDeclarationType {
+ if (viewName === SCORES_LISTABLE_COUNT_VIEW) {
+ return internalViewDeclarations[version];
+ }
+
const versionViews = viewDeclarations[version];
// TypeScript knows the exact shape of each version now
diff --git a/packages/shared/src/features/query/server/queryBuilder.scoresListableCountView.test.ts b/packages/shared/src/features/query/server/queryBuilder.scoresListableCountView.test.ts
new file mode 100644
index 0000000000..333e5a61b1
--- /dev/null
+++ b/packages/shared/src/features/query/server/queryBuilder.scoresListableCountView.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { LISTABLE_SCORE_TYPES } from "../../../domain/scores";
+import { getViewDeclaration } from "../dataModel";
+import {
+ SCORES_LISTABLE_COUNT_VIEW,
+ views,
+ viewsV2,
+ type QueryType,
+} from "../types";
+import { QueryBuilder } from "./queryBuilder";
+
+// QueryBuilder.build checks the OTEL FINAL optimization before filter lowering.
+// Mock it so this stays unit-level and does not need ClickHouse.
+vi.mock("../../../server/queries/clickhouse-sql/query-options", () => ({
+ shouldSkipObservationsFinal: vi.fn().mockResolvedValue(false),
+}));
+
+const baseQuery = {
+ view: SCORES_LISTABLE_COUNT_VIEW,
+ dimensions: [],
+ metrics: [{ measure: "count", aggregation: "count" }],
+ filters: [],
+ timeDimension: { granularity: "hour" },
+ fromTimestamp: "2025-01-01T00:00:00.000Z",
+ toTimestamp: "2025-01-02T00:00:00.000Z",
+ orderBy: null,
+} as unknown as QueryType;
+
+describe("scores-listable-count view (internal-only, powers ScoresOutlierStrip's Count mode)", () => {
+ it("is not part of the public views enum", () => {
+ expect(views.options).not.toContain(SCORES_LISTABLE_COUNT_VIEW);
+ expect(viewsV2.options).not.toContain(SCORES_LISTABLE_COUNT_VIEW);
+ });
+
+ it("scopes its segment to every listable score type", () => {
+ const view = getViewDeclaration(SCORES_LISTABLE_COUNT_VIEW, "v1");
+ expect(view.segments).toEqual([
+ {
+ column: "data_type",
+ operator: "any of",
+ value: [...LISTABLE_SCORE_TYPES],
+ type: "stringOptions",
+ },
+ ]);
+ // CORRECTION scores are intentionally excluded β€” they aren't a listable type.
+ expect(view.segments[0]?.value).not.toContain("CORRECTION");
+ });
+
+ it("exposes only a count measure β€” no value measure, on purpose", () => {
+ const view = getViewDeclaration(SCORES_LISTABLE_COUNT_VIEW, "v1");
+ expect(Object.keys(view.measures)).toEqual(["count"]);
+ });
+
+ it("compiles a query whose count(*) is unguarded (covers every listable type)", async () => {
+ const { query: compiledQuery, parameters } = await new QueryBuilder(
+ undefined,
+ "v1",
+ ).build(baseQuery, "test-project");
+
+ expect(compiledQuery).toContain("count(*)");
+ expect(compiledQuery).toContain("scores_listable_count.data_type IN");
+ // The segment's data_type allow-list is a bound parameter, not inlined SQL.
+ const dataTypeParam = Object.values(parameters).find(
+ (value) =>
+ Array.isArray(value) &&
+ LISTABLE_SCORE_TYPES.every((t) => value.includes(t)),
+ );
+ expect(dataTypeParam).toEqual([...LISTABLE_SCORE_TYPES]);
+ expect(dataTypeParam).not.toContain("CORRECTION");
+ });
+});
diff --git a/packages/shared/src/features/query/server/queryBuilder.ts b/packages/shared/src/features/query/server/queryBuilder.ts
index 61b548833c..cf07b95a24 100644
--- a/packages/shared/src/features/query/server/queryBuilder.ts
+++ b/packages/shared/src/features/query/server/queryBuilder.ts
@@ -19,6 +19,7 @@ import type {
import {
query as queryModel,
getValidAggregationsForMeasureType,
+ SCORES_LISTABLE_COUNT_VIEW,
} from "../types";
import { getViewDeclaration } from "../dataModel";
import { InvalidRequestError } from "../../../errors";
@@ -178,7 +179,7 @@ export class QueryBuilder {
}
private getViewDeclaration(
- viewName: z.infer<typeof views>,
+ viewName: z.infer<typeof views> | typeof SCORES_LISTABLE_COUNT_VIEW,
): ViewDeclarationType {
return getViewDeclaration(viewName, this.version);
}
diff --git a/packages/shared/src/features/query/types.ts b/packages/shared/src/features/query/types.ts
index a169f82b5b..30a8e454ba 100644
--- a/packages/shared/src/features/query/types.ts
+++ b/packages/shared/src/features/query/types.ts
@@ -129,6 +129,14 @@ export const viewsV2 = z.enum([
"scores-boolean",
]);
+/**
+ * Internal-only view name (see `dataModel.ts`), deliberately NOT a member of
+ * `views`/`viewsV2` β€” those are iterated by the public metrics API and the
+ * widget-builder view picker, and this powers only one internal call site.
+ * Unioned onto the internal `query` schema below instead.
+ */
+export const SCORES_LISTABLE_COUNT_VIEW = "scores-listable-count" as const;
+
/**
* Persisted dashboard-widget view ids β†’ query view ids. Lives here (not with
* the server-only DashboardService types) so client code can classify a stored
@@ -196,7 +204,11 @@ export type QueryType = z.infer<typeof query>;
export const query = z
.object({
- view: views,
+ // See `SCORES_LISTABLE_COUNT_VIEW`'s doc comment: unioned on here (the
+ // internal query schema) rather than added to `views` itself, so it
+ // stays out of the public metrics API and the widget-builder view
+ // picker, both of which read `views`/`viewsV2` directly.
+ view: z.union([views, z.literal(SCORES_LISTABLE_COUNT_VIEW)]),
dimensions: z.array(dimension),
metrics: z.array(metric),
filters: z.array(singleFilter),
diff --git a/packages/shared/src/server/clickhouse/schema.ts b/packages/shared/src/server/clickhouse/schema.ts
index f3a40ee798..b70a2a4b40 100644
--- a/packages/shared/src/server/clickhouse/schema.ts
+++ b/packages/shared/src/server/clickhouse/schema.ts
@@ -16,6 +16,10 @@ export const ClickhouseTableNames = {
scores_numeric: "scores_numeric",
scores_boolean: "scores_boolean",
scores_categorical: "scores_categorical",
+ // Internal-only, count-only view backing `ScoresOutlierStrip`'s Count mode
+ // (see `dataModel.ts`'s `SCORES_LISTABLE_COUNT_VIEW` doc comment) β€” scopes
+ // to every listable score type.
+ scores_listable_count: "scores_listable_count",
events_traces: "events_traces",
events_observations: "events_observations",
} as const;
diff --git a/web/src/components/table/table-link.tsx b/web/src/components/table/table-link.tsx
index 0ccf8930af..a52537a3a6 100644
--- a/web/src/components/table/table-link.tsx
+++ b/web/src/components/table/table-link.tsx
@@ -20,10 +20,19 @@ export default function TableLink({
title,
}: TableLinkProps) {
const handleClick = (event: React.MouseEvent) => {
- if (onClick) {
- event.preventDefault();
- onClick(event);
- }
+ if (!onClick) return;
+ // A modifier click (cmd/ctrl+click, shift+click) or a non-primary button
+ // (middle-click) is the browser's own "open in a new tab/window" gesture
+ // β€” let it through to the real anchor href instead of hijacking it (e.g. a
+ // peek-opening `onClick`), as long as there IS a real destination to open.
+ // `path=""` callers (e.g. folder breadcrumbs, which use `onClick` as their
+ // only action) have no real destination, so they keep the old
+ // always-intercept behavior.
+ const isModifiedClick =
+ event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0;
+ if (path && isModifiedClick) return;
+ event.preventDefault();
+ onClick(event);
};
return (
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 7cbb459e2a..5ec47ada95 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -1,3 +1,4 @@
+import { type ViewVersion } from "@langfuse/shared/query";
import { DataTable } from "@/src/components/table/data-table";
import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
@@ -20,6 +21,8 @@ import {
useSidebarFilterState,
} from "@/src/features/filters/hooks/useSidebarFilterState";
import { usePeekTableState } from "@/src/components/table/peek/contexts/PeekTableStateContext";
+import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
+import { TablePeekViewTraceDetail } from "@/src/components/table/peek/peek-trace-detail";
import {
getScoreFilterConfig,
observationScopeFilter,
@@ -40,6 +43,7 @@ import {
import { transformFiltersForBackend } from "@/src/features/filters/lib/filter-transform";
import { sortOptionValues } from "@/src/features/filters/lib/option-sort";
import { isNumericDataType } from "@/src/features/scores/lib/helpers";
+import { getScoreChartTimeRange } from "@/src/features/scores-chart-view/fns/scoreChartConfig";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import { useTableDateRange } from "@/src/hooks/useTableDateRange";
import { toAbsoluteTimeRange } from "@/src/utils/date-range-utils";
@@ -70,6 +74,12 @@ import {
scoreLevelFromScore,
type ScoreLevel,
} from "@/src/components/score-tag";
+import { ViewModeToggle } from "@/src/features/chart-view/components/ViewModeToggle";
+import {
+ ScoresChartView,
+ ScoresOutlierStrip,
+ useScoresChartViewState,
+} from "@/src/features/scores-chart-view";
export type ScoresTableRow = {
id: string;
@@ -162,6 +172,11 @@ export default function ScoresTable({
const { isBetaEnabled } = useV4Beta();
// In v4beta, scores must exclusively use events-backed endpoints (no traces-table route).
const useEventsBackedScores = isBetaEnabled;
+ // Same derivation `WidgetForm.tsx`/`ChartScores` use (`activeVersion`/
+ // `metricsVersion`) β€” the chart/outlier strip must read the same version
+ // as the table's own data, or a non-beta project's trace/observation
+ // breakdown would run against the events-backed view and come back empty.
+ const chartViewVersion: ViewVersion = isBetaEnabled ? "v2" : "v1";
const utils = api.useUtils();
const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});
const [paginationState, setPaginationState] = usePaginationState(0, 50, {
@@ -206,6 +221,62 @@ export default function ScoresTable({
const isTraceScoped = Boolean(traceId);
const rowDateRangeFilter: FilterState = isTraceScoped ? [] : dateRangeFilter;
+ // Open a score's trace/observation in the peek side panel instead of
+ // navigating away, mirroring the traces/observations tables. Not offered
+ // when this table is itself embedded in a trace/observation detail view
+ // (peeking the very trace you're already looking at would be redundant,
+ // and that embed already renders inside a peek panel of its own).
+ const peekEnabled = !traceId && !observationId;
+ const {
+ openPeek: openScorePeek,
+ closePeek: closeScorePeek,
+ expandPeek: expandScorePeek,
+ } = usePeekNavigation({
+ // A stale `traceId` can already be in the URL (e.g. a v4-dialect shared
+ // link); listing it clears it on open/navigate/close so it can't pin
+ // the peek to that trace instead of the one just clicked β€” matches the
+ // same guard `traces.tsx`/`EventsTable.tsx` already have.
+ queryParams: ["observation", "display", "timestamp", "traceId"],
+ extractParamsValuesFromRow: (
+ row: ScoresTableRow,
+ ): Record<string, string> =>
+ row.observationId ? { observation: row.observationId } : {},
+ expandConfig: {
+ basePath: `/project/${projectId}/traces`,
+ reader: "trace",
+ },
+ });
+
+ // The chart toggle only makes sense on the project-wide table β€” a
+ // trace/observation/user-scoped embed (trace detail, observation detail,
+ // user page) has too few scores to chart meaningfully and its filters don't
+ // fully map onto the scores-numeric view. Mirrors the same embed gate the
+ // events table uses for its chart view.
+ const chartEnabled = !traceId && !observationId && !userId;
+ const {
+ viewMode: chartViewMode,
+ setViewMode: setChartViewMode,
+ config: chartConfig,
+ setConfig: setChartConfig,
+ } = useScoresChartViewState();
+ // Charts only render when the table has a time range. Inventing a default
+ // range here would make the chart silently omit table rows.
+ const chartTimeRange = useMemo(
+ () => getScoreChartTimeRange(dateRange, new Date()),
+ [dateRange],
+ );
+ const chartActive =
+ chartEnabled && chartTimeRange !== undefined && chartViewMode === "chart";
+
+ // Drill-in from the outlier strip writes the clicked bucket as an absolute
+ // range. URL-only and deliberately NOT persisted as the project's default
+ // range β€” a transient zoom must not become tomorrow's baseline. Mirrors the
+ // events table's `setTimeRangeTransient`.
+ const { setTimeRange: setScoresTimeRangeTransient } = useTableDateRange(
+ projectId,
+ { persistAsDefault: false },
+ );
+
const environmentFilterOptions =
api.projects.environmentFilterOptions.useQuery(
{
@@ -428,24 +499,40 @@ export default function ScoresTable({
orderBy: orderByState,
};
+ // In chart mode the table is hidden and the chart runs its own aggregate
+ // query β€” don't also run the row/count/metrics fetches below, matching
+ // `EventsTable.tsx`'s `rowsEnabled: !chartActive`.
+
// Base data β€” v3 (existing, unchanged)
const scoresV3 = api.scores.all.useQuery(getAllPayload, {
- enabled: !environmentFilterOptions.isLoading && !useEventsBackedScores,
+ enabled:
+ !environmentFilterOptions.isLoading &&
+ !useEventsBackedScores &&
+ !chartActive,
});
// Base data β€” v4 (no traces JOIN)
const scoresV4 = api.scores.allFromEvents.useQuery(getAllPayload, {
- enabled: !environmentFilterOptions.isLoading && useEventsBackedScores,
+ enabled:
+ !environmentFilterOptions.isLoading &&
+ useEventsBackedScores &&
+ !chartActive,
});
const scores = useEventsBackedScores ? scoresV4 : scoresV3;
// Count β€” v3 vs v4
const countV3 = api.scores.countAll.useQuery(getCountPayload, {
- enabled: !environmentFilterOptions.isLoading && !useEventsBackedScores,
+ enabled:
+ !environmentFilterOptions.isLoading &&
+ !useEventsBackedScores &&
+ !chartActive,
});
const countV4 = api.scores.countAllFromEvents.useQuery(getCountPayload, {
- enabled: !environmentFilterOptions.isLoading && useEventsBackedScores,
+ enabled:
+ !environmentFilterOptions.isLoading &&
+ useEventsBackedScores &&
+ !chartActive,
});
const totalScoreCountQuery = useEventsBackedScores ? countV4 : countV3;
@@ -464,7 +551,8 @@ export default function ScoresTable({
],
},
{
- enabled: scoresV4.data !== undefined && useEventsBackedScores,
+ enabled:
+ scoresV4.data !== undefined && useEventsBackedScores && !chartActive,
},
);
@@ -692,6 +780,10 @@ export default function ScoresTable({
<TableLink
path={`/project/${projectId}/traces/${encodeURIComponent(value)}`}
value={value}
+ // Opens the trace in the peek side panel instead of navigating
+ // away; a modifier-click (cmd/ctrl, middle-click) still opens
+ // the real page in a new tab via the href above.
+ onClick={peekEnabled ? () => openScorePeek(value) : undefined}
/>
</>
) : undefined;
@@ -712,6 +804,14 @@ export default function ScoresTable({
<TableLink
path={`/project/${projectId}/traces/${encodeURIComponent(traceId)}?observation=${encodeURIComponent(observationId)}`}
value={observationId}
+ // extractParamsValuesFromRow reads `row.observationId` (the
+ // original, not the table row wrapper) to add `?observation=`
+ // to the peek URL, focusing this observation within the trace.
+ onClick={
+ peekEnabled
+ ? () => openScorePeek(traceId, row.original)
+ : undefined
+ }
/>
) : undefined;
},
@@ -1032,6 +1132,14 @@ export default function ScoresTable({
setTimeRange={
showControlsInPageHeader || isTraceScoped ? undefined : setTimeRange
}
+ viewModeToggle={
+ chartEnabled && chartTimeRange ? (
+ <ViewModeToggle
+ mode={chartViewMode}
+ onModeChange={setChartViewMode}
+ />
+ ) : undefined
+ }
multiSelect={{
selectAll,
setSelectAll,
@@ -1051,55 +1159,91 @@ export default function ScoresTable({
/>
<div className="flex flex-1 flex-col overflow-hidden">
- <DataTable
- tableName="scores"
- columns={columns}
- noResultsMessage={
- <div className="flex flex-col items-center">
- <span>No scores found.</span>
- <a
- href="https://langfuse.com/faq/all/what-are-scores"
- className="text-primary pointer-events-auto italic underline"
- target="_blank"
- rel="noopener noreferrer"
- >
- What are scores?
- </a>
- </div>
- }
- data={
- scores.isPending || isViewLoading
- ? { isLoading: true, isError: false }
- : scores.isError
- ? {
- isLoading: false,
- isError: true,
- error: scores.error.message,
- }
- : {
- isLoading: false,
- isError: false,
- data: enrichedScores ?? [],
- }
- }
- pagination={{
- totalCount,
- onChange: setPaginationState,
- state: paginationState,
- }}
- setOrderBy={setOrderByState}
- orderBy={orderByState}
- rowSelection={selectedRows}
- highlightAllRows={selectAll}
- setRowSelection={setSelectedRows}
- columnVisibility={columnVisibility}
- onColumnVisibilityChange={setColumnVisibility}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
- rowHeight={rowHeight}
- />
+ {/* `effectiveFilterState`, not `explicitFilterState`: the table's
+ own data query (`getAllPayload` above) reads `effectiveFilterState`,
+ which folds in the implicit environment filter (hides internal
+ eval/experiment environments by default). Using the explicit
+ state here would let the chart/strip aggregate scores the table
+ itself doesn't show. */}
+ {chartEnabled && chartTimeRange && !chartActive && (
+ <ScoresOutlierStrip
+ projectId={projectId}
+ filterState={queryFilter.effectiveFilterState}
+ fromTimestamp={chartTimeRange.from}
+ toTimestamp={chartTimeRange.to}
+ onSelectRange={setScoresTimeRangeTransient}
+ viewVersion={chartViewVersion}
+ />
+ )}
+ {chartActive && chartTimeRange ? (
+ <ScoresChartView
+ projectId={projectId}
+ filterState={queryFilter.effectiveFilterState}
+ fromTimestamp={chartTimeRange.from}
+ toTimestamp={chartTimeRange.to}
+ config={chartConfig}
+ viewVersion={chartViewVersion}
+ onConfigChange={setChartConfig}
+ />
+ ) : (
+ <DataTable
+ tableName="scores"
+ columns={columns}
+ noResultsMessage={
+ <div className="flex flex-col items-center">
+ <span>No scores found.</span>
+ <a
+ href="https://langfuse.com/faq/all/what-are-scores"
+ className="text-primary pointer-events-auto italic underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ What are scores?
+ </a>
+ </div>
+ }
+ data={
+ scores.isPending || isViewLoading
+ ? { isLoading: true, isError: false }
+ : scores.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: scores.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: enrichedScores ?? [],
+ }
+ }
+ pagination={{
+ totalCount,
+ onChange: setPaginationState,
+ state: paginationState,
+ }}
+ setOrderBy={setOrderByState}
+ orderBy={orderByState}
+ rowSelection={selectedRows}
+ highlightAllRows={selectAll}
+ setRowSelection={setSelectedRows}
+ columnVisibility={columnVisibility}
+ onColumnVisibilityChange={setColumnVisibility}
+ columnOrder={columnOrder}
+ onColumnOrderChange={setColumnOrder}
+ rowHeight={rowHeight}
+ />
+ )}
</div>
</ResizableFilterLayout>
+ {peekEnabled && (
+ <TablePeekViewTraceDetail
+ closePeek={closeScorePeek}
+ expandPeek={expandScorePeek}
+ itemType="TRACE"
+ projectId={projectId}
+ />
+ )}
</div>
</DataTableControlsProvider>
);
diff --git a/web/src/features/chart-view-prototype/components/ChartViewPrototype.tsx b/web/src/features/chart-view-prototype/components/ChartViewPrototype.tsx
index 17ea05fe9b..ef5ccafa7f 100644
--- a/web/src/features/chart-view-prototype/components/ChartViewPrototype.tsx
+++ b/web/src/features/chart-view-prototype/components/ChartViewPrototype.tsx
@@ -19,6 +19,7 @@ import {
coerceConfig,
DEFAULT_CONFIG,
describeConfig,
+ getMetric,
isTimeSeriesChartType,
} from "@/src/features/chart-view/vocab";
import {
@@ -189,7 +190,15 @@ function InlineTake({
{describeConfig(config)}
</div>
<div className="min-h-0 flex-1">
- <ChartCanvas data={data} config={config} />
+ <ChartCanvas
+ data={data}
+ chartType={config.chartType}
+ breakdown={config.breakdown}
+ aggregation={config.aggregation}
+ metricLabel={getMetric(config.metric).label}
+ metricUnit={getMetric(config.metric).unit}
+ emptyMessage="No events match the current filters."
+ />
</div>
</div>
</div>
diff --git a/web/src/features/chart-view/EventsChartView.tsx b/web/src/features/chart-view/EventsChartView.tsx
index 3085264c30..5c6a1979a8 100644
--- a/web/src/features/chart-view/EventsChartView.tsx
+++ b/web/src/features/chart-view/EventsChartView.tsx
@@ -3,6 +3,7 @@ import { type FilterState } from "@langfuse/shared";
import { api } from "@/src/utils/api";
import { type ChartViewConfig } from "./types";
import { buildChartQuery, rowsToDataPoints } from "./lib/buildChartQuery";
+import { chartConfigToWidgetInput } from "./lib/chartConfigToWidget";
import { toChartFilters } from "./lib/chartFilterCompatibility";
import { ChartViewPanel } from "./components/ChartViewPanel";
import { AddToDashboardButton } from "./components/AddToDashboardButton";
@@ -62,6 +63,11 @@ export function EventsChartView({
"Couldn't build a chart for the current view.")
: null;
+ const widgetInput = useMemo(
+ () => chartConfigToWidgetInput({ config, filters }),
+ [config, filters],
+ );
+
return (
<ChartViewPanel
config={config}
@@ -70,11 +76,7 @@ export function EventsChartView({
isLoading={validRange && queryResult.isPending && !queryResult.isError}
error={error}
chartActions={
- <AddToDashboardButton
- projectId={projectId}
- config={config}
- filters={filters}
- />
+ <AddToDashboardButton projectId={projectId} widgetInput={widgetInput} />
}
/>
);
diff --git a/web/src/features/chart-view/components/AddToDashboardButton.tsx b/web/src/features/chart-view/components/AddToDashboardButton.tsx
index 850ec2a0ec..269fef8146 100644
--- a/web/src/features/chart-view/components/AddToDashboardButton.tsx
+++ b/web/src/features/chart-view/components/AddToDashboardButton.tsx
@@ -1,31 +1,33 @@
import React, { useCallback, useState } from "react";
import { useRouter } from "next/router";
import { LayoutDashboard } from "lucide-react";
-import { type FilterState } from "@langfuse/shared";
import { Button } from "@/src/components/ui/button";
import { api } from "@/src/utils/api";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import { SelectDashboardDialog } from "@/src/features/dashboard/components/SelectDashboardDialog";
-import { type ChartViewConfig } from "../types";
-import { chartConfigToWidgetInput } from "../lib/chartConfigToWidget";
+import { type ChartWidgetInput } from "../lib/chartConfigToWidget";
/**
- * "Add to dashboard" β€” turns the in-view chart into a real dashboard widget by
- * REUSING the existing add-widget machinery, not duplicating it: map the chart
- * config to the `dashboardWidgets.create` input, pick a dashboard via the
- * existing `SelectDashboardDialog`, then hand off to the dashboard's own
- * `?addWidgetId=…` placement flow (same as the widget builder's save path).
- * Gated on `dashboards:CUD`, matching the server scope, so it never dead-ends.
+ * "Add to dashboard" β€” turns an in-view chart into a real dashboard widget by
+ * REUSING the existing add-widget machinery, not duplicating it: hand the
+ * already-built `dashboardWidgets.create` input to the mutation, pick a
+ * dashboard via the existing `SelectDashboardDialog`, then hand off to the
+ * dashboard's own `?addWidgetId=…` placement flow (same as the widget
+ * builder's save path). Gated on `dashboards:CUD`, matching the server scope,
+ * so it never dead-ends.
+ *
+ * Shared between the observations chart view (`EventsChartView`) and the
+ * scores chart view (`@/src/features/scores-chart-view`) β€” building
+ * `widgetInput` is the only domain-specific step (`chartConfigToWidgetInput`
+ * vs `scoreChartConfigToWidgetInput`); everything after that is identical.
*/
export const AddToDashboardButton = React.memo(function AddToDashboardButton({
projectId,
- config,
- filters,
+ widgetInput,
}: {
projectId: string;
- config: ChartViewConfig;
- filters: FilterState;
+ widgetInput: ChartWidgetInput;
}) {
const router = useRouter();
const [open, setOpen] = useState(false);
@@ -35,7 +37,7 @@ export const AddToDashboardButton = React.memo(function AddToDashboardButton({
const onSelectDashboard = useCallback(
(dashboardId: string) => {
createWidget.mutate(
- { projectId, ...chartConfigToWidgetInput({ config, filters }) },
+ { projectId, ...widgetInput },
{
onSuccess: async (data) => {
setOpen(false);
@@ -52,7 +54,7 @@ export const AddToDashboardButton = React.memo(function AddToDashboardButton({
},
);
},
- [createWidget, projectId, config, filters, router],
+ [createWidget, projectId, widgetInput, router],
);
if (!hasAccess) return null;
diff --git a/web/src/features/chart-view/components/ChartCanvas.tsx b/web/src/features/chart-view/components/ChartCanvas.tsx
index 64c3ff7668..589b071bdf 100644
--- a/web/src/features/chart-view/components/ChartCanvas.tsx
+++ b/web/src/features/chart-view/components/ChartCanvas.tsx
@@ -1,11 +1,12 @@
import React, { useMemo } from "react";
import { BarChart3 } from "lucide-react";
+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
import { Chart } from "@/src/features/widgets/chart-library/Chart";
import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";
import { getWidgetMissingBucketValue } from "@/src/features/widgets/utils";
import { type ChartConfig } from "@/src/components/ui/chart";
-import { type ChartViewConfig } from "../types";
-import { getMetric, isTimeSeriesChartType } from "../vocab";
+import { type AggregationFn } from "../types";
+import { isTimeSeriesChartType } from "../vocab";
const RANKED_ROW_LIMIT = 20;
@@ -30,23 +31,39 @@ function buildChartConfig(data: DataPoint[], metricLabel: string): ChartConfig {
/**
* View-only chart renderer: takes already-aggregated `DataPoint[]` (from the
- * server query, or the mock aggregator in Storybook) plus the config, and hands
- * them to the shared `chart-library`. Memoized so a parent re-render or an
- * unrelated config change doesn't re-render the chart.
+ * server query, or the mock aggregator in Storybook) plus the resolved metric
+ * label/unit and the handful of config fields that affect rendering, and
+ * hands them to the shared `chart-library`. Memoized so a parent re-render or
+ * an unrelated config change doesn't re-render the chart.
+ *
+ * Shared between the observations chart view (`EventsChartView`) and the
+ * scores chart view (`@/src/features/scores-chart-view`) β€” the two configs
+ * pick metrics/dimensions from entirely different vocabularies, but once a
+ * metric is resolved to a label/unit, the actual rendering is identical.
+ * Deliberately takes primitives instead of a `ChartViewConfig`/
+ * `ScoreChartViewConfig`, so this component has no dependency on either.
*/
export const ChartCanvas = React.memo(function ChartCanvas({
data,
- config,
- emptyMessage = "No events match the current filters.",
+ chartType,
+ breakdown,
+ aggregation,
+ metricLabel,
+ metricUnit,
+ emptyMessage,
}: {
data: DataPoint[];
- config: ChartViewConfig;
- emptyMessage?: string;
+ chartType: DashboardWidgetChartType;
+ /** The config's breakdown dimension key; only ever compared to `"none"`. */
+ breakdown: string;
+ aggregation: AggregationFn;
+ metricLabel: string;
+ metricUnit?: string;
+ emptyMessage: string;
}) {
- const metric = getMetric(config.metric);
const chartConfig = useMemo(
- () => buildChartConfig(data, metric.label),
- [data, metric.label],
+ () => buildChartConfig(data, metricLabel),
+ [data, metricLabel],
);
if (data.length === 0) {
@@ -61,22 +78,22 @@ export const ChartCanvas = React.memo(function ChartCanvas({
// Show the series legend only for a multi-series time chart. The shared
// chart-library renders the legend below the plot now (LFE-10576), so "below"
// is the value that used to be "above" here.
- const isTimeSeries = isTimeSeriesChartType(config.chartType);
+ const isTimeSeries = isTimeSeriesChartType(chartType);
const legendPosition =
- isTimeSeries && config.breakdown !== "none" ? "below" : "none";
+ isTimeSeries && breakdown !== "none" ? "below" : "none";
return (
<Chart
- chartType={config.chartType}
+ chartType={chartType}
data={data}
rowLimit={RANKED_ROW_LIMIT}
- chartConfig={{ type: config.chartType, unit: metric.unit }}
+ chartConfig={{ type: chartType, unit: metricUnit }}
config={chartConfig}
legendPosition={legendPosition}
// Match dashboard widgets: additive metrics (count/sum) fill an empty
// bucket with a 0 (continuous line), non-additive ones leave a gap β€” so a
// chart renders the same here as once saved to a dashboard.
- missingValue={getWidgetMissingBucketValue(config.aggregation)}
+ missingValue={getWidgetMissingBucketValue(aggregation)}
/>
);
});
diff --git a/web/src/features/chart-view/components/ChartViewPanel.tsx b/web/src/features/chart-view/components/ChartViewPanel.tsx
index ac3a820483..23390d253a 100644
--- a/web/src/features/chart-view/components/ChartViewPanel.tsx
+++ b/web/src/features/chart-view/components/ChartViewPanel.tsx
@@ -11,7 +11,7 @@ import {
type DimensionKey,
type MetricKey,
} from "../types";
-import { describeConfig } from "../vocab";
+import { describeConfig, getMetric } from "../vocab";
import { ChartCanvas } from "./ChartCanvas";
import {
AggregationSelect,
@@ -54,6 +54,7 @@ export const ChartViewPanel = React.memo(function ChartViewPanel({
className?: string;
}) {
const [open, setOpen] = useState(true);
+ const metric = getMetric(config.metric);
const onMetric = useCallback(
(metric: MetricKey) => onConfigChange({ metric }),
@@ -100,8 +101,14 @@ export const ChartViewPanel = React.memo(function ChartViewPanel({
) : (
<ChartCanvas
data={data}
- config={config}
- emptyMessage={emptyMessage}
+ chartType={config.chartType}
+ breakdown={config.breakdown}
+ aggregation={config.aggregation}
+ metricLabel={metric.label}
+ metricUnit={metric.unit}
+ emptyMessage={
+ emptyMessage ?? "No events match the current filters."
+ }
/>
)}
</div>
diff --git a/web/src/features/scores-chart-view/components/AggregationSelect.tsx b/web/src/features/scores-chart-view/components/AggregationSelect.tsx
new file mode 100644
index 0000000000..ccfc39169e
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/AggregationSelect.tsx
@@ -0,0 +1,50 @@
+import React from "react";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { AGGREGATION_LABELS } from "@/src/features/chart-view/vocab";
+import { type AggregationFn } from "@/src/features/chart-view/types";
+import { getScoreMetric } from "@/src/features/scores-chart-view/fns/scoreChartConfig";
+import {
+ type ScoreChartDataset,
+ type ScoreMetricKey,
+} from "@/src/features/scores-chart-view/types";
+
+const TRIGGER_CLASS = "h-7 w-auto gap-1 text-xs";
+
+/** The "Aggregation" picker in the scores chart config panel. */
+export const AggregationSelect = React.memo(function AggregationSelect({
+ dataset,
+ metric,
+ value,
+ onChange,
+}: {
+ dataset: ScoreChartDataset;
+ metric: ScoreMetricKey;
+ value: AggregationFn;
+ onChange: (value: AggregationFn) => void;
+}) {
+ const options = getScoreMetric(metric, dataset).aggregations;
+ return (
+ <Select
+ value={value}
+ onValueChange={(v) => onChange(v as AggregationFn)}
+ disabled={options.length <= 1}
+ >
+ <SelectTrigger className={TRIGGER_CLASS} aria-label="Aggregation">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((agg) => (
+ <SelectItem key={agg} value={agg}>
+ {AGGREGATION_LABELS[agg]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+});
diff --git a/web/src/features/scores-chart-view/components/BreakdownSelect.tsx b/web/src/features/scores-chart-view/components/BreakdownSelect.tsx
new file mode 100644
index 0000000000..2fd3b1d6e0
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/BreakdownSelect.tsx
@@ -0,0 +1,54 @@
+import React from "react";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { getScoreDimensionsForDataset } from "@/src/features/scores-chart-view/constants/scoreDimensions";
+import {
+ type ScoreChartDataset,
+ type ScoreDimensionKey,
+} from "@/src/features/scores-chart-view/types";
+
+const TRIGGER_CLASS = "h-7 w-auto gap-1 text-xs";
+
+/**
+ * The "Breakdown" picker in the scores chart config panel β€” options are the
+ * selected `dataset`'s real view dimensions (see
+ * `getScoreDimensionsForDataset`), so e.g. "String Value" only exists on the
+ * categorical view because that's the only view declaring it. `isTimeSeries`
+ * additionally hides `highCardinality` dimensions (id, traceId, ...) for a
+ * time-series chart type β€” the server rejects that combination with a 422.
+ */
+export const BreakdownSelect = React.memo(function BreakdownSelect({
+ dataset,
+ isTimeSeries,
+ value,
+ onChange,
+}: {
+ dataset: ScoreChartDataset;
+ isTimeSeries: boolean;
+ value: ScoreDimensionKey;
+ onChange: (value: ScoreDimensionKey) => void;
+}) {
+ const options = getScoreDimensionsForDataset(dataset, isTimeSeries);
+ return (
+ <Select
+ value={value}
+ onValueChange={(v) => onChange(v as ScoreDimensionKey)}
+ >
+ <SelectTrigger className={TRIGGER_CLASS} aria-label="Breakdown dimension">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((d) => (
+ <SelectItem key={d.key} value={d.key}>
+ {d.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+});
diff --git a/web/src/features/scores-chart-view/components/DatasetSelect.tsx b/web/src/features/scores-chart-view/components/DatasetSelect.tsx
new file mode 100644
index 0000000000..165bacafb2
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/DatasetSelect.tsx
@@ -0,0 +1,54 @@
+import React from "react";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { type ScoreChartDataset } from "@/src/features/scores-chart-view/types";
+
+const TRIGGER_CLASS = "h-7 w-auto gap-1 text-xs";
+
+// Same wording the rest of the app already uses for these three views
+// (`viewLabels` in `@/src/features/monitors/helpers/monitorLabels`,
+// the scores filter groups in `@/src/features/experiments/config/
+// experiment-items-filter-config`) β€” not fresh labels invented here.
+const DATASET_OPTIONS: { key: ScoreChartDataset; label: string }[] = [
+ { key: "numeric", label: "Scores (numeric)" },
+ { key: "boolean", label: "Scores (boolean)" },
+ { key: "categorical", label: "Scores (categorical)" },
+];
+
+/**
+ * The "View" picker in the scores chart config panel β€” which underlying
+ * scores view (`scores-numeric`, `scores-boolean`, or `scores-categorical`)
+ * the chart queries.
+ * Switching this changes which metrics/breakdowns are offered below it (see
+ * `coerceScoreChartConfig`), since the two views expose different measures.
+ */
+export const DatasetSelect = React.memo(function DatasetSelect({
+ value,
+ onChange,
+}: {
+ value: ScoreChartDataset;
+ onChange: (value: ScoreChartDataset) => void;
+}) {
+ return (
+ <Select
+ value={value}
+ onValueChange={(v) => onChange(v as ScoreChartDataset)}
+ >
+ <SelectTrigger className={TRIGGER_CLASS} aria-label="View">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {DATASET_OPTIONS.map((d) => (
+ <SelectItem key={d.key} value={d.key}>
+ {d.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+});
diff --git a/web/src/features/scores-chart-view/components/MetricSelect.tsx b/web/src/features/scores-chart-view/components/MetricSelect.tsx
new file mode 100644
index 0000000000..79548005cf
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/MetricSelect.tsx
@@ -0,0 +1,46 @@
+import React from "react";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { getScoreMetricsForDataset } from "@/src/features/scores-chart-view/constants/scoreMetrics";
+import {
+ type ScoreChartDataset,
+ type ScoreMetricKey,
+} from "@/src/features/scores-chart-view/types";
+
+const TRIGGER_CLASS = "h-7 w-auto gap-1 text-xs";
+
+/**
+ * The "Metric" picker in the scores chart config panel β€” options depend on
+ * the selected `dataset` (numeric scores can be counted or averaged;
+ * categorical/text scores can only be counted).
+ */
+export const MetricSelect = React.memo(function MetricSelect({
+ dataset,
+ value,
+ onChange,
+}: {
+ dataset: ScoreChartDataset;
+ value: ScoreMetricKey;
+ onChange: (value: ScoreMetricKey) => void;
+}) {
+ const options = getScoreMetricsForDataset(dataset);
+ return (
+ <Select value={value} onValueChange={(v) => onChange(v as ScoreMetricKey)}>
+ <SelectTrigger className={TRIGGER_CLASS} aria-label="Metric">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((m) => (
+ <SelectItem key={m.key} value={m.key}>
+ {m.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+});
diff --git a/web/src/features/scores-chart-view/components/ScoreChartViewPanel/ScoreChartViewPanel.stories.tsx b/web/src/features/scores-chart-view/components/ScoreChartViewPanel/ScoreChartViewPanel.stories.tsx
new file mode 100644
index 0000000000..a9930285c6
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/ScoreChartViewPanel/ScoreChartViewPanel.stories.tsx
@@ -0,0 +1,70 @@
+import preview from "../../../../../.storybook/preview";
+import { fn } from "storybook/test";
+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";
+import { DEFAULT_SCORE_CHART_CONFIG } from "@/src/features/scores-chart-view/constants/defaultScoreChartConfig";
+import { type ScoreChartViewConfig } from "@/src/features/scores-chart-view/types";
+import { ScoreChartViewPanel } from "@/src/features/scores-chart-view/components/ScoreChartViewPanel/ScoreChartViewPanel";
+
+/**
+ * Deterministic fixture β€” average score value per hour, broken down by score
+ * name. Small on purpose: `ScoreChartViewPanel` just hands `data` to the shared
+ * `chart-library`, so a couple of buckets/series are enough to render a real
+ * line chart.
+ */
+const SCORE_NAMES = [
+ { name: "accuracy", base: 0.82 },
+ { name: "toxicity", base: 0.04 },
+];
+const HOURS = ["00:00", "01:00", "02:00", "03:00"];
+
+const DATA: DataPoint[] = HOURS.flatMap((hour, hourIndex) =>
+ SCORE_NAMES.map(({ name, base }, seed) => ({
+ time_dimension: hour,
+ dimension: name,
+ metric:
+ Math.round((base + ((hourIndex + seed * 2) % 4) * 0.02) * 100) / 100,
+ })),
+);
+
+/**
+ * The scores-table chart layout (production UI rendered by `ScoresChartView`).
+ * Presentational β€” `data`/`config` come in as props, so it renders without any
+ * query or context dependency. Same responsive layout as the observations
+ * chart view's `ChartViewPanel` story (`@/src/features/chart-view`): a config
+ * panel beside the chart at desktop widths, stacked below it under the `md`
+ * breakpoint β€” narrow the browser window (or the devtools device toolbar) to
+ * ~390px to see it.
+ */
+const CONFIG: ScoreChartViewConfig = {
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "value",
+ aggregation: "avg",
+};
+
+const meta = preview.meta({
+ component: ScoreChartViewPanel,
+ args: {
+ config: CONFIG,
+ data: DATA,
+ onConfigChange: fn(),
+ // In production the panel fills a bounded-height flex ancestor (`flex-1`
+ // inside `ScoresChartView`); standalone it needs an explicit height. Give it
+ // one through the component's own `className` prop rather than a layout
+ // decorator (Storybook guide: render the component as it is).
+ className: "h-[420px]",
+ },
+});
+
+export const Default = meta.story({});
+
+export const Empty = meta.story({
+ args: { data: [] },
+});
+
+export const Loading = meta.story({
+ args: { isLoading: true },
+});
+
+export const Error = meta.story({
+ args: { error: "Pick a wider time range to chart." },
+});
diff --git a/web/src/features/scores-chart-view/components/ScoreChartViewPanel/ScoreChartViewPanel.tsx b/web/src/features/scores-chart-view/components/ScoreChartViewPanel/ScoreChartViewPanel.tsx
new file mode 100644
index 0000000000..db09c5f287
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/ScoreChartViewPanel/ScoreChartViewPanel.tsx
@@ -0,0 +1,204 @@
+/* eslint-disable @repo/no-style-props */
+import React, { useCallback, useState } from "react";
+import { AlertCircle, ChevronLeft, ChevronRight, Loader2 } from "lucide-react";
+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";
+import { Button } from "@/src/components/ui/button";
+import { cn } from "@/src/utils/tailwind";
+// Chart type picker is view-agnostic (only depends on `DashboardWidgetChartType`),
+// so it's reused as-is rather than duplicated.
+import { ChartTypePicker } from "@/src/features/chart-view/components/ConfigControls";
+import { type AggregationFn } from "@/src/features/chart-view/types";
+import { isTimeSeriesChartType } from "@/src/features/chart-view/vocab";
+import {
+ describeScoreChartConfig,
+ getScoreMetric,
+} from "@/src/features/scores-chart-view/fns/scoreChartConfig";
+import {
+ type ScoreChartDataset,
+ type ScoreChartViewConfig,
+ type ScoreDimensionKey,
+ type ScoreMetricKey,
+} from "@/src/features/scores-chart-view/types";
+// Shared with the observations chart view: once a metric resolves to a
+// label/unit, rendering an already-aggregated series is identical regardless
+// of which vocabulary (events vs. scores) picked that metric.
+import { ChartCanvas } from "@/src/features/chart-view/components/ChartCanvas";
+import { DatasetSelect } from "@/src/features/scores-chart-view/components/DatasetSelect";
+import { MetricSelect } from "@/src/features/scores-chart-view/components/MetricSelect";
+import { AggregationSelect } from "@/src/features/scores-chart-view/components/AggregationSelect";
+import { BreakdownSelect } from "@/src/features/scores-chart-view/components/BreakdownSelect";
+
+/**
+ * The scores-table chart layout β€” same "maximized canvas + collapsible config
+ * panel" shape as the observations chart view's `ChartViewPanel`
+ * (`@/src/features/chart-view`), reading the scores vocab instead. View-only:
+ * data/loading/error come from the caller (`ScoresChartView`, which runs the
+ * real aggregate query).
+ */
+export const ScoreChartViewPanel = React.memo(function ScoreChartViewPanel({
+ config,
+ onConfigChange,
+ data,
+ isLoading = false,
+ error = null,
+ emptyMessage,
+ chartActions,
+ className,
+}: {
+ config: ScoreChartViewConfig;
+ onConfigChange: (patch: Partial<ScoreChartViewConfig>) => void;
+ data: DataPoint[];
+ isLoading?: boolean;
+ error?: string | null;
+ emptyMessage?: string;
+ /** Right-aligned actions next to the chart subtitle (e.g. "Add to dashboard"). */
+ chartActions?: React.ReactNode;
+ className?: string;
+}) {
+ const [open, setOpen] = useState(true);
+ const metric = getScoreMetric(config.metric, config.dataset);
+
+ const onDataset = useCallback(
+ (dataset: ScoreChartDataset) => onConfigChange({ dataset }),
+ [onConfigChange],
+ );
+ const onMetric = useCallback(
+ (metric: ScoreMetricKey) => onConfigChange({ metric }),
+ [onConfigChange],
+ );
+ const onAggregation = useCallback(
+ (aggregation: AggregationFn) => onConfigChange({ aggregation }),
+ [onConfigChange],
+ );
+ const onBreakdown = useCallback(
+ (breakdown: ScoreDimensionKey) => onConfigChange({ breakdown }),
+ [onConfigChange],
+ );
+ const onChartType = useCallback(
+ (chartType: DashboardWidgetChartType) => onConfigChange({ chartType }),
+ [onConfigChange],
+ );
+
+ return (
+ <div className={cn("flex min-h-0 flex-1 flex-col md:flex-row", className)}>
+ <div className="flex min-h-64 min-w-0 flex-1 flex-col gap-1 p-3 md:min-h-0">
+ <div className="flex items-center justify-between gap-2">
+ <div
+ className="text-foreground min-w-0 truncate text-sm font-bold"
+ title={describeScoreChartConfig(config)}
+ >
+ {describeScoreChartConfig(config)}
+ </div>
+ {chartActions}
+ </div>
+ <div className="min-h-0 flex-1">
+ {error ? (
+ <div className="text-muted-foreground flex h-full flex-col items-center justify-center gap-2 p-8 text-center">
+ <AlertCircle className="h-10 w-10 opacity-40" />
+ <p className="max-w-md text-sm">{error}</p>
+ </div>
+ ) : isLoading ? (
+ <div className="text-muted-foreground flex h-full items-center justify-center">
+ <Loader2 className="h-6 w-6 animate-spin" />
+ </div>
+ ) : (
+ <ChartCanvas
+ data={data}
+ chartType={config.chartType}
+ breakdown={config.breakdown}
+ aggregation={config.aggregation}
+ metricLabel={metric.label}
+ metricUnit={metric.unit}
+ emptyMessage={
+ emptyMessage ?? "No scores match the current filters."
+ }
+ />
+ )}
+ </div>
+ </div>
+
+ {open ? (
+ <div className="flex w-full flex-col gap-3 overflow-y-auto border-t p-3 md:w-72 md:shrink-0 md:border-t-0 md:border-l">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-bold">Visualize</span>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Collapse panel"
+ onClick={() => setOpen(false)}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </div>
+ <PanelField label="Chart type">
+ <ChartTypePicker
+ value={config.chartType}
+ onChange={onChartType}
+ showLabels
+ />
+ </PanelField>
+ <PanelField label="View">
+ <DatasetSelect value={config.dataset} onChange={onDataset} />
+ </PanelField>
+ {/* One "Metric" section holding both selects β€” matches the real
+ dashboard widget builder's `SingleMetricField`, which nests the
+ aggregation select directly under the measure select with no
+ separate "Aggregation" label, and hides it entirely once the
+ measure ("Count") has no other aggregation to offer. */}
+ <PanelField label="Metric">
+ <div className="flex flex-col gap-1.5">
+ <MetricSelect
+ dataset={config.dataset}
+ value={config.metric}
+ onChange={onMetric}
+ />
+ {metric.aggregations.length > 1 ? (
+ <AggregationSelect
+ dataset={config.dataset}
+ metric={config.metric}
+ value={config.aggregation}
+ onChange={onAggregation}
+ />
+ ) : null}
+ </div>
+ </PanelField>
+ <PanelField label="Breakdown">
+ <BreakdownSelect
+ dataset={config.dataset}
+ isTimeSeries={isTimeSeriesChartType(config.chartType)}
+ value={config.breakdown}
+ onChange={onBreakdown}
+ />
+ </PanelField>
+ </div>
+ ) : (
+ <div className="flex flex-col items-center border-t p-1.5 md:shrink-0 md:border-t-0 md:border-l">
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Expand panel"
+ onClick={() => setOpen(true)}
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+});
+
+function PanelField({
+ label,
+ children,
+}: {
+ label: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-1.5">
+ <span className="text-muted-foreground text-xs font-bold">{label}</span>
+ {children}
+ </div>
+ );
+}
diff --git a/web/src/features/scores-chart-view/components/ScoreOutlierBarStrip/ScoreOutlierBarStrip.stories.tsx b/web/src/features/scores-chart-view/components/ScoreOutlierBarStrip/ScoreOutlierBarStrip.stories.tsx
new file mode 100644
index 0000000000..82bb52fc0c
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/ScoreOutlierBarStrip/ScoreOutlierBarStrip.stories.tsx
@@ -0,0 +1,155 @@
+import { fn } from "storybook/test";
+import preview from "../../../../../.storybook/preview";
+import { ScoreOutlierBarStrip } from "@/src/features/scores-chart-view/components/ScoreOutlierBarStrip/ScoreOutlierBarStrip";
+import { prepareScoreOutlierSeries } from "@/src/features/scores-chart-view/fns/binning/scoreOutlierBinning";
+import { type ScoreOutlierBin } from "@/src/features/scores-chart-view/types";
+
+/**
+ * Design surface for the outlier strip above the scores table β€” the scores
+ * analogue of the observations strip's `OutlierBarStrip.stories.tsx`. Each
+ * bar aggregates its time bucket (score count, or avg/min/max value); the
+ * strip exists to click into spikes, so the visual must read at a glance.
+ */
+
+// mulberry32 β€” tiny, deterministic PRNG so every Storybook render is identical.
+const mulberry32 = (seed: number) => {
+ let a = seed;
+ return () => {
+ a |= 0;
+ a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+};
+
+const BASE_MS = Date.UTC(2026, 6, 26, 0, 0, 0);
+
+function makeFixtureBins(params: {
+ rangeMs: number;
+ stepSeconds: number;
+ sparse?: boolean;
+ noMetricData?: boolean;
+ seed?: number;
+}): { bins: ScoreOutlierBin[]; fromMs: number; toMs: number } {
+ const rand = mulberry32(params.seed ?? 42);
+ const stepMs = params.stepSeconds * 1000;
+ const fromMs = BASE_MS;
+ const toMs = fromMs + params.rangeMs;
+
+ const bins: ScoreOutlierBin[] = [];
+ for (let t = fromMs; t < toMs; t += stepMs) {
+ if (params.sparse && rand() < 0.7) continue;
+ const count = Math.max(1, Math.round(rand() * 20));
+ const avg = 0.5 + rand() * 0.4;
+ bins.push({
+ bucketStart: new Date(t),
+ count,
+ values: {
+ count_count: count,
+ avg_value: params.noMetricData ? null : avg,
+ min_value: params.noMetricData ? null : Math.max(0, avg - 0.3),
+ max_value: params.noMetricData ? null : Math.min(1, avg + 0.3),
+ },
+ });
+ }
+ return { bins, fromMs, toMs };
+}
+
+function makeFixtureSeries(params: {
+ rangeMs: number;
+ stepSeconds: number;
+ metric: "count" | "value";
+ widthPx: number;
+ sparse?: boolean;
+ noMetricData?: boolean;
+}) {
+ const { bins, fromMs, toMs } = makeFixtureBins(params);
+ return {
+ ...prepareScoreOutlierSeries({
+ bins,
+ metric: params.metric,
+ fromMs,
+ toMs,
+ stepSeconds: params.stepSeconds,
+ widthPx: params.widthPx,
+ }),
+ stepMs: params.stepSeconds * 1000,
+ widthPx: params.widthPx,
+ };
+}
+
+const dayOfCounts = makeFixtureSeries({
+ rangeMs: 24 * 3600 * 1000,
+ stepSeconds: 600,
+ metric: "count",
+ widthPx: 720,
+});
+
+const meta = preview.meta({
+ component: ScoreOutlierBarStrip,
+ args: {
+ onSelectBucket: fn(),
+ },
+});
+
+export const Default = meta.story({
+ args: { ...dayOfCounts, metric: "count" },
+});
+
+export const Disabled = meta.story({
+ args: {
+ ...dayOfCounts,
+ metric: "count",
+ disabledReason: "Chart unavailable for the current filters",
+ },
+});
+
+export const AverageValue = meta.story({
+ args: {
+ ...makeFixtureSeries({
+ rangeMs: 24 * 3600 * 1000,
+ stepSeconds: 600,
+ metric: "value",
+ widthPx: 720,
+ }),
+ metric: "value",
+ },
+});
+
+export const SparseData = meta.story({
+ args: {
+ ...makeFixtureSeries({
+ rangeMs: 24 * 3600 * 1000,
+ stepSeconds: 600,
+ metric: "count",
+ widthPx: 720,
+ sparse: true,
+ }),
+ metric: "count",
+ },
+});
+
+/** Scores exist but carry no numeric value (all-CATEGORICAL bucket) β€” the
+ * strip shows activity ticks + an honest hint instead of a fake-zero skyline. */
+export const NoMetricData = meta.story({
+ args: {
+ ...makeFixtureSeries({
+ rangeMs: 24 * 3600 * 1000,
+ stepSeconds: 600,
+ metric: "value",
+ widthPx: 720,
+ noMetricData: true,
+ }),
+ metric: "value",
+ },
+});
+
+export const EmptyRange = meta.story({
+ args: {
+ ...dayOfCounts,
+ dense: dayOfCounts.dense.map((bin) => ({ ...bin, value: null, count: 0 })),
+ maxValue: 0,
+ metric: "count",
+ },
+});
diff --git a/web/src/features/scores-chart-view/components/ScoreOutlierBarStrip/ScoreOutlierBarStrip.tsx b/web/src/features/scores-chart-view/components/ScoreOutlierBarStrip/ScoreOutlierBarStrip.tsx
new file mode 100644
index 0000000000..b774e835a8
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/ScoreOutlierBarStrip/ScoreOutlierBarStrip.tsx
@@ -0,0 +1,590 @@
+/* eslint-disable @repo/no-style-props */
+import { useCallback, useMemo, useRef, useState } from "react";
+import { cn } from "@/src/utils/tailwind";
+import { X } from "lucide-react";
+import { Button } from "@/src/components/ui/button";
+import { Layer } from "@/src/components/ui/layer";
+import { formatBucketRange } from "@/src/features/events/components/outlier-strip/lib/binning";
+import { SCORE_OUTLIER_STRIP_METRICS } from "@/src/features/scores-chart-view/constants/scoreOutlierStripMetrics";
+import { prepareScoreOutlierYTicks } from "@/src/features/scores-chart-view/fns/binning/scoreOutlierBinning";
+import {
+ type ScoreOutlierDenseBin,
+ type ScoreOutlierMetricKey,
+ type ScoreOutlierTick,
+} from "@/src/features/scores-chart-view/types";
+
+/**
+ * ScoreOutlierBarStrip β€” the scores-table analogue of the observations
+ * strip's `OutlierBarStrip` (`@/src/features/events/components/outlier-strip`):
+ * a compact, Firefox-devtools-inspired bar strip. Pure visualiser β€” renders
+ * the dense series `prepareScoreOutlierSeries` produced and decides nothing
+ * about data. Each bar is a prepared aggregate for its time bucket; clicking
+ * it reports the bucket's range so the caller can narrow the table's time
+ * window.
+ */
+
+/** Pointer travel before a press becomes a range-drag instead of a click. */
+const DRAG_THRESHOLD_PX = 5;
+
+/** Which gesture drove a drill-in β€” carried to the caller for analytics. */
+export type ScoreOutlierStripDrillTrigger =
+ | "bucket_click"
+ | "drag_span"
+ | "touch_explore";
+
+export type ScoreOutlierBarStripProps = {
+ dense: ScoreOutlierDenseBin[];
+ /** Max metric value across buckets (0 = no data anywhere). */
+ maxValue: number;
+ stepMs: number;
+ metric: ScoreOutlierMetricKey;
+ /** Full plot width; bars stretch/shrink to span it exactly. */
+ widthPx: number;
+ /** Prepared gridline ticks (`prepareScoreOutlierSeries`). */
+ ticks: ScoreOutlierTick[];
+ /** Height of the bar canvas, labels excluded. */
+ heightPx?: number;
+ /** Bar-height scale; sqrt (default) keeps a low base load readable next to
+ * a handful of outlier buckets. */
+ scale?: "linear" | "sqrt";
+ /** 1px baseline tick where scores exist but carry no metric data. */
+ showActivityTicks?: boolean;
+ /** Sparse time labels under the gridline ticks. */
+ showTimeLabels?: boolean;
+ onSelectBucket?: (
+ range: { fromMs: number; toMs: number },
+ meta: { trigger: ScoreOutlierStripDrillTrigger },
+ ) => void;
+ /** Touch preview pinned (tap or drag release) β€” the analytics seam for the
+ * preview β†’ explore funnel; never fired for mouse interactions. */
+ onPreviewPinned?: (trigger: "tap" | "drag") => void;
+ /** Transient drag selection (ms range). */
+ selection?: { fromMs: number; toMs: number } | null;
+ onSelectionChange?: (range: { fromMs: number; toMs: number } | null) => void;
+ /** Why the chart cannot represent the current table state. */
+ disabledReason?: string;
+ className?: string;
+};
+
+export function ScoreOutlierBarStrip({
+ dense,
+ maxValue,
+ stepMs,
+ metric,
+ widthPx,
+ ticks,
+ heightPx = 50,
+ scale = "sqrt",
+ showActivityTicks = true,
+ showTimeLabels = true,
+ onSelectBucket,
+ onPreviewPinned,
+ selection = null,
+ onSelectionChange,
+ disabledReason,
+ className,
+}: ScoreOutlierBarStripProps) {
+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);
+ const [mouse, setMouse] = useState<{ x: number; y: number } | null>(null);
+ // Touch model: taps and drags PREVIEW (pinned tooltip with an explicit
+ // Explore action) instead of navigating β€” accidental touches must never
+ // change the table's range.
+ const [touchPreview, setTouchPreview] = useState<{
+ fromMs: number;
+ toMs: number;
+ anchorX: number;
+ anchorY: number;
+ windowKey: string;
+ } | null>(null);
+ const dragRef = useRef<{ startX: number; dragging: boolean } | null>(null);
+ const [previewSize, setPreviewSize] = useState<{
+ width: number;
+ height: number;
+ } | null>(null);
+ const previewResizeObserverRef = useRef<ResizeObserver | null>(null);
+ const measurePreview = useCallback((el: HTMLDivElement | null) => {
+ previewResizeObserverRef.current?.disconnect();
+ previewResizeObserverRef.current = null;
+ if (!el) {
+ setPreviewSize(null);
+ return;
+ }
+ const measure = () =>
+ setPreviewSize((prev) => {
+ const width = el.offsetWidth;
+ const height = el.offsetHeight;
+ return prev && prev.width === width && prev.height === height
+ ? prev
+ : { width, height };
+ });
+ measure();
+ if (typeof ResizeObserver !== "undefined") {
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ previewResizeObserverRef.current = observer;
+ }
+ }, []);
+
+ const metricSpec = SCORE_OUTLIER_STRIP_METRICS[metric];
+ const color = metricSpec.color;
+ const binCount = Math.max(dense.length, 1);
+ const slotPx = widthPx / binCount;
+ const barWidth = Math.max(slotPx - 1, 0.5);
+ const plotHeight = heightPx - 1;
+ const labelHeight = showTimeLabels ? 13 : 0;
+ const hasData = maxValue > 0;
+ const hasActivity = dense.some((bin) => bin.count > 0);
+
+ const spanToRange = (x1: number, x2: number) => {
+ const clamp = (x: number) =>
+ Math.min(Math.max(x, 0), Math.max(widthPx - 1, 0));
+ const startIdx = Math.min(
+ Math.floor(clamp(Math.min(x1, x2)) / slotPx),
+ binCount - 1,
+ );
+ const endIdx = Math.min(
+ Math.floor(clamp(Math.max(x1, x2)) / slotPx),
+ binCount - 1,
+ );
+ const startMs = dense[startIdx]?.bucketStartMs ?? 0;
+ const endMs = (dense[endIdx]?.bucketStartMs ?? 0) + stepMs;
+ return { fromMs: startMs, toMs: endMs };
+ };
+
+ const staticLayers = useMemo(() => {
+ const barHeight = (value: number) => {
+ const fraction = Math.max(value, 0) / maxValue;
+ const scaled = scale === "sqrt" ? Math.sqrt(fraction) : fraction;
+ return Math.max(1.5, scaled * plotHeight);
+ };
+ const yTicks = prepareScoreOutlierYTicks({
+ maxValue,
+ metric,
+ plotHeightPx: plotHeight,
+ scale,
+ });
+ return (
+ <>
+ {yTicks.map((tick) => (
+ <line
+ key={`y-tick-${tick.value}`}
+ x1={0}
+ y1={plotHeight - tick.offsetPx}
+ x2={widthPx}
+ y2={plotHeight - tick.offsetPx}
+ className="stroke-foreground"
+ strokeWidth={1}
+ opacity={0.07}
+ />
+ ))}
+
+ <line
+ x1={0}
+ y1={heightPx - 0.5}
+ x2={widthPx}
+ y2={heightPx - 0.5}
+ className="stroke-border"
+ strokeWidth={1}
+ />
+
+ {dense.map((bin, i) => {
+ if (bin.value === null) {
+ return showActivityTicks && bin.count > 0 ? (
+ <rect
+ key={i}
+ x={i * slotPx}
+ y={plotHeight - 1.5}
+ width={barWidth}
+ height={1.5}
+ className="fill-muted-foreground"
+ opacity={0.6}
+ />
+ ) : null;
+ }
+ const h = hasData ? barHeight(bin.value) : 0;
+ return (
+ <rect
+ key={i}
+ x={i * slotPx}
+ y={plotHeight - h}
+ width={barWidth}
+ height={h}
+ fill={color}
+ opacity={0.8}
+ />
+ );
+ })}
+
+ {showTimeLabels &&
+ ticks.map((tick) => (
+ <text
+ key={`label-${tick.index}`}
+ x={tick.index * slotPx + 3}
+ y={heightPx + 9}
+ className="fill-muted-foreground/80 font-sans"
+ fontSize={9}
+ >
+ {tick.label}
+ </text>
+ ))}
+
+ {yTicks.map((tick) => {
+ const lineY = plotHeight - tick.offsetPx;
+ return (
+ <text
+ key={`y-label-${tick.value}`}
+ x={3}
+ y={lineY + 9}
+ textAnchor="start"
+ className="fill-muted-foreground stroke-background font-sans"
+ fontSize={9}
+ strokeWidth={2.5}
+ style={{ paintOrder: "stroke" }}
+ >
+ {tick.label}
+ </text>
+ );
+ })}
+ </>
+ );
+ }, [
+ dense,
+ slotPx,
+ barWidth,
+ heightPx,
+ plotHeight,
+ widthPx,
+ color,
+ ticks,
+ maxValue,
+ metric,
+ scale,
+ hasData,
+ showActivityTicks,
+ showTimeLabels,
+ ]);
+
+ const hovered = hoverIndex !== null ? (dense[hoverIndex] ?? null) : null;
+ const windowKey = `${stepMs}:${dense[0]?.bucketStartMs ?? 0}:${dense.length}`;
+ const activePreview =
+ touchPreview && touchPreview.windowKey === windowKey ? touchPreview : null;
+ const previewStats = activePreview
+ ? dense.reduce(
+ (acc, bin) => {
+ if (
+ bin.bucketStartMs >= activePreview.fromMs &&
+ bin.bucketStartMs < activePreview.toMs
+ ) {
+ acc.count += bin.count;
+ if (bin.value !== null) {
+ acc.value =
+ acc.value === null ? bin.value : Math.max(acc.value, bin.value);
+ }
+ }
+ return acc;
+ },
+ { count: 0, value: null as number | null },
+ )
+ : null;
+ const previewHasData =
+ previewStats !== null &&
+ (previewStats.count > 0 || previewStats.value !== null);
+ const previewHalfWidth = (previewSize?.width ?? 0) / 2;
+ const viewportWidth =
+ typeof window !== "undefined" ? window.innerWidth : Number.MAX_SAFE_INTEGER;
+
+ if (disabledReason) {
+ return (
+ <div
+ className={cn(
+ "text-muted-foreground bg-muted/30 flex items-center justify-center rounded text-[11px]",
+ className,
+ )}
+ style={{ width: widthPx, height: heightPx + labelHeight }}
+ aria-disabled="true"
+ >
+ {disabledReason}
+ </div>
+ );
+ }
+
+ return (
+ <div className={cn("relative", className)} style={{ width: widthPx }}>
+ <svg
+ width={widthPx}
+ height={heightPx + labelHeight}
+ role="img"
+ aria-label={`${metricSpec.shortLabel} per bucket`}
+ className="block cursor-crosshair touch-pan-y select-none"
+ onPointerLeave={(event) => {
+ if (event.pointerType !== "mouse") return;
+ setHoverIndex(null);
+ setMouse(null);
+ }}
+ onPointerDown={(event) => {
+ if (event.button !== 0 && event.pointerType === "mouse") return;
+ event.preventDefault();
+ const rect = event.currentTarget.getBoundingClientRect();
+ dragRef.current = {
+ startX: event.clientX - rect.left,
+ dragging: false,
+ };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }}
+ onPointerMove={(event) => {
+ const rect = event.currentTarget.getBoundingClientRect();
+ const x = event.clientX - rect.left;
+ if (event.pointerType === "mouse") {
+ const index = Math.floor(x / slotPx);
+ setHoverIndex(index >= 0 && index < dense.length ? index : null);
+ setMouse({ x: event.clientX, y: event.clientY });
+ }
+ const drag = dragRef.current;
+ if (!drag) return;
+ if (!drag.dragging && Math.abs(x - drag.startX) < DRAG_THRESHOLD_PX) {
+ return;
+ }
+ if (!drag.dragging) setTouchPreview(null);
+ drag.dragging = true;
+ onSelectionChange?.(spanToRange(drag.startX, x));
+ }}
+ onPointerUp={(event) => {
+ const drag = dragRef.current;
+ dragRef.current = null;
+ if (!drag) return;
+ const rect = event.currentTarget.getBoundingClientRect();
+ const x = event.clientX - rect.left;
+ if (drag.dragging) {
+ const range = spanToRange(drag.startX, x);
+ if (event.pointerType !== "mouse") {
+ setTouchPreview({
+ ...range,
+ anchorX: rect.left + (drag.startX + x) / 2,
+ anchorY: rect.top,
+ windowKey,
+ });
+ onPreviewPinned?.("drag");
+ return;
+ }
+ onSelectionChange?.(null);
+ setTouchPreview(null);
+ onSelectBucket?.(range, { trigger: "drag_span" });
+ return;
+ }
+ const index = Math.floor(x / slotPx);
+ const bin = dense[index];
+ if (!bin) return;
+ if (event.pointerType !== "mouse") {
+ onSelectionChange?.(null);
+ setTouchPreview({
+ fromMs: bin.bucketStartMs,
+ toMs: bin.bucketStartMs + stepMs,
+ anchorX: rect.left + (index + 0.5) * slotPx,
+ anchorY: rect.top,
+ windowKey,
+ });
+ setHoverIndex(index);
+ setMouse(null);
+ onPreviewPinned?.("tap");
+ return;
+ }
+ if ((bin.count > 0 || bin.value !== null) && onSelectBucket) {
+ onSelectBucket(
+ {
+ fromMs: bin.bucketStartMs,
+ toMs: bin.bucketStartMs + stepMs,
+ },
+ { trigger: "bucket_click" },
+ );
+ }
+ }}
+ onPointerCancel={() => {
+ dragRef.current = null;
+ onSelectionChange?.(null);
+ }}
+ >
+ {staticLayers}
+
+ {selection &&
+ (() => {
+ const first = dense[0]?.bucketStartMs;
+ if (first === undefined) return null;
+ const startX = ((selection.fromMs - first) / stepMs) * slotPx;
+ const endX = ((selection.toMs - first) / stepMs) * slotPx;
+ const x = Math.max(startX, 0);
+ const w = Math.min(endX, widthPx) - x;
+ if (w <= 0) return null;
+ return (
+ <g>
+ <rect
+ x={x}
+ y={0}
+ width={w}
+ height={plotHeight}
+ className="fill-foreground"
+ opacity={0.18}
+ />
+ <line
+ x1={x + 0.5}
+ y1={0}
+ x2={x + 0.5}
+ y2={plotHeight}
+ className="stroke-foreground"
+ strokeWidth={1}
+ opacity={0.55}
+ />
+ <line
+ x1={x + w - 0.5}
+ y1={0}
+ x2={x + w - 0.5}
+ y2={plotHeight}
+ className="stroke-foreground"
+ strokeWidth={1}
+ opacity={0.55}
+ />
+ </g>
+ );
+ })()}
+
+ {hoverIndex !== null && (
+ <rect
+ x={hoverIndex * slotPx}
+ y={0}
+ width={slotPx}
+ height={heightPx}
+ className="fill-foreground"
+ opacity={0.08}
+ />
+ )}
+ </svg>
+
+ {!hasData && (
+ <span
+ className="text-muted-foreground/70 pointer-events-none absolute inset-x-0 top-0 flex items-center justify-center text-[10px]"
+ style={{ height: heightPx }}
+ >
+ {hasActivity
+ ? `No ${metricSpec.shortLabel.toLowerCase()} data in range`
+ : "No scores in range"}
+ </span>
+ )}
+
+ {hovered && mouse && !activePreview && (
+ <Layer name="tooltip">
+ <div
+ className="bg-popover text-popover-foreground pointer-events-none fixed rounded border px-1.5 py-1 text-[11px] leading-tight whitespace-nowrap shadow-sm"
+ style={
+ mouse.x + 200 > window.innerWidth
+ ? {
+ left: mouse.x - 10,
+ top: mouse.y - 8,
+ transform: "translate(-100%, -100%)",
+ }
+ : {
+ left: mouse.x + 10,
+ top: mouse.y - 8,
+ transform: "translateY(-100%)",
+ }
+ }
+ >
+ <div className="text-muted-foreground">
+ {formatBucketRange(hovered.bucketStartMs, stepMs)}
+ </div>
+ <div className="font-bold">
+ {hovered.value !== null
+ ? metricSpec.format(hovered.value)
+ : hovered.count > 0
+ ? "no data"
+ : metricSpec.format(0)}
+ {/* No "Β· N scores" suffix here in Value mode: `hovered.count` is
+ the every-listable-type total (from the count-only query),
+ while the value itself only ever reflects NUMERIC/Boolean
+ rows (from a separate query) β€” showing them together would
+ misleadingly imply the value was computed over that count. */}
+ </div>
+ </div>
+ </Layer>
+ )}
+
+ {activePreview && previewStats && (
+ <Layer name="tooltip">
+ <div
+ key={`${activePreview.fromMs}:${activePreview.toMs}`}
+ ref={measurePreview}
+ className="bg-popover text-popover-foreground fixed max-w-[calc(100vw-16px)] rounded border px-2 py-1.5 text-[11px] leading-tight whitespace-nowrap shadow-md"
+ style={{
+ left: Math.min(
+ Math.max(activePreview.anchorX, 8 + previewHalfWidth),
+ Math.max(
+ viewportWidth - 8 - previewHalfWidth,
+ 8 + previewHalfWidth,
+ ),
+ ),
+ top: Math.max(
+ activePreview.anchorY - 6,
+ (previewSize?.height ?? 0) + 8,
+ ),
+ transform: "translate(-50%, -100%)",
+ }}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div>
+ <div className="text-muted-foreground">
+ {formatBucketRange(
+ activePreview.fromMs,
+ activePreview.toMs - activePreview.fromMs,
+ )}
+ </div>
+ <div className="font-bold">
+ {/* Count mode: `previewStats.count` is the span's correctly
+ summed total; `previewStats.value` below is instead the
+ max of per-bucket counts (a "busiest bucket" reduce that
+ only fits avg/max, not a sum), so it's used only for the
+ other metric/aggregations, not Count. */}
+ {metric === "count"
+ ? metricSpec.format(previewStats.count)
+ : previewStats.value !== null
+ ? metricSpec.format(previewStats.value)
+ : previewStats.count > 0
+ ? "no data"
+ : metricSpec.format(0)}
+ {/* Same omission as the hover tooltip above β€” see its comment. */}
+ </div>
+ </div>
+ <button
+ type="button"
+ aria-label="Dismiss preview"
+ className="text-muted-foreground -mt-0.5 -mr-0.5 p-0.5"
+ onClick={() => {
+ setTouchPreview(null);
+ setHoverIndex(null);
+ onSelectionChange?.(null);
+ }}
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </div>
+ {previewHasData && (
+ <Button
+ size="sm"
+ className="mt-1.5 h-6 w-full text-[10px]"
+ onClick={() => {
+ const range = {
+ fromMs: activePreview.fromMs,
+ toMs: activePreview.toMs,
+ };
+ setTouchPreview(null);
+ setHoverIndex(null);
+ onSelectionChange?.(null);
+ onSelectBucket?.(range, { trigger: "touch_explore" });
+ }}
+ >
+ Explore this window
+ </Button>
+ )}
+ </div>
+ </Layer>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/features/scores-chart-view/components/ScoreOutlierStripHeader.stories.tsx b/web/src/features/scores-chart-view/components/ScoreOutlierStripHeader.stories.tsx
new file mode 100644
index 0000000000..dcbbd19052
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/ScoreOutlierStripHeader.stories.tsx
@@ -0,0 +1,36 @@
+import { fn } from "storybook/test";
+import preview from "../../../../.storybook/preview";
+import { ScoreOutlierStripHeader } from "@/src/features/scores-chart-view/components/ScoreOutlierStripHeader";
+
+/**
+ * Design surface for the outlier strip's controls row β€” isolated from
+ * `ScoresOutlierStrip` (which needs a live `dashboard.executeQuery`) so
+ * purely visual concerns, like the value-mode info icon's alignment against
+ * the text-based mode/aggregation triggers, can be checked without the rest
+ * of the app.
+ */
+const meta = preview.meta({
+ component: ScoreOutlierStripHeader,
+ args: {
+ onModeChange: fn(),
+ onAggregationChange: fn(),
+ },
+});
+
+export const CountMode = meta.story({
+ args: {
+ mode: "count",
+ aggregation: "count",
+ aggOptions: ["count"],
+ },
+});
+
+/** "Value" mode adds the info icon flagging that categorical/text scores are
+ * excluded, next to the aggregation dropdown (avg/min/max). */
+export const ValueMode = meta.story({
+ args: {
+ mode: "value",
+ aggregation: "avg",
+ aggOptions: ["avg", "min", "max"],
+ },
+});
diff --git a/web/src/features/scores-chart-view/components/ScoreOutlierStripHeader.tsx b/web/src/features/scores-chart-view/components/ScoreOutlierStripHeader.tsx
new file mode 100644
index 0000000000..1a681bc944
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/ScoreOutlierStripHeader.tsx
@@ -0,0 +1,152 @@
+import { useRef } from "react";
+import { ChevronDown } from "lucide-react";
+import DocPopup from "@/src/components/layouts/doc-popup";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/src/components/ui/dropdown-menu";
+import { SCORE_OUTLIER_STRIP_METRICS } from "@/src/features/scores-chart-view/constants/scoreOutlierStripMetrics";
+import {
+ type ScoreOutlierAggKey,
+ type ScoreOutlierMetricKey,
+} from "@/src/features/scores-chart-view/types";
+
+const MODE_OPTIONS: ScoreOutlierMetricKey[] = ["count", "value"];
+
+const modeLabel = (mode: ScoreOutlierMetricKey): string =>
+ SCORE_OUTLIER_STRIP_METRICS[mode].shortLabel;
+
+/**
+ * Prevent Radix's close-refocus ONLY after a pointer-driven selection β€” the
+ * programmatic refocus renders as a keyboard-style outline on the trigger.
+ */
+const usePointerSelectionFocusGuard = () => {
+ const selectedViaPointerRef = useRef(false);
+ return {
+ markPointerSelection: (event: { detail: number }) => {
+ if (event.detail > 0) selectedViaPointerRef.current = true;
+ },
+ onCloseAutoFocus: (event: Event) => {
+ if (selectedViaPointerRef.current) {
+ event.preventDefault();
+ selectedViaPointerRef.current = false;
+ }
+ },
+ };
+};
+
+/**
+ * The small controls row above the outlier strip's bars: the mode
+ * ("Count"/"Value") dropdown, the value-mode info popup, and the
+ * aggregation (avg/min/max) dropdown when there's a choice. Pulled out of
+ * `ScoresOutlierStrip` (the data-fetching container) so it's a plain,
+ * storyable component β€” verifying something purely visual like the info
+ * icon's alignment shouldn't require mocking `dashboard.executeQuery`.
+ */
+export function ScoreOutlierStripHeader({
+ mode,
+ onModeChange,
+ aggregation,
+ aggOptions,
+ onAggregationChange,
+}: {
+ mode: ScoreOutlierMetricKey;
+ onModeChange: (mode: ScoreOutlierMetricKey) => void;
+ aggregation: ScoreOutlierAggKey;
+ aggOptions: readonly ScoreOutlierAggKey[];
+ onAggregationChange: (aggregation: ScoreOutlierAggKey) => void;
+}) {
+ const modeFocusGuard = usePointerSelectionFocusGuard();
+ const aggregationFocusGuard = usePointerSelectionFocusGuard();
+ const def = SCORE_OUTLIER_STRIP_METRICS[mode];
+
+ // "Count" covers every score type; "Value" only reflects numeric/Boolean
+ // rows, so flag that explicitly rather than leaving it a silent gap.
+ const valueModeInfo =
+ mode === "value" ? (
+ <DocPopup description="Categorical and text scores have no numeric value, so they're excluded from Value." />
+ ) : null;
+
+ const modeMenu = (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label={`Chart mode: ${modeLabel(mode)}`}
+ className="text-foreground hover:text-muted-foreground flex items-center gap-0.5 text-xs leading-none font-bold"
+ >
+ {modeLabel(mode)}
+ <ChevronDown className="h-2.5 w-2.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ onCloseAutoFocus={modeFocusGuard.onCloseAutoFocus}
+ >
+ {MODE_OPTIONS.map((nextMode) => (
+ <DropdownMenuItem
+ key={nextMode}
+ onClick={(event) => {
+ modeFocusGuard.markPointerSelection(event);
+ if (nextMode !== mode) onModeChange(nextMode);
+ }}
+ className="text-xs"
+ >
+ {modeLabel(nextMode)}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+
+ const aggregationMenu =
+ aggOptions.length > 1 ? (
+ <span className="flex items-baseline gap-1">
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label={`${def.shortLabel} aggregation: ${aggregation}`}
+ className="text-muted-foreground hover:text-foreground flex items-center gap-0.5 text-xs leading-none underline-offset-2 hover:underline"
+ >
+ {aggregation}
+ <ChevronDown className="h-2.5 w-2.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ onCloseAutoFocus={aggregationFocusGuard.onCloseAutoFocus}
+ >
+ {aggOptions.map((agg) => (
+ <DropdownMenuItem
+ key={agg}
+ onClick={(event) => {
+ aggregationFocusGuard.markPointerSelection(event);
+ if (agg !== aggregation) onAggregationChange(agg);
+ }}
+ className="text-xs"
+ >
+ {agg}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </span>
+ ) : null;
+
+ return (
+ // `items-center`, not `items-baseline`: the info icon has no text
+ // baseline to align against, and both text triggers share the same
+ // `text-xs leading-none` line height, so centering by box (not text
+ // metrics) lines everything up without any one-off icon offset.
+ <div className="flex items-center gap-1.5">
+ {/* Tighter gap than the row's own `gap-1.5`: the icon annotates
+ "Value" specifically, so it reads as attached to it rather than
+ floating evenly between it and the aggregation dropdown. */}
+ <span className="flex items-center gap-1">
+ {modeMenu}
+ {valueModeInfo}
+ </span>
+ {/* The bar's aggregate must be legible where there is a choice
+ (avg/min/max); single-option metrics are unambiguous and render no
+ aggregation label. */}
+ {aggregationMenu}
+ </div>
+ );
+}
diff --git a/web/src/features/scores-chart-view/components/ScoresChartView.tsx b/web/src/features/scores-chart-view/components/ScoresChartView.tsx
new file mode 100644
index 0000000000..26c0dfa9d1
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/ScoresChartView.tsx
@@ -0,0 +1,117 @@
+import React, { useMemo } from "react";
+import { type FilterState } from "@langfuse/shared";
+import { type ViewVersion } from "@langfuse/shared/query";
+import { api } from "@/src/utils/api";
+import { mapLegacyUiTableFilterToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";
+import { VIEW_BY_DATASET } from "@/src/features/scores-chart-view/constants/viewByDataset";
+import {
+ buildScoresChartQuery,
+ scoreChartConfigToWidgetInput,
+ scoreRowsToDataPoints,
+} from "@/src/features/scores-chart-view/fns/scoreChartConfig";
+import { type ScoreChartViewConfig } from "@/src/features/scores-chart-view/types";
+import { ScoreChartViewPanel } from "@/src/features/scores-chart-view/components/ScoreChartViewPanel/ScoreChartViewPanel";
+// Shared with the observations chart view; only the widget-input mapper
+// passed to it (`scoreChartConfigToWidgetInput`) is scores-specific.
+import { AddToDashboardButton } from "@/src/features/chart-view/components/AddToDashboardButton";
+
+/**
+ * Production chart view for the scores table. Mirrors `EventsChartView` (the
+ * observations chart view): builds the aggregate query from the same filters
+ * + time window the table is showing, runs it through `dashboard.executeQuery`
+ * β€” the same read path the "Scores" dashboard widgets use β€” and renders the
+ * shared chart panel.
+ *
+ * `filterState` is mapped onto the config's dataset view (`scores-numeric`,
+ * `scores-boolean`, or `scores-categorical`) via the existing
+ * `mapLegacyUiTableFilterToView` helper (the same one
+ * `ChartScores`/`CategoricalScoreChart` use), so a
+ * scores-table filter that has no dimension on that view (e.g. the numeric
+ * "Value" range, which is a measure, not a filterable dimension) is silently
+ * dropped from the chart query rather than erroring β€” it keeps narrowing the
+ * table underneath.
+ *
+ * `viewVersion` MUST come from the caller's own `isBetaEnabled` check (the
+ * same one `scores.tsx` already uses to pick `scoresV3`/`scoresV4` for the
+ * table rows, and the same one `ChartScores`/`WidgetForm` use as
+ * `metricsVersion`/`activeVersion`) β€” hardcoding "v2" here would run the
+ * events-backed view against a project that isn't events-backed yet, and
+ * silently return empty groups for any trace/observation breakdown.
+ */
+export function ScoresChartView({
+ projectId,
+ filterState,
+ fromTimestamp,
+ toTimestamp,
+ config,
+ onConfigChange,
+ viewVersion,
+}: {
+ projectId: string;
+ filterState: FilterState;
+ fromTimestamp: Date;
+ toTimestamp: Date;
+ config: ScoreChartViewConfig;
+ onConfigChange: (patch: Partial<ScoreChartViewConfig>) => void;
+ viewVersion: ViewVersion;
+}) {
+ const filters = useMemo(
+ () =>
+ mapLegacyUiTableFilterToView(
+ VIEW_BY_DATASET[config.dataset],
+ filterState,
+ ),
+ [filterState, config.dataset],
+ );
+
+ const query = useMemo(
+ () =>
+ buildScoresChartQuery({ config, filters, fromTimestamp, toTimestamp }),
+ [config, filters, fromTimestamp, toTimestamp],
+ );
+
+ // A degenerate window (from === to, or from > to from independent time picks)
+ // can't be charted; the query is disabled, which react-query keeps at
+ // isPending forever β€” so surface a hint instead of an endless spinner.
+ const validRange = fromTimestamp < toTimestamp;
+
+ const queryResult = api.dashboard.executeQuery.useQuery(
+ { projectId, query, version: viewVersion },
+ {
+ enabled: validRange,
+ meta: { silentHttpCodes: [422] },
+ trpc: { context: { skipBatch: true } },
+ },
+ );
+
+ const data = useMemo(
+ () =>
+ queryResult.data ? scoreRowsToDataPoints(queryResult.data, config) : [],
+ [queryResult.data, config],
+ );
+
+ const error = !validRange
+ ? "Pick a wider time range to chart."
+ : queryResult.isError
+ ? (queryResult.error?.message ??
+ "Couldn't build a chart for the current view.")
+ : null;
+
+ const widgetInput = useMemo(
+ () => scoreChartConfigToWidgetInput({ config, filters }),
+ [config, filters],
+ );
+
+ return (
+ <ScoreChartViewPanel
+ config={config}
+ onConfigChange={onConfigChange}
+ data={data}
+ isLoading={validRange && queryResult.isPending && !queryResult.isError}
+ error={error}
+ chartActions={
+ <AddToDashboardButton projectId={projectId} widgetInput={widgetInput} />
+ }
+ />
+ );
+}
diff --git a/web/src/features/scores-chart-view/components/ScoresOutlierStrip.tsx b/web/src/features/scores-chart-view/components/ScoresOutlierStrip.tsx
new file mode 100644
index 0000000000..552111c20a
--- /dev/null
+++ b/web/src/features/scores-chart-view/components/ScoresOutlierStrip.tsx
@@ -0,0 +1,362 @@
+import { useMemo, useState } from "react";
+import { type FilterState, type QueryType } from "@langfuse/shared";
+import {
+ SCORES_LISTABLE_COUNT_VIEW,
+ type ViewVersion,
+} from "@langfuse/shared/query";
+import { api } from "@/src/utils/api";
+import { cn } from "@/src/utils/tailwind";
+import { useElementSize } from "@/src/hooks/useElementSize";
+import {
+ canReuseOutlierPlaceholder,
+ pickChartGranularity,
+} from "@/src/features/events/components/outlier-strip/lib/binning";
+import { mapLegacyUiTableFilterToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { ScoreOutlierStripHeader } from "@/src/features/scores-chart-view/components/ScoreOutlierStripHeader";
+import { SCORE_OUTLIER_STRIP_METRICS } from "@/src/features/scores-chart-view/constants/scoreOutlierStripMetrics";
+import { canApplyScoreOutlierStripFilters } from "@/src/features/scores-chart-view/fns/outlierStripFilters";
+import {
+ mergeScoreOutlierRows,
+ prepareScoreOutlierSeries,
+ rowsToScoreOutlierBins,
+ scoreOutlierCountQueryMetrics,
+ scoreOutlierValueQueryMetrics,
+} from "@/src/features/scores-chart-view/fns/binning/scoreOutlierBinning";
+import {
+ type ScoreOutlierAggKey,
+ type ScoreOutlierMetricKey,
+ type ScoreOutlierQueryRow,
+} from "@/src/features/scores-chart-view/types";
+import { useScoreOutlierStripSettings } from "@/src/features/scores-chart-view/hooks/useScoreOutlierStripSettings";
+import {
+ ScoreOutlierBarStrip,
+ type ScoreOutlierStripDrillTrigger,
+} from "@/src/features/scores-chart-view/components/ScoreOutlierBarStrip/ScoreOutlierBarStrip";
+
+/**
+ * The outlier strip ("Pulse") above the scores table β€” the scores-table
+ * analogue of `EventsOutlierStrip`. Runs two always-eager
+ * `dashboard.executeQuery` calls: `countQuery` (count-only, every listable
+ * score type) feeds "Count" mode, `valueQuery` (unchanged `scores-numeric`)
+ * feeds "Value" mode's avg/min/max, so switching mode never refetches.
+ */
+
+/** Target horizontal pixels per bar for granularity picking. */
+const BAR_SLOT_TARGET_PX = 5;
+
+type StripMode = ScoreOutlierMetricKey;
+
+export function ScoresOutlierStrip({
+ projectId,
+ filterState,
+ fromTimestamp,
+ toTimestamp,
+ onSelectRange,
+ viewVersion,
+}: {
+ projectId: string;
+ filterState: FilterState;
+ fromTimestamp: Date;
+ toTimestamp: Date;
+ onSelectRange: (range: { from: Date; to: Date }) => void;
+ /** Must match the caller's own `isBetaEnabled` check β€” see `ScoresChartView`'s doc comment. */
+ viewVersion: ViewVersion;
+}) {
+ const capture = usePostHogClientCapture();
+ const [wrapperRef, size] = useElementSize<HTMLDivElement>();
+ // Transient drag selection, window-keyed: a range/granularity change
+ // (drill, browser back/forward) invalidates a lingering band by derivation.
+ const [dragSelection, setDragSelection] = useState<{
+ fromMs: number;
+ toMs: number;
+ windowKey: string;
+ } | null>(null);
+ const { settings, update } = useScoreOutlierStripSettings();
+
+ const fromMs = fromTimestamp.getTime();
+ const toMs = toTimestamp.getTime();
+ const validRange = fromMs < toMs;
+ // getBoundingClientRect includes the wrapper's px-2 padding (border-box).
+ const width = Math.max((size?.width ?? 0) - 16, 0);
+
+ const mode: StripMode = settings.mode;
+ const chartWidth = width;
+ const def = SCORE_OUTLIER_STRIP_METRICS[mode];
+ const aggOptions = def.aggregations.map((agg) => agg.key);
+
+ const granularity = pickChartGranularity({
+ rangeMs: toMs - fromMs,
+ widthPx: Math.max(chartWidth, 1),
+ barSlotPx: BAR_SLOT_TARGET_PX,
+ });
+
+ // The `scores-categorical` mapping's column names match `scores-numeric`'s
+ // and `scores-listable-count`'s own dimensions, so it's reused here too.
+ const countFilters = useMemo(
+ () => mapLegacyUiTableFilterToView("scores-categorical", filterState),
+ [filterState],
+ );
+ const valueFilters = useMemo(
+ () => mapLegacyUiTableFilterToView("scores-numeric", filterState),
+ [filterState],
+ );
+ const canApplyFilters = canApplyScoreOutlierStripFilters(filterState);
+
+ const countQuery: QueryType = useMemo(
+ () => ({
+ // Internal-only view, scoped to every listable score type β€” see its
+ // doc comment in `dataModel.ts`.
+ view: SCORES_LISTABLE_COUNT_VIEW,
+ dimensions: [],
+ metrics: scoreOutlierCountQueryMetrics(),
+ filters: countFilters,
+ timeDimension: { granularity: granularity.granularity },
+ fromTimestamp: fromTimestamp.toISOString(),
+ toTimestamp: toTimestamp.toISOString(),
+ // Must stay null: an orderBy disables the WITH FILL densification.
+ orderBy: null,
+ }),
+ [countFilters, granularity.granularity, fromTimestamp, toTimestamp],
+ );
+
+ const valueQuery: QueryType = useMemo(
+ () => ({
+ view: "scores-numeric",
+ dimensions: [],
+ // Numeric/Boolean value only β€” the count-only query above already
+ // covers "Count" mode's true, every-type total.
+ metrics: scoreOutlierValueQueryMetrics(),
+ filters: valueFilters,
+ timeDimension: { granularity: granularity.granularity },
+ fromTimestamp: fromTimestamp.toISOString(),
+ toTimestamp: toTimestamp.toISOString(),
+ orderBy: null,
+ }),
+ [valueFilters, granularity.granularity, fromTimestamp, toTimestamp],
+ );
+
+ // Shared by both queries' `placeholderData` below: whether a previous
+ // result's granularity still matches the current one.
+ const isSameGridAsCurrent = (
+ prevQuery: { queryKey?: unknown[] } | undefined,
+ ): boolean => {
+ const prevInput = (
+ prevQuery?.queryKey?.[1] as { input?: { query?: QueryType } } | undefined
+ )?.input?.query;
+ return (
+ !!prevInput?.timeDimension &&
+ canReuseOutlierPlaceholder(
+ { granularity: prevInput.timeDimension.granularity },
+ { granularity: granularity.granularity },
+ )
+ );
+ };
+
+ const countQueryResult = api.dashboard.executeQuery.useQuery(
+ { projectId, query: countQuery, version: viewVersion },
+ {
+ enabled: validRange && width > 0 && canApplyFilters,
+ // Keep the previous bins ONLY across same-grid refetches β€” a
+ // persistent band must not flash to a skeleton every interval; a grid
+ // change (drill-in, Back, preset hop) shows the skeleton instead.
+ placeholderData: (prev, prevQuery) =>
+ prev && isSameGridAsCurrent(prevQuery) ? prev : undefined,
+ meta: { silentHttpCodes: [422] },
+ trpc: { context: { skipBatch: true } },
+ },
+ );
+
+ const valueQueryResult = api.dashboard.executeQuery.useQuery(
+ { projectId, query: valueQuery, version: viewVersion },
+ {
+ enabled: validRange && width > 0 && canApplyFilters,
+ // Same same-grid placeholder reuse as `countQuery` above.
+ placeholderData: (prev, prevQuery) =>
+ prev && isSameGridAsCurrent(prevQuery) ? prev : undefined,
+ meta: { silentHttpCodes: [422] },
+ trpc: { context: { skipBatch: true } },
+ },
+ );
+
+ const bins = useMemo(
+ () =>
+ countQueryResult.data
+ ? rowsToScoreOutlierBins(
+ mergeScoreOutlierRows(
+ countQueryResult.data as ScoreOutlierQueryRow[],
+ (valueQueryResult.data as ScoreOutlierQueryRow[] | undefined) ??
+ [],
+ ),
+ )
+ : [],
+ [countQueryResult.data, valueQueryResult.data],
+ );
+
+ const aggregation: ScoreOutlierAggKey =
+ mode === "count" ? "count" : settings.valueAgg;
+
+ const series = useMemo(
+ () =>
+ prepareScoreOutlierSeries({
+ bins,
+ metric: mode,
+ aggregation,
+ fromMs,
+ toMs,
+ stepSeconds: granularity.stepSeconds,
+ widthPx: chartWidth,
+ }),
+ [
+ bins,
+ fromMs,
+ toMs,
+ granularity.stepSeconds,
+ mode,
+ aggregation,
+ chartWidth,
+ ],
+ );
+
+ // Analytics props are metadata only (enums, counts, the granularity step)
+ // β€” never bucket values or range contents.
+ const handleSelectBucket = (
+ range: { fromMs: number; toMs: number },
+ meta: { trigger: ScoreOutlierStripDrillTrigger },
+ ) => {
+ capture("pulse:drill_in", {
+ trigger: meta.trigger,
+ metric: mode,
+ aggregation,
+ mode,
+ stepSeconds: granularity.stepSeconds,
+ spanBuckets: Math.max(
+ 1,
+ Math.round(
+ (range.toMs - range.fromMs) / (granularity.stepSeconds * 1000),
+ ),
+ ),
+ surface: "scores",
+ });
+ onSelectRange({ from: new Date(range.fromMs), to: new Date(range.toMs) });
+ };
+
+ const handleModeChange = (next: StripMode) => {
+ if (next === mode) return;
+ capture("pulse:mode_switch", {
+ mode: next,
+ previousMode: mode,
+ surface: "scores",
+ });
+ update({ mode: next });
+ };
+
+ const setAggregation = (agg: ScoreOutlierAggKey) => {
+ if (agg === aggregation) return;
+ capture("pulse:aggregation_switch", {
+ metric: mode,
+ aggregation: agg,
+ previousAggregation: aggregation,
+ surface: "scores",
+ });
+ update({ valueAgg: agg as "avg" | "min" | "max" });
+ };
+
+ const stepMs = granularity.stepSeconds * 1000;
+ const selectionWindowKey = `${fromMs}:${toMs}:${stepMs}`;
+ const activeSelection =
+ dragSelection && dragSelection.windowKey === selectionWindowKey
+ ? dragSelection
+ : null;
+ const handleSelectionChange = (
+ range: { fromMs: number; toMs: number } | null,
+ ) =>
+ setDragSelection(
+ range ? { ...range, windowKey: selectionWindowKey } : null,
+ );
+ const placeholderMissesGrid =
+ countQueryResult.isPlaceholderData &&
+ series.maxValue === 0 &&
+ series.dense.every((bin) => bin.count === 0);
+ const isLoading =
+ validRange &&
+ width > 0 &&
+ ((countQueryResult.isPending && !countQueryResult.isError) ||
+ (valueQueryResult.isPending && !valueQueryResult.isError) ||
+ placeholderMissesGrid);
+
+ return (
+ // Ruled top and bottom: the strip reads as its own band instead of
+ // floating between the toolbar and the table header.
+ <div ref={wrapperRef} className="shrink-0 border-y">
+ {size === undefined ? null : (
+ <div className="relative px-2 pt-2.5 pb-1">
+ {!canApplyFilters ? (
+ <div>
+ <ScoreOutlierStripHeader
+ mode={mode}
+ onModeChange={handleModeChange}
+ aggregation={aggregation}
+ aggOptions={aggOptions}
+ onAggregationChange={setAggregation}
+ />
+ <ScoreOutlierBarStrip
+ className="mt-1.5"
+ dense={[]}
+ maxValue={0}
+ ticks={[]}
+ stepMs={stepMs}
+ metric={mode}
+ widthPx={chartWidth}
+ disabledReason="Chart unavailable for the current filters"
+ />
+ </div>
+ ) : isLoading || width === 0 ? (
+ <div className="bg-muted h-[76px] animate-pulse rounded" />
+ ) : countQueryResult.isError || valueQueryResult.isError ? (
+ <div className="text-muted-foreground flex h-[76px] items-center justify-center text-[11px]">
+ No Data
+ </div>
+ ) : (
+ <div
+ className={cn("min-w-0 transition-opacity", {
+ "opacity-60":
+ (countQueryResult.isPlaceholderData &&
+ countQueryResult.isFetching) ||
+ (valueQueryResult.isPlaceholderData &&
+ valueQueryResult.isFetching),
+ })}
+ >
+ <ScoreOutlierStripHeader
+ mode={mode}
+ onModeChange={handleModeChange}
+ aggregation={aggregation}
+ aggOptions={aggOptions}
+ onAggregationChange={setAggregation}
+ />
+ <ScoreOutlierBarStrip
+ className="mt-1.5"
+ dense={series.dense}
+ maxValue={series.maxValue}
+ ticks={series.ticks}
+ stepMs={stepMs}
+ metric={mode}
+ widthPx={chartWidth}
+ onSelectBucket={handleSelectBucket}
+ onPreviewPinned={(trigger) =>
+ capture("pulse:preview_pinned", {
+ trigger,
+ metric: mode,
+ surface: "scores",
+ })
+ }
+ selection={activeSelection}
+ onSelectionChange={handleSelectionChange}
+ />
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/features/scores-chart-view/constants/defaultScoreChartConfig.ts b/web/src/features/scores-chart-view/constants/defaultScoreChartConfig.ts
new file mode 100644
index 0000000000..29cca84d2a
--- /dev/null
+++ b/web/src/features/scores-chart-view/constants/defaultScoreChartConfig.ts
@@ -0,0 +1,10 @@
+import { type ScoreChartViewConfig } from "@/src/features/scores-chart-view/types";
+
+export const DEFAULT_SCORE_CHART_CONFIG: ScoreChartViewConfig = {
+ dataset: "numeric",
+ metric: "count",
+ aggregation: "count",
+ breakdown: "name",
+ chartType: "LINE_TIME_SERIES",
+ timeGranularity: "hour",
+};
diff --git a/web/src/features/scores-chart-view/constants/scoreDimensions.ts b/web/src/features/scores-chart-view/constants/scoreDimensions.ts
new file mode 100644
index 0000000000..e0c7cd7038
--- /dev/null
+++ b/web/src/features/scores-chart-view/constants/scoreDimensions.ts
@@ -0,0 +1,46 @@
+import startCase from "lodash/startCase";
+import { viewDeclarations } from "@langfuse/shared";
+import { VIEW_BY_DATASET } from "@/src/features/scores-chart-view/constants/viewByDataset";
+import {
+ type ScoreChartDataset,
+ type ScoreDimensionDef,
+} from "@/src/features/scores-chart-view/types";
+
+const NO_BREAKDOWN: ScoreDimensionDef = {
+ key: "none",
+ label: "Total (no breakdown)",
+ field: null,
+};
+
+/**
+ * The breakdown dimensions offered for a dataset β€” read straight off the
+ * same view declaration the real dashboard widget builder uses
+ * (`viewDeclarations` in `packages/shared/src/features/query/dataModel.ts`),
+ * with the same `uiHidden` filter and `startCase` labeling `WidgetForm.tsx`'s
+ * `availableDimensions` applies. Deliberately NOT a hand-maintained list β€”
+ * a hand-picked subset is exactly what drifted out of sync with the boolean
+ * view earlier, and would silently drift again the next time a dimension is
+ * added to/removed from a view declaration.
+ *
+ * `isTimeSeries` additionally excludes `highCardinality` dimensions (id,
+ * traceId, observationId, sessionId, userId): the server's `validateQuery`
+ * rejects a `timeDimension` query breaking down by one of those with a 422
+ * (unbounded result set), so offering them for a time-series chart type
+ * would just be a guaranteed error. They stay available for ranked/pie/
+ * number charts, which cap rows instead of opening a time axis.
+ */
+export const getScoreDimensionsForDataset = (
+ dataset: ScoreChartDataset,
+ isTimeSeries: boolean,
+): ScoreDimensionDef[] => {
+ const { dimensions } = viewDeclarations.v2[VIEW_BY_DATASET[dataset]];
+ const options = Object.entries(dimensions)
+ .filter(
+ ([, def]) => !def.uiHidden && !(isTimeSeries && def.highCardinality),
+ )
+ .map(([key]) => ({ key, label: startCase(key), field: key }))
+ .sort((a, b) =>
+ a.label.localeCompare(b.label, "en", { sensitivity: "base" }),
+ );
+ return [NO_BREAKDOWN, ...options];
+};
diff --git a/web/src/features/scores-chart-view/constants/scoreMetrics.ts b/web/src/features/scores-chart-view/constants/scoreMetrics.ts
new file mode 100644
index 0000000000..53db4498a0
--- /dev/null
+++ b/web/src/features/scores-chart-view/constants/scoreMetrics.ts
@@ -0,0 +1,78 @@
+import {
+ type ScoreChartDataset,
+ type ScoreMetricDef,
+} from "@/src/features/scores-chart-view/types";
+
+/**
+ * The measures the three score views expose. `value` is a `number`-typed
+ * measure on both `scores-numeric` and `scores-boolean` (see
+ * `packages/shared/src/features/query/dataModel.ts`), and the actual
+ * dashboard widget builder offers EVERY aggregation for a `number`-typed
+ * measure (`getValidAggregationsForMeasureType` in
+ * `packages/shared/src/features/query/types.ts` returns the full
+ * `metricAggregations` list, not just `avg`) β€” so `value` gets the full set
+ * our shared `AggregationFn` expresses here too, matching that screen
+ * instead of the narrower choice the fixed "Scores" dashboard widgets
+ * (`ChartScores`, `NumericScoreTimeSeriesChart`) happen to hardcode. For
+ * "boolean", `avg` is the true-rate; the other aggregations (min/max/p50 of
+ * a 0/1 value) are less commonly useful but still valid, same as the
+ * builder. Categorical scores have no numeric value to aggregate (see the
+ * `ScoreChartDataset` doc comment), so their only metric is a plain count.
+ *
+ * Labels are the plain measure name ("Count"/"Value"), matching the widget
+ * builder's own `startCase(measureKey)` labeling (`WidgetForm.tsx`'s
+ * `singleChartMetrics`) instead of a more "explanatory" label invented here.
+ */
+const VALUE_AGGREGATIONS: ScoreMetricDef["aggregations"] = [
+ "avg",
+ "sum",
+ "min",
+ "max",
+ "count",
+ "p50",
+ "p95",
+ "p99",
+];
+
+export const SCORE_METRICS: ScoreMetricDef[] = [
+ {
+ key: "count",
+ label: "Count",
+ dataset: "numeric",
+ measure: "count",
+ aggregations: ["count"],
+ },
+ {
+ key: "value",
+ label: "Value",
+ dataset: "numeric",
+ measure: "value",
+ aggregations: VALUE_AGGREGATIONS,
+ },
+ {
+ key: "count",
+ label: "Count",
+ dataset: "boolean",
+ measure: "count",
+ aggregations: ["count"],
+ },
+ {
+ key: "value",
+ label: "Value",
+ dataset: "boolean",
+ measure: "value",
+ aggregations: VALUE_AGGREGATIONS,
+ },
+ {
+ key: "count",
+ label: "Count",
+ dataset: "categorical",
+ measure: "count",
+ aggregations: ["count"],
+ },
+];
+
+/** The metrics valid for one dataset β€” drives the "Metric" picker options. */
+export const getScoreMetricsForDataset = (
+ dataset: ScoreChartDataset,
+): ScoreMetricDef[] => SCORE_METRICS.filter((m) => m.dataset === dataset);
diff --git a/web/src/features/scores-chart-view/constants/scoreOutlierStripMetrics.ts b/web/src/features/scores-chart-view/constants/scoreOutlierStripMetrics.ts
new file mode 100644
index 0000000000..882fd56a15
--- /dev/null
+++ b/web/src/features/scores-chart-view/constants/scoreOutlierStripMetrics.ts
@@ -0,0 +1,59 @@
+import { numberFormatter } from "@/src/utils/numbers";
+import {
+ type ScoreOutlierAggKey,
+ type ScoreOutlierMetricKey,
+} from "@/src/features/scores-chart-view/types";
+
+type ScoreOutlierAggregationDef = {
+ /** The user-facing option key (currently 1:1 with the query aggregation). */
+ key: ScoreOutlierAggKey;
+ /** The executeQuery aggregation this option lowers to. */
+ queryAggregation: "count" | "avg" | "min" | "max";
+};
+
+export type ScoreOutlierMetricDef = {
+ shortLabel: string;
+ /** First entry is the default. */
+ aggregations: readonly ScoreOutlierAggregationDef[];
+ /** The executeQuery measure name on the `scores-numeric` view. */
+ measure: string;
+ /** Raw result value -> plotted unit (identity for both current metrics). */
+ fromRaw: (raw: number) => number;
+ format: (value: number) => string;
+ /** SVG bar / gridline color. */
+ color: string;
+};
+
+/**
+ * The metrics the scores outlier strip can plot β€” mirrors the observations
+ * strip's `OUTLIER_STRIP_METRICS` (`@/src/features/events/components/outlier-strip`),
+ * trimmed to the two measures the `scores-numeric` view exposes. `min`/`max`
+ * are offered instead of the observations strip's percentiles: a p95 of a
+ * handful of scores per bucket is rarely meaningful, while a bucket's
+ * min/max value is.
+ */
+export const SCORE_OUTLIER_STRIP_METRICS: Record<
+ ScoreOutlierMetricKey,
+ ScoreOutlierMetricDef
+> = {
+ count: {
+ shortLabel: "Count",
+ measure: "count",
+ aggregations: [{ key: "count", queryAggregation: "count" }],
+ fromRaw: (raw) => raw,
+ format: (value) => numberFormatter(value, 0),
+ color: "hsl(var(--chart-4))",
+ },
+ value: {
+ shortLabel: "Value",
+ measure: "value",
+ aggregations: [
+ { key: "avg", queryAggregation: "avg" },
+ { key: "min", queryAggregation: "min" },
+ { key: "max", queryAggregation: "max" },
+ ],
+ fromRaw: (raw) => raw,
+ format: (value) => numberFormatter(value, 2),
+ color: "hsl(var(--chart-1))",
+ },
+};
diff --git a/web/src/features/scores-chart-view/constants/viewByDataset.ts b/web/src/features/scores-chart-view/constants/viewByDataset.ts
new file mode 100644
index 0000000000..bf05361ab1
--- /dev/null
+++ b/web/src/features/scores-chart-view/constants/viewByDataset.ts
@@ -0,0 +1,16 @@
+import { type ScoreChartDataset } from "@/src/features/scores-chart-view/types";
+
+/**
+ * The view a config's `dataset` queries β€” one-to-one with the three score
+ * views the query engine exposes (`packages/shared/src/features/query/
+ * dataModel.ts`) and the same three-way split `viewLabels`
+ * (`@/src/features/monitors/helpers/monitorLabels`) and the experiments
+ * filter config already use. Its own file so both `buildScoresChartQuery`
+ * and `scoreDimensions` (which reads `viewDeclarations[view]` directly) can
+ * import it without one depending on the other.
+ */
+export const VIEW_BY_DATASET = {
+ numeric: "scores-numeric",
+ boolean: "scores-boolean",
+ categorical: "scores-categorical",
+} as const satisfies Record<ScoreChartDataset, string>;
diff --git a/web/src/features/scores-chart-view/fns/binning/scoreOutlierBinning.clienttest.ts b/web/src/features/scores-chart-view/fns/binning/scoreOutlierBinning.clienttest.ts
new file mode 100644
index 0000000000..3433bc9f9e
--- /dev/null
+++ b/web/src/features/scores-chart-view/fns/binning/scoreOutlierBinning.clienttest.ts
@@ -0,0 +1,254 @@
+import {
+ mergeScoreOutlierRows,
+ prepareScoreOutlierSeries,
+ prepareScoreOutlierYTicks,
+ resolveScoreOutlierAggregation,
+ rowsToScoreOutlierBins,
+ scoreOutlierCountQueryMetrics,
+ scoreOutlierValueQueryMetrics,
+} from "@/src/features/scores-chart-view/fns/binning/scoreOutlierBinning";
+import { type ScoreOutlierBin } from "@/src/features/scores-chart-view/types";
+
+describe("scoreOutlierCountQueryMetrics", () => {
+ it("derives one query metric per registered Count aggregation", () => {
+ const metrics = scoreOutlierCountQueryMetrics();
+ expect(metrics).toEqual([{ measure: "count", aggregation: "count" }]);
+ });
+});
+
+describe("scoreOutlierValueQueryMetrics", () => {
+ it("derives one query metric per registered Value aggregation", () => {
+ const metrics = scoreOutlierValueQueryMetrics();
+ expect(metrics).toContainEqual({ measure: "value", aggregation: "avg" });
+ expect(metrics).toContainEqual({ measure: "value", aggregation: "min" });
+ expect(metrics).toContainEqual({ measure: "value", aggregation: "max" });
+ expect(metrics).toHaveLength(3);
+ });
+});
+
+describe("mergeScoreOutlierRows", () => {
+ it("layers value columns from the value rows onto the count rows' true totals, without summing counts", () => {
+ expect(
+ mergeScoreOutlierRows(
+ [{ time_dimension: "2026-06-25T10:00:00Z", count_count: 5 }],
+ [
+ {
+ time_dimension: "2026-06-25T10:00:00Z",
+ avg_value: 0.5,
+ min_value: 0.1,
+ max_value: 0.9,
+ },
+ ],
+ ),
+ ).toEqual([
+ {
+ time_dimension: "2026-06-25T10:00:00Z",
+ count_count: 5,
+ avg_value: 0.5,
+ min_value: 0.1,
+ max_value: 0.9,
+ },
+ ]);
+ });
+
+ it("keeps a count-only bucket when the value query has no matching row (e.g. all-categorical bucket)", () => {
+ expect(
+ mergeScoreOutlierRows(
+ [{ time_dimension: "2026-06-25T10:00:00Z", count_count: 3 }],
+ [],
+ ),
+ ).toEqual([{ time_dimension: "2026-06-25T10:00:00Z", count_count: 3 }]);
+ });
+
+ it("drops a value-only row with no matching count bucket rather than fabricating a count", () => {
+ expect(
+ mergeScoreOutlierRows(
+ [],
+ [{ time_dimension: "2026-06-25T10:00:00Z", avg_value: 0.5 }],
+ ),
+ ).toEqual([]);
+ });
+});
+
+describe("resolveScoreOutlierAggregation", () => {
+ it("resolves a known aggregation", () => {
+ expect(resolveScoreOutlierAggregation("value", "max").key).toBe("max");
+ });
+
+ it("falls back to the metric's default when unknown or absent", () => {
+ expect(resolveScoreOutlierAggregation("value", "bogus").key).toBe("avg");
+ expect(resolveScoreOutlierAggregation("value", undefined).key).toBe("avg");
+ expect(resolveScoreOutlierAggregation("count", undefined).key).toBe(
+ "count",
+ );
+ });
+});
+
+describe("rowsToScoreOutlierBins", () => {
+ it("maps a row with data into a bin, values keyed by result column", () => {
+ const [bin] = rowsToScoreOutlierBins([
+ {
+ time_dimension: "2026-06-25T10:00:00Z",
+ count_count: 5,
+ avg_value: 0.72,
+ min_value: 0.1,
+ max_value: 0.9,
+ },
+ ]);
+ expect(bin.count).toBe(5);
+ expect(bin.bucketStart.toISOString()).toBe("2026-06-25T10:00:00.000Z");
+ expect(bin.values).toMatchObject({
+ count_count: 5,
+ avg_value: 0.72,
+ min_value: 0.1,
+ max_value: 0.9,
+ });
+ });
+
+ it("drops a WITH FILL row (count 0) rather than mapping a phantom bucket", () => {
+ expect(
+ rowsToScoreOutlierBins([
+ { time_dimension: "2026-06-25T10:00:00Z", count_count: 0 },
+ ]),
+ ).toEqual([]);
+ });
+
+ it("drops a row with no parseable time dimension", () => {
+ expect(
+ rowsToScoreOutlierBins([{ time_dimension: undefined, count_count: 5 }]),
+ ).toEqual([]);
+ });
+
+ it("maps a missing measure column to null", () => {
+ const [bin] = rowsToScoreOutlierBins([
+ { time_dimension: "2026-06-25T10:00:00Z", count_count: 3 },
+ ]);
+ expect(bin.values.avg_value).toBeNull();
+ });
+});
+
+describe("prepareScoreOutlierSeries", () => {
+ const FROM = new Date("2026-06-25T10:00:00Z").getTime();
+ const TO = new Date("2026-06-25T10:03:00Z").getTime(); // 3 minute buckets
+
+ const bin = (
+ isoTime: string,
+ values: Record<string, number | null>,
+ ): ScoreOutlierBin => ({
+ bucketStart: new Date(isoTime),
+ count: 1,
+ values,
+ });
+
+ it("densifies the grid, filling gaps with null", () => {
+ const { dense, maxValue } = prepareScoreOutlierSeries({
+ bins: [
+ bin("2026-06-25T10:00:00Z", { count_count: 4 }),
+ bin("2026-06-25T10:02:00Z", { count_count: 6 }),
+ ],
+ metric: "count",
+ fromMs: FROM,
+ toMs: TO,
+ stepSeconds: 60,
+ });
+ expect(dense).toHaveLength(3);
+ expect(dense[0].value).toBe(4);
+ expect(dense[1].value).toBeNull(); // no bin at 10:01
+ expect(dense[2].value).toBe(6);
+ expect(maxValue).toBe(6);
+ });
+
+ it("extracts the requested aggregation for the value metric", () => {
+ const { dense } = prepareScoreOutlierSeries({
+ bins: [bin("2026-06-25T10:00:00Z", { avg_value: 0.5, max_value: 0.9 })],
+ metric: "value",
+ aggregation: "max",
+ fromMs: FROM,
+ toMs: FROM + 60_000,
+ stepSeconds: 60,
+ });
+ expect(dense[0].value).toBe(0.9);
+ });
+
+ it("falls back to the metric's default aggregation for an unknown option", () => {
+ const { dense } = prepareScoreOutlierSeries({
+ bins: [bin("2026-06-25T10:00:00Z", { avg_value: 0.5 })],
+ metric: "value",
+ aggregation: "bogus",
+ fromMs: FROM,
+ toMs: FROM + 60_000,
+ stepSeconds: 60,
+ });
+ expect(dense[0].value).toBe(0.5);
+ });
+
+ it("returns no ticks without a width", () => {
+ const { ticks } = prepareScoreOutlierSeries({
+ bins: [],
+ metric: "count",
+ fromMs: FROM,
+ toMs: TO,
+ stepSeconds: 60,
+ });
+ expect(ticks).toEqual([]);
+ });
+
+ it("caps the max value at 0 for an all-empty range", () => {
+ const { maxValue } = prepareScoreOutlierSeries({
+ bins: [],
+ metric: "count",
+ fromMs: FROM,
+ toMs: TO,
+ stepSeconds: 60,
+ });
+ expect(maxValue).toBe(0);
+ });
+});
+
+describe("prepareScoreOutlierYTicks", () => {
+ it("returns no ticks for a non-positive or non-finite max", () => {
+ expect(
+ prepareScoreOutlierYTicks({
+ maxValue: 0,
+ metric: "count",
+ plotHeightPx: 50,
+ scale: "sqrt",
+ }),
+ ).toEqual([]);
+ expect(
+ prepareScoreOutlierYTicks({
+ maxValue: Number.POSITIVE_INFINITY,
+ metric: "count",
+ plotHeightPx: 50,
+ scale: "sqrt",
+ }),
+ ).toEqual([]);
+ });
+
+ it("places nice descending values below the max", () => {
+ const ticks = prepareScoreOutlierYTicks({
+ maxValue: 42,
+ metric: "count",
+ plotHeightPx: 100,
+ scale: "linear",
+ });
+ expect(ticks.length).toBeGreaterThan(0);
+ for (const tick of ticks) {
+ expect(tick.value).toBeLessThanOrEqual(42);
+ }
+ // Strictly descending.
+ for (let i = 1; i < ticks.length; i++) {
+ expect(ticks[i].value).toBeLessThan(ticks[i - 1].value);
+ }
+ });
+
+ it("caps at 3 ticks", () => {
+ const ticks = prepareScoreOutlierYTicks({
+ maxValue: 1_000_000,
+ metric: "count",
+ plotHeightPx: 500,
+ scale: "linear",
+ });
+ expect(ticks.length).toBeLessThanOrEqual(3);
+ });
+});
diff --git a/web/src/features/scores-chart-view/fns/binning/scoreOutlierBinning.ts b/web/src/features/scores-chart-view/fns/binning/scoreOutlierBinning.ts
new file mode 100644
index 0000000000..ef1e0a46bb
--- /dev/null
+++ b/web/src/features/scores-chart-view/fns/binning/scoreOutlierBinning.ts
@@ -0,0 +1,299 @@
+import { format } from "date-fns";
+import {
+ OUTLIER_STRIP_STEP_LADDER_SECONDS,
+ outlierStripResultColumn,
+} from "@/src/features/events/components/outlier-strip/lib/binning";
+import { parseChartTimestamp } from "@/src/features/widgets/chart-library/prepareTimeAxis";
+import { SCORE_OUTLIER_STRIP_METRICS } from "@/src/features/scores-chart-view/constants/scoreOutlierStripMetrics";
+import {
+ type ScoreOutlierBin,
+ type ScoreOutlierDenseBin,
+ type ScoreOutlierMetricKey,
+ type ScoreOutlierQueryRow,
+ type ScoreOutlierTick,
+ type ScoreOutlierYTick,
+} from "@/src/features/scores-chart-view/types";
+
+/**
+ * The outlier strip's ("Pulse") binning math β€” one module because every
+ * function here operates on the same bin/row shapes and only the strip
+ * container (`ScoresOutlierStrip`) calls them, always together in the same
+ * pipeline: rows β†’ bins β†’ merged bins β†’ dense series β†’ ticks.
+ */
+
+// ---------------------------------------------------------------------------
+// Query metrics
+// ---------------------------------------------------------------------------
+
+type ScoreOutlierQueryMetric = {
+ measure: string;
+ aggregation: "count" | "avg" | "min" | "max";
+};
+
+const queryMetricsFor = (
+ metric: ScoreOutlierMetricKey,
+): ScoreOutlierQueryMetric[] => {
+ const def = SCORE_OUTLIER_STRIP_METRICS[metric];
+ return def.aggregations.map((agg) => ({
+ measure: def.measure,
+ aggregation: agg.queryAggregation,
+ }));
+};
+
+/** "Count" mode's executeQuery `metrics`, against the count-only `scores-listable-count` view. */
+export const scoreOutlierCountQueryMetrics = (): ScoreOutlierQueryMetric[] =>
+ queryMetricsFor("count");
+
+/** "Value" mode's executeQuery `metrics`, against the unchanged `scores-numeric` view. */
+export const scoreOutlierValueQueryMetrics = (): ScoreOutlierQueryMetric[] =>
+ queryMetricsFor("value");
+
+/** Resolves an aggregation option, falling back to the metric's default. */
+export const resolveScoreOutlierAggregation = (
+ metric: ScoreOutlierMetricKey,
+ aggregation: string | undefined,
+) => {
+ const def = SCORE_OUTLIER_STRIP_METRICS[metric];
+ return (
+ def.aggregations.find((agg) => agg.key === aggregation) ??
+ def.aggregations[0]
+ );
+};
+
+// ---------------------------------------------------------------------------
+// Rows β†’ bins
+// ---------------------------------------------------------------------------
+
+const toNumberOrNull = (raw: unknown): number | null =>
+ raw === null || raw === undefined ? null : Number(raw);
+
+/**
+ * Maps executeQuery rows to strip bins. Mirrors the observations strip's
+ * `rowsToOutlierBins`: a WITH FILL row (count 0) is dropped rather than
+ * mapped, since the client densifies empty buckets to honest nulls anyway.
+ */
+export const rowsToScoreOutlierBins = (
+ rows: ScoreOutlierQueryRow[],
+): ScoreOutlierBin[] =>
+ rows.flatMap((row) => {
+ const bucketStart = parseChartTimestamp(row.time_dimension);
+ const count = Number(row.count_count ?? 0);
+ if (!bucketStart || count === 0) return [];
+ const values: Record<string, number | null> = {};
+ for (const def of Object.values(SCORE_OUTLIER_STRIP_METRICS)) {
+ for (const agg of def.aggregations) {
+ const column = outlierStripResultColumn(
+ def.measure,
+ agg.queryAggregation,
+ );
+ values[column] = toNumberOrNull(row[column]);
+ }
+ }
+ return [{ bucketStart, count, values }];
+ });
+
+/**
+ * Combines the count query's rows with the value query's rows, keyed by
+ * time bucket. `count_count` always comes from the count rows; value
+ * columns are layered on top where present β€” no summing involved.
+ */
+export const mergeScoreOutlierRows = (
+ countRows: ScoreOutlierQueryRow[],
+ valueRows: ScoreOutlierQueryRow[],
+): ScoreOutlierQueryRow[] => {
+ const rowsByTimestamp = new Map<string, ScoreOutlierQueryRow>();
+
+ for (const row of countRows) {
+ if (typeof row.time_dimension === "string") {
+ rowsByTimestamp.set(row.time_dimension, { ...row });
+ }
+ }
+
+ for (const row of valueRows) {
+ if (typeof row.time_dimension !== "string") continue;
+
+ // Count rows are the only source of truth for which buckets exist; a
+ // value row with no matching count bucket is dropped, not invented.
+ const existing = rowsByTimestamp.get(row.time_dimension);
+ if (existing) {
+ Object.assign(existing, row);
+ }
+ }
+
+ return [...rowsByTimestamp.values()].sort((a, b) =>
+ String(a.time_dimension).localeCompare(String(b.time_dimension)),
+ );
+};
+
+// ---------------------------------------------------------------------------
+// Bins β†’ dense series + gridline ticks
+// ---------------------------------------------------------------------------
+
+/** Even the coarsest preset on an URL-injected absurd custom range must not
+ * build an unbounded client-side array. */
+const MAX_DENSE_BINS = 4000;
+/** Minimum horizontal pixels between gridline ticks / labels. */
+const TICK_MIN_SPACING_PX = 110;
+
+/**
+ * Smallest "nice" tick step at least `minPx` wide at the current bar slot.
+ * Ticks must be MULTIPLES of the bucket step β€” mirrors the observations
+ * strip's private `pickTickStepMs`.
+ */
+function pickScoreOutlierTickStepMs(
+ stepMs: number,
+ slotPx: number,
+ minPx: number,
+): number {
+ for (const step of OUTLIER_STRIP_STEP_LADDER_SECONDS) {
+ const tickMs = step * 1000;
+ if (tickMs % stepMs === 0 && (tickMs / stepMs) * slotPx >= minPx) {
+ return tickMs;
+ }
+ }
+ return Math.max(1, Math.ceil(minPx / slotPx)) * stepMs;
+}
+
+/**
+ * Densifies server buckets onto the bucket grid covering [fromMs, toMs),
+ * extracts one metric/aggregation via the registry, and places gridline
+ * ticks. Mirrors the observations strip's `prepareOutlierSeries` β€” same grid
+ * math (phase-snapped to the server's own buckets), same densification.
+ */
+export function prepareScoreOutlierSeries(params: {
+ bins: ScoreOutlierBin[];
+ metric: ScoreOutlierMetricKey;
+ /** Aggregation option key; invalid values fall back to the metric default. */
+ aggregation?: string;
+ fromMs: number;
+ toMs: number;
+ stepSeconds: number;
+ /** Plot width; drives tick spacing. 0/absent = no ticks (tests). */
+ widthPx?: number;
+}): {
+ dense: ScoreOutlierDenseBin[];
+ /** Max metric value across buckets; 0 when the range has no data. */
+ maxValue: number;
+ ticks: ScoreOutlierTick[];
+} {
+ const stepMs = params.stepSeconds * 1000;
+ const def = SCORE_OUTLIER_STRIP_METRICS[params.metric];
+ const agg = resolveScoreOutlierAggregation(params.metric, params.aggregation);
+ const column = outlierStripResultColumn(def.measure, agg.queryAggregation);
+
+ const byBucketMs = new Map<number, ScoreOutlierBin>();
+ for (const bin of params.bins) {
+ byBucketMs.set(bin.bucketStart.getTime(), bin);
+ }
+
+ const phase =
+ params.bins.length > 0
+ ? ((params.bins[0].bucketStart.getTime() % stepMs) + stepMs) % stepMs
+ : 0;
+ const firstBucketMs =
+ Math.floor((params.fromMs - phase) / stepMs) * stepMs + phase;
+ const dense: ScoreOutlierDenseBin[] = [];
+ let maxValue = 0;
+
+ for (
+ let bucketMs = firstBucketMs;
+ bucketMs < params.toMs && dense.length < MAX_DENSE_BINS;
+ bucketMs += stepMs
+ ) {
+ const bin = byBucketMs.get(bucketMs);
+ const raw = bin ? (bin.values[column] ?? null) : null;
+ const value = raw === null ? null : def.fromRaw(raw);
+ if (value !== null && value > maxValue) maxValue = value;
+ dense.push({
+ bucketStartMs: bucketMs,
+ count: bin?.count ?? 0,
+ value,
+ });
+ }
+
+ const ticks: ScoreOutlierTick[] = [];
+ if (params.widthPx && params.widthPx > 0 && dense.length > 0) {
+ const slotPx = params.widthPx / dense.length;
+ const tickStepMs = pickScoreOutlierTickStepMs(
+ stepMs,
+ slotPx,
+ TICK_MIN_SPACING_PX,
+ );
+ for (let i = 1; i < dense.length; i++) {
+ if ((dense[i].bucketStartMs - phase) % tickStepMs === 0) {
+ ticks.push({
+ index: i,
+ label: format(
+ new Date(dense[i].bucketStartMs),
+ tickStepMs >= 86_400_000 ? "MMM d" : "HH:mm",
+ ),
+ });
+ }
+ }
+ }
+
+ return { dense, maxValue, ticks };
+}
+
+/** Vertical room a 9px axis label needs between accepted gridlines. */
+const Y_TICK_MIN_SPACING_PX = 14;
+/** Ticks closer to the baseline than this collide with activity ticks. */
+const Y_TICK_MIN_OFFSET_PX = 10;
+const Y_TICK_MAX_COUNT = 3;
+
+/**
+ * Descending "nice" tick candidates <= maxValue: 1-2-5 decades below the max
+ * β€” neither of the two score metrics has a natural "step ladder" (unlike the
+ * observations strip's latency), so this always takes the decade path.
+ * Mirrors the observations strip's private `descendNiceValues`.
+ */
+function* descendNiceScoreOutlierValues(maxValue: number): Generator<number> {
+ for (let exp = Math.ceil(Math.log10(maxValue)); ; exp--) {
+ for (const mantissa of [5, 2, 1]) {
+ const value = mantissa * 10 ** exp;
+ if (value <= maxValue) yield value;
+ }
+ }
+}
+
+/**
+ * Places horizontal value gridlines for the strip: nice values below the
+ * max, walked top-down and accepted only where the label fits. Mirrors the
+ * observations strip's `prepareOutlierYTicks`.
+ */
+export function prepareScoreOutlierYTicks(params: {
+ /** Max metric value across buckets (the bar scale's domain). */
+ maxValue: number;
+ metric: ScoreOutlierMetricKey;
+ /** Bar canvas height above the baseline. */
+ plotHeightPx: number;
+ /** Must match the visualiser's bar-height scale. */
+ scale: "linear" | "sqrt";
+}): ScoreOutlierYTick[] {
+ const { maxValue, plotHeightPx } = params;
+ if (
+ !Number.isFinite(maxValue) ||
+ maxValue <= 0 ||
+ plotHeightPx <= Y_TICK_MIN_OFFSET_PX
+ ) {
+ return [];
+ }
+ const def = SCORE_OUTLIER_STRIP_METRICS[params.metric];
+ const toOffsetPx = (value: number) => {
+ const fraction = value / maxValue;
+ const scaled = params.scale === "sqrt" ? Math.sqrt(fraction) : fraction;
+ return scaled * plotHeightPx;
+ };
+
+ const ticks: ScoreOutlierYTick[] = [];
+ let lastOffsetPx = Number.POSITIVE_INFINITY;
+ for (const value of descendNiceScoreOutlierValues(maxValue)) {
+ const offsetPx = toOffsetPx(value);
+ if (offsetPx < Y_TICK_MIN_OFFSET_PX) break;
+ if (lastOffsetPx - offsetPx < Y_TICK_MIN_SPACING_PX) continue;
+ ticks.push({ value, label: def.format(value), offsetPx });
+ if (ticks.length >= Y_TICK_MAX_COUNT) break;
+ lastOffsetPx = offsetPx;
+ }
+ return ticks;
+}
diff --git a/web/src/features/scores-chart-view/fns/outlierStripFilters.clienttest.ts b/web/src/features/scores-chart-view/fns/outlierStripFilters.clienttest.ts
new file mode 100644
index 0000000000..9a6c47cdbe
--- /dev/null
+++ b/web/src/features/scores-chart-view/fns/outlierStripFilters.clienttest.ts
@@ -0,0 +1,37 @@
+import { canApplyScoreOutlierStripFilters } from "@/src/features/scores-chart-view/fns/outlierStripFilters";
+
+describe("canApplyScoreOutlierStripFilters", () => {
+ it("allows an empty filter state", () => {
+ expect(canApplyScoreOutlierStripFilters([])).toBe(true);
+ });
+
+ it("allows filters on scores-numeric dimensions", () => {
+ expect(
+ canApplyScoreOutlierStripFilters([
+ { column: "name", type: "string", operator: "=", value: "accuracy" },
+ { column: "source", type: "string", operator: "=", value: "API" },
+ ]),
+ ).toBe(true);
+ });
+
+ it("disallows a presence (null) filter", () => {
+ expect(
+ canApplyScoreOutlierStripFilters([
+ { column: "comment", type: "null", operator: "is null", value: "" },
+ ]),
+ ).toBe(false);
+ });
+
+ it("disallows a filter with no scores-numeric dimension", () => {
+ expect(
+ canApplyScoreOutlierStripFilters([
+ {
+ column: "stringValue",
+ type: "string",
+ operator: "=",
+ value: "x",
+ },
+ ]),
+ ).toBe(false);
+ });
+});
diff --git a/web/src/features/scores-chart-view/fns/outlierStripFilters.ts b/web/src/features/scores-chart-view/fns/outlierStripFilters.ts
new file mode 100644
index 0000000000..5cef58c213
--- /dev/null
+++ b/web/src/features/scores-chart-view/fns/outlierStripFilters.ts
@@ -0,0 +1,21 @@
+import { type FilterState } from "@langfuse/shared";
+import { partitionStoredUiTableFiltersToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";
+
+/**
+ * Whether every active scores-table filter can be forwarded to the strip's
+ * queries. Checked against `scores-numeric` and `scores-categorical`'s
+ * mapping tables (not the internal `scores-listable-count` view, which isn't
+ * registered there, but shares their common dimension set). A filter with no
+ * dimension on either (e.g. the numeric "Value" range) disables the strip
+ * instead of showing a partial distribution.
+ */
+export const canApplyScoreOutlierStripFilters = (
+ filterState: FilterState,
+): boolean => {
+ if (filterState.some((filter) => filter.type === "null")) return false;
+ return (["scores-numeric", "scores-categorical"] as const).every(
+ (view) =>
+ partitionStoredUiTableFiltersToView(view, filterState).unsupportedFilters
+ .length === 0,
+ );
+};
diff --git a/web/src/features/scores-chart-view/fns/scoreChartConfig.clienttest.ts b/web/src/features/scores-chart-view/fns/scoreChartConfig.clienttest.ts
new file mode 100644
index 0000000000..9890a290c9
--- /dev/null
+++ b/web/src/features/scores-chart-view/fns/scoreChartConfig.clienttest.ts
@@ -0,0 +1,363 @@
+import {
+ coerceScoreChartConfig,
+ describeScoreChartConfig,
+ getScoreChartTimeRange,
+ scoreChartConfigToWidgetInput,
+ scoreMetricField,
+ scoreRowsToDataPoints,
+} from "@/src/features/scores-chart-view/fns/scoreChartConfig";
+import { DEFAULT_SCORE_CHART_CONFIG } from "@/src/features/scores-chart-view/constants/defaultScoreChartConfig";
+import { type ScoreChartViewConfig } from "@/src/features/scores-chart-view/types";
+
+describe("coerceScoreChartConfig", () => {
+ it("resets the aggregation when the metric does not support it", () => {
+ const coerced = coerceScoreChartConfig({
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "count",
+ aggregation: "avg", // count only supports "count"
+ });
+ expect(coerced.aggregation).toBe("count");
+ });
+
+ it("keeps a valid aggregation untouched", () => {
+ const coerced = coerceScoreChartConfig({
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "value",
+ aggregation: "avg",
+ });
+ expect(coerced.aggregation).toBe("avg");
+ });
+
+ it("offers the full aggregation set for value, matching the dashboard widget builder", () => {
+ // Regression: `value` used to be pinned to "avg" only, unlike the real
+ // widget builder, which offers every aggregation for a number-typed
+ // measure (`getValidAggregationsForMeasureType`).
+ const coerced = coerceScoreChartConfig({
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "value",
+ aggregation: "max",
+ });
+ expect(coerced.aggregation).toBe("max");
+ });
+
+ it("preserves the boolean dataset (regression: a stale two-way check used to clamp it back to numeric)", () => {
+ const coerced = coerceScoreChartConfig({
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ dataset: "boolean",
+ });
+ expect(coerced.dataset).toBe("boolean");
+ });
+
+ it("picks the boolean dataset's own metrics, not the numeric dataset's", () => {
+ const coerced = coerceScoreChartConfig({
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ dataset: "boolean",
+ metric: "value",
+ aggregation: "avg",
+ });
+ expect(coerced.dataset).toBe("boolean");
+ expect(coerced.metric).toBe("value");
+ expect(coerced.aggregation).toBe("avg");
+ });
+
+ it("clamps unknown fields (untrusted URL params) to safe defaults", () => {
+ const coerced = coerceScoreChartConfig({
+ dataset: "bogus" as ScoreChartViewConfig["dataset"],
+ metric: "bogus" as ScoreChartViewConfig["metric"],
+ aggregation: "nope" as ScoreChartViewConfig["aggregation"],
+ breakdown: "whoops" as ScoreChartViewConfig["breakdown"],
+ chartType: "FOO" as ScoreChartViewConfig["chartType"],
+ timeGranularity: "century" as ScoreChartViewConfig["timeGranularity"],
+ });
+ expect(coerced.dataset).toBe("numeric");
+ expect(coerced.metric).toBe("count");
+ expect(coerced.aggregation).toBe("count");
+ expect(coerced.breakdown).toBe("none");
+ expect(coerced.chartType).toBe("LINE_TIME_SERIES");
+ expect(coerced.timeGranularity).toBe("hour");
+ });
+});
+
+describe("describeScoreChartConfig", () => {
+ it("describes a count time series with a breakdown", () => {
+ expect(
+ describeScoreChartConfig({
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "count",
+ breakdown: "name",
+ chartType: "LINE_TIME_SERIES",
+ }),
+ ).toBe("Count of scores by name over time");
+ });
+
+ it("includes the aggregation for the value metric", () => {
+ expect(
+ describeScoreChartConfig({
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "value",
+ aggregation: "avg",
+ breakdown: "name",
+ chartType: "HORIZONTAL_BAR",
+ }),
+ ).toBe("Average value by name");
+ });
+
+ it("omits the breakdown for a big number (it shows a single total)", () => {
+ expect(
+ describeScoreChartConfig({
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "count",
+ breakdown: "name",
+ chartType: "NUMBER",
+ }),
+ ).toBe("Count of scores");
+ });
+});
+
+describe("scoreMetricField", () => {
+ it("names the metric column as aggregation_measure", () => {
+ expect(
+ scoreMetricField({
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "value",
+ aggregation: "avg",
+ }),
+ ).toBe("avg_value");
+ expect(
+ scoreMetricField({
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "count",
+ aggregation: "count",
+ }),
+ ).toBe("count_count");
+ });
+});
+
+describe("scoreRowsToDataPoints", () => {
+ it("maps time-series breakdown rows", () => {
+ const rows = [
+ {
+ time_dimension: "2026-06-25T10:00:00Z",
+ name: "accuracy",
+ count_count: 5,
+ },
+ {
+ time_dimension: "2026-06-25T10:00:00Z",
+ name: "toxicity",
+ count_count: 3,
+ },
+ ];
+ expect(
+ scoreRowsToDataPoints(rows, {
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "count",
+ aggregation: "count",
+ breakdown: "name",
+ chartType: "LINE_TIME_SERIES",
+ }),
+ ).toEqual([
+ {
+ time_dimension: "2026-06-25T10:00:00Z",
+ dimension: "accuracy",
+ metric: 5,
+ },
+ {
+ time_dimension: "2026-06-25T10:00:00Z",
+ dimension: "toxicity",
+ metric: 3,
+ },
+ ]);
+ });
+
+ it("labels a no-breakdown series by the metric", () => {
+ const rows = [{ time_dimension: "2026-06-25T10:00:00Z", count_count: 8 }];
+ const [point] = scoreRowsToDataPoints(rows, {
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ breakdown: "none",
+ chartType: "LINE_TIME_SERIES",
+ });
+ expect(point.dimension).toBe("Count");
+ expect(point.metric).toBe(8);
+ });
+
+ it("maps a categorical row and maps null/empty dimensions to n/a", () => {
+ const config: ScoreChartViewConfig = {
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "value",
+ aggregation: "avg",
+ breakdown: "source",
+ chartType: "HORIZONTAL_BAR",
+ };
+ const [nullPoint] = scoreRowsToDataPoints(
+ [{ source: null, avg_value: 0.5 }],
+ config,
+ );
+ expect(nullPoint.dimension).toBe("n/a");
+ expect(nullPoint.metric).toBe(0.5);
+
+ const [emptyPoint] = scoreRowsToDataPoints(
+ [{ source: "", avg_value: 0.8 }],
+ config,
+ );
+ expect(emptyPoint.dimension).toBe("n/a");
+ });
+
+ it("produces a single dimensionless point for a big number", () => {
+ const rows = [{ count_count: 42 }];
+ expect(
+ scoreRowsToDataPoints(rows, {
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ chartType: "NUMBER",
+ }),
+ ).toEqual([
+ { time_dimension: undefined, dimension: undefined, metric: 42 },
+ ]);
+ });
+
+ it("preserves an explicit null as a gap on a time series (never coerces to 0)", () => {
+ const config: ScoreChartViewConfig = {
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ metric: "value",
+ aggregation: "avg",
+ breakdown: "none",
+ chartType: "LINE_TIME_SERIES",
+ };
+ const [point] = scoreRowsToDataPoints(
+ [{ time_dimension: "2026-06-25T10:00:00Z", avg_value: null }],
+ config,
+ );
+ expect(point.metric).toBeNull();
+ });
+});
+
+describe("scoreChartConfigToWidgetInput", () => {
+ const build = (config: Partial<ScoreChartViewConfig>) =>
+ scoreChartConfigToWidgetInput({
+ config: { ...DEFAULT_SCORE_CHART_CONFIG, ...config },
+ filters: [],
+ });
+
+ it("maps the numeric dataset to the scores-numeric view", () => {
+ expect(build({}).view).toBe("scores-numeric");
+ });
+
+ // Regression: `scores-numeric`'s own segment allow-lists NUMERIC AND
+ // BOOLEAN, so leaving the numeric dataset unscoped mixed boolean 0/1
+ // values into it once "boolean" became a separately selectable dataset.
+ it("scopes the numeric dataset to NUMERIC only, excluding boolean scores", () => {
+ expect(build({}).filters).toEqual([
+ { column: "dataType", operator: "=", value: "NUMERIC", type: "string" },
+ ]);
+ });
+
+ it("adds a redundant BOOLEAN-only filter for the boolean dataset (the view is already BOOLEAN-only)", () => {
+ expect(build({ dataset: "boolean", metric: "value" }).filters).toEqual([
+ { column: "dataType", operator: "=", value: "BOOLEAN", type: "string" },
+ ]);
+ });
+
+ // The table's own Data Type filter is appended to, never replaced by, the
+ // dataset's own scoping filter: if the two conflict (e.g. the sidebar set
+ // to NUMERIC while viewing the boolean chart), they AND to zero rows and
+ // the chart shows "No data" instead of silently overriding the user's
+ // filter to show unrelated (boolean) data.
+ it("ANDs a conflicting incoming dataType filter with the boolean dataset's own scope, yielding no data rather than overriding the filter", () => {
+ const input = scoreChartConfigToWidgetInput({
+ config: {
+ ...DEFAULT_SCORE_CHART_CONFIG,
+ dataset: "boolean",
+ metric: "value",
+ },
+ filters: [
+ { column: "dataType", operator: "=", value: "NUMERIC", type: "string" },
+ ],
+ });
+ expect(input.filters).toEqual([
+ { column: "dataType", operator: "=", value: "NUMERIC", type: "string" },
+ { column: "dataType", operator: "=", value: "BOOLEAN", type: "string" },
+ ]);
+ });
+
+ it("ANDs a conflicting incoming dataType filter with the categorical dataset's own scope, yielding no data rather than overriding the filter", () => {
+ const input = scoreChartConfigToWidgetInput({
+ config: { ...DEFAULT_SCORE_CHART_CONFIG, dataset: "categorical" },
+ filters: [
+ {
+ column: "dataType",
+ operator: "=",
+ value: "BOOLEAN",
+ type: "string",
+ },
+ ],
+ });
+ expect(input.filters).toEqual([
+ { column: "dataType", operator: "=", value: "BOOLEAN", type: "string" },
+ {
+ column: "dataType",
+ operator: "=",
+ value: "CATEGORICAL",
+ type: "string",
+ },
+ ]);
+ });
+
+ // Regression: a stale two-way check (`dataset === "categorical" ? ... :
+ // "scores-numeric"`) used to fall the boolean dataset through to
+ // scores-numeric, so "Add to dashboard" would save a widget querying the
+ // wrong view.
+ it("maps the boolean dataset to the scores-boolean view", () => {
+ expect(build({ dataset: "boolean", metric: "value" }).view).toBe(
+ "scores-boolean",
+ );
+ });
+
+ it("maps the categorical dataset to the scores-categorical view, with its own redundant CATEGORICAL-only filter", () => {
+ const input = build({ dataset: "categorical" });
+ expect(input.view).toBe("scores-categorical");
+ expect(input.filters).toEqual([
+ {
+ column: "dataType",
+ operator: "=",
+ value: "CATEGORICAL",
+ type: "string",
+ },
+ ]);
+ });
+
+ // Regression: `scopeFiltersToDataset` used to replace an existing dataType
+ // filter for the numeric dataset instead of ANDing it, so a table filtered
+ // to BOOLEAN while viewing the numeric chart silently showed numeric data
+ // instead of the "no data" a genuinely conflicting filter should produce.
+ it("ANDs a conflicting incoming dataType filter with the numeric dataset's own scope, yielding no data rather than overriding the filter", () => {
+ const input = scoreChartConfigToWidgetInput({
+ config: { ...DEFAULT_SCORE_CHART_CONFIG, dataset: "numeric" },
+ filters: [
+ { column: "dataType", operator: "=", value: "BOOLEAN", type: "string" },
+ ],
+ });
+ expect(input.filters).toEqual([
+ { column: "dataType", operator: "=", value: "BOOLEAN", type: "string" },
+ { column: "dataType", operator: "=", value: "NUMERIC", type: "string" },
+ ]);
+ });
+});
+
+describe("getScoreChartTimeRange", () => {
+ const now = new Date("2026-06-26T12:00:00.000Z");
+
+ it("does not invent a 24-hour range when the table is unfiltered", () => {
+ expect(getScoreChartTimeRange(undefined, now)).toBeUndefined();
+ });
+
+ it("closes an open-ended table range at now", () => {
+ expect(
+ getScoreChartTimeRange(
+ { from: new Date("2026-06-25T12:00:00.000Z") },
+ now,
+ ),
+ ).toEqual({
+ from: new Date("2026-06-25T12:00:00.000Z"),
+ to: now,
+ });
+ });
+});
diff --git a/web/src/features/scores-chart-view/fns/scoreChartConfig.ts b/web/src/features/scores-chart-view/fns/scoreChartConfig.ts
new file mode 100644
index 0000000000..eda39f42a0
--- /dev/null
+++ b/web/src/features/scores-chart-view/fns/scoreChartConfig.ts
@@ -0,0 +1,359 @@
+import { type FilterState, type QueryType } from "@langfuse/shared";
+import {
+ AGGREGATION_LABELS,
+ CHART_TYPES,
+ GRANULARITIES,
+ isTimeSeriesChartType,
+} from "@/src/features/chart-view/vocab";
+import { type ChartWidgetInput } from "@/src/features/chart-view/lib/chartConfigToWidget";
+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";
+import { getWidgetMissingBucketValue } from "@/src/features/widgets/utils";
+import { getScoreDimensionsForDataset } from "@/src/features/scores-chart-view/constants/scoreDimensions";
+import {
+ getScoreMetricsForDataset,
+ SCORE_METRICS,
+} from "@/src/features/scores-chart-view/constants/scoreMetrics";
+import { VIEW_BY_DATASET } from "@/src/features/scores-chart-view/constants/viewByDataset";
+import {
+ type ScoreChartDataset,
+ type ScoreChartViewConfig,
+ type ScoreDimensionDef,
+ type ScoreDimensionKey,
+ type ScoreMetricDef,
+ type ScoreMetricKey,
+} from "@/src/features/scores-chart-view/types";
+
+/**
+ * Everything that reads or derives from a `ScoreChartViewConfig` β€” one
+ * module because these functions are small, call each other constantly, and
+ * are never used independently of the config they all take. Mirrors the
+ * observations chart view's equivalent surface
+ * (`@/src/features/chart-view/vocab` + `lib/buildChartQuery` +
+ * `lib/chartConfigToWidget`), just consolidated into a single file instead
+ * of split across three.
+ */
+
+// ---------------------------------------------------------------------------
+// Metric / dimension lookups
+// ---------------------------------------------------------------------------
+
+/**
+ * `key` alone doesn't uniquely identify a metric β€” "count" exists on every
+ * dataset (see `SCORE_METRICS`) β€” so `dataset` disambiguates which view's
+ * definition to use.
+ */
+export const getScoreMetric = (
+ key: ScoreMetricKey,
+ dataset: ScoreChartDataset,
+): ScoreMetricDef =>
+ SCORE_METRICS.find((m) => m.key === key && m.dataset === dataset) ??
+ SCORE_METRICS.find((m) => m.dataset === dataset) ??
+ SCORE_METRICS[0];
+
+/**
+ * `key` alone doesn't uniquely identify a dimension across datasets (the
+ * dimension list is per-view, see `getScoreDimensionsForDataset`), so
+ * `dataset` disambiguates which view's list to look in.
+ */
+export const getScoreDimension = (
+ key: ScoreDimensionKey,
+ dataset: ScoreChartDataset,
+ isTimeSeries: boolean,
+): ScoreDimensionDef => {
+ const options = getScoreDimensionsForDataset(dataset, isTimeSeries);
+ return options.find((d) => d.key === key) ?? options[0];
+};
+
+/** The executeQuery column name for a metric, e.g. `avg_value`, `count_count`. */
+export const scoreMetricField = (config: ScoreChartViewConfig): string =>
+ `${config.aggregation}_${getScoreMetric(config.metric, config.dataset).measure}`;
+
+// ---------------------------------------------------------------------------
+// Config validation / description
+// ---------------------------------------------------------------------------
+
+/**
+ * Coerces a config to a valid, internally-consistent spec β€” same contract as
+ * the observations chart view's `coerceConfig`: every field clamped to a
+ * known enum member (untrusted URL params), and the aggregation reset when
+ * the metric changed underneath it.
+ */
+export const coerceScoreChartConfig = (
+ config: ScoreChartViewConfig,
+): ScoreChartViewConfig => {
+ // A stale two-way ternary here previously clamped "boolean" straight back
+ // down to "numeric" on every config update, silently making the boolean
+ // view unselectable no matter what the picker offered.
+ const dataset: ScoreChartDataset =
+ config.dataset === "boolean" || config.dataset === "categorical"
+ ? config.dataset
+ : "numeric";
+ const datasetMetrics = getScoreMetricsForDataset(dataset);
+ // The metric may not exist on the new dataset (e.g. switching from
+ // "numeric" while "value" is selected β€” categorical scores have no value
+ // measure), so fall back to that dataset's first metric rather than the
+ // global default.
+ const metric = datasetMetrics.some((m) => m.key === config.metric)
+ ? getScoreMetric(config.metric, dataset)
+ : datasetMetrics[0];
+ const aggregation = metric.aggregations.includes(config.aggregation)
+ ? config.aggregation
+ : metric.aggregations[0];
+ const chartType = CHART_TYPES.some((c) => c.value === config.chartType)
+ ? config.chartType
+ : CHART_TYPES[0].value;
+ // Resolved before the breakdown check below: switching TO a time-series
+ // chart type must also re-validate a highCardinality breakdown the user
+ // had picked on a ranked/pie/number chart, or the next query 422s.
+ const isTimeSeries = isTimeSeriesChartType(chartType);
+ const datasetDimensions = getScoreDimensionsForDataset(dataset, isTimeSeries);
+ const breakdown = datasetDimensions.some((d) => d.key === config.breakdown)
+ ? config.breakdown
+ : "none";
+ const timeGranularity = GRANULARITIES.includes(config.timeGranularity)
+ ? config.timeGranularity
+ : "hour";
+ return {
+ dataset,
+ metric: metric.key,
+ aggregation,
+ breakdown,
+ chartType,
+ timeGranularity,
+ };
+};
+
+/** Human sentence describing a config β€” the chart subtitle. */
+export const describeScoreChartConfig = (
+ config: ScoreChartViewConfig,
+): string => {
+ const metric = getScoreMetric(config.metric, config.dataset);
+ const metricPart =
+ config.metric === "count"
+ ? "Count of scores"
+ : `${AGGREGATION_LABELS[config.aggregation]} ${metric.label.toLowerCase()}`;
+ const byPart =
+ config.breakdown === "none" || config.chartType === "NUMBER"
+ ? ""
+ : ` by ${getScoreDimension(
+ config.breakdown,
+ config.dataset,
+ isTimeSeriesChartType(config.chartType),
+ ).label.toLowerCase()}`;
+ const timePart = isTimeSeriesChartType(config.chartType) ? " over time" : "";
+ return `${metricPart}${byPart}${timePart}`;
+};
+
+// ---------------------------------------------------------------------------
+// Query building / row mapping / widget export
+// ---------------------------------------------------------------------------
+
+/** Ranked/pie charts (and widgets) show a top-N slice. */
+const CATEGORICAL_ROW_LIMIT = 20;
+
+/**
+ * `scores-numeric` also carries BOOLEAN scores (its segment allow-lists both
+ * NUMERIC and BOOLEAN), so every dataset gets its own `dataType` filter
+ * appended β€” numeric to exclude boolean scores, boolean/categorical
+ * redundantly with their own view segment. Appended, not replacing: if the
+ * table's own Data Type filter conflicts with the dataset (e.g. filtered to
+ * BOOLEAN while viewing the numeric chart), the two AND together to zero
+ * rows, and the chart shows "No data" β€” an honest answer, instead of
+ * silently overriding the user's filter to show unrelated data.
+ */
+const DATASET_DATA_TYPE: Record<ScoreChartDataset, string> = {
+ numeric: "NUMERIC",
+ boolean: "BOOLEAN",
+ categorical: "CATEGORICAL",
+};
+
+const scopeFiltersToDataset = (
+ filters: FilterState,
+ dataset: ScoreChartDataset,
+): FilterState => [
+ ...filters,
+ {
+ column: "dataType",
+ operator: "=" as const,
+ value: DATASET_DATA_TYPE[dataset],
+ type: "string" as const,
+ },
+];
+
+/**
+ * Builds the dashboard `QueryType` for a scores chart-view config. Mirrors
+ * `buildChartQuery` (the observations chart view) and the existing "Scores"
+ * dashboard widgets β€” same views, same shape. `filters` should already be
+ * mapped onto the config's dataset view, e.g. via
+ * `mapLegacyUiTableFilterToView("scores-numeric" | "scores-boolean" | "scores-categorical", ...)`.
+ */
+export function buildScoresChartQuery({
+ config,
+ filters,
+ fromTimestamp,
+ toTimestamp,
+}: {
+ config: ScoreChartViewConfig;
+ filters: FilterState;
+ fromTimestamp: Date;
+ toTimestamp: Date;
+}): QueryType {
+ const isTimeSeries = isTimeSeriesChartType(config.chartType);
+ const metric = getScoreMetric(config.metric, config.dataset);
+ const dimension = getScoreDimension(
+ config.breakdown,
+ config.dataset,
+ isTimeSeries,
+ );
+ const isNumber = config.chartType === "NUMBER";
+
+ const dimensions =
+ !isNumber && dimension.field ? [{ field: dimension.field }] : [];
+
+ const isCategoricalBreakdown =
+ !isTimeSeries && !isNumber && dimensions.length > 0;
+ const field = scoreMetricField(config);
+
+ return {
+ view: VIEW_BY_DATASET[config.dataset],
+ dimensions,
+ metrics: [{ measure: metric.measure, aggregation: config.aggregation }],
+ filters: scopeFiltersToDataset(filters, config.dataset),
+ timeDimension: isTimeSeries ? { granularity: "auto" } : null,
+ fromTimestamp: fromTimestamp.toISOString(),
+ toTimestamp: toTimestamp.toISOString(),
+ orderBy: isCategoricalBreakdown
+ ? [{ field, direction: "desc" as const }]
+ : null,
+ chartConfig: isCategoricalBreakdown
+ ? { type: config.chartType, row_limit: CATEGORICAL_ROW_LIMIT }
+ : { type: config.chartType },
+ };
+}
+
+/** Stringify a raw dimension cell the way the widget charts do. */
+function dimensionValue(raw: unknown): string {
+ if (raw === null || raw === undefined || raw === "") return "n/a";
+ if (typeof raw === "string") return raw;
+ if (Array.isArray(raw)) return raw.join(", ");
+ return String(raw);
+}
+
+/**
+ * Turns `executeQuery` rows into chart-library `DataPoint[]` for a config β€”
+ * the inverse of `buildScoresChartQuery`. Mirrors the observations chart
+ * view's `rowsToDataPoints`.
+ */
+export function scoreRowsToDataPoints(
+ rows: Array<Record<string, unknown>>,
+ config: ScoreChartViewConfig,
+): DataPoint[] {
+ const isTimeSeries = isTimeSeriesChartType(config.chartType);
+ const metric = getScoreMetric(config.metric, config.dataset);
+ const dimension = getScoreDimension(
+ config.breakdown,
+ config.dataset,
+ isTimeSeries,
+ );
+ const field = scoreMetricField(config);
+ const isNumber = config.chartType === "NUMBER";
+ const hasBreakdown = !isNumber && dimension.field !== null;
+
+ return rows.map((row) => {
+ const time_dimension = row["time_dimension"] as string | undefined;
+ const value = row[field];
+
+ if (isTimeSeries && hasBreakdown) {
+ const rawDim = row[dimension.field as string];
+ const isFiller =
+ value == null ||
+ (getWidgetMissingBucketValue(config.aggregation) === "zero" &&
+ Number(value) === 0);
+ if ((rawDim === null || rawDim === "") && isFiller) {
+ return { time_dimension, dimension: undefined, metric: null };
+ }
+ }
+
+ const dim = hasBreakdown
+ ? dimensionValue(row[dimension.field as string])
+ : isNumber
+ ? undefined
+ : metric.label;
+ const metricValue = Array.isArray(value)
+ ? value
+ : isTimeSeries && value == null
+ ? null
+ : Number(value ?? 0);
+ return { time_dimension, dimension: dim, metric: metricValue };
+ });
+}
+
+/**
+ * Maps a scores chart-view config (+ the filters the chart is showing) to the
+ * input of the EXISTING `dashboardWidgets.create` mutation β€” same bridge the
+ * observations chart view uses (`chartConfigToWidgetInput`), so "Add to
+ * dashboard" reuses the widget-creation flow instead of duplicating it.
+ */
+export function scoreChartConfigToWidgetInput({
+ config,
+ filters,
+}: {
+ config: ScoreChartViewConfig;
+ filters: FilterState;
+}): ChartWidgetInput {
+ const isTimeSeries = isTimeSeriesChartType(config.chartType);
+ const metric = getScoreMetric(config.metric, config.dataset);
+ const dimension = getScoreDimension(
+ config.breakdown,
+ config.dataset,
+ isTimeSeries,
+ );
+ const isNumber = config.chartType === "NUMBER";
+
+ const dimensions =
+ !isNumber && dimension.field ? [{ field: dimension.field }] : [];
+ const metrics = [{ measure: metric.measure, agg: config.aggregation }];
+
+ const isCategoricalBreakdown =
+ !isTimeSeries && !isNumber && dimensions.length > 0;
+
+ const chartConfig = (
+ isCategoricalBreakdown
+ ? { type: config.chartType, row_limit: CATEGORICAL_ROW_LIMIT }
+ : { type: config.chartType }
+ ) as ChartWidgetInput["chartConfig"];
+
+ return {
+ name: describeScoreChartConfig(config),
+ description: "",
+ view: VIEW_BY_DATASET[config.dataset],
+ dimensions,
+ metrics,
+ // Matches `buildScoresChartQuery`'s per-dataset data-type scoping so
+ // "Add to dashboard" saves the same scope the chart showed.
+ filters: scopeFiltersToDataset(filters, config.dataset),
+ chartType: config.chartType,
+ chartConfig,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Time range
+// ---------------------------------------------------------------------------
+
+/**
+ * Charts only render when the table has a time range; inventing a default
+ * range here would make the chart silently omit table rows, so an unfiltered
+ * table (`dateRange` undefined) yields no chart range at all.
+ */
+export function getScoreChartTimeRange(
+ dateRange: { from: Date; to?: Date } | undefined,
+ now: Date,
+): { from: Date; to: Date } | undefined {
+ if (!dateRange) return undefined;
+
+ return {
+ from: dateRange.from,
+ to: dateRange.to ?? now,
+ };
+}
diff --git a/web/src/features/scores-chart-view/hooks/useScoreOutlierStripSettings.ts b/web/src/features/scores-chart-view/hooks/useScoreOutlierStripSettings.ts
new file mode 100644
index 0000000000..9c25a9bca2
--- /dev/null
+++ b/web/src/features/scores-chart-view/hooks/useScoreOutlierStripSettings.ts
@@ -0,0 +1,39 @@
+import { useMemo } from "react";
+import { z } from "zod";
+import useLocalStorage from "@/src/components/useLocalStorage";
+
+/**
+ * The strip's per-user chart settings as ONE zod-validated localStorage
+ * object β€” mirrors the observations strip's `useOutlierStripSettings`.
+ * localStorage is user-editable and cross-tab-writable; validating at a
+ * single seam makes a corrupted or legacy value structurally incapable of
+ * crashing the page.
+ */
+const scoreOutlierStripSettingsSchema = z
+ .object({
+ mode: z.enum(["count", "value"]).catch("count"),
+ valueAgg: z.enum(["avg", "min", "max"]).catch("avg"),
+ })
+ .catch({ mode: "count", valueAgg: "avg" });
+
+export type ScoreOutlierStripSettings = z.infer<
+ typeof scoreOutlierStripSettingsSchema
+>;
+
+export function useScoreOutlierStripSettings(): {
+ settings: ScoreOutlierStripSettings;
+ update: (patch: Partial<ScoreOutlierStripSettings>) => void;
+} {
+ const [raw, setRaw] = useLocalStorage<unknown>(
+ "scores-pulse-chart-settings",
+ {},
+ );
+ const settings = useMemo(
+ () => scoreOutlierStripSettingsSchema.parse(raw ?? {}),
+ [raw],
+ );
+ return {
+ settings,
+ update: (patch) => setRaw({ ...settings, ...patch }),
+ };
+}
diff --git a/web/src/features/scores-chart-view/hooks/useScoresChartViewState.ts b/web/src/features/scores-chart-view/hooks/useScoresChartViewState.ts
new file mode 100644
index 0000000000..f4b2603da9
--- /dev/null
+++ b/web/src/features/scores-chart-view/hooks/useScoresChartViewState.ts
@@ -0,0 +1,112 @@
+import { useCallback, useMemo } from "react";
+import { StringParam, useQueryParams, withDefault } from "use-query-params";
+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
+import {
+ type AggregationFn,
+ type ViewMode,
+} from "@/src/features/chart-view/types";
+import { DEFAULT_SCORE_CHART_CONFIG } from "@/src/features/scores-chart-view/constants/defaultScoreChartConfig";
+import { coerceScoreChartConfig } from "@/src/features/scores-chart-view/fns/scoreChartConfig";
+import {
+ type ScoreChartDataset,
+ type ScoreChartViewConfig,
+ type ScoreDimensionKey,
+ type ScoreMetricKey,
+} from "@/src/features/scores-chart-view/types";
+
+const orUndefined = <T>(value: T, fallback: T): T | undefined =>
+ value === fallback ? undefined : value;
+
+/**
+ * URL-driven table<->chart state for the scores table β€” same contract as the
+ * observations chart view's `useChartViewState`, namespaced under `scores*`
+ * so it can't collide with it on a page that renders both (e.g. a trace
+ * detail panel).
+ */
+export function useScoresChartViewState(): {
+ viewMode: ViewMode;
+ setViewMode: (mode: ViewMode) => void;
+ config: ScoreChartViewConfig;
+ setConfig: (patch: Partial<ScoreChartViewConfig>) => void;
+} {
+ const [params, setParams] = useQueryParams({
+ scoresView: withDefault(StringParam, "table"),
+ scoresChartDataset: withDefault(
+ StringParam,
+ DEFAULT_SCORE_CHART_CONFIG.dataset,
+ ),
+ scoresChartMetric: withDefault(
+ StringParam,
+ DEFAULT_SCORE_CHART_CONFIG.metric,
+ ),
+ scoresChartAgg: withDefault(
+ StringParam,
+ DEFAULT_SCORE_CHART_CONFIG.aggregation,
+ ),
+ scoresChartBreakdown: withDefault(
+ StringParam,
+ DEFAULT_SCORE_CHART_CONFIG.breakdown,
+ ),
+ scoresChartType: withDefault(
+ StringParam,
+ DEFAULT_SCORE_CHART_CONFIG.chartType,
+ ),
+ });
+
+ const viewMode: ViewMode = params.scoresView === "chart" ? "chart" : "table";
+
+ const config = useMemo<ScoreChartViewConfig>(
+ () =>
+ coerceScoreChartConfig({
+ dataset: params.scoresChartDataset as ScoreChartDataset,
+ metric: params.scoresChartMetric as ScoreMetricKey,
+ aggregation: params.scoresChartAgg as AggregationFn,
+ breakdown: params.scoresChartBreakdown as ScoreDimensionKey,
+ chartType: params.scoresChartType as DashboardWidgetChartType,
+ timeGranularity: DEFAULT_SCORE_CHART_CONFIG.timeGranularity,
+ }),
+ [
+ params.scoresChartDataset,
+ params.scoresChartMetric,
+ params.scoresChartAgg,
+ params.scoresChartBreakdown,
+ params.scoresChartType,
+ ],
+ );
+
+ const setViewMode = useCallback(
+ (mode: ViewMode) => setParams({ scoresView: orUndefined(mode, "table") }),
+ [setParams],
+ );
+
+ const setConfig = useCallback(
+ (patch: Partial<ScoreChartViewConfig>) => {
+ const next = coerceScoreChartConfig({ ...config, ...patch });
+ setParams({
+ scoresChartDataset: orUndefined(
+ next.dataset,
+ DEFAULT_SCORE_CHART_CONFIG.dataset,
+ ),
+ scoresChartMetric: orUndefined(
+ next.metric,
+ DEFAULT_SCORE_CHART_CONFIG.metric,
+ ),
+ scoresChartAgg: orUndefined(
+ next.aggregation,
+ DEFAULT_SCORE_CHART_CONFIG.aggregation,
+ ),
+ scoresChartBreakdown: orUndefined(
+ next.breakdown,
+ DEFAULT_SCORE_CHART_CONFIG.breakdown,
+ ),
+ scoresChartType: orUndefined(
+ next.chartType,
+ DEFAULT_SCORE_CHART_CONFIG.chartType,
+ ),
+ });
+ },
+ [config, setParams],
+ );
+
+ return { viewMode, setViewMode, config, setConfig };
+}
diff --git a/web/src/features/scores-chart-view/index.ts b/web/src/features/scores-chart-view/index.ts
new file mode 100644
index 0000000000..ffcbca8c2b
--- /dev/null
+++ b/web/src/features/scores-chart-view/index.ts
@@ -0,0 +1,7 @@
+// Client-safe surface for this feature. Named re-exports only β€” see the
+// project's code-structure RFC. Everything else in this feature is internal;
+// import it through here.
+export { ScoresChartView } from "@/src/features/scores-chart-view/components/ScoresChartView";
+export { ScoresOutlierStrip } from "@/src/features/scores-chart-view/components/ScoresOutlierStrip";
+export { useScoresChartViewState } from "@/src/features/scores-chart-view/hooks/useScoresChartViewState";
+export type { ScoreChartViewConfig } from "@/src/features/scores-chart-view/types";
diff --git a/web/src/features/scores-chart-view/types.ts b/web/src/features/scores-chart-view/types.ts
new file mode 100644
index 0000000000..63119f13cf
--- /dev/null
+++ b/web/src/features/scores-chart-view/types.ts
@@ -0,0 +1,126 @@
+import { type DashboardWidgetChartType } from "@langfuse/shared/src/db";
+import {
+ type AggregationFn,
+ type TimeGranularity,
+} from "@/src/features/chart-view/types";
+
+/**
+ * All types for the scores chart view + outlier strip, in one module β€”
+ * mostly small type aliases/interfaces with no runtime logic, so splitting
+ * them into a dozen one-liner files added navigation overhead without
+ * adding isolation.
+ */
+
+// ---------------------------------------------------------------------------
+// Chart view config
+// ---------------------------------------------------------------------------
+
+/**
+ * Which underlying scores view the chart queries β€” matches the three views
+ * the query engine already exposes for scores (`packages/shared/src/features/
+ * query/dataModel.ts`) and the same three-way split the rest of the app uses
+ * (`viewLabels` in `@/src/features/monitors/helpers/monitorLabels`, the
+ * scores filter groups in `@/src/features/experiments/config/
+ * experiment-items-filter-config`):
+ * - "numeric": the `scores-numeric` view. NUMERIC scores, average/sum/min/max-able.
+ * - "boolean": the `scores-boolean` view. BOOLEAN scores; its "value" measure
+ * is the 0/1 average, i.e. the true-rate.
+ * - "categorical": the `scores-categorical` view, count-only β€” categorical
+ * scores have no numeric magnitude to aggregate.
+ */
+export type ScoreChartDataset = "numeric" | "boolean" | "categorical";
+
+/**
+ * The two measures the `scores-numeric` view exposes (see
+ * `packages/shared/src/features/query/dataModel.ts`). Query surface is
+ * deliberately smaller than the events/observations chart view
+ * (`@/src/features/chart-view`): the scores table only ever charts one view,
+ * so there is no per-view picker.
+ */
+export type ScoreMetricKey = "count" | "value";
+
+export interface ScoreMetricDef {
+ key: ScoreMetricKey;
+ label: string;
+ /** Which view (`scores-numeric` or `scores-categorical`) this metric queries. */
+ dataset: ScoreChartDataset;
+ /** The measure name this metric aggregates over on that view. */
+ measure: string;
+ aggregations: AggregationFn[];
+ /** Passed through to the shared `ChartCanvas` so axes/tooltips render units. */
+ unit?: string;
+}
+
+/**
+ * The breakdown dimensions the scores chart view offers are read directly
+ * off each view's real dimension declaration (see
+ * `getScoreDimensionsForDataset`) β€” the same source the dashboard widget
+ * builder reads β€” rather than a fixed, hand-maintained enum that could drift
+ * from it. So this is just a plain string, not a closed union.
+ */
+export type ScoreDimensionKey = string;
+
+export interface ScoreDimensionDef {
+ key: ScoreDimensionKey;
+ label: string;
+ /** The dimension field on the active dataset's view; `null` for "no breakdown". */
+ field: string | null;
+}
+
+export interface ScoreChartViewConfig {
+ /** Which scores view ("Scores (numeric)" vs "Scores (categorical)") to chart. */
+ dataset: ScoreChartDataset;
+ metric: ScoreMetricKey;
+ // Reuses the observations chart view's `AggregationFn`/`TimeGranularity` β€”
+ // both are already view-agnostic (they only describe a SQL aggregation and
+ // a bucket size, not a specific metric or dimension).
+ aggregation: AggregationFn;
+ breakdown: ScoreDimensionKey;
+ chartType: DashboardWidgetChartType;
+ timeGranularity: TimeGranularity;
+}
+
+// ---------------------------------------------------------------------------
+// Outlier strip ("Pulse")
+// ---------------------------------------------------------------------------
+
+/**
+ * The metrics the scores outlier strip can plot β€” mirrors the observations
+ * strip's `OutlierStripMetricKey`
+ * (`@/src/features/events/components/outlier-strip`), trimmed to the two
+ * measures `scores-numeric` exposes.
+ */
+export type ScoreOutlierMetricKey = "count" | "value";
+
+export type ScoreOutlierAggKey = "count" | "avg" | "min" | "max";
+
+/** One executeQuery row; metric columns are looked up via the registry. */
+export type ScoreOutlierQueryRow = Record<string, unknown> & {
+ time_dimension?: string;
+ count_count?: unknown;
+};
+
+/** One bucket of aggregates, keyed by result column (`agg_measure`). */
+export type ScoreOutlierBin = {
+ bucketStart: Date;
+ count: number;
+ values: Record<string, number | null>;
+};
+
+/** One bucket on the dense grid; `value` null = no data in this bucket. */
+export type ScoreOutlierDenseBin = {
+ bucketStartMs: number;
+ count: number;
+ value: number | null;
+};
+
+/** A prepared gridline tick: dense-bin index + presentation-ready label. */
+export type ScoreOutlierTick = { index: number; label: string };
+
+/** A prepared horizontal value gridline. */
+export type ScoreOutlierYTick = {
+ value: number;
+ label: string;
+ /** px above the baseline, already mapped through the bar-height scale. */
+ offsetPx: number;
+};