Skip to content

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

refactor(monitors): extract metric definition into separate component (#19519)

Mark Salpeter8ff6ff30a710
diff --git a/web/src/components/design-system/DropdownMenu/DropdownMenu.tsx b/web/src/components/design-system/DropdownMenu/DropdownMenu.tsx
index 793e780e84..10486830fd 100644
--- a/web/src/components/design-system/DropdownMenu/DropdownMenu.tsx
+++ b/web/src/components/design-system/DropdownMenu/DropdownMenu.tsx
@@ -10,6 +10,7 @@ import {
offset,
safePolygon,
shift,
+ size,
useClick,
useDismiss,
useFloating,
@@ -175,6 +176,8 @@ type DropdownMenuProps = {
items: DropdownMenuItemDefinition[];
disabled?: boolean;
maxHeight?: React.CSSProperties["maxHeight"];
+ /** Sizes the menu to the trigger's width, e.g. for a full-width button. */
+ matchTriggerWidth?: boolean;
placement?: Placement;
search?: { placeholder: string };
title?: string;
@@ -206,6 +209,7 @@ function DropdownMenuNode({
internal = false,
items,
maxHeight = "15rem",
+ matchTriggerWidth = false,
placement = "bottom-start",
search,
title,
@@ -242,7 +246,20 @@ function DropdownMenuNode({
if (open) tree?.events.emit("menuopen", { nodeId, parentId });
},
placement,
- middleware: [offset(4), flip(), shift({ padding: 8, crossAxis: true })],
+ middleware: [
+ offset(4),
+ flip(),
+ shift({ padding: 8, crossAxis: true }),
+ ...(matchTriggerWidth
+ ? [
+ size({
+ apply({ rects, elements }) {
+ elements.floating.style.width = `${rects.reference.width}px`;
+ },
+ }),
+ ]
+ : []),
+ ],
transform: false,
whileElementsMounted: autoUpdate,
});
diff --git a/web/src/components/design-system/internal/charts/CartesianLayout.tsx b/web/src/components/design-system/internal/charts/CartesianLayout.tsx
index 5334ddc722..bf9b7bdd56 100644
--- a/web/src/components/design-system/internal/charts/CartesianLayout.tsx
+++ b/web/src/components/design-system/internal/charts/CartesianLayout.tsx
@@ -6,6 +6,7 @@ export const CARTESIAN_CHART_INSETS = {
bottomWithLabels: 26,
bottomWithoutLabels: 12,
minLeft: 64,
+ compactMinLeft: 32,
};
const Y_TICK_HEIGHT = 28;
@@ -25,19 +26,27 @@ function getCartesianTickCount(plotHeight: number) {
return Math.min(5, Math.max(1, Math.floor(plotHeight / Y_TICK_HEIGHT)));
}
+/** getMinLeft picks the y-axis gutter floor; compact fits short tick labels. */
+function getMinLeft(compactYAxis: boolean) {
+ if (compactYAxis) return CARTESIAN_CHART_INSETS.compactMinLeft;
+ return CARTESIAN_CHART_INSETS.minLeft;
+}
+
function getCartesianLayout({
width,
height,
showXAxisLabels,
+ compactYAxis,
yTickLabels,
}: {
width: number;
height: number;
showXAxisLabels: boolean;
+ compactYAxis: boolean;
yTickLabels: string[];
}) {
const left = Math.max(
- CARTESIAN_CHART_INSETS.minLeft,
+ getMinLeft(compactYAxis),
...yTickLabels.map((label) => label.length * 7 + 16),
);
return {
@@ -54,11 +63,13 @@ export function CartesianLayout({
width,
height,
showXAxisLabels,
+ compactYAxis = false,
children,
}: {
width: number;
height: number;
showXAxisLabels: boolean;
+ compactYAxis?: boolean;
children: (layout: {
measuredPlot: CartesianPlot;
maxYTicks: number;
@@ -72,6 +83,7 @@ export function CartesianLayout({
width,
height,
showXAxisLabels,
+ compactYAxis,
yTickLabels: [],
});
return children({
@@ -82,6 +94,7 @@ export function CartesianLayout({
width,
height,
showXAxisLabels: options?.showXAxisLabels ?? showXAxisLabels,
+ compactYAxis,
yTickLabels,
}),
});
diff --git a/web/src/components/design-system/internal/charts/SeriesChartCore.tsx b/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
index 0962b7c34d..b397cb3a6b 100644
--- a/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
+++ b/web/src/components/design-system/internal/charts/SeriesChartCore.tsx
@@ -62,6 +62,8 @@ type CommonLineChartProps = {
onActiveKeyChange: (key: string | undefined) => void;
};
legend?: LineChartLegend;
+ /** compactYAxis shrinks the y-axis gutter to fit short tick labels. */
+ compactYAxis?: boolean;
};
type LineChartProps = CommonLineChartProps &
@@ -305,6 +307,7 @@ export function SeriesChartCore(
props.xAxis.type !== "category" ||
props.xAxis.labels !== "hidden"
}
+ compactYAxis={props.compactYAxis}
>
{(layout) => (
<LineChartContent
diff --git a/web/src/components/layouts/page-header.tsx b/web/src/components/layouts/page-header.tsx
index a2bc58e231..4445fa9aa0 100644
--- a/web/src/components/layouts/page-header.tsx
+++ b/web/src/components/layouts/page-header.tsx
@@ -59,6 +59,8 @@ export type PageHeaderProps = {
leadingControl?: ReactNode;
titleBadges?: ReactNode;
breadcrumbBadges?: ReactNode;
+ /** hideTitleRow drops the title and actions row, keeping the breadcrumb bar. */
+ hideTitleRow?: boolean;
};
const PageHeader = ({
@@ -78,6 +80,7 @@ const PageHeader = ({
leadingControl,
titleBadges,
breadcrumbBadges,
+ hideTitleRow = false,
}: PageHeaderProps) => {
const hasAppSidebar = useHasAppSidebar();
const envLabel = useEnvLabel();
@@ -91,7 +94,7 @@ const PageHeader = ({
<div
className={cn([
"top-banner-offset bg-background sticky z-30 w-full",
- divider && !tabsProps && "border-b",
+ divider && !tabsProps && !hideTitleRow && "border-b",
className,
])}
id="page-header"
@@ -151,7 +154,7 @@ const PageHeader = ({
</div>
{/* Bottom Row */}
- <div>
+ <div className={cn(hideTitleRow && "hidden")}>
<div
className={cn(
"flex w-full flex-wrap items-center justify-between gap-1 px-4 md:flex-nowrap",
diff --git a/web/src/features/filters/components/CompactConnectorRow.tsx b/web/src/features/filters/components/CompactConnectorRow.tsx
new file mode 100644
index 0000000000..3b9631781d
--- /dev/null
+++ b/web/src/features/filters/components/CompactConnectorRow.tsx
@@ -0,0 +1,36 @@
+import type * as React from "react";
+import { cva } from "class-variance-authority";
+
+/** indentVariants offsets the elbow: past a row label ("Where") or just inside the field above. */
+const indentVariants = cva("shrink-0", {
+ variants: {
+ indent: { label: "w-16", field: "w-3.5" },
+ },
+});
+
+/** contentVariants aligns the continuation line's controls. */
+const contentVariants = cva("flex min-w-0 flex-1 gap-1.5 pt-2", {
+ variants: {
+ align: { center: "items-center", start: "items-start" },
+ },
+});
+
+/** CompactConnectorRow renders a compact row's continuation line, hung off the row above by an elbow bracket. */
+export const CompactConnectorRow = ({
+ indent,
+ align,
+ children,
+}: {
+ indent: "label" | "field";
+ align: "center" | "start";
+ children: React.ReactNode;
+}) => (
+ <div className="flex items-start">
+ <span className={indentVariants({ indent })} aria-hidden="true" />
+ <div
+ aria-hidden="true"
+ className="border-input h-6 w-3 shrink-0 rounded-bl-md border-b-2 border-l-2"
+ />
+ <div className={contentVariants({ align })}>{children}</div>
+ </div>
+);
diff --git a/web/src/features/filters/components/CompactPickerButton.tsx b/web/src/features/filters/components/CompactPickerButton.tsx
new file mode 100644
index 0000000000..a574151e19
--- /dev/null
+++ b/web/src/features/filters/components/CompactPickerButton.tsx
@@ -0,0 +1,40 @@
+import type * as React from "react";
+import { cva } from "class-variance-authority";
+
+import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";
+import { Button } from "@/src/components/ui/button";
+
+/** pickerVariants sizes the picker: shrinking freely in compact rows or keeping a readable minimum. */
+const pickerVariants = cva("flex w-full items-center justify-between gap-2", {
+ variants: {
+ minWidth: { none: "min-w-0", default: "min-w-32" },
+ },
+});
+
+/** CompactPickerButton is the outlined picker trigger of compact filter rows, for use as a popover or select trigger. */
+export const CompactPickerButton = ({
+ title,
+ minWidth = "none",
+ children,
+ ...props
+}: Omit<
+ React.ComponentProps<typeof Button>,
+ "variant" | "className" | "children"
+> & {
+ title?: string;
+ minWidth?: "none" | "default";
+ children: React.ReactNode;
+}) => (
+ <Button
+ variant="outline"
+ role="combobox"
+ type="button"
+ className={pickerVariants({ minWidth })}
+ {...props}
+ >
+ <span className="min-w-0 truncate" title={title}>
+ {children}
+ </span>
+ <DropdownIndicator />
+ </Button>
+);
diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsx
index 2eae1125f2..a2c4b1980f 100644
--- a/web/src/features/filters/components/filter-builder.tsx
+++ b/web/src/features/filters/components/filter-builder.tsx
@@ -59,6 +59,8 @@ import {
getSessionPositionInTraceFilterMode,
} from "@langfuse/shared";
import { cn } from "@/src/utils/tailwind";
+import { CompactConnectorRow } from "@/src/features/filters/components/CompactConnectorRow";
+import { CompactPickerButton } from "@/src/features/filters/components/CompactPickerButton";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import {
InputCommand,
@@ -700,21 +702,13 @@ function FilterBuilderForm({
onOpenChange={(open) => setOpenColumnRow(open ? i : null)}
>
<PopoverTrigger asChild>
- <Button
- variant="outline"
- role="combobox"
- type="button"
+ <CompactPickerButton
disabled={disabled}
- className={cn(
- "flex items-center justify-between gap-2",
- compact ? "w-full min-w-0" : "w-full min-w-32",
- )}
+ title={columnLabel}
+ minWidth={compact ? "none" : "default"}
>
- <span className="min-w-0 truncate" title={columnLabel}>
- {columnLabel}
- </span>
- <DropdownIndicator />
- </Button>
+ {columnLabel}
+ </CompactPickerButton>
</PopoverTrigger>
<PopoverContent align="start" className="ph-no-capture max-w-fit p-0">
<InputCommand>
@@ -1139,17 +1133,13 @@ function FilterBuilderForm({
) : null}
<div className="flex w-5 shrink-0 justify-end">{removeButton}</div>
</div>
- <div className="flex items-start">
- <span className="w-16 shrink-0" aria-hidden="true" />
- <div className="border-input h-6 w-3 shrink-0 rounded-bl-md border-b-2 border-l-2" />
- <div className="flex min-w-0 flex-1 items-center gap-1.5 pt-2">
- <div className="shrink-0">{operatorSelect}</div>
- {valueControl ? (
- <div className="min-w-0 flex-1">{valueControl}</div>
- ) : null}
- <span className="w-5 shrink-0" aria-hidden="true" />
- </div>
- </div>
+ <CompactConnectorRow indent="label" align="center">
+ <div className="shrink-0">{operatorSelect}</div>
+ {valueControl ? (
+ <div className="min-w-0 flex-1">{valueControl}</div>
+ ) : null}
+ <span className="w-5 shrink-0" aria-hidden="true" />
+ </CompactConnectorRow>
</div>
) : (
<tr key={i}>
diff --git a/web/src/features/filters/index.ts b/web/src/features/filters/index.ts
index b8f2ea5cc9..0ca76a62e6 100644
--- a/web/src/features/filters/index.ts
+++ b/web/src/features/filters/index.ts
@@ -6,6 +6,8 @@
// useFilterState imports it, so routing it here would close a runtime cycle.
// events/config/filter-config stays on the deep path for the same reason
// against users-config.
+export { CompactConnectorRow } from "@/src/features/filters/components/CompactConnectorRow";
+export { CompactPickerButton } from "@/src/features/filters/components/CompactPickerButton";
export { FilterToken } from "@/src/features/filters/components/FilterToken";
export {
InlineFilterBuilder,
diff --git a/web/src/features/monitors/components/DeleteMonitorButton.tsx b/web/src/features/monitors/components/DeleteMonitorButton.tsx
index a8e21e838a..de981ff327 100644
--- a/web/src/features/monitors/components/DeleteMonitorButton.tsx
+++ b/web/src/features/monitors/components/DeleteMonitorButton.tsx
@@ -38,12 +38,12 @@ export function DeleteMonitorButton({
trigger={
<Button
type="button"
- variant="outline"
- size="icon"
+ variant="destructive"
title="Delete alert"
aria-label="Delete alert"
>
- <Trash2 size="base" color="destructive" />
+ <Trash2 size="base" __rawClassName="mr-2" />
+ Delete Alert
</Button>
}
/>
diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsx
index 2ef8f8fdb8..ca0897ef20 100644
--- a/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsx
+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsx
@@ -102,7 +102,7 @@ describe("MonitorAutomationsPanel automation creation", () => {
{ wrapper: LayerProvider },
);
- await openCreateDialog(/new automation/i);
+ await openCreateDialog(/^webhook$/i);
// Navigating to the automations page unmounted the monitor form (LFE-10982).
expect(document.querySelector('a[href*="/automations"]')).toBeNull();
@@ -165,7 +165,7 @@ describe("MonitorAutomationsPanel automation creation", () => {
);
const { rerender } = render(panel([]), { wrapper: LayerProvider });
- await openCreateDialog(/new automation/i);
+ await openCreateDialog(/^webhook$/i);
fireEvent.click(await screen.findByRole("button", { name: /stub save/i }));
// The user ticks another automation before the read resolves.
diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.tsx
index 752d175018..25b450d8fe 100644
--- a/web/src/features/monitors/components/MonitorAutomationsPanel.tsx
+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.tsx
@@ -263,22 +263,14 @@ const AddAutomationDropdown = ({
<DropdownMenu
disabled={isDisabled}
placement="bottom-end"
- items={[
- {
- type: "item",
- id: "new",
- title: "New automation",
- icon: Plus,
- onClick: () => openDialog(),
- },
- ...actionTypes.map((actionType) => ({
- type: "item" as const,
- id: actionType,
- title: actionTypeLabel[actionType],
- icon: actionIcon[actionType],
- onClick: () => openDialog({ actionType }),
- })),
- ]}
+ matchTriggerWidth={fullWidth}
+ items={actionTypes.map((actionType) => ({
+ type: "item" as const,
+ id: actionType,
+ title: actionTypeLabel[actionType],
+ icon: actionIcon[actionType],
+ onClick: () => openDialog({ actionType }),
+ }))}
>
{({ getTriggerProps }) => (
<Button
diff --git a/web/src/features/monitors/components/MonitorChartPreview.tsx b/web/src/features/monitors/components/MonitorChartPreview.tsx
index 1f77567e0e..382896941a 100644
--- a/web/src/features/monitors/components/MonitorChartPreview.tsx
+++ b/web/src/features/monitors/components/MonitorChartPreview.tsx
@@ -178,6 +178,7 @@ export const MonitorChartPreview = ({
rowLimit={1000}
thresholds={thresholds}
metricFormatter={metricFormatter}
+ compactYAxis
// Both queries feed `data`; while either is still pending it can
// be spuriously `[]`, which would otherwise flash "No data"
// before the real result (or the leading point) arrives.
diff --git a/web/src/features/monitors/components/MonitorForm.clienttest.ts b/web/src/features/monitors/components/MonitorForm.clienttest.ts
index ebdf13ad2f..f5f9632473 100644
--- a/web/src/features/monitors/components/MonitorForm.clienttest.ts
+++ b/web/src/features/monitors/components/MonitorForm.clienttest.ts
@@ -14,9 +14,9 @@ import { __test } from "./MonitorForm";
const {
createDefaults,
+ thresholdUnit,
monitorToDefaults,
nameOrPlaceholder,
- resolveViewChangePatch,
monitorCreateAnalyticsProperties,
} = __test;
@@ -79,6 +79,28 @@ describe("createDefaults", () => {
});
});
+describe("thresholdUnit", () => {
+ it("uses the counted rows' unit for a count", () => {
+ expect(thresholdUnit("observations", "count", "count")).toBe(
+ "observations",
+ );
+ expect(thresholdUnit("observations", "latency", "count")).toBe(
+ "observations",
+ );
+ });
+
+ it("uses the measure's spelled-out unit for a value aggregation", () => {
+ expect(thresholdUnit("observations", "latency", "p95")).toBe(
+ "milliseconds",
+ );
+ expect(thresholdUnit("observations", "totalCost", "sum")).toBe("USD");
+ });
+
+ it("names the score value unit, which the view leaves undeclared", () => {
+ expect(thresholdUnit("scores-numeric", "value", "avg")).toBe("score value");
+ });
+});
+
describe("monitorCreateAnalyticsProperties", () => {
it("tracks the selected score window", () => {
expect(
@@ -117,36 +139,6 @@ describe("nameOrPlaceholder", () => {
});
});
-describe("resolveViewChangePatch", () => {
- it("view change: never patches filters", () => {
- expect(
- resolveViewChangePatch("scores-numeric", "count"),
- ).not.toHaveProperty("filters");
- expect(
- resolveViewChangePatch("scores-numeric", "latency"),
- ).not.toHaveProperty("filters");
- expect(resolveViewChangePatch("observations", "value")).not.toHaveProperty(
- "filters",
- );
- });
-
- it("measure absent on the new view: resets the metric to count", () => {
- expect(resolveViewChangePatch("scores-numeric", "latency").metric).toEqual({
- measure: "count",
- aggregation: "count",
- });
- });
-
- it("measure present on the new view: leaves the metric alone", () => {
- expect(
- resolveViewChangePatch("observations", "latency"),
- ).not.toHaveProperty("metric");
- expect(
- resolveViewChangePatch("scores-numeric", "value"),
- ).not.toHaveProperty("metric");
- });
-});
-
describe("monitorToDefaults", () => {
it("maps monitor.triggerIds into the form defaults", () => {
const monitor: Monitor = {
diff --git a/web/src/features/monitors/components/MonitorForm.tsx b/web/src/features/monitors/components/MonitorForm.tsx
index 016b471a51..f3b709668f 100644
--- a/web/src/features/monitors/components/MonitorForm.tsx
+++ b/web/src/features/monitors/components/MonitorForm.tsx
@@ -8,14 +8,12 @@ import { type IconComponent, Plus } from "@langfuse/icons";
import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";
import { useForm, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
-import { startCase } from "lodash";
import { api } from "@/src/utils/api";
import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
import { AIAssistedInput } from "@/src/components/ui/AIAssistedInput";
import { Button } from "@/src/components/ui/button";
import {
- Card,
CardContent,
CardDescription,
CardFooter,
@@ -43,8 +41,6 @@ import {
import { useHasProjectAccess } from "@/src/features/rbac";
import { useLangfuseCloudRegion } from "@/src/features/organizations";
import { useProject } from "@/src/features/projects";
-import { WidgetPropertySelectItem } from "@/src/features/widgets";
-import { ConnectedMetricsFilterBuilder } from "@/src/features/metrics";
import { partitionWidgetUiTableFiltersToView } from "@/src/features/dashboard";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import {
@@ -56,7 +52,6 @@ import { cn } from "@/src/utils/tailwind";
import {
CreateMonitorSchema,
type CreateMonitor,
- getValidMonitorAggregationsForMeasure,
type Monitor,
type MonitorNoData,
MonitorNoDataModeSchema,
@@ -66,7 +61,6 @@ import {
type MonitorThresholdOperator,
MonitorThresholdOperatorSchema,
type MonitorView,
- MonitorViewSchema,
type MonitorWindow,
MonitorWindowSchema,
UpdateMonitorSchema,
@@ -78,18 +72,25 @@ import { TagManager } from "@/src/features/tag";
import { MonitorChartPreview } from "./MonitorChartPreview";
import { getMonitorFilterOptionsLookbackFrom } from "../helpers/monitorTimeRanges";
import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";
+import { MonitorMetricDefinition } from "./MonitorMetricDefinition";
import { MonitorSeverityBadge } from "./MonitorSeverityBadge";
import { Badge } from "@/src/components/design-system/Badge/Badge";
+import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";
import {
operatorLabels,
operatorSymbol,
- viewLabels,
windowLabels,
} from "../helpers/monitorLabels";
-import {
- aggregationLabel,
- renderNamePlaceholder,
-} from "../helpers/renderMonitorLabels";
+import { renderNamePlaceholder } from "../helpers/renderMonitorLabels";
+
+/** numericMeasureTypes are the measure types whose values carry their own unit. */
+const numericMeasureTypes = new Set(["integer", "decimal", "number"]);
+
+/** unitLabels spells out measure units that read better pluralized. */
+const unitLabels: Record<string, string> = { millisecond: "milliseconds" };
+
+/** unitlessMeasureLabels names the unit of measures declared without one. */
+const unitlessMeasureLabels: Record<string, string> = { value: "score value" };
/** createDefaults returns the form defaults for a brand-new monitor. */
const createDefaults = (
@@ -132,18 +133,6 @@ const monitorToDefaults = (monitor: Monitor): UpdateMonitor => ({
// status omitted: the pause/resume toolbar owns it.
});
-/** resolveViewChangePatch returns the form fields that must change when the view changes. */
-const resolveViewChangePatch = (
- nextView: keyof (typeof viewDeclarations)["v2"],
- currentMeasure: string,
-): Partial<Pick<CreateMonitor, "metric">> => {
- const measures = viewDeclarations.v2[nextView]?.measures ?? {};
- // Filters are never patched; MetricsFilterBuilder drops rows the view cannot render.
- return currentMeasure in measures
- ? {}
- : { metric: { measure: "count", aggregation: "count" } };
-};
-
/** nameOrPlaceholder falls back to the placeholder when the name is blank. */
const nameOrPlaceholder = (
name: string | undefined,
@@ -175,6 +164,7 @@ export const MonitorForm = ({
analyticsSource = "alerts",
initialTriggerIds = [],
onNameChange,
+ secondaryAction,
}: {
projectId: string;
monitor?: Monitor;
@@ -185,6 +175,8 @@ export const MonitorForm = ({
initialTriggerIds?: string[];
/** onNameChange fires on every form change so the host (e.g. the edit page header) can mirror the live name. */
onNameChange?: (name: string) => void;
+ /** secondaryAction renders left of the submit button, e.g. the edit page's delete button. */
+ secondaryAction?: React.ReactNode;
}) => {
/** router is the Next router used to redirect after a successful create. */
const router = useRouter();
@@ -402,23 +394,6 @@ export const MonitorForm = ({
{ staleTime: Infinity, refetchOnWindowFocus: false },
);
- /** measureOptions is the list of measure names available on the currently picked view. */
- const measureOptions = useMemo(() => {
- const view = (watched.view ??
- "observations") as keyof (typeof viewDeclarations)["v2"];
- const measures = viewDeclarations.v2[view]?.measures ?? {};
- return Object.keys(measures);
- }, [watched.view]);
-
- /** aggregationOptions is the set of valid aggregations for the picked (view, measure) pair. */
- const aggregationOptions = useMemo(() => {
- const view = (watched.view ??
- "observations") as keyof (typeof viewDeclarations)["v2"];
- const measureName = watched.metric?.measure ?? "count";
- const measureDef = viewDeclarations.v2[view]?.measures[measureName];
- return getValidMonitorAggregationsForMeasure(measureDef);
- }, [watched.view, watched.metric?.measure]);
-
/** namePlaceholder builds an auto-suggested name from the current view + metric + threshold (e.g. "Sum of Observations Latency is below 100"). */
const namePlaceholder = useMemo(
() =>
@@ -466,176 +441,43 @@ export const MonitorForm = ({
createMutation.isPending ||
updateMutation.isPending ||
suggestName.isPending;
+ /** thresholdUnitLabel names the unit the thresholds are compared in, e.g. "milliseconds". */
+ const thresholdUnitLabel = thresholdUnit(
+ (watched.view ?? "observations") as MonitorView,
+ watched.metric?.measure ?? "count",
+ watched.metric?.aggregation ?? "count",
+ );
+ /** isIncomplete is true while a new alert is missing required fields. */
+ const isIncomplete = !isEdit && !form.formState.isValid;
return (
<Form {...form}>
<form onSubmit={onSubmit} className="flex h-full gap-4 overflow-hidden">
- <div className="h-full min-h-0 w-full min-w-107.5 md:w-1/3">
- <Card className="flex h-full flex-col">
+ <div className="@container h-full min-h-0 w-full min-w-0 md:w-1/3 md:min-w-80">
+ <div className="flex h-full flex-col">
<CardHeader>
- <CardTitle>Alert Configuration</CardTitle>
- <CardDescription>
- Receive notifications when a metric crosses a threshold. (eg.
- &ldquo;sudden cost increase&rdquo;, &ldquo;accuracy has
- dropped&rdquo;)
- </CardDescription>
+ <FormHeading
+ isEdit={isEdit}
+ name={nameOrPlaceholder(watched.name, namePlaceholder)}
+ />
</CardHeader>
<CardContent className="min-h-0 flex-1 overflow-y-auto overscroll-contain py-0">
- <Section title="Metric Definition" step={1}>
- <FormField
- control={form.control}
- name="view"
- render={({ field }) => (
- <FormItem>
- <FormLabel>View</FormLabel>
- <Select
- value={field.value}
- onValueChange={(next) => {
- field.onChange(next);
- const patch = resolveViewChangePatch(
- next as keyof (typeof viewDeclarations)["v2"],
- form.getValues("metric.measure"),
- );
- if (patch.metric) {
- form.setValue("metric", patch.metric, {
- shouldValidate: true,
- });
- }
- }}
- disabled={!hasAccess}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {MonitorViewSchema.options.map((v) => (
- <WidgetPropertySelectItem
- key={v}
- value={v}
- label={viewLabels[v]}
- description={
- viewDeclarations.v2[v]?.description ?? undefined
- }
- />
- ))}
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="metric.measure"
- render={({ field }) => {
- const view = (watched.view ??
- "observations") as keyof (typeof viewDeclarations)["v2"];
- const measures = viewDeclarations.v2[view]?.measures ?? {};
- return (
- <FormItem>
- <FormLabel>Measure</FormLabel>
- <Select
- value={field.value}
- onValueChange={(next) => {
- field.onChange(next);
- // The aggregation dropdown filters by the new
- // measure, but the stored value can stay stale
- // (e.g. "sum" against a string measure, or "p95"
- // against `count`). Snap it to the first valid
- // option whenever the current one isn't supported.
- const validAggs =
- getValidMonitorAggregationsForMeasure(
- measures[next],
- );
- const currentAgg =
- form.getValues("metric.aggregation");
- if (!validAggs.includes(currentAgg)) {
- form.setValue(
- "metric.aggregation",
- validAggs[0] ?? "count",
- { shouldValidate: true },
- );
- }
- }}
- disabled={!hasAccess}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {measureOptions.map((m) => {
- const meta = measures[m];
- return (
- <WidgetPropertySelectItem
- key={m}
- value={m}
- label={startCase(m)}
- description={meta?.description}
- unit={meta?.unit}
- type={meta?.type}
- />
- );
- })}
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- );
- }}
- />
- {watched.metric?.measure !== "count" && (
- <FormField
- control={form.control}
- name="metric.aggregation"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Aggregation</FormLabel>
- <Select
- value={field.value}
- onValueChange={field.onChange}
- disabled={!hasAccess}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {aggregationOptions.map((a) => (
- <SelectItem key={a} value={a}>
- {aggregationLabel(a)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
- )}
- <FormField
- control={form.control}
- name="filters"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Filters</FormLabel>
- <FormControl>
- <ConnectedMetricsFilterBuilder
- version="v2"
- view={(watched.view ?? "observations") as MonitorView}
- projectId={projectId}
- dateRange={{ from: filterOptionsLookbackFrom }}
- filters={(field.value ?? []) as FilterState}
- onChange={(next: FilterState) => field.onChange(next)}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
+ {/* Fades content out as it slides under the form header. */}
+ <div
+ aria-hidden
+ className="from-background pointer-events-none sticky top-0 z-20 -mb-3 h-3 bg-linear-to-b to-transparent"
+ />
+ <Section title="Metric Definition" step={1} hasNextStep>
+ <MonitorMetricDefinition
+ form={form}
+ view={(watched.view ?? "observations") as MonitorView}
+ aggregation={
+ (watched.metric?.aggregation ??
+ "count") as CreateMonitor["metric"]["aggregation"]
+ }
+ projectId={projectId}
+ filterOptionsLookbackFrom={filterOptionsLookbackFrom}
+ disabled={!hasAccess}
/>
{formError.query && (
<p className="text-destructive text-xs">
@@ -644,7 +486,7 @@ export const MonitorForm = ({
)}
</Section>
- <Section title="Alert Conditions" step={2}>
+ <Section title="Alert Conditions" step={2} hasNextStep>
<FormField
control={form.control}
name="thresholdOperator"
@@ -694,7 +536,7 @@ export const MonitorForm = ({
<MonitorSeverityBadge
severity={MonitorSeveritySchema.enum.ALERT}
/>
- <span className="text-sm whitespace-nowrap">
+ <span className="hidden text-sm whitespace-nowrap @sm:inline">
Threshold
</span>
<span className="mr-1.5 ml-1 font-mono text-xs font-bold">
@@ -707,9 +549,8 @@ export const MonitorForm = ({
}
</span>
<FormControl>
- <Input
- type="number"
- className="flex-1"
+ <ThresholdInput
+ unit={thresholdUnitLabel}
placeholder="0"
value={field.value ?? ""}
onChange={(e) => {
@@ -738,7 +579,7 @@ export const MonitorForm = ({
<MonitorSeverityBadge
severity={MonitorSeveritySchema.enum.WARNING}
/>
- <span className="text-sm whitespace-nowrap">
+ <span className="hidden text-sm whitespace-nowrap @sm:inline">
Threshold
</span>
<span className="mr-1.5 ml-1 font-mono text-xs font-bold">
@@ -751,9 +592,8 @@ export const MonitorForm = ({
}
</span>
<FormControl>
- <Input
- type="number"
- className="flex-1"
+ <ThresholdInput
+ unit={thresholdUnitLabel}
placeholder="optional"
value={field.value ?? ""}
onChange={(e) => {
@@ -846,7 +686,7 @@ export const MonitorForm = ({
</AccordionPrimitive.Root>
</Section>
- <Section title="Notifications" step={3} className="pb-2">
+ <Section title="Notifications" step={3}>
<FormField
control={form.control}
name="name"
@@ -941,23 +781,54 @@ export const MonitorForm = ({
)}
/>
</Section>
+ {/* Fades content out as it slides under the action bar. */}
+ <div
+ aria-hidden
+ className="from-background pointer-events-none sticky bottom-0 z-20 -mt-3 h-3 bg-linear-to-t to-transparent"
+ />
</CardContent>
<CardFooter className="mt-auto">
- <div className="w-full items-center pt-4">
+ <div className="flex w-full items-center justify-end gap-2 pt-4">
+ {!isEdit && (
+ <ConfirmationDialogController
+ title="Discard this alert?"
+ text="Your changes to this alert will be lost."
+ confirmLabel="Discard"
+ variant="destructive"
+ onConfirm={async () => {
+ await router.push(`/project/${projectId}/alerts`);
+ }}
+ >
+ {({ openDialog }) => (
+ <Button
+ type="button"
+ variant="outline"
+ onClick={openDialog}
+ >
+ Cancel
+ </Button>
+ )}
+ </ConfirmationDialogController>
+ )}
+ {secondaryAction}
+ {/* Looks disabled while incomplete but stays clickable, so a click still reveals the field errors. */}
<Button
type="submit"
- size="lg"
- className="w-full"
+ className={cn(
+ isIncomplete &&
+ "hover:bg-primary cursor-not-allowed opacity-50",
+ )}
+ aria-disabled={isIncomplete || undefined}
disabled={!hasAccess || submitting}
>
{isEdit ? "Save Alert" : "Create Alert"}
</Button>
</div>
</CardFooter>
- </Card>
+ </div>
</div>
- <div className="hidden h-full w-2/3 min-w-107.5 flex-col gap-6 overflow-y-auto overscroll-contain md:flex">
+ <div className="hidden h-full w-2/3 min-w-56 flex-col gap-6 overflow-y-auto overscroll-contain md:flex">
<MonitorChartPreview
projectId={projectId}
view={(watched.view ?? "observations") as MonitorView}
@@ -981,6 +852,22 @@ export const MonitorForm = ({
);
};
+/** FormHeading titles the form: the alert being edited, or a description of a new one. */
+function FormHeading({ isEdit, name }: { isEdit: boolean; name: string }) {
+ if (isEdit) {
+ return <CardTitle>Edit Alert &ldquo;{name}&rdquo;</CardTitle>;
+ }
+ return (
+ <>
+ <CardTitle>Alert Configuration</CardTitle>
+ <CardDescription>
+ Receive notifications when a metric crosses a threshold. (eg.
+ &ldquo;sudden cost increase&rdquo;, &ldquo;accuracy has dropped&rdquo;)
+ </CardDescription>
+ </>
+ );
+}
+
/** Header pins a section title to the top of the scrolling CardContent. */
const Header = ({
title,
@@ -991,8 +878,8 @@ const Header = ({
step?: number;
icon?: IconComponent;
}) => (
- <div className="bg-card sticky top-0 z-10">
- <h3 className="flex items-center gap-2 py-2 text-lg font-bold">
+ <div className="sticky top-0 z-10">
+ <h3 className="bg-background flex items-center gap-2 pt-2 text-lg font-bold">
{step != null ? (
<span className="bg-foreground text-background flex h-6 w-6 items-center justify-center rounded-full text-sm font-bold">
{step}
@@ -1001,26 +888,63 @@ const Header = ({
{Icon ? <Icon size="lg" aria-hidden="true" /> : null}
{title}
</h3>
+ {/* Fades content out as it slides under the pinned title. */}
+ <div
+ aria-hidden
+ className="from-background h-3 bg-linear-to-b to-transparent"
+ />
</div>
);
-/** Section wraps a Header and its body in the layout used by every MonitorForm section. */
+/** Section wraps a Header and its body in the layout used by every MonitorForm section, linking its step to the next one. */
const Section = ({
title,
step,
icon,
+ hasNextStep = false,
children,
className,
}: {
title: string;
step?: number;
icon?: IconComponent;
+ hasNextStep?: boolean;
children: React.ReactNode;
className?: string;
}) => (
- <div>
+ <div className="relative">
+ {hasNextStep && (
+ <div
+ aria-hidden
+ className="bg-border absolute top-9 bottom-0 left-3 w-px -translate-x-1/2"
+ />
+ )}
<Header title={title} step={step} icon={icon} />
- <div className={cn("space-y-4 px-2 pb-4", className)}>{children}</div>
+ <div className={cn("space-y-4 pr-2 pb-4 pl-8", className)}>{children}</div>
+ </div>
+);
+
+/** ThresholdInput is a number input with the threshold's unit as a muted suffix inside the same box. */
+const ThresholdInput = ({
+ unit,
+ ...props
+}: Omit<React.ComponentProps<typeof Input>, "type" | "className"> & {
+ unit?: string;
+}) => (
+ <div className="border-input bg-background focus-within:ring-ring flex h-8 min-w-0 flex-1 items-center rounded-md border pr-2 focus-within:ring-1">
+ <Input
+ type="number"
+ className="h-full min-w-10 flex-1 appearance-none border-0 bg-transparent"
+ {...props}
+ />
+ {unit && (
+ <span
+ className="text-muted-foreground min-w-0 truncate pl-1 text-sm"
+ title={unit}
+ >
+ {unit}
+ </span>
+ )}
</div>
);
@@ -1164,11 +1088,26 @@ const RenotifyField = ({
</div>
);
+/** thresholdUnit returns the unit a metric's value is in, or undefined when it has none. */
+function thresholdUnit(
+ view: MonitorView,
+ measure: string,
+ aggregation: string,
+): string | undefined {
+ const measures = viewDeclarations.v2[view]?.measures ?? {};
+ const definition = measures[measure];
+ const isNumeric = numericMeasureTypes.has(definition?.type ?? "");
+ if (aggregation === "count" && isNumeric) return measures.count?.unit;
+ if (aggregation === "uniq" && isNumeric) return undefined;
+ if (!definition?.unit) return unitlessMeasureLabels[measure];
+ return unitLabels[definition.unit] ?? definition.unit;
+}
+
/** __test exposes private helpers to co-located tests without widening the module API. */
export const __test = {
createDefaults,
+ thresholdUnit,
monitorToDefaults,
nameOrPlaceholder,
- resolveViewChangePatch,
monitorCreateAnalyticsProperties,
};
diff --git a/web/src/features/monitors/components/MonitorMetricDefinition.clienttest.ts b/web/src/features/monitors/components/MonitorMetricDefinition.clienttest.ts
new file mode 100644
index 0000000000..6e01ae4b30
--- /dev/null
+++ b/web/src/features/monitors/components/MonitorMetricDefinition.clienttest.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+
+import { __test } from "./MonitorMetricDefinition";
+
+const { getMeasuresByAggregation } = __test;
+
+describe("getMeasuresByAggregation", () => {
+ it("offers count first, with the row count as its first measure", () => {
+ const byAggregation = getMeasuresByAggregation("observations");
+
+ expect([...byAggregation.keys()][0]).toBe("count");
+ expect(byAggregation.get("count")?.[0]).toBe("count");
+ });
+
+ it("only pairs numeric measures with numeric aggregations", () => {
+ const sumMeasures = getMeasuresByAggregation("observations").get("sum");
+
+ expect(sumMeasures).toContain("latency");
+ expect(sumMeasures).not.toContain("traceId");
+ });
+
+ it("keeps the row count to the count aggregation in every view", () => {
+ const byAggregation = getMeasuresByAggregation("scores-numeric");
+
+ expect(byAggregation.get("count")).toEqual(["count", "value"]);
+ expect(byAggregation.get("sum")).toEqual(["value"]);
+ });
+});
diff --git a/web/src/features/monitors/components/MonitorMetricDefinition.tsx b/web/src/features/monitors/components/MonitorMetricDefinition.tsx
new file mode 100644
index 0000000000..168683e609
--- /dev/null
+++ b/web/src/features/monitors/components/MonitorMetricDefinition.tsx
@@ -0,0 +1,305 @@
+import { type ComponentProps, useMemo } from "react";
+import { startCase } from "lodash";
+import { type UseFormReturn } from "react-hook-form";
+
+import {
+ FormControl,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { Label } from "@/src/components/ui/label";
+import { SelectDropdown } from "@/src/components/design-system/SelectDropdown/SelectDropdown";
+import {
+ CompactConnectorRow,
+ CompactPickerButton,
+} from "@/src/features/filters";
+import { ConnectedMetricsFilterBuilder } from "@/src/features/metrics";
+import { viewDeclarations, type FilterState } from "@langfuse/shared";
+import {
+ type CreateMonitor,
+ getValidMonitorAggregationsForMeasure,
+ type MonitorView,
+ MonitorViewSchema,
+ type UpdateMonitor,
+} from "@langfuse/shared/monitors";
+import { viewLabels } from "../helpers/monitorLabels";
+import { aggregationLabel } from "../helpers/renderMonitorLabels";
+
+/** countMeasure is the row-count measure, shown as "All" and only offered with the count aggregation. */
+const countMeasure = "count";
+
+/** MonitorMetricDefinition picks a monitor's metric as "[view]", then "[aggregation] [measure]", then filters. */
+export const MonitorMetricDefinition = ({
+ form,
+ view,
+ aggregation,
+ projectId,
+ filterOptionsLookbackFrom,
+ disabled,
+}: {
+ form: UseFormReturn<CreateMonitor | UpdateMonitor>;
+ view: MonitorView;
+ aggregation: MonitorAggregation;
+ projectId: string;
+ filterOptionsLookbackFrom: Date;
+ disabled: boolean;
+}) => {
+ const measuresByAggregation = useMemo(
+ () => getMeasuresByAggregation(view),
+ [view],
+ );
+
+ /** changeAggregation snaps the measure to the first one the new aggregation supports. */
+ const changeAggregation = (next: MonitorAggregation) => {
+ form.setValue("metric.aggregation", next, { shouldValidate: true });
+ const validMeasures = measuresByAggregation.get(next) ?? [];
+ if (!validMeasures.includes(form.getValues("metric.measure"))) {
+ form.setValue("metric.measure", validMeasures[0] ?? countMeasure, {
+ shouldValidate: true,
+ });
+ }
+ };
+
+ /** changeView resets the metric to a bare count when the new view lacks the measure or pairing. */
+ const changeView = (next: MonitorView) => {
+ form.setValue("view", next, { shouldValidate: true });
+ const { measure, aggregation: currentAggregation } =
+ form.getValues("metric");
+ const validMeasures =
+ getMeasuresByAggregation(next).get(currentAggregation) ?? [];
+ if (!validMeasures.includes(measure)) {
+ form.setValue(
+ "metric",
+ { measure: countMeasure, aggregation: "count" },
+ { shouldValidate: true },
+ );
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col">
+ <Label className="mb-2">Metric</Label>
+ <div className="flex items-start gap-1.5">
+ <FormField
+ control={form.control}
+ name="view"
+ render={({ field }) => (
+ <FormItem className="min-w-0 flex-1 space-y-0">
+ <FormControl>
+ <SelectDropdown
+ value={field.value as MonitorView}
+ onValueChange={changeView}
+ options={MonitorViewSchema.options.map(viewOption)}
+ aria-label="View"
+ disabled={disabled}
+ >
+ {({ getTriggerProps, selectedLabel }) => (
+ <CompactPickerButton {...getTriggerProps()}>
+ {selectedLabel}
+ </CompactPickerButton>
+ )}
+ </SelectDropdown>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ <CompactConnectorRow indent="field" align="start">
+ <FormField
+ control={form.control}
+ name="metric.aggregation"
+ render={({ field }) => (
+ <FormItem className="min-w-0 flex-1 space-y-0">
+ <FormControl>
+ <SelectDropdown
+ value={field.value}
+ onValueChange={changeAggregation}
+ options={[...measuresByAggregation.keys()].map((a) => ({
+ value: a,
+ label: aggregationLabel(a),
+ }))}
+ aria-label="Aggregation"
+ disabled={disabled}
+ >
+ {({ getTriggerProps, selectedLabel }) => (
+ <CompactPickerButton {...getTriggerProps()}>
+ {selectedLabel}
+ </CompactPickerButton>
+ )}
+ </SelectDropdown>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="metric.measure"
+ render={({ field }) => (
+ <FormItem className="min-w-0 flex-1 space-y-0">
+ <FormControl>
+ <SelectDropdown
+ value={field.value}
+ onValueChange={field.onChange}
+ options={measureOptions(
+ measuresByAggregation.get(aggregation) ?? [],
+ view,
+ )}
+ aria-label="Measure"
+ disabled={disabled}
+ >
+ {({ getTriggerProps, selectedLabel }) => (
+ <CompactPickerButton {...getTriggerProps()}>
+ <MeasureValue
+ measure={field.value}
+ label={selectedLabel}
+ />
+ </CompactPickerButton>
+ )}
+ </SelectDropdown>
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </CompactConnectorRow>
+ </div>
+ <FormField
+ control={form.control}
+ name="filters"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Filters</FormLabel>
+ <FormControl>
+ <ConnectedMetricsFilterBuilder
+ version="v2"
+ view={view}
+ projectId={projectId}
+ dateRange={{ from: filterOptionsLookbackFrom }}
+ filters={(field.value ?? []) as FilterState}
+ onChange={(next: FilterState) => field.onChange(next)}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </div>
+ );
+};
+
+/** MeasureValue shows the picked measure, with the row count as a muted "All". */
+function MeasureValue({
+ measure,
+ label,
+}: {
+ measure: string;
+ label: string | undefined;
+}) {
+ if (measure !== countMeasure) return label;
+ return <span className="text-muted-foreground">All</span>;
+}
+
+/** viewOption is a view's dropdown option, explained by its description. */
+function viewOption(view: MonitorView): SelectDropdownOption<MonitorView> {
+ return {
+ value: view,
+ label: viewLabels[view],
+ explanation: {
+ title: viewLabels[view],
+ description: viewDeclarations.v2[view]?.description ?? undefined,
+ },
+ };
+}
+
+/** measureOptions lists the measures as dropdown options, with the row count ahead of the field measures. */
+function measureOptions(
+ measureNames: string[],
+ view: MonitorView,
+): SelectDropdownNode<string>[] {
+ const options = measureNames.map((name) => measureOption(name, view));
+ const [first, ...rest] = options;
+ if (measureNames[0] !== countMeasure || rest.length === 0) return options;
+ return [
+ first,
+ { type: "group", id: "fields", label: "Fields", options: rest },
+ ];
+}
+
+/** measureOption is a measure's dropdown option, explained by its description, unit and type. */
+function measureOption(
+ name: string,
+ view: MonitorView,
+): SelectDropdownOption<string> {
+ const definition = viewDeclarations.v2[view]?.measures[name];
+ const label = measureLabel(name, view);
+ return {
+ value: name,
+ label,
+ explanation: {
+ title: label,
+ description: definition?.description,
+ badges: measureBadges(definition),
+ },
+ };
+}
+
+/** measureLabel renders a measure name, with the row count as "All <view>", e.g. "All observations". */
+function measureLabel(measure: string, view: MonitorView): string {
+ if (measure === countMeasure) return `All ${viewLabels[view].toLowerCase()}`;
+ return startCase(measure);
+}
+
+/** getMeasuresByAggregation maps each aggregation to the view's measures it is valid for, count first. */
+function getMeasuresByAggregation(
+ view: MonitorView,
+): Map<MonitorAggregation, string[]> {
+ const measures = viewDeclarations.v2[view]?.measures ?? {};
+ const byAggregation = new Map<MonitorAggregation, string[]>([["count", []]]);
+ for (const [name, definition] of Object.entries(measures)) {
+ for (const a of aggregationsForMeasure(name, definition)) {
+ byAggregation.set(a, [...(byAggregation.get(a) ?? []), name]);
+ }
+ }
+ return byAggregation;
+}
+
+/** aggregationsForMeasure lists a measure's valid aggregations, pinning the row count to count. */
+function aggregationsForMeasure(
+ name: string,
+ definition: Parameters<typeof getValidMonitorAggregationsForMeasure>[0],
+): MonitorAggregation[] {
+ if (name === countMeasure) return ["count"];
+ return getValidMonitorAggregationsForMeasure(definition);
+}
+
+/** measureBadges lists a measure's unit and type for its explanation. */
+function measureBadges(
+ definition: { unit?: string; type?: string } | undefined,
+): { label: string; value: string }[] {
+ const badges: { label: string; value: string }[] = [];
+ if (definition?.unit) badges.push({ label: "Unit", value: definition.unit });
+ if (definition?.type) badges.push({ label: "Type", value: definition.type });
+ return badges;
+}
+
+/** SelectDropdownNode is an option or option group of a SelectDropdown. */
+type SelectDropdownNode<V extends string> = ComponentProps<
+ typeof SelectDropdown<V>
+>["options"][number];
+
+/** SelectDropdownOption is a single, ungrouped SelectDropdown option. */
+type SelectDropdownOption<V extends string> = Exclude<
+ SelectDropdownNode<V>,
+ { type: "group" }
+>;
+
+/** MonitorAggregation is an aggregation a monitor metric can use. */
+type MonitorAggregation = CreateMonitor["metric"]["aggregation"];
+
+/** __test exposes private helpers to co-located tests without widening the module API. */
+export const __test = { getMeasuresByAggregation };
diff --git a/web/src/features/monitors/components/MonitorSeverityBadge.tsx b/web/src/features/monitors/components/MonitorSeverityBadge.tsx
index e4db6bb84a..e9d7fe7be5 100644
--- a/web/src/features/monitors/components/MonitorSeverityBadge.tsx
+++ b/web/src/features/monitors/components/MonitorSeverityBadge.tsx
@@ -7,7 +7,7 @@ const badgeBaseClassName =
/** severityVariantClassName maps each MonitorSeverity to its base badge chrome. */
const severityVariantClassName: Record<MonitorSeverity, string> = {
- UNKNOWN: "border-border text-foreground-secondary",
+ UNKNOWN: "border-transparent text-foreground-secondary",
NO_DATA:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
PAUSED:
diff --git a/web/src/features/monitors/pages/EditMonitorPage.tsx b/web/src/features/monitors/pages/EditMonitorPage.tsx
index 24c7c77c32..963343dc64 100644
--- a/web/src/features/monitors/pages/EditMonitorPage.tsx
+++ b/web/src/features/monitors/pages/EditMonitorPage.tsx
@@ -77,24 +77,27 @@ const EditMonitorFormPage = ({ monitor }: { monitor: Monitor }) => {
withPadding
headerProps={{
...getHeaderProps(monitor.projectId, liveName),
- actionButtonsRight: canDelete ? (
- <DeleteMonitorButton
- monitorName={monitor.name}
- deleting={deleteMonitor.isPending}
- onDelete={async () => {
- await deleteMonitor.mutateAsync({
- projectId: monitor.projectId,
- id: monitor.id,
- });
- }}
- />
- ) : undefined,
+ hideTitleRow: true,
}}
>
<MonitorForm
projectId={monitor.projectId}
monitor={monitor}
onNameChange={setLiveName}
+ secondaryAction={
+ canDelete && (
+ <DeleteMonitorButton
+ monitorName={monitor.name}
+ deleting={deleteMonitor.isPending}
+ onDelete={async () => {
+ await deleteMonitor.mutateAsync({
+ projectId: monitor.projectId,
+ id: monitor.id,
+ });
+ }}
+ />
+ )
+ }
/>
</Page>
);
diff --git a/web/src/features/monitors/pages/NewMonitorPage.tsx b/web/src/features/monitors/pages/NewMonitorPage.tsx
index 9809f38865..2ca65cdf55 100644
--- a/web/src/features/monitors/pages/NewMonitorPage.tsx
+++ b/web/src/features/monitors/pages/NewMonitorPage.tsx
@@ -44,6 +44,7 @@ export default function NewMonitorPage() {
withPadding
headerProps={{
title: "New Alert",
+ hideTitleRow: true,
breadcrumb: [
{ name: "Alerts", href: `/project/${projectId}/alerts` },
],
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index ad25be9212..8ab36d7de5 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -66,6 +66,7 @@ const ChartComponent = ({
thresholds,
missingValue,
hideXAxisLabels,
+ compactYAxis,
colorBarsByCategory,
zeroBaseline,
emptyState,
@@ -106,6 +107,8 @@ const ChartComponent = ({
* charts and forwarded to `prepareTimeAxis`. Used by dataset-compare charts.
*/
hideXAxisLabels?: boolean;
+ /** See {@link ChartProps.compactYAxis}. Consumed by LINE_TIME_SERIES. */
+ compactYAxis?: boolean;
/**
* Colour each bar of a categorical axis and name it in a legend below the
* plot; see {@link ChartProps.colorBarsByCategory}. Consumed by VERTICAL_BAR.
@@ -193,6 +196,7 @@ const ChartComponent = ({
thresholds={thresholds}
missingValue={missingValue}
hideXAxisLabels={hideXAxisLabels}
+ compactYAxis={compactYAxis}
/>
);
case "AREA_TIME_SERIES":
diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
index c308d51aea..6f11223a4a 100644
--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
@@ -83,6 +83,7 @@ export function LineChartTimeSeries({
missingValue = "gap",
connectNulls = false,
hideXAxisLabels = false,
+ compactYAxis = false,
}: ChartProps) {
const allDimensions = useMemo(() => getUniqueDimensions(data), [data]);
const groupedData = useMemo(
@@ -187,6 +188,7 @@ export function LineChartTimeSeries({
thresholds={chartThresholds}
sync={sync}
legend={chartLegend}
+ compactYAxis={compactYAxis}
xAxis={{
type: "category",
labels: hideXAxisLabels ? "hidden" : "visible",
@@ -214,6 +216,7 @@ export function LineChartTimeSeries({
thresholds={chartThresholds}
sync={sync}
legend={chartLegend}
+ compactYAxis={compactYAxis}
xAxis={{
type: "time",
}}
diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.ts
index a2ab53e358..23abfb194f 100644
--- a/web/src/features/widgets/chart-library/chart-props.ts
+++ b/web/src/features/widgets/chart-library/chart-props.ts
@@ -165,6 +165,8 @@ export interface ChartProps {
* affects a categorical axis — a temporal axis keeps its timestamp labels.
*/
hideXAxisLabels?: boolean;
+ /** compactYAxis shrinks the y-axis gutter to fit short tick labels. Consumed by LINE_TIME_SERIES. */
+ compactYAxis?: boolean;
/**
* Give each bar of a categorical (entity) axis its own palette colour, plus a
* legend below the plot that names it. Off by default: a dashboard bar chart
diff --git a/web/src/features/widgets/components/WidgetPropertySelectItem.tsx b/web/src/features/widgets/components/WidgetPropertySelectItem.tsx
index ea0583f845..3a25ad127f 100644
--- a/web/src/features/widgets/components/WidgetPropertySelectItem.tsx
+++ b/web/src/features/widgets/components/WidgetPropertySelectItem.tsx
@@ -1,6 +1,5 @@
-/* eslint-disable @repo/no-style-props, @repo/component-file-structure */
+/* eslint-disable @repo/component-file-structure */
import { HoverCard } from "@/src/components/design-system/HoverCard/HoverCard";
-import { SelectItem } from "@/src/components/ui/select";
import * as React from "react";
interface PropertyHoverCardProps {
@@ -8,7 +7,7 @@ interface PropertyHoverCardProps {
description?: string;
unit?: string;
type?: string;
- children: React.ReactNode;
+ children: React.ReactElement<React.HTMLProps<HTMLElement>>;
}
export const PropertyHoverCard = ({
@@ -45,40 +44,10 @@ export const PropertyHoverCard = ({
</div>
}
>
- {({ getTriggerProps }) => <div {...getTriggerProps()}>{children}</div>}
+ {/* Anchors the card on the item itself, not a full-width wrapper. */}
+ {({ getTriggerProps }) =>
+ React.cloneElement(children, getTriggerProps(children.props))
+ }
</HoverCard>
);
};
-
-/**
- * Generic SelectItem with a hover-card that shows documentation for a widget property
- * (view, metric, dimension).
- */
-export const WidgetPropertySelectItem = ({
- value,
- label,
- description,
- unit,
- type,
- className,
-}: {
- value: string;
- label: string;
- description?: string;
- unit?: string;
- type?: string;
- className?: string;
-}) => {
- return (
- <PropertyHoverCard
- label={label}
- description={description}
- unit={unit}
- type={type}
- >
- <SelectItem value={value} className={className ?? "max-w-56"}>
- {label}
- </SelectItem>
- </PropertyHoverCard>
- );
-};
diff --git a/web/src/features/widgets/index.ts b/web/src/features/widgets/index.ts
index 9b9692ef56..e80dd89d3c 100644
--- a/web/src/features/widgets/index.ts
+++ b/web/src/features/widgets/index.ts
@@ -24,7 +24,6 @@ export type { DashboardPlacement } from "@/src/features/widgets/components/Dashb
export { useClipboardWidgetProbe } from "@/src/features/widgets/hooks/useClipboardWidgetProbe";
export { pushDownForInsertion } from "@/src/features/widgets/utils/grid-placement";
export { WidgetContent } from "@/src/features/widgets/components/InlineWidget";
-export { WidgetPropertySelectItem } from "@/src/features/widgets/components/WidgetPropertySelectItem";
export type { WidgetDimensionConfig } from "@/src/features/widgets/hooks/useWidgetQuery";
export {
getWidgetMetricPresentation,