🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
/* eslint-disable no-nested-ternary, @typescript-eslint/no-use-before-define */
/* eslint-disable @repo/no-style-props */
import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
import { showErrorToast } from "@/src/features/notifications/showErrorToast";
import React, { useMemo, useRef } from "react";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { useRouter } from "next/router";
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 { 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 {
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/src/components/ui/card";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/src/components/ui/form";
import { Input } from "@/src/components/ui/input";
import { Label } from "@/src/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/src/components/ui/select";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
import { useProject } from "@/src/features/projects/hooks";
import { partitionWidgetUiTableFiltersToView } from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import {
resolveMonitorNameForSave,
type MonitorNameResolution,
} from "@/src/features/monitors/fns/resolveMonitorNameForSave";
import { cn } from "@/src/utils/tailwind";
import {
CreateMonitorSchema,
type CreateMonitor,
type Monitor,
type MonitorNoData,
MonitorNoDataModeSchema,
type MonitorRenotify,
MonitorSeveritySchema,
MonitorStatusSchema,
type MonitorThresholdOperator,
MonitorThresholdOperatorSchema,
type MonitorView,
type MonitorWindow,
MonitorWindowSchema,
UpdateMonitorSchema,
type UpdateMonitor,
} from "@langfuse/shared/monitors";
import { viewDeclarations, type FilterState } from "@langfuse/shared";
import { default as TagManager } from "@/src/features/tag/components/TagManager";
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,
windowLabels,
} from "../helpers/monitorLabels";
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 = (
projectId: string,
prefill?: Partial<
Pick<CreateMonitor, "view" | "filters" | "metric" | "window" | "tags">
>,
initialTriggerIds: string[] = [],
): Partial<CreateMonitor> => ({
projectId,
view: prefill?.view ?? "observations",
filters: prefill?.filters ?? [],
metric: prefill?.metric ?? { measure: "count", aggregation: "count" },
window: prefill?.window ?? "5m",
thresholdOperator: MonitorThresholdOperatorSchema.enum.GT,
warningThreshold: null,
noData: { mode: MonitorNoDataModeSchema.enum.SUBSTITUTE_ZERO },
renotify: { mode: "OFF" },
tags: prefill?.tags ?? [],
triggerIds: initialTriggerIds,
status: MonitorStatusSchema.enum.ACTIVE,
});
/** monitorToDefaults maps a persisted Monitor into the edit form's defaults. */
const monitorToDefaults = (monitor: Monitor): UpdateMonitor => ({
id: monitor.id,
projectId: monitor.projectId,
view: monitor.view,
filters: monitor.filters,
metric: monitor.metric,
window: monitor.window,
thresholdOperator: monitor.thresholdOperator,
alertThreshold: monitor.alertThreshold,
warningThreshold: monitor.warningThreshold,
noData: monitor.noData,
renotify: monitor.renotify,
name: monitor.name,
tags: monitor.tags,
triggerIds: monitor.triggerIds,
// status omitted: the pause/resume toolbar owns it.
});
/** nameOrPlaceholder falls back to the placeholder when the name is blank. */
const nameOrPlaceholder = (
name: string | undefined,
placeholder: string,
): string => name || placeholder;
type MonitorAnalyticsSource =
| "alerts"
| "evaluator_score"
| "evaluator_cost"
| "all_evaluator_cost";
const monitorCreateAnalyticsProperties = (
source: MonitorAnalyticsSource,
monitor: Pick<CreateMonitor, "view" | "metric" | "window">,
) => ({
source,
view: monitor.view,
measure: monitor.metric.measure,
aggregation: monitor.metric.aggregation,
window: monitor.window,
});
/** MonitorForm renders the create/edit form for a Monitor. */
export const MonitorForm = ({
projectId,
monitor,
prefill,
analyticsSource = "alerts",
initialTriggerIds = [],
onNameChange,
secondaryAction,
}: {
projectId: string;
monitor?: Monitor;
prefill?: Partial<
Pick<CreateMonitor, "view" | "filters" | "metric" | "window" | "tags">
>;
analyticsSource?: MonitorAnalyticsSource;
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();
const capture = usePostHogClientCapture();
const { isLangfuseCloud } = useLangfuseCloudRegion();
const { organization } = useProject(projectId);
const nameAIAssistanceAvailable =
isLangfuseCloud && Boolean(organization?.aiFeaturesEnabled);
/** isEdit is true when the form is bound to an existing monitor. */
const isEdit = Boolean(monitor);
/** hasAccess gates write controls behind the alerts:CUD RBAC scope. */
const hasAccess = useHasProjectAccess({ projectId, scope: "alerts:CUD" });
/** utils is the tRPC utils handle used to invalidate caches after mutations. */
const utils = api.useUtils();
/** schema selects the Zod schema to validate against based on isEdit. */
const schema = isEdit ? UpdateMonitorSchema : CreateMonitorSchema;
/** defaultValues seeds the form from the existing monitor on edit, otherwise from createDefaults. */
const defaultValues = isEdit
? monitorToDefaults(monitor as Monitor)
: createDefaults(projectId, prefill, initialTriggerIds);
/** namePlaceholderRef holds the latest computed name placeholder for the resolver. */
const namePlaceholderRef = useRef("");
/** resolver wraps zodResolver, filling a blank name with the computed placeholder before validation. */
const resolver = useMemo(() => {
const base = zodResolver(schema as any);
return ((values, context, options) => {
const v = values as { name?: string };
const mapped = {
...values,
name: nameOrPlaceholder(v.name, namePlaceholderRef.current),
};
return base(mapped as any, context, options);
}) as typeof base;
}, [schema]);
/** form is the react-hook-form instance bound to schema and defaultValues. */
const form = useForm<CreateMonitor | UpdateMonitor>({
resolver,
defaultValues: defaultValues as CreateMonitor,
mode: "onChange",
});
const suggestName = api.monitors.suggestName.useMutation();
const generateNameSuggestion = async (): Promise<string | null> => {
if (!nameAIAssistanceAvailable) return null;
return suggestName.mutateAsync({
projectId,
description: namePlaceholderRef.current,
});
};
const requestNameSuggestion = async () => {
let generatedName: string | null;
try {
generatedName = await generateNameSuggestion();
} catch (error) {
showErrorToast(
"Couldn't generate an alert title",
"Please enter a title manually.",
classifyTrpcToastError(error, "monitor_title.generate"),
);
return;
}
if (!generatedName) {
showErrorToast(
"Couldn't generate an alert title",
"Please enter a title manually.",
{
operation: "monitor_title.generate",
errorOrigin: "backend",
errorCategory: "internal",
},
);
return;
}
form.setValue("name", generatedName, {
shouldDirty: true,
shouldValidate: true,
});
onNameChange?.(generatedName);
};
/** createMutation creates a new monitor and returns to the monitors list on success. */
const createMutation = api.monitors.create.useMutation({
onSuccess: async (_data, variables) => {
await utils.monitors.invalidate();
capture(
"monitors:create",
monitorCreateAnalyticsProperties(analyticsSource, variables),
);
showSuccessToast({
operation: "monitor.create",
title: "Alert created",
description: `"${variables.name}" is now active.`,
});
router.replace(`/project/${projectId}/alerts`);
},
onError: (e) =>
showErrorToast(
"Failed to create alert",
e.message,
classifyTrpcToastError(e, "monitor.create"),
),
});
/** updateMutation saves edits to an existing monitor and returns to the monitors list on success. */
const updateMutation = api.monitors.update.useMutation({
onSuccess: async (_data, variables) => {
await utils.monitors.invalidate();
showSuccessToast({
operation: "monitor.update",
title: "Alert saved",
description: `Your changes to "${variables.name}" have been applied.`,
});
router.replace(`/project/${projectId}/alerts`);
},
onError: (e) =>
showErrorToast(
"Failed to save alert",
e.message,
classifyTrpcToastError(e, "monitor.update"),
),
});
/** onSubmit strips unsupported filter rows and dispatches the create or update mutation. */
const onSubmit = form.handleSubmit(
async (values) => {
let nameResolution: MonitorNameResolution;
try {
nameResolution = await resolveMonitorNameForSave({
name: form.getValues("name"),
fallbackName: namePlaceholderRef.current,
aiAvailable: nameAIAssistanceAvailable,
generateName: generateNameSuggestion,
});
} catch (error) {
showErrorToast(
"Couldn't generate an alert title",
"Please enter a title manually and try again.",
classifyTrpcToastError(error, "monitor_title.generate"),
);
return;
}
if (nameResolution.status === "generation-failed") {
showErrorToast(
"Couldn't generate an alert title",
"Please enter a title manually and try again.",
{
operation: "monitor_title.generate",
errorOrigin: "backend",
errorCategory: "internal",
},
);
return;
}
if (nameResolution.status === "validation-failed") {
showErrorToast(
"Couldn't generate an alert title",
"Please enter a title manually and try again.",
{
operation: isEdit ? "monitor.update" : "monitor.create",
errorOrigin: "frontend",
errorCategory: "user_input",
},
);
return;
}
const normalizedValues = {
...values,
name: nameResolution.name,
filters: partitionWidgetUiTableFiltersToView(
values.view as Parameters<
typeof partitionWidgetUiTableFiltersToView
>[0],
(values.filters ?? []) as FilterState,
).mappedFilters,
} as typeof values;
if (isEdit && monitor) {
// status omitted: the pause/resume toolbar owns it.
updateMutation.mutate({
...(normalizedValues as UpdateMonitor),
id: monitor.id,
});
} else {
createMutation.mutate(normalizedValues as CreateMonitor);
}
},
/** onInvalid scroll to the first error message */
() => {
requestAnimationFrame(() => {
document
.querySelector('[id$="-form-item-message"]')
?.scrollIntoView({ behavior: "smooth", block: "center" });
});
},
);
/** watched is the live snapshot of form values used to derive preview state, dropdown contents, and placeholders. */
const watched = useWatch({ control: form.control });
const monitorWindow = (watched.window ?? "5m") as MonitorWindow;
/** filterOptionsLookbackFrom lower-bounds discovery at max(20×window, 7d) so even a small monitor window still yields value suggestions. */
const filterOptionsLookbackFrom = useMemo(
() => getMonitorFilterOptionsLookbackFrom(monitorWindow, Date.now()),
[monitorWindow],
);
/** monitorFilterOptions loads the project's existing monitor tags for the tag picker's available-options list. */
const monitorFilterOptions = api.monitors.getFilterOptions.useQuery(
{ projectId },
{ staleTime: Infinity, refetchOnWindowFocus: false },
);
/** namePlaceholder builds an auto-suggested name from the current view + metric + threshold (e.g. "Sum of Observations Latency is below 100"). */
const namePlaceholder = useMemo(
() =>
renderNamePlaceholder({
view: (watched.view ?? "observations") as MonitorView,
metric: {
measure: watched.metric?.measure ?? "count",
aggregation: watched.metric?.aggregation ?? "count",
},
thresholdOperator: (watched.thresholdOperator ??
MonitorThresholdOperatorSchema.enum.GT) as MonitorThresholdOperator,
alertThreshold: watched.alertThreshold,
}),
[
watched.view,
watched.metric?.measure,
watched.metric?.aggregation,
watched.thresholdOperator,
watched.alertThreshold,
],
);
namePlaceholderRef.current = namePlaceholder;
/** previewFilters strips unsupported rows from the picked view's filters for the preview query. */
const previewFilters = useMemo<FilterState>(
() =>
partitionWidgetUiTableFiltersToView(
(watched.view ?? "observations") as Parameters<
typeof partitionWidgetUiTableFiltersToView
>[0],
(watched.filters ?? []) as FilterState,
).mappedFilters,
[watched.view, watched.filters],
);
/** formError is a typed view onto react-hook-form's flat error map. */
const formError = form.formState.errors as Record<
string,
{ message?: string } | undefined
>;
/** submitting is true while the form is submitting or either mutation is pending. */
const submitting =
form.formState.isSubmitting ||
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="@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>
<FormHeading
isEdit={isEdit}
name={nameOrPlaceholder(watched.name, namePlaceholder)}
/>
</CardHeader>
<CardContent className="min-h-0 flex-1 overflow-y-auto overscroll-contain py-0">
{/* 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">
{formError.query.message}
</p>
)}
</Section>
<Section title="Alert Conditions" step={2} hasNextStep>
<FormField
control={form.control}
name="thresholdOperator"
render={({ field }) => (
<FormItem className="flex flex-row items-center gap-2 space-y-0">
<span className="text-muted-foreground text-sm whitespace-nowrap">
Trigger when the value is
</span>
<Select
value={field.value}
onValueChange={(next) => {
field.onChange(next);
// A warning band before a "not equal" alert has no
// meaningful ordering, so drop any stale value.
if (
next === MonitorThresholdOperatorSchema.enum.NEQ
) {
form.setValue("warningThreshold", null, {
shouldValidate: true,
});
}
}}
disabled={!hasAccess}
>
<FormControl>
<SelectTrigger className="w-auto">
<SelectValue />
</SelectTrigger>
</FormControl>
<SelectContent>
{MonitorThresholdOperatorSchema.options.map((op) => (
<SelectItem key={op} value={op}>
{operatorLabels[op]}
</SelectItem>
))}
</SelectContent>
</Select>
</FormItem>
)}
/>
<FormField
control={form.control}
name="alertThreshold"
render={({ field }) => (
<FormItem>
<div className="flex items-center gap-2">
<MonitorSeverityBadge
severity={MonitorSeveritySchema.enum.ALERT}
/>
<span className="hidden text-sm whitespace-nowrap @sm:inline">
Threshold
</span>
<span className="mr-1.5 ml-1 font-mono text-xs font-bold">
{
operatorSymbol[
(watched.thresholdOperator ??
MonitorThresholdOperatorSchema.enum
.GT) as keyof typeof operatorSymbol
]
}
</span>
<FormControl>
<ThresholdInput
unit={thresholdUnitLabel}
placeholder="0"
value={field.value ?? ""}
onChange={(e) => {
const raw = e.target.value;
field.onChange(raw === "" ? null : Number(raw));
}}
disabled={!hasAccess}
/>
</FormControl>
</div>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="warningThreshold"
render={({ field }) => (
<FormItem
hidden={
watched.thresholdOperator ===
MonitorThresholdOperatorSchema.enum.NEQ
}
>
<div className="flex items-center gap-2">
<MonitorSeverityBadge
severity={MonitorSeveritySchema.enum.WARNING}
/>
<span className="hidden text-sm whitespace-nowrap @sm:inline">
Threshold
</span>
<span className="mr-1.5 ml-1 font-mono text-xs font-bold">
{
operatorSymbol[
(watched.thresholdOperator ??
MonitorThresholdOperatorSchema.enum
.GT) as keyof typeof operatorSymbol
]
}
</span>
<FormControl>
<ThresholdInput
unit={thresholdUnitLabel}
placeholder="optional"
value={field.value ?? ""}
onChange={(e) => {
const raw = e.target.value;
field.onChange(raw === "" ? null : Number(raw));
}}
disabled={!hasAccess}
/>
</FormControl>
</div>
<FormMessage />
</FormItem>
)}
/>
{formError.threshold && (
<p className="text-destructive text-xs">
{formError.threshold.message}
</p>
)}
<FormField
control={form.control}
name="window"
render={({ field }) => (
<FormItem className="flex flex-row items-center gap-2 space-y-0">
<span className="text-muted-foreground text-sm whitespace-nowrap">
Over the past
</span>
<Select
value={field.value}
onValueChange={field.onChange}
disabled={!hasAccess}
>
<FormControl>
<SelectTrigger className="w-auto">
<SelectValue />
</SelectTrigger>
</FormControl>
<SelectContent>
{MonitorWindowSchema.options.map((w) => (
<SelectItem key={w} value={w}>
{windowLabels[w]}
</SelectItem>
))}
</SelectContent>
</Select>
</FormItem>
)}
/>
<AccordionPrimitive.Root type="single" collapsible>
<AccordionPrimitive.Item value="advanced">
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger className="flex flex-1 items-center justify-start gap-2 py-2 text-sm font-bold transition-all hover:underline [&>svg]:order-first [&>svg]:-rotate-90 [&[data-state=open]>svg]:rotate-0">
<DropdownIndicator nudge />
Advanced Options
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
<AccordionPrimitive.Content className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm transition-all">
<div className="space-y-6 px-1 pt-2 pb-4">
<FormField
control={form.control}
name="noData"
render={({ field }) => (
<FormItem>
<NoDataField
value={field.value as MonitorNoData}
onChange={field.onChange}
disabled={!hasAccess}
/>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="renotify"
render={({ field }) => (
<FormItem>
<RenotifyField
value={field.value as MonitorRenotify}
onChange={field.onChange}
disabled={!hasAccess}
/>
<FormMessage />
</FormItem>
)}
/>
</div>
</AccordionPrimitive.Content>
</AccordionPrimitive.Item>
</AccordionPrimitive.Root>
</Section>
<Section title="Notifications" step={3}>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Title</FormLabel>
<FormControl>
<AIAssistedInput
id="monitor-title"
maxLength={200}
placeholder={namePlaceholder}
disabled={!hasAccess}
value={field.value ?? ""}
onChange={(e) => {
field.onChange(e);
onNameChange?.(e.target.value ?? "");
}}
fieldName="title"
aiAssistance={
!nameAIAssistanceAvailable
? { state: "unavailable" }
: suggestName.isPending
? { state: "generating" }
: {
state: "idle",
onGenerate: () => {
requestNameSuggestion().catch(
() => undefined,
);
},
}
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="tags"
render={({ field }) => (
<FormItem>
<FormControl>
<TagManager
itemName="alert"
tags={(field.value ?? []) as string[]}
allTags={
monitorFilterOptions.data?.tags.map(
(t) => t.value,
) ?? []
}
hasAccess={hasAccess}
isLoading={monitorFilterOptions.isPending}
mutateTags={field.onChange}
triggerButton={
<Button
type="button"
variant="default"
size="sm"
className="gap-1"
>
<Plus size="base" />
Add tag
</Button>
}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="triggerIds"
render={({ field }) => (
<FormItem>
<FormLabel>Automations</FormLabel>
<FormMessage />
<FormDescription>
Send Alerts to Slack, Webhooks, and GitHub Actions.
</FormDescription>
<FormControl>
<MonitorAutomationsPanel
projectId={projectId}
hasAccess={hasAccess}
triggerIds={(field.value ?? []) as string[]}
onTriggerIdsChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
</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="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"
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>
</div>
</div>
<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}
filters={previewFilters}
measure={watched.metric?.measure ?? "count"}
aggregation={
(watched.metric?.aggregation ??
"count") as CreateMonitor["metric"]["aggregation"]
}
window={(watched.window ?? "5m") as MonitorWindow}
thresholdOperator={
watched.thresholdOperator ??
MonitorThresholdOperatorSchema.enum.GT
}
alertThreshold={watched.alertThreshold}
warningThreshold={watched.warningThreshold ?? null}
/>
</div>
</form>
</Form>
);
};
/** 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 “{name}”</CardTitle>;
}
return (
<>
<CardTitle>Alert Configuration</CardTitle>
<CardDescription>
Receive notifications when a metric crosses a threshold. (eg.
“sudden cost increase”, “accuracy has dropped”)
</CardDescription>
</>
);
}
/** Header pins a section title to the top of the scrolling CardContent. */
const Header = ({
title,
step,
icon: Icon,
}: {
title: string;
step?: number;
icon?: IconComponent;
}) => (
<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}
</span>
) : null}
{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, 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 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 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>
);
/** NoDataField renders the no-data mode picker plus its dependent fields. */
const NoDataField = ({
value,
onChange,
disabled,
}: {
value: MonitorNoData;
onChange: (next: MonitorNoData) => void;
disabled?: boolean;
}) => (
<div className="space-y-2">
<Label>When there is no data</Label>
<Select
value={value.mode}
onValueChange={(mode) =>
onChange(
mode === MonitorNoDataModeSchema.enum.NOTIFY_NO_DATA
? {
mode: MonitorNoDataModeSchema.enum.NOTIFY_NO_DATA,
intervalMinutes: 60,
}
: {
mode: mode as Exclude<MonitorNoData["mode"], "NOTIFY_NO_DATA">,
},
)
}
disabled={disabled}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value={MonitorNoDataModeSchema.enum.SUBSTITUTE_ZERO}>
<span className="inline-flex items-center gap-1.5">
Treat missing data as
<code className="bg-secondary rounded border px-0.5">0</code>
</span>
</SelectItem>
<SelectItem value={MonitorNoDataModeSchema.enum.LAST_SEVERITY}>
<span className="inline-flex items-center gap-1.5">
Keep the previous
<Badge color="inverted" text="SEVERITY" />
</span>
</SelectItem>
<SelectItem value={MonitorNoDataModeSchema.enum.SHOW_NO_DATA}>
<span className="inline-flex items-center gap-1.5">
Show severity
<MonitorSeverityBadge
severity={MonitorSeveritySchema.enum.NO_DATA}
/>
</span>
</SelectItem>
<SelectItem value={MonitorNoDataModeSchema.enum.NOTIFY_NO_DATA}>
<span className="inline-flex items-center gap-1.5">
Notify after sustained
<MonitorSeverityBadge
severity={MonitorSeveritySchema.enum.NO_DATA}
/>
</span>
</SelectItem>
</SelectContent>
</Select>
{value.mode === MonitorNoDataModeSchema.enum.NOTIFY_NO_DATA && (
<div className="flex items-center gap-2">
<Label className="text-muted-foreground text-xs">Notify after</Label>
<Input
type="number"
min={1}
max={60 * 24}
value={value.intervalMinutes}
onChange={(e) =>
onChange({
mode: MonitorNoDataModeSchema.enum.NOTIFY_NO_DATA,
intervalMinutes: Math.max(1, Number(e.target.value) || 1),
})
}
disabled={disabled}
className="w-24"
/>
<Label className="text-muted-foreground text-xs">minutes</Label>
</div>
)}
</div>
);
/** RenotifyField renders the renotify mode picker plus its interval input. */
const RenotifyField = ({
value,
onChange,
disabled,
}: {
value: MonitorRenotify;
onChange: (next: MonitorRenotify) => void;
disabled?: boolean;
}) => (
<div className="space-y-2">
<Label>Renotify</Label>
<Select
value={value.mode}
onValueChange={(mode) =>
onChange(
mode === "EVERY"
? { mode: "EVERY", intervalMinutes: 60 }
: { mode: "OFF" },
)
}
disabled={disabled}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="OFF">Off (alert only on transitions)</SelectItem>
<SelectItem value="EVERY">Re-alert at a regular interval</SelectItem>
</SelectContent>
</Select>
{value.mode === "EVERY" && (
<div className="flex items-center gap-2">
<Label className="text-muted-foreground text-xs">
Re-alert every (minutes)
</Label>
<Input
type="number"
min={1}
max={60 * 24 * 7}
value={value.intervalMinutes}
onChange={(e) =>
onChange({
mode: "EVERY",
intervalMinutes: Math.max(1, Number(e.target.value) || 1),
})
}
disabled={disabled}
className="w-32"
/>
</div>
)}
</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,
monitorCreateAnalyticsProperties,
};