🪢 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
feat(monitors): metric alerting - scheduler, processor, alert dispatch, and management ui (#13874)
Mark Salpetera9678ad9c174
diff --git a/.gitignore b/.gitignoreindex 512b4e1c44..debf78fc85 100644--- a/.gitignore+++ b/.gitignore@@ -102,6 +102,7 @@ web/test-results/*# claude meta files.claude/tsc-cache+.claude/worktrees# Refactoring planning files (local only)**/.refactor/diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 06bdfe55c0..b5c3bf8d96 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -54,6 +54,14 @@"./query/server": {"import": "./dist/src/features/query/server/index.js","require": "./dist/src/features/query/server/index.js"+ },+ "./monitors": {+ "import": "./dist/src/features/monitors/index.js",+ "require": "./dist/src/features/monitors/index.js"+ },+ "./monitors/server": {+ "import": "./dist/src/features/monitors/server.js",+ "require": "./dist/src/features/monitors/server.js"}},"scripts": {diff --git a/packages/shared/prisma/migrations/20260522113010_add_paused_monitor_severity/migration.sql b/packages/shared/prisma/migrations/20260522113010_add_paused_monitor_severity/migration.sqlnew file mode 100644index 0000000000..2645b6a6db--- /dev/null+++ b/packages/shared/prisma/migrations/20260522113010_add_paused_monitor_severity/migration.sql@@ -0,0 +1,30 @@+-- Add PAUSED to MonitorSeverity (positioned first so `severity DESC` sinks+-- paused monitors to the bottom) and backfill non-ACTIVE rows. The enum is+-- recreated rather than evolved via ALTER TYPE ADD VALUE so the new value is+-- usable in the same migration's backfill (Postgres otherwise requires a+-- separate transaction before a newly-added enum value can be referenced).+ALTER TYPE "MonitorSeverity" RENAME TO "MonitorSeverity_old";++CREATE TYPE "MonitorSeverity" AS ENUM (+ 'PAUSED',+ 'UNKNOWN',+ 'NO_DATA',+ 'OK',+ 'WARNING',+ 'ALERT'+);++ALTER TABLE monitors+ ALTER COLUMN severity DROP DEFAULT,+ ALTER COLUMN severity TYPE "MonitorSeverity"+ USING severity::text::"MonitorSeverity",+ ALTER COLUMN severity SET DEFAULT 'UNKNOWN'::"MonitorSeverity";++DROP TYPE "MonitorSeverity_old";++-- Backfill existing non-ACTIVE rows (PAUSED + ERROR_BAD_QUERY) so the list+-- view renders them with the new "paused" appearance from the first deploy.+-- New transitions are written by MonitorService.update going forward.+UPDATE monitors SET severity = 'PAUSED' WHERE status <> 'ACTIVE';++ALTER TABLE "monitors" ADD COLUMN "trigger_ids" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[];diff --git a/packages/shared/prisma/migrations/20260527110000_monitor_wallclock_lifecycle/migration.sql b/packages/shared/prisma/migrations/20260527110000_monitor_wallclock_lifecycle/migration.sqlnew file mode 100644index 0000000000..74c37f12e0--- /dev/null+++ b/packages/shared/prisma/migrations/20260527110000_monitor_wallclock_lifecycle/migration.sql@@ -0,0 +1,10 @@+ALTER TABLE "monitors" ALTER COLUMN "next_run_at" DROP NOT NULL;++ALTER TABLE "monitors" RENAME COLUMN "last_published_run_at" TO "last_published_at";++ALTER TABLE "monitors" RENAME COLUMN "last_completed_run_at" TO "last_completed_at";++ALTER TABLE "monitors" ADD COLUMN "last_claimed_at" TIMESTAMP(3);++CREATE INDEX "monitors_scheduler_rescue_idx" ON "monitors"("last_published_at")+ WHERE "last_completed_at" IS NULL OR "last_completed_at" < "last_published_at";diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 15c59ccf22..67c0492021 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -1678,6 +1678,7 @@ enum MonitorView {}enum MonitorSeverity {+ PAUSEDUNKNOWNNO_DATAOK@@ -1724,15 +1725,17 @@ model Monitor {renotify Json// === Scheduling ===- status MonitorStatus @default(ACTIVE)- schedulerBatchId BigInt @map("scheduler_batch_id")- nextRunAt DateTime @map("next_run_at")- lastPublishedRunAt DateTime? @map("last_published_run_at")- lastCompletedRunAt DateTime? @map("last_completed_run_at")+ status MonitorStatus @default(ACTIVE)+ schedulerBatchId BigInt @map("scheduler_batch_id")+ nextRunAt DateTime? @map("next_run_at")+ lastPublishedAt DateTime? @map("last_published_at")+ lastClaimedAt DateTime? @map("last_claimed_at")+ lastCompletedAt DateTime? @map("last_completed_at")// === Alerts ===name String- tags String[] @default([])+ tags String[] @default([])+ triggerIds String[] @default([]) @map("trigger_ids")alertedAt DateTime? @map("alerted_at")@@index([projectId])diff --git a/packages/shared/src/domain/automations.test.ts b/packages/shared/src/domain/automations.test.tsnew file mode 100644index 0000000000..57b3eb7731--- /dev/null+++ b/packages/shared/src/domain/automations.test.ts@@ -0,0 +1,34 @@+import { describe, it, expect } from "vitest";++import { AvailableWebhookApiSchema } from "./automations";++describe("AvailableWebhookApiSchema", () => {+ it("accepts monitor: v1", () => {+ expect(AvailableWebhookApiSchema.safeParse({ monitor: "v1" }).success).toBe(+ true,+ );+ });++ it("accepts prompt and monitor together", () => {+ expect(+ AvailableWebhookApiSchema.safeParse({ prompt: "v1", monitor: "v1" })+ .success,+ ).toBe(true);+ });++ it("accepts an empty record", () => {+ expect(AvailableWebhookApiSchema.safeParse({}).success).toBe(true);+ });++ it("rejects unknown api keys", () => {+ expect(AvailableWebhookApiSchema.safeParse({ bogus: "v1" }).success).toBe(+ false,+ );+ });++ it("rejects unknown api versions", () => {+ expect(AvailableWebhookApiSchema.safeParse({ monitor: "v2" }).success).toBe(+ false,+ );+ });+});diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.tsindex 7452b9395c..f32b8b2342 100644--- a/packages/shared/src/domain/automations.ts+++ b/packages/shared/src/domain/automations.ts@@ -42,8 +42,8 @@ export type ActionDomainWithSecrets = Omit<Action, "config"> & {export const ActionTypeSchema = z.enum(["WEBHOOK", "SLACK", "GITHUB_DISPATCH"]);-export const AvailableWebhookApiSchema = z.record(- z.enum(["prompt"]),+export const AvailableWebhookApiSchema = z.partialRecord(+ z.enum(["prompt", "monitor"]),z.enum(["v1"]),);diff --git a/packages/shared/src/features/monitors/filterColumns.ts b/packages/shared/src/features/monitors/filterColumns.tsnew file mode 100644index 0000000000..10883eeffe--- /dev/null+++ b/packages/shared/src/features/monitors/filterColumns.ts@@ -0,0 +1,17 @@+/** filterColumns.ts owns the monitor-domain rule for which filter columns+ * are valid in a monitor query. Consumed by `./isValidQuery` (server-side+ * validation) and by the monitor form in `web/` (UI column list) so both+ * surfaces agree on the same constraint. */+import { type ColumnDefinition } from "../../tableDefinitions/types";++/** disallowedMonitorFilterColumns lists filter column ids that are not valid+ * in a monitor query. `metadata` is rejected because its `stringObject`+ * JSON-key probe is prohibitively expensive at monitor evaluation cadence. */+export const disallowedMonitorFilterColumns: readonly string[] = ["metadata"];++/** getValidMonitorFilterColumns drops columns whose `id` is in+ * `disallowedMonitorFilterColumns`. */+export const getValidMonitorFilterColumns = (+ columns: ColumnDefinition[],+): ColumnDefinition[] =>+ columns.filter((c) => !disallowedMonitorFilterColumns.includes(c.id));diff --git a/packages/shared/src/features/monitors/index.ts b/packages/shared/src/features/monitors/index.tsindex 1dd7d465ab..57e9897cd3 100644--- a/packages/shared/src/features/monitors/index.ts+++ b/packages/shared/src/features/monitors/index.ts@@ -1,6 +1,9 @@/** index.ts is the client-safe barrel for the monitors feature — domain- * schemas, types, refinements, and standalone predicates. Server-only code- * (the service, scheduler DTOs) is re-exported from `./server` instead. */+ * schemas, types, refinements, standalone predicates, and the MonitorService+ * input DTOs. Server-only code (the service implementation, scheduler DTOs)+ * is re-exported from `./server` instead. */export * from "./types";export * from "./isValidQuery";export * from "./isValidThresholdOrder";+export * from "./filterColumns";+export * from "./service/types";diff --git a/packages/shared/src/features/monitors/isValidQuery.test.ts b/packages/shared/src/features/monitors/isValidQuery.test.tsindex 5549ffc34c..cfa2bb7e3d 100644--- a/packages/shared/src/features/monitors/isValidQuery.test.ts+++ b/packages/shared/src/features/monitors/isValidQuery.test.ts@@ -6,7 +6,7 @@ describe("isValidQuery", () => {it("accepts a valid (view, measure, aggregation) tuple", () => {const result = isValidQuery({view: "observations",- metric: { measure: "count", aggregation: "count" },+ metrics: [{ measure: "count", aggregation: "count" }],filters: [],});expect(result.valid).toBe(true);@@ -15,7 +15,7 @@ describe("isValidQuery", () => {it("rejects an unknown measure for the view", () => {const result = isValidQuery({view: "observations",- metric: { measure: "bogus_measure", aggregation: "count" },+ metrics: [{ measure: "bogus_measure", aggregation: "count" }],filters: [],});expect(result.valid).toBe(false);@@ -25,10 +25,10 @@ describe("isValidQuery", () => {}});- it("accepts a `metadata` filter column without checking the view's dimensions", () => {+ it("rejects a `metadata` filter column: too expensive at evaluation cadence", () => {const result = isValidQuery({view: "observations",- metric: { measure: "count", aggregation: "count" },+ metrics: [{ measure: "count", aggregation: "count" }],filters: [{type: "stringObject",@@ -39,26 +39,10 @@ describe("isValidQuery", () => {},],});- expect(result.valid).toBe(true);- });-- it("rejects a filter column that isn't a dimension on the view", () => {- const result = isValidQuery({- view: "observations",- metric: { measure: "count", aggregation: "count" },- filters: [- {- type: "string",- column: "not_a_dimension",- operator: "=",- value: "x",- },- ],- });expect(result.valid).toBe(false);if (!result.valid) {- expect(result.reason).toContain("Invalid filter column");- expect(result.reason).toContain("not_a_dimension");+ expect(result.reason).toContain("metadata");+ expect(result.reason).toContain("not supported for monitors");}});@@ -67,7 +51,7 @@ describe("isValidQuery", () => {expect(() =>isValidQuery({view: "bogus" as never,- metric: { measure: "count", aggregation: "count" },+ metrics: [{ measure: "count", aggregation: "count" }],filters: [],}),).toThrow(/View 'bogus' is not supported/);@@ -78,7 +62,7 @@ describe("isValidQuery", () => {(measure) => {const result = isValidQuery({view: "observations",- metric: { measure, aggregation: "count" },+ metrics: [{ measure, aggregation: "count" }],filters: [],});expect(result.valid).toBe(false);@@ -88,25 +72,10 @@ describe("isValidQuery", () => {},);- it.each(["constructor", "toString", "hasOwnProperty", "__proto__"])(- "rejects %s as a filter column (does not walk the prototype chain)",- (column) => {- const result = isValidQuery({- view: "observations",- metric: { measure: "count", aggregation: "count" },- filters: [{ type: "string", column, operator: "=", value: "x" }],- });- expect(result.valid).toBe(false);- if (!result.valid) {- expect(result.reason).toContain("Invalid filter column");- }- },- );-it("rejects histogram aggregation (bucket array is not comparable to a scalar threshold)", () => {const result = isValidQuery({view: "observations",- metric: { measure: "count", aggregation: "histogram" },+ metrics: [{ measure: "count", aggregation: "histogram" }],filters: [],});expect(result.valid).toBe(false);@@ -132,7 +101,7 @@ describe("isValidQuery", () => {])("rejects a $type filter with duplicate value entries", (filter) => {const result = isValidQuery({view: "observations",- metric: { measure: "count", aggregation: "count" },+ metrics: [{ measure: "count", aggregation: "count" }],filters: [filter],});expect(result.valid).toBe(false);@@ -142,84 +111,68 @@ describe("isValidQuery", () => {}});- it("rejects a string filter on an array-typed dimension (tags is string[])", () => {+ it("rejects a non-stringObject filter on the metadata column too", () => {+ // Metadata is disallowed regardless of filter type — the column itself+ // is not a valid monitor filter.const result = isValidQuery({view: "observations",- metric: { measure: "count", aggregation: "count" },+ metrics: [{ measure: "count", aggregation: "count" }],filters: [- { type: "string", column: "tags", operator: "=", value: "foo" },+ {+ type: "string",+ column: "metadata",+ operator: "=",+ value: "acme",+ },],});expect(result.valid).toBe(false);if (!result.valid) {- expect(result.reason).toContain("tags");- expect(result.reason).toContain("arrayOptions");+ expect(result.reason).toContain("metadata");+ expect(result.reason).toContain("not supported for monitors");}});- it("rejects a stringOptions filter on an array-typed dimension (tags is string[])", () => {+ it("partitions a mixed batch: keeps valid metrics, rejects only the invalid ones", () => {+ const valid = { measure: "count", aggregation: "count" as const };+ const invalid = { measure: "bogus_measure", aggregation: "count" as const };const result = isValidQuery({view: "observations",- metric: { measure: "count", aggregation: "count" },- filters: [- {- type: "stringOptions",- column: "tags",- operator: "any of",- value: ["foo"],- },- ],+ metrics: [valid, invalid],+ filters: [],});expect(result.valid).toBe(false);if (!result.valid) {- expect(result.reason).toContain("tags");- expect(result.reason).toContain("arrayOptions");+ expect(result.accepted).toEqual([valid]);+ expect(result.rejected).toEqual([invalid]);+ expect(result.reason).toContain("bogus_measure");}});- it("accepts a stringOptions filter on a scalar string dimension", () => {- const result = isValidQuery({- view: "observations",- metric: { measure: "count", aggregation: "count" },- filters: [- {- type: "stringOptions",- column: "environment",- operator: "any of",- value: ["production", "staging"],- },- ],- });- expect(result.valid).toBe(true);- });-- it("accepts an arrayOptions filter on a string[] dimension", () => {+ it("accepts an all-valid batch: every metric accepted, none rejected", () => {+ const metrics = [{ measure: "count", aggregation: "count" as const }];const result = isValidQuery({view: "observations",- metric: { measure: "count", aggregation: "count" },- filters: [- {- type: "arrayOptions",- column: "tags",- operator: "all of",- value: ["alpha", "beta"],- },- ],+ metrics,+ filters: [],});expect(result.valid).toBe(true);+ if (result.valid) {+ expect(result.accepted).toEqual(metrics);+ expect(result.rejected).toEqual([]);+ }});- it("rejects a non-stringObject filter on the metadata column", () => {- // queryBuilder requires metadata filters to be `type: "stringObject"`.- // Without this, a `{type: "string", column: "metadata"}` filter would- // parse cleanly here but fail at every scheduler tick downstream.+ it("rejects a bad filter as a whole-query failure: every metric rejected, none accepted", () => {+ const metrics = [{ measure: "count", aggregation: "count" as const }];const result = isValidQuery({view: "observations",- metric: { measure: "count", aggregation: "count" },+ metrics,filters: [{- type: "string",+ type: "stringObject",column: "metadata",+ key: "tenant",operator: "=",value: "acme",},@@ -227,8 +180,9 @@ describe("isValidQuery", () => {});expect(result.valid).toBe(false);if (!result.valid) {+ expect(result.accepted).toEqual([]);+ expect(result.rejected).toEqual(metrics);expect(result.reason).toContain("metadata");- expect(result.reason).toContain("stringObject");}});});diff --git a/packages/shared/src/features/monitors/isValidQuery.ts b/packages/shared/src/features/monitors/isValidQuery.tsindex 39bc3b1439..f189b3f42d 100644--- a/packages/shared/src/features/monitors/isValidQuery.ts+++ b/packages/shared/src/features/monitors/isValidQuery.ts@@ -7,88 +7,83 @@ import { type singleFilter } from "../../interfaces/filters";import { getViewDeclaration } from "../query/dataModel";import {getValidAggregationsForMeasureType,+ type MeasureDefinition,type metric,+ type metricAggregations,type viewsV2,} from "../query/types";+import { disallowedMonitorFilterColumns } from "./filterColumns";++/** getValidMonitorAggregationsForMeasure returns the aggregations valid for a monitor metric: the widget set minus `histogram`, and pinned to the measure's inner `aggs.agg` when set (e.g. observations.count is always `count`). */+export const getValidMonitorAggregationsForMeasure = (+ measure: MeasureDefinition | undefined,+): z.infer<typeof metricAggregations>[] => {+ const aggs = getValidAggregationsForMeasureType(measure?.type).filter(+ (a) => a !== "histogram",+ );+ const pinned = measure?.aggs?.agg as+ | z.infer<typeof metricAggregations>+ | undefined;+ if (pinned && pinned !== "histogram" && aggs.includes(pinned)) {+ return [pinned];+ }+ return aggs;+};/**- * isValidQuery ensures:- * - The measure exists on the view's v2 declaration.- * - The aggregation is compatible with the measure's declared type.- * - Each filter column is either a declared dimension or the `metadata`- * escape hatch.+ * isValidQuery partitions a monitor's metrics against the view's v2+ * declaration. A bad filter is a whole-query failure (every metric rejected);+ * otherwise each metric is partitioned by the measure-exists + aggregation+ * checks, `reason` carrying the first rejection. Filter-column-vs-view+ * alignment is intentionally NOT checked here (see LF-2181) — dimensions are+ * the group-by surface, not the filter surface, so the dimension map is the+ * wrong proxy.*/export function isValidQuery(input: {view: z.infer<typeof viewsV2>;- metric: z.infer<typeof metric>;+ metrics: z.infer<typeof metric>[];filters: z.infer<typeof singleFilter>[];-}): { valid: true } | { valid: false; reason: string } {+}): QueryValidation {const declaration = getViewDeclaration(input.view, "v2");- if (!Object.hasOwn(declaration.measures, input.metric.measure)) {+ const filterReason = invalidFilterReason(declaration, input.filters);+ if (filterReason) {return {valid: false,- reason:- `Invalid measure "${input.metric.measure}" for view "${input.view}". ` +- `Must be one of: ${Object.keys(declaration.measures).join(", ")}`,+ reason: filterReason,+ accepted: [],+ rejected: input.metrics,};}- const measureDef = declaration.measures[input.metric.measure];- const validAggs = getValidAggregationsForMeasureType(measureDef.type);- if (!validAggs.some((a) => a === input.metric.aggregation)) {- return {- valid: false,- reason:- `Aggregation "${input.metric.aggregation}" is not valid for measure ` +- `"${input.metric.measure}" (type: ${measureDef.type}). Valid: ${validAggs.join(", ")}`,- };+ const accepted: z.infer<typeof metric>[] = [];+ const rejected: z.infer<typeof metric>[] = [];+ let reason: string | undefined;+ for (const m of input.metrics) {+ const metricReason = invalidMetricReason(declaration, input.view, m);+ if (metricReason) {+ rejected.push(m);+ reason ??= metricReason;+ } else {+ accepted.push(m);+ }}- // `histogram` returns a bucket-array (Array(Tuple(...))) at the ClickHouse- // layer; monitor thresholds are scalars (`z.number()`) compared with- // `gt`/`gte`/`lt`/`lte`/`eq`/`neq`. No defined comparison semantics →- // reject at the input boundary rather than failing in the worker.- if (input.metric.aggregation === "histogram") {- return {- valid: false,- reason:- `Aggregation "histogram" is not supported for monitors — it produces ` +- `a bucket array, not a scalar value comparable to the threshold.`,- };- }+ if (reason) return { valid: false, reason, accepted, rejected };+ return { valid: true, accepted, rejected: [] };+}- for (const filter of input.filters) {- if (filter.column === "metadata") {- if (filter.type !== "stringObject") {- return {- valid: false,- reason:- `Filter on "metadata" must be type "stringObject" with a "key" property ` +- `(got "${filter.type}"). queryBuilder rejects other metadata filter types.`,- };- }- continue;- }- if (!Object.hasOwn(declaration.dimensions, filter.column)) {- return {- valid: false,- reason:- `Invalid filter column "${filter.column}" for view "${input.view}". ` +- `Must be a dimension on the view or the special "metadata" column.`,- };- }- // Array-typed dimensions (e.g. `tags`) require the `arrayOptions` filter- // variant; queryBuilder rejects scalar filters on them. Fail fast at the- // input boundary instead of letting the scheduler tick fail.- const dimension = declaration.dimensions[filter.column];- if (dimension.type === "string[]" && filter.type !== "arrayOptions") {- return {- valid: false,- reason:- `Filter on "${filter.column}" must be type "arrayOptions" — the dimension is an array ` +- `(got "${filter.type}"). queryBuilder requires scalar dimensions for non-array filter types.`,- };+/** invalidFilterReason returns why a filter makes the whole query invalid, or undefined when all filters pass. */+function invalidFilterReason(+ declaration: ReturnType<typeof getViewDeclaration>,+ filters: z.infer<typeof singleFilter>[],+): string | undefined {+ for (const filter of filters) {+ if (disallowedMonitorFilterColumns.includes(filter.column)) {+ return (+ `Filter on "${filter.column}" is not supported for monitors — ` ++ `too expensive at evaluation cadence.`+ );}// Set-semantics value arrays must not contain duplicates — `any of` /// `none of` / `all of` are set operators, so duplicate elements produce@@ -99,15 +94,53 @@ export function isValidQuery(input: {filter.type === "arrayOptions") {if (new Set(filter.value).size !== filter.value.length) {- return {- valid: false,- reason:- `Filter on "${filter.column}" (type "${filter.type}") must have unique values; ` +- `duplicates are not allowed for set-semantics operators.`,- };+ return (+ `Filter on "${filter.column}" (type "${filter.type}") must have unique values; ` ++ `duplicates are not allowed for set-semantics operators.`+ );}}}+ return undefined;+}++/** invalidMetricReason returns why a metric doesn't resolve on the view declaration, or undefined when it is valid. */+function invalidMetricReason(+ declaration: ReturnType<typeof getViewDeclaration>,+ view: z.infer<typeof viewsV2>,+ m: z.infer<typeof metric>,+): string | undefined {+ if (!Object.hasOwn(declaration.measures, m.measure)) {+ return (+ `Invalid measure "${m.measure}" for view "${view}". ` ++ `Must be one of: ${Object.keys(declaration.measures).join(", ")}`+ );+ }+ const measureDef = declaration.measures[m.measure];- return { valid: true };+ if (m.aggregation === "histogram") {+ return (+ `Aggregation "histogram" is not supported for monitors — it produces ` ++ `a bucket array, not a scalar value comparable to the threshold.`+ );+ }++ const validAggs = getValidMonitorAggregationsForMeasure(measureDef);+ if (!validAggs.some((a) => a === m.aggregation)) {+ return (+ `Aggregation "${m.aggregation}" is not valid for measure ` ++ `"${m.measure}" (type: ${measureDef.type}). Valid: ${validAggs.join(", ")}`+ );+ }+ return undefined;}++/** QueryValidation is the partition isValidQuery returns: accepted/rejected metrics plus a rejection reason when invalid. */+export type QueryValidation =+ | { valid: true; accepted: z.infer<typeof metric>[]; rejected: [] }+ | {+ valid: false;+ reason: string;+ accepted: z.infer<typeof metric>[];+ rejected: z.infer<typeof metric>[];+ };diff --git a/packages/shared/src/features/monitors/isValidThresholdOrder.test.ts b/packages/shared/src/features/monitors/isValidThresholdOrder.test.tsindex 811f8a0c90..f9d35d0269 100644--- a/packages/shared/src/features/monitors/isValidThresholdOrder.test.ts+++ b/packages/shared/src/features/monitors/isValidThresholdOrder.test.ts@@ -3,7 +3,7 @@ import { describe, it, expect } from "vitest";import { isValidThresholdOrder } from "./isValidThresholdOrder";describe("isValidThresholdOrder", () => {- it.each(["gt", "gte"] as const)(+ it.each(["GT", "GTE"] as const)("%s requires warningThreshold < alertThreshold",(op) => {expect(@@ -12,25 +12,25 @@ describe("isValidThresholdOrder", () => {alertThreshold: 100,warningThreshold: 50,}),- ).toBe(true);- expect(- isValidThresholdOrder({- thresholdOperator: op,- alertThreshold: 100,- warningThreshold: 100, // equal → invalid- }),- ).toBe(false);- expect(- isValidThresholdOrder({- thresholdOperator: op,- alertThreshold: 100,- warningThreshold: 200, // warning > alert → invalid for gt- }),- ).toBe(false);+ ).toEqual({ valid: true });+ const equal = isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 100,+ });+ expect(equal.valid).toBe(false);+ if (!equal.valid) expect(equal.reason).toContain(">");+ const higher = isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 200,+ });+ expect(higher.valid).toBe(false);+ if (!higher.valid) expect(higher.reason).toContain(">");},);- it.each(["lt", "lte"] as const)(+ it.each(["LT", "LTE"] as const)("%s requires warningThreshold > alertThreshold",(op) => {expect(@@ -39,25 +39,25 @@ describe("isValidThresholdOrder", () => {alertThreshold: 100,warningThreshold: 200,}),- ).toBe(true);- expect(- isValidThresholdOrder({- thresholdOperator: op,- alertThreshold: 100,- warningThreshold: 100,- }),- ).toBe(false);- expect(- isValidThresholdOrder({- thresholdOperator: op,- alertThreshold: 100,- warningThreshold: 50,- }),- ).toBe(false);+ ).toEqual({ valid: true });+ const equal = isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 100,+ });+ expect(equal.valid).toBe(false);+ if (!equal.valid) expect(equal.reason).toContain("<");+ const lower = isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 50,+ });+ expect(lower.valid).toBe(false);+ if (!lower.valid) expect(lower.reason).toContain("<");},);- it.each(["eq", "neq"] as const)("%s passes regardless of ordering", (op) => {+ it.each(["EQ", "NEQ"] as const)("%s passes regardless of ordering", (op) => {for (const warning of [50, 100, 200]) {expect(isValidThresholdOrder({@@ -65,11 +65,11 @@ describe("isValidThresholdOrder", () => {alertThreshold: 100,warningThreshold: warning,}),- ).toBe(true);+ ).toEqual({ valid: true });}});- it.each(["gt", "gte", "lt", "lte", "eq", "neq"] as const)(+ it.each(["GT", "GTE", "LT", "LTE", "EQ", "NEQ"] as const)("%s passes when warningThreshold is null",(op) => {expect(@@ -78,7 +78,7 @@ describe("isValidThresholdOrder", () => {alertThreshold: 100,warningThreshold: null,}),- ).toBe(true);+ ).toEqual({ valid: true });},);});diff --git a/packages/shared/src/features/monitors/isValidThresholdOrder.ts b/packages/shared/src/features/monitors/isValidThresholdOrder.tsindex 5ae2463234..6c6280826f 100644--- a/packages/shared/src/features/monitors/isValidThresholdOrder.ts+++ b/packages/shared/src/features/monitors/isValidThresholdOrder.ts@@ -3,26 +3,34 @@* via `validateThresholdOrder` in `./types`. */import { type MonitorThresholdOperator } from "./types";-/**- * isValidThresholdOrder returns true when the warning and alert thresholds- * are ordered correctly for the given operator. Null `warningThreshold` and- * the unordered `eq`/`neq` operators always pass.- */+/** isValidThresholdOrder returns ok when the warning and alert thresholds are ordered correctly for the given operator; null `warningThreshold` and the unordered `EQ`/`NEQ` operators always pass. */export const isValidThresholdOrder = (monitor: {thresholdOperator: MonitorThresholdOperator;alertThreshold: number;warningThreshold: number | null;-}): boolean => {- if (monitor.warningThreshold == null) return true;+}): { valid: true } | { valid: false; reason: string } => {+ if (monitor.warningThreshold == null) return { valid: true };switch (monitor.thresholdOperator) {- case "gt":- case "gte":- return monitor.warningThreshold < monitor.alertThreshold;- case "lt":- case "lte":- return monitor.warningThreshold > monitor.alertThreshold;- case "eq":- case "neq":- return true;+ case "GT":+ case "GTE":+ if (monitor.warningThreshold < monitor.alertThreshold) {+ return { valid: true };+ }+ return {+ valid: false,+ reason: "alertThreshold must be > warningThreshold",+ };+ case "LT":+ case "LTE":+ if (monitor.warningThreshold > monitor.alertThreshold) {+ return { valid: true };+ }+ return {+ valid: false,+ reason: "alertThreshold must be < warningThreshold",+ };+ case "EQ":+ case "NEQ":+ return { valid: true };}};diff --git a/packages/shared/src/features/monitors/processor/applyStateMachine.test.ts b/packages/shared/src/features/monitors/processor/applyStateMachine.test.tsnew file mode 100644index 0000000000..9f92bbaae4--- /dev/null+++ b/packages/shared/src/features/monitors/processor/applyStateMachine.test.ts@@ -0,0 +1,787 @@+import { describe, it, expect } from "vitest";++import { applyStateMachine } from "./applyStateMachine";+import type {+ Monitor,+ MonitorNoData,+ MonitorRenotify,+ MonitorSeverity,+} from "../types";++/** StateMachineCase is one applyStateMachine transition-table row. */+type StateMachineCase = {+ name: string;+ input: {+ prevSeverity: MonitorSeverity;+ computedSeverity: MonitorSeverity;+ prevSeverityChangedAt: Date | null;+ prevAlertedAt: Date | null;+ now: Date;+ noData: MonitorNoData;+ renotify: MonitorRenotify;+ };+ expected: {+ emit: boolean;+ nextSeverity: MonitorSeverity;+ nextSeverityChangedAt: Date | null;+ nextAlertedAt: Date | null;+ };+};++const t0 = new Date("2026-05-27T12:00:00.000Z");+const tMinus2m = new Date("2026-05-27T11:58:00.000Z");+const tMinus10m = new Date("2026-05-27T11:50:00.000Z");+const tMinus12m = new Date("2026-05-27T11:48:00.000Z");+const noDataSilent: MonitorNoData = { mode: "SILENT" };+const noDataNotify5: MonitorNoData = { mode: "NOTIFY", intervalMinutes: 5 };+const renotifyOff: MonitorRenotify = { mode: "OFF" };+const renotifyEvery5: MonitorRenotify = { mode: "EVERY", intervalMinutes: 5 };++/** baseMonitor supplies the Monitor fields applyStateMachine ignores. */+const baseMonitor: Monitor = {+ id: "m_test",+ createdAt: t0,+ updatedAt: t0,+ createdBy: null,+ updatedBy: null,+ projectId: "p_test",+ view: "observations",+ filters: [],+ metric: { measure: "count", aggregation: "count" },+ window: "5m",+ thresholdOperator: "GT",+ alertThreshold: 100,+ warningThreshold: null,+ noData: { mode: "SILENT" },+ renotify: { mode: "OFF" },+ name: "Test",+ tags: [],+ triggerIds: [],+ severity: "UNKNOWN",+ severityChangedAt: null,+ alertedAt: null,+ status: "ACTIVE",+ nextRunAt: null,+ lastPublishedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,+};++/** cases enumerates the applyStateMachine transition table. */+const cases: StateMachineCase[] = [+ // === Cold-start (prev = UNKNOWN) ===+ {+ name: "UNKNOWN -> OK: silent",+ input: {+ prevSeverity: "UNKNOWN",+ computedSeverity: "OK",+ prevSeverityChangedAt: null,+ prevAlertedAt: null,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: false,+ nextSeverity: "OK",+ nextSeverityChangedAt: t0,+ nextAlertedAt: null,+ },+ },+ {+ name: "UNKNOWN -> WARNING: emit",+ input: {+ prevSeverity: "UNKNOWN",+ computedSeverity: "WARNING",+ prevSeverityChangedAt: null,+ prevAlertedAt: null,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "WARNING",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },+ {+ name: "UNKNOWN -> ALERT: emit",+ input: {+ prevSeverity: "UNKNOWN",+ computedSeverity: "ALERT",+ prevSeverityChangedAt: null,+ prevAlertedAt: null,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "ALERT",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },+ {+ name: "UNKNOWN -> NO_DATA: silent regardless of noData mode",+ input: {+ prevSeverity: "UNKNOWN",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: null,+ prevAlertedAt: null,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyOff,+ },+ expected: {+ emit: false,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: t0,+ nextAlertedAt: null,+ },+ },++ // === NO_DATA -> OK (recovery) ===+ {+ name: "NO_DATA -> OK with noData SILENT: silent",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "OK",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: null,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: false,+ nextSeverity: "OK",+ nextSeverityChangedAt: t0,+ nextAlertedAt: null,+ },+ },+ {+ name: "NO_DATA -> OK with noData NOTIFY: emit",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "OK",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "OK",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },++ // === NO_DATA -> WARNING / ALERT ===+ {+ name: "NO_DATA -> WARNING with noData SILENT: emit",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "WARNING",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: null,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "WARNING",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },+ {+ name: "NO_DATA -> ALERT: emit",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "ALERT",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: null,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "ALERT",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },++ // === OK / WARN / ALERT -> NO_DATA ===+ {+ name: "OK -> NO_DATA with noData SILENT: silent",+ input: {+ prevSeverity: "OK",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: false,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: t0,+ nextAlertedAt: tMinus10m,+ },+ },+ {+ name: "OK -> NO_DATA with noData NOTIFY and prevAlertedAt past interval: emit",+ input: {+ prevSeverity: "OK",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m, // interval 5m elapsed+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },+ {+ name: "OK -> NO_DATA with noData NOTIFY and prevAlertedAt within interval: silent (cooldown)",+ input: {+ prevSeverity: "OK",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus2m, // interval 5m not elapsed+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyOff,+ },+ expected: {+ emit: false,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: t0,+ nextAlertedAt: tMinus2m,+ },+ },+ {+ name: "OK -> NO_DATA with noData NOTIFY and prevAlertedAt NULL: emit",+ input: {+ prevSeverity: "OK",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: null,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },+ {+ name: "WARNING -> NO_DATA with noData NOTIFY past interval: emit",+ input: {+ prevSeverity: "WARNING",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },+ {+ name: "ALERT -> NO_DATA with noData SILENT: silent",+ input: {+ prevSeverity: "ALERT",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: false,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: t0,+ nextAlertedAt: tMinus10m,+ },+ },++ // === OK -> WARNING / ALERT ===+ {+ name: "OK -> WARNING: emit",+ input: {+ prevSeverity: "OK",+ computedSeverity: "WARNING",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: null,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "WARNING",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },+ {+ name: "OK -> ALERT: emit",+ input: {+ prevSeverity: "OK",+ computedSeverity: "ALERT",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: null,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "ALERT",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },++ // === WARNING <-> ALERT ===+ {+ name: "WARNING -> ALERT: emit",+ input: {+ prevSeverity: "WARNING",+ computedSeverity: "ALERT",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "ALERT",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },+ {+ name: "ALERT -> WARNING: emit",+ input: {+ prevSeverity: "ALERT",+ computedSeverity: "WARNING",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "WARNING",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },++ // === WARNING / ALERT -> OK ===+ {+ name: "WARNING -> OK: emit",+ input: {+ prevSeverity: "WARNING",+ computedSeverity: "OK",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "OK",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },+ {+ name: "ALERT -> OK: emit",+ input: {+ prevSeverity: "ALERT",+ computedSeverity: "OK",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "OK",+ nextSeverityChangedAt: t0,+ nextAlertedAt: t0,+ },+ },++ // === OK -> OK ===+ {+ name: "OK -> OK: silent",+ input: {+ prevSeverity: "OK",+ computedSeverity: "OK",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyEvery5,+ },+ expected: {+ emit: false,+ nextSeverity: "OK",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: tMinus10m,+ },+ },++ // === WARNING/ALERT/NO_DATA self-loops (renotify) ===+ {+ name: "WARNING -> WARNING with renotify OFF: silent",+ input: {+ prevSeverity: "WARNING",+ computedSeverity: "WARNING",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: false,+ nextSeverity: "WARNING",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: tMinus10m,+ },+ },+ {+ name: "WARNING -> WARNING with renotify EVERY past interval: emit",+ input: {+ prevSeverity: "WARNING",+ computedSeverity: "WARNING",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m, // interval 5m elapsed+ now: t0,+ noData: noDataSilent,+ renotify: renotifyEvery5,+ },+ expected: {+ emit: true,+ nextSeverity: "WARNING",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: t0,+ },+ },+ {+ name: "WARNING -> WARNING with renotify EVERY within interval: silent",+ input: {+ prevSeverity: "WARNING",+ computedSeverity: "WARNING",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus2m, // interval 5m not elapsed+ now: t0,+ noData: noDataSilent,+ renotify: renotifyEvery5,+ },+ expected: {+ emit: false,+ nextSeverity: "WARNING",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: tMinus2m,+ },+ },+ {+ name: "ALERT -> ALERT with renotify EVERY past interval: emit",+ input: {+ prevSeverity: "ALERT",+ computedSeverity: "ALERT",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyEvery5,+ },+ expected: {+ emit: true,+ nextSeverity: "ALERT",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: t0,+ },+ },+ {+ name: "NO_DATA -> NO_DATA with renotify OFF: silent",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyOff,+ },+ expected: {+ emit: false,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: tMinus10m,+ },+ },+ {+ name: "NO_DATA -> NO_DATA with noData SILENT and renotify EVERY past interval: silent",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyEvery5,+ },+ expected: {+ emit: false,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: tMinus10m,+ },+ },+ {+ name: "NO_DATA -> NO_DATA with noData NOTIFY and renotify EVERY past interval: emit",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyEvery5,+ },+ expected: {+ emit: true,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: t0,+ },+ },+ {+ name: "NO_DATA -> NO_DATA with noData NOTIFY and renotify EVERY within interval: silent",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus2m,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyEvery5,+ },+ expected: {+ emit: false,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: tMinus2m,+ },+ },+ {+ name: "NO_DATA -> NO_DATA with noData NOTIFY and renotify OFF: silent",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyOff,+ },+ expected: {+ emit: false,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: tMinus10m,+ },+ },+ {+ name: "NO_DATA -> NO_DATA, NOTIFY, prior-stretch alert predates NO_DATA stretch, interval elapsed: emit",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus12m,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: t0,+ },+ },+ {+ name: "NO_DATA -> NO_DATA, NOTIFY, no prior alert, interval elapsed: emit",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: null,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyOff,+ },+ expected: {+ emit: true,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: t0,+ },+ },+ {+ name: "NO_DATA -> NO_DATA, NOTIFY, no prior alert, interval not elapsed: silent",+ input: {+ prevSeverity: "NO_DATA",+ computedSeverity: "NO_DATA",+ prevSeverityChangedAt: tMinus2m,+ prevAlertedAt: null,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyOff,+ },+ expected: {+ emit: false,+ nextSeverity: "NO_DATA",+ nextSeverityChangedAt: tMinus2m,+ nextAlertedAt: null,+ },+ },+ {+ name: "WARNING -> WARNING with renotify EVERY and prevAlertedAt NULL: silent",+ input: {+ prevSeverity: "WARNING",+ computedSeverity: "WARNING",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: null,+ now: t0,+ noData: noDataSilent,+ renotify: renotifyEvery5,+ },+ expected: {+ emit: false,+ nextSeverity: "WARNING",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: null,+ },+ },+ // === PAUSED guard: user paused between publish and process ===+ {+ name: "PAUSED -> anything: no-op, preserve PAUSED + prev stamps",+ input: {+ prevSeverity: "PAUSED",+ computedSeverity: "ALERT",+ prevSeverityChangedAt: tMinus10m,+ prevAlertedAt: tMinus10m,+ now: t0,+ noData: noDataNotify5,+ renotify: renotifyEvery5,+ },+ expected: {+ emit: false,+ nextSeverity: "PAUSED",+ nextSeverityChangedAt: tMinus10m,+ nextAlertedAt: tMinus10m,+ },+ },+];++describe("applyStateMachine", () => {+ it.each(cases)("$name", ({ input, expected }) => {+ const result = applyStateMachine({+ prev: {+ ...baseMonitor,+ severity: input.prevSeverity,+ severityChangedAt: input.prevSeverityChangedAt,+ alertedAt: input.prevAlertedAt,+ noData: input.noData,+ renotify: input.renotify,+ },+ next: { severity: input.computedSeverity },+ now: input.now,+ publishedAt: input.now,+ });+ expect(result.emit).toBe(expected.emit);+ expect(result.completion.severity).toBe(expected.nextSeverity);+ expect(result.completion.severityChangedAt?.toISOString() ?? null).toBe(+ expected.nextSeverityChangedAt?.toISOString() ?? null,+ );+ expect(result.completion.alertedAt?.toISOString() ?? null).toBe(+ expected.nextAlertedAt?.toISOString() ?? null,+ );+ });++ it("ALERT -> OK -> NO_DATA -> NO_DATA with noData SILENT stays silent on the self-loop", () => {+ const tAlert = new Date("2026-05-27T11:40:00.000Z");+ const tOk = new Date("2026-05-27T11:50:00.000Z");+ const tNoData = new Date("2026-05-27T11:55:00.000Z");+ const tLoop = new Date("2026-05-27T12:05:00.000Z");+ const monitor: Monitor = {+ ...baseMonitor,+ noData: noDataSilent,+ renotify: renotifyEvery5,+ severity: "ALERT",+ severityChangedAt: tAlert,+ alertedAt: tAlert,+ };++ const recovery = applyStateMachine({+ prev: monitor,+ next: { severity: "OK" },+ now: tOk,+ publishedAt: tOk,+ });+ expect(recovery.emit).toBe(true);+ expect(recovery.completion.alertedAt).toEqual(tOk);++ const enterNoData = applyStateMachine({+ prev: { ...monitor, ...recovery.completion },+ next: { severity: "NO_DATA" },+ now: tNoData,+ publishedAt: tNoData,+ });+ expect(enterNoData.emit).toBe(false);+ expect(enterNoData.completion.alertedAt).toEqual(tOk);++ const selfLoop = applyStateMachine({+ prev: { ...monitor, ...enterNoData.completion },+ next: { severity: "NO_DATA" },+ now: tLoop,+ publishedAt: tLoop,+ });+ expect(selfLoop.emit).toBe(false);+ });+});diff --git a/packages/shared/src/features/monitors/processor/applyStateMachine.ts b/packages/shared/src/features/monitors/processor/applyStateMachine.tsnew file mode 100644index 0000000000..0507df6540--- /dev/null+++ b/packages/shared/src/features/monitors/processor/applyStateMachine.ts@@ -0,0 +1,163 @@+import type {+ MonitorNoData,+ MonitorRenotify,+ MonitorSeverity,+ MonitorStatus,+ Monitor,+} from "../types";++/** applyStateMachine maps a monitor's prior row and newly computed severity to its lifecycle writeback and whether to emit an alert. */+export function applyStateMachine(args: {+ prev: Monitor;+ next: { severity: MonitorSeverity };+ now: Date;+ publishedAt: Date;+}): StateMachineDecision {+ const { prev, next, now, publishedAt } = args;++ // PAUSED is service-written; no-op so the worker doesn't overwrite user intent.+ if (prev.severity === "PAUSED") {+ return {+ emit: false,+ completion: {+ monitorId: prev.id,+ lastClaimedAt: now,+ lastCompletedAt: now,+ publishedAt,+ status: prev.status,+ severity: "PAUSED",+ severityChangedAt: prev.severityChangedAt,+ alertedAt: prev.alertedAt,+ },+ };+ }++ const severityChanged = prev.severity !== next.severity;++ const emit = shouldEmit({+ prev: prev.severity,+ next: next.severity,+ prevAlertedAt: prev.alertedAt,+ prevSeverityChangedAt: prev.severityChangedAt,+ now,+ noData: prev.noData,+ renotify: prev.renotify,+ });++ return {+ emit,+ completion: {+ monitorId: prev.id,+ lastClaimedAt: now,+ lastCompletedAt: now,+ publishedAt,+ status: prev.status,+ severity: next.severity,+ severityChangedAt: severityChanged ? now : prev.severityChangedAt,+ alertedAt: emit ? now : prev.alertedAt,+ },+ };+}++/** shouldEmit applies the RFC transition-table row matching (prev, next). */+function shouldEmit(args: {+ prev: MonitorSeverity;+ next: MonitorSeverity;+ prevAlertedAt: Date | null;+ prevSeverityChangedAt: Date | null;+ now: Date;+ noData: MonitorNoData;+ renotify: MonitorRenotify;+}): boolean {+ // Cold-start: UNKNOWN -> anything. Only unhealthy fires.+ if (args.prev === "UNKNOWN") {+ return args.next === "WARNING" || args.next === "ALERT";+ }++ // Recovery from NO_DATA.+ if (args.prev === "NO_DATA" && args.next === "OK") {+ return args.noData.mode === "NOTIFY";+ }++ // NO_DATA -> WARNING/ALERT always surfaces.+ if (args.prev === "NO_DATA" && args.next !== "NO_DATA") {+ return true;+ }++ // Escalation into NO_DATA: NOTIFY mode with cooldown elapsed.+ if (args.next === "NO_DATA" && args.prev !== "NO_DATA") {+ return (+ args.noData.mode === "NOTIFY" &&+ passedDelay(args.prevAlertedAt, args.noData.intervalMinutes, args.now)+ );+ }++ // NO_DATA persistence: SILENT never re-emits. NOTIFY fires the first alert+ // after intervalMinutes of sustained NO_DATA (anchored on severityChangedAt+ // when no prior alert exists), then re-emits on the renotify cadence.+ if (args.prev === "NO_DATA" && args.next === "NO_DATA") {+ if (args.noData.mode !== "NOTIFY") return false;+ // An alert from a prior severity stretch doesn't count toward the current+ // NO_DATA stretch; treat it as cold-start.+ const stretchAlertedAt =+ args.prevAlertedAt !== null &&+ args.prevSeverityChangedAt !== null &&+ args.prevAlertedAt < args.prevSeverityChangedAt+ ? null+ : args.prevAlertedAt;+ if (stretchAlertedAt === null) {+ return passedDelay(+ args.prevSeverityChangedAt,+ args.noData.intervalMinutes,+ args.now,+ );+ }+ return (+ args.renotify.mode === "EVERY" &&+ passedDelay(stretchAlertedAt, args.renotify.intervalMinutes, args.now)+ );+ }++ // Self-loops. OK -> OK is the only one that ignores renotify entirely.+ if (args.prev === args.next) {+ if (args.next === "OK") return false;+ // Renotify is a *re*-emit, so a NULL prevAlertedAt is silent.+ if (args.prevAlertedAt === null) return false;+ return (+ args.renotify.mode === "EVERY" &&+ passedDelay(args.prevAlertedAt, args.renotify.intervalMinutes, args.now)+ );+ }++ // Remaining severity changes between OK / WARNING / ALERT always emit.+ return true;+}++/** passedDelay returns true when at least `intervalMinutes` has elapsed since `prevAlertedAt`; NULL fires immediately. */+function passedDelay(+ prevAlertedAt: Date | null,+ intervalMinutes: number,+ now: Date,+): boolean {+ if (prevAlertedAt === null) return true;+ const intervalMs = intervalMinutes * 60_000;+ return now.getTime() - prevAlertedAt.getTime() >= intervalMs;+}++/** MonitorCompletion is one row of the bulk update the state machine emits for a single monitor. */+export type MonitorCompletion = {+ monitorId: string;+ lastClaimedAt: Date;+ lastCompletedAt: Date;+ publishedAt: Date;+ status: MonitorStatus;+ severity: MonitorSeverity;+ severityChangedAt: Date | null;+ alertedAt: Date | null;+};++/** StateMachineDecision is the per-monitor evaluation outcome: the lifecycle writeback and whether to emit an alert. */+export type StateMachineDecision = {+ completion: MonitorCompletion;+ emit: boolean;+};diff --git a/packages/shared/src/features/monitors/processor/buildPermalink.test.ts b/packages/shared/src/features/monitors/processor/buildPermalink.test.tsnew file mode 100644index 0000000000..9ee35238b0--- /dev/null+++ b/packages/shared/src/features/monitors/processor/buildPermalink.test.ts@@ -0,0 +1,25 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++const envMock = vi.hoisted(() => ({+ env: { NEXTAUTH_URL: undefined as string | undefined },+}));+vi.mock("../../../env", () => envMock);++import { buildPermalink } from "./processor";++describe("buildPermalink", () => {+ beforeEach(() => {+ envMock.env.NEXTAUTH_URL = undefined;+ });++ it("returns undefined when NEXTAUTH_URL is unset (self-hosted)", () => {+ expect(buildPermalink("proj_01", "mon_01")).toBeUndefined();+ });++ it("returns an absolute URL when NEXTAUTH_URL is set", () => {+ envMock.env.NEXTAUTH_URL = "https://cloud.langfuse.com";+ expect(buildPermalink("proj_01", "mon_01")).toBe(+ "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",+ );+ });+});diff --git a/packages/shared/src/features/monitors/processor/computeSeverity.test.ts b/packages/shared/src/features/monitors/processor/computeSeverity.test.tsnew file mode 100644index 0000000000..498d874083--- /dev/null+++ b/packages/shared/src/features/monitors/processor/computeSeverity.test.ts@@ -0,0 +1,292 @@+import { describe, it, expect } from "vitest";++import { computeSeverity } from "./computeSeverity";+import type { MonitorThresholdOperator } from "../types";++/** ComputeSeverityCase is one computeSeverity table row: inputs and the expected severity. */+type ComputeSeverityCase = {+ name: string;+ input: {+ value: number | null;+ operator: MonitorThresholdOperator;+ alertThreshold: number;+ warningThreshold: number | null;+ };+ expected: "NO_DATA" | "OK" | "WARNING" | "ALERT";+};++/** cases covers the NO_DATA branch plus each operator's alert/warning/OK bands. */+const cases: ComputeSeverityCase[] = [+ {+ name: "null value -> NO_DATA (with warning)",+ input: {+ value: null,+ operator: "GT",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "NO_DATA",+ },+ {+ name: "null value -> NO_DATA (no warning)",+ input: {+ value: null,+ operator: "LT",+ alertThreshold: 100,+ warningThreshold: null,+ },+ expected: "NO_DATA",+ },++ {+ name: "GT: value > alert -> ALERT",+ input: {+ value: 120,+ operator: "GT",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "ALERT",+ },+ {+ name: "GT: value == alert, no warning -> OK (strict >)",+ input: {+ value: 100,+ operator: "GT",+ alertThreshold: 100,+ warningThreshold: null,+ },+ expected: "OK",+ },+ {+ name: "GT: value > warning, value <= alert -> WARNING",+ input: {+ value: 80,+ operator: "GT",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "WARNING",+ },+ {+ name: "GT: value == warning -> OK (strict >)",+ input: {+ value: 50,+ operator: "GT",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "OK",+ },+ {+ name: "GT: value < warning -> OK",+ input: {+ value: 40,+ operator: "GT",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "OK",+ },+ {+ name: "GT: value > alert, no warning -> ALERT",+ input: {+ value: 120,+ operator: "GT",+ alertThreshold: 100,+ warningThreshold: null,+ },+ expected: "ALERT",+ },+ {+ name: "GT: value < alert, no warning -> OK",+ input: {+ value: 80,+ operator: "GT",+ alertThreshold: 100,+ warningThreshold: null,+ },+ expected: "OK",+ },++ {+ name: "GTE: value == alert -> ALERT",+ input: {+ value: 100,+ operator: "GTE",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "ALERT",+ },+ {+ name: "GTE: value > alert -> ALERT",+ input: {+ value: 101,+ operator: "GTE",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "ALERT",+ },+ {+ name: "GTE: value == warning -> WARNING",+ input: {+ value: 50,+ operator: "GTE",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "WARNING",+ },+ {+ name: "GTE: value < warning -> OK",+ input: {+ value: 49,+ operator: "GTE",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "OK",+ },++ {+ name: "LT: value < alert -> ALERT",+ input: {+ value: 80,+ operator: "LT",+ alertThreshold: 100,+ warningThreshold: 150,+ },+ expected: "ALERT",+ },+ {+ name: "LT: value == alert, no warning -> OK (strict <)",+ input: {+ value: 100,+ operator: "LT",+ alertThreshold: 100,+ warningThreshold: null,+ },+ expected: "OK",+ },+ {+ name: "LT: value < warning, value >= alert -> WARNING",+ input: {+ value: 120,+ operator: "LT",+ alertThreshold: 100,+ warningThreshold: 150,+ },+ expected: "WARNING",+ },+ {+ name: "LT: value > warning -> OK",+ input: {+ value: 200,+ operator: "LT",+ alertThreshold: 100,+ warningThreshold: 150,+ },+ expected: "OK",+ },++ {+ name: "LTE: value == alert -> ALERT",+ input: {+ value: 100,+ operator: "LTE",+ alertThreshold: 100,+ warningThreshold: 150,+ },+ expected: "ALERT",+ },+ {+ name: "LTE: value == warning -> WARNING",+ input: {+ value: 150,+ operator: "LTE",+ alertThreshold: 100,+ warningThreshold: 150,+ },+ expected: "WARNING",+ },+ {+ name: "LTE: value > warning -> OK",+ input: {+ value: 151,+ operator: "LTE",+ alertThreshold: 100,+ warningThreshold: 150,+ },+ expected: "OK",+ },++ {+ name: "EQ: value == alert -> ALERT",+ input: {+ value: 100,+ operator: "EQ",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "ALERT",+ },+ {+ name: "EQ: value == warning -> WARNING",+ input: {+ value: 50,+ operator: "EQ",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "WARNING",+ },+ {+ name: "EQ: value matches neither -> OK",+ input: {+ value: 75,+ operator: "EQ",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "OK",+ },++ {+ name: "NEQ: value != alert -> ALERT (alert checked first)",+ input: {+ value: 99,+ operator: "NEQ",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "ALERT",+ },+ {+ name: "NEQ: value == alert, value != warning -> WARNING",+ input: {+ value: 100,+ operator: "NEQ",+ alertThreshold: 100,+ warningThreshold: 50,+ },+ expected: "WARNING",+ },+ {+ name: "NEQ: value == alert == warning -> OK",+ input: {+ value: 100,+ operator: "NEQ",+ alertThreshold: 100,+ warningThreshold: 100,+ },+ expected: "OK",+ },+];++describe("computeSeverity", () => {+ it.each(cases)("$name", ({ input, expected }) => {+ expect(computeSeverity(input)).toBe(expected);+ });+});diff --git a/packages/shared/src/features/monitors/processor/computeSeverity.ts b/packages/shared/src/features/monitors/processor/computeSeverity.tsnew file mode 100644index 0000000000..0ee9324061--- /dev/null+++ b/packages/shared/src/features/monitors/processor/computeSeverity.ts@@ -0,0 +1,50 @@+import {+ MonitorThresholdOperatorSchema,+ type MonitorThresholdOperator,+ MonitorSeveritySchema,+ type MonitorSeverity,+} from "../types";++/** computeSeverity maps a metric value to a non-lifecycle severity by comparing it against the alert (and optional warning) thresholds. */+export function computeSeverity(args: {+ value: number | null;+ operator: MonitorThresholdOperator;+ alertThreshold: number;+ warningThreshold: number | null;+}): MonitorSeverity {+ if (args.value === null) {+ return MonitorSeveritySchema.enum.NO_DATA;+ }+ if (matches(args.value, args.operator, args.alertThreshold)) {+ return MonitorSeveritySchema.enum.ALERT;+ }+ if (+ args.warningThreshold !== null &&+ matches(args.value, args.operator, args.warningThreshold)+ ) {+ return MonitorSeveritySchema.enum.WARNING;+ }+ return MonitorSeveritySchema.enum.OK;+}++/** matches returns true when `value <op> threshold` holds. */+function matches(+ value: number,+ operator: MonitorThresholdOperator,+ threshold: number,+): boolean {+ switch (operator) {+ case MonitorThresholdOperatorSchema.enum.GT:+ return value > threshold;+ case MonitorThresholdOperatorSchema.enum.GTE:+ return value >= threshold;+ case MonitorThresholdOperatorSchema.enum.LT:+ return value < threshold;+ case MonitorThresholdOperatorSchema.enum.LTE:+ return value <= threshold;+ case MonitorThresholdOperatorSchema.enum.EQ:+ return value === threshold;+ case MonitorThresholdOperatorSchema.enum.NEQ:+ return value !== threshold;+ }+}diff --git a/packages/shared/src/features/monitors/processor/processor.ts b/packages/shared/src/features/monitors/processor/processor.tsnew file mode 100644index 0000000000..eb4a55c4f9--- /dev/null+++ b/packages/shared/src/features/monitors/processor/processor.ts@@ -0,0 +1,468 @@+import { randomUUID } from "crypto";++import { JobConfigState, Prisma, type PrismaClient } from "../../../db";+import { env } from "../../../env";+import { TriggerEventSource } from "../../../domain/automations";+import { matchesTriggerFilter } from "../../../server/automations";+import {+ instrumentAsync,+ instrumentSync,+} from "../../../server/instrumentation";+import { logger } from "../../../server/logger";+import {+ getTriggerConfigurations as defaultGetTriggerConfigurations,+ type TriggerDomainWithActions,+} from "../../../server/repositories/automation-repository";+import { executeQuery as defaultExecuteQuery } from "../../query/server/queryExecutor";+import type { QueryType } from "../../query/types";+import { isValidQuery } from "../isValidQuery";+import {+ MonitorQueueEventSchema,+ type MonitorQueueEvent,+ type MonitorQueueEventInput,+ type MonitorWebhookInput,+} from "../scheduler/types";+import { monitorFromPrisma, windowToMs } from "../service/helpers";+import { type MonitorAlert, type MonitorWindow, type Monitor } from "../types";+import { applyStateMachine, type MonitorCompletion } from "./applyStateMachine";+import { computeSeverity } from "./computeSeverity";+import { renderAlertMessage } from "./renderAlertMessage";++/** monitorEvaluationOffsetMs shifts the query window back so ClickHouse reads data settled past the events-table write lag. */+export const monitorEvaluationOffsetMs = 30 * 1000;++/** ErrorBadQuery sentinels a metric whose shape doesn't resolve against the v2 data model or whose batch query failed to execute. */+export const ErrorBadQuery = Symbol("ErrorBadQuery");++/** MonitorProcessor evaluates queued monitor events and emits MonitorAlerts. */+export class MonitorProcessor {+ constructor(+ private readonly db: PrismaClient,+ private readonly publish: MonitorPublisher,+ private readonly executeQuery: QueryExecutor = defaultExecuteQuery,+ private readonly getTriggerConfigurations: GetTriggerConfigurations = defaultGetTriggerConfigurations,+ ) {}++ /** process evaluates one queued monitor event and publishes any resulting alerts; the input is parsed to recoerce dates the queue serialized to strings. */+ async process(input: MonitorQueueEventInput, now: Date): Promise<void> {+ const event = MonitorQueueEventSchema.parse(input);+ return instrumentAsync({ name: "process" }, async (span) => {+ const monitors = await instrumentAsync({ name: "claimMonitors" }, () =>+ this.claimMonitors(event, now),+ );+ span.setAttribute("monitors", monitors.length);+ if (monitors.length === 0) return;++ const [metrics, triggers] = await Promise.all([+ instrumentAsync({ name: "queryMetrics" }, () =>+ this.queryMetrics(event),+ ),+ instrumentAsync({ name: "getTriggerConfigurations" }, () =>+ this.getTriggerConfigurations({+ projectId: event.projectId,+ eventSource: TriggerEventSource.Monitor,+ status: JobConfigState.ACTIVE,+ }),+ ),+ ]);++ span.setAttribute("metrics", Object.keys(metrics).length);+ span.setAttribute("triggers", triggers.length);++ const [completions, monitorWebhookInputs] = instrumentSync(+ { name: "processMonitors" },+ () =>+ processMonitors({+ monitors,+ metrics,+ triggers,+ now,+ runAt: event.runAt,+ publishedAt: event.publishedAt,+ }),+ );+ span.setAttribute("monitorWebhookInputs", monitorWebhookInputs.length);++ await instrumentAsync({ name: "publishWebhookInputs" }, () =>+ this.publishWebhookInputs(monitorWebhookInputs),+ );++ await instrumentAsync({ name: "complete" }, () =>+ this.complete({ projectId: event.projectId, completions }),+ );+ });+ }++ /** claimMonitors conditionally claims the event's monitors for this worker, returning the rows it won. */+ private async claimMonitors(+ event: MonitorQueueEvent,+ now: Date,+ ): Promise<Monitor[]> {+ if (event.monitors.length === 0) return [];+ const prismaMonitors = await this.db.monitor.updateManyAndReturn({+ where: {+ id: { in: event.monitors.map((m) => m.monitorId) },+ projectId: event.projectId,+ status: "ACTIVE", // active monitors for the+ lastPublishedAt: { lte: event.publishedAt }, // newest event+ AND: [+ // not already claimed+ {+ OR: [+ { lastClaimedAt: null },+ { lastClaimedAt: { lte: event.publishedAt } },+ ],+ },+ // and not yet completed+ {+ OR: [+ { lastCompletedAt: null },+ { lastCompletedAt: { lt: event.publishedAt } },+ ],+ },+ ],+ },+ data: { lastClaimedAt: now },+ });+ return prismaMonitors.map(monitorFromPrisma);+ }++ /** queryMetrics pre-screens the batch's metrics against the v2 data model, runs the accepted ones, and returns each metric keyed by `${aggregation}_${measure}` as a number, null, or the ErrorBadQuery sentinel. */+ private async queryMetrics(event: MonitorQueueEvent): Promise<MetricMap> {+ const validation = isValidQuery({+ view: event.view,+ metrics: event.metrics,+ filters: event.filters,+ });+ const metricMap: MetricMap = {};+ for (const metric of validation.rejected) {+ metricMap[metricKey(metric)] = ErrorBadQuery;+ }+ if (validation.accepted.length === 0) return metricMap;++ try {+ const rows = await this.executeQuery(+ event.projectId,+ buildMonitorQuery(validation.accepted, event),+ "v2",+ true,+ );+ const row = (rows[0] ?? {}) as Record<string, unknown>;+ for (const metric of validation.accepted) {+ const key = metricKey(metric);+ metricMap[key] = parseNumericValue(row[key]);+ }+ metricMap["count_count"] = parseNumericValue(row["count_count"]);+ } catch (error) {+ logger.error(+ "queryMetrics failed; flipping affected monitors to ERROR_BAD_QUERY",+ {+ projectId: event.projectId,+ schedulerBatchId: event.schedulerBatchId.toString(),+ monitorIds: event.monitors.map((m) => m.monitorId),+ error,+ },+ );+ for (const metric of validation.accepted) {+ metricMap[metricKey(metric)] = ErrorBadQuery;+ }+ metricMap["count_count"] = ErrorBadQuery;+ }+ return metricMap;+ }++ private async publishWebhookInputs(+ inputs: MonitorWebhookInput[],+ ): Promise<void> {+ for (const input of inputs) {+ await this.publish(input);+ }+ }++ /** complete writes each monitor's post-evaluation lifecycle stamps in one statement. */+ private async complete(args: {+ projectId: string;+ completions: MonitorCompletion[];+ }): Promise<void> {+ if (args.completions.length === 0) return;+ await this.db.$executeRaw(+ buildCompleteQuery({+ projectId: args.projectId,+ completions: args.completions,+ }),+ );+ }+}++/** buildMonitorQuery converts the accepted metrics of a MonitorQueueEvent into the scalar QueryType executeQuery accepts. */+function buildMonitorQuery(+ acceptedMetrics: QueryType["metrics"],+ event: MonitorQueueEvent,+): QueryType {+ const { fromTimestamp, toTimestamp } = evaluationWindow(+ event.window,+ event.runAt,+ );+ const metrics = dedupeMetrics([+ ...acceptedMetrics,+ { measure: "count", aggregation: "count" as const },+ ]);+ return {+ view: event.view,+ dimensions: [],+ metrics,+ filters: event.filters,+ timeDimension: null,+ fromTimestamp: fromTimestamp.toISOString(),+ toTimestamp: toTimestamp.toISOString(),+ orderBy: null,+ };+}++/** dedupeMetrics drops duplicate metrics keyed by `${aggregation}_${measure}` so the appended row-count metric never collides with an existing count metric. */+function dedupeMetrics(metrics: QueryType["metrics"]): QueryType["metrics"] {+ const seen = new Set<string>();+ return metrics.filter((m) => {+ const key = metricKey(m);+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++/** metricKey is the `${aggregation}_${measure}` column name a metric resolves to in the query result row. */+function metricKey(metric: { measure: string; aggregation: string }): string {+ return `${metric.aggregation}_${metric.measure}`;+}++/** evaluationWindow returns the `[runAt - window, runAt]` edges, both shifted back by monitorEvaluationOffsetMs. */+function evaluationWindow(+ window: MonitorWindow,+ runAt: Date,+): {+ fromTimestamp: Date;+ toTimestamp: Date;+} {+ const windowMs = Number(windowToMs(window));+ const toTimestamp = new Date(runAt.getTime() - monitorEvaluationOffsetMs);+ const fromTimestamp = new Date(toTimestamp.getTime() - windowMs);+ return { fromTimestamp, toTimestamp };+}++/** parseNumericValue coerces a ClickHouse cell to number | null, mapping missing or non-finite values to null. */+function parseNumericValue(raw: unknown): number | null {+ if (raw === null || raw === undefined) return null;+ if (typeof raw === "number") return Number.isFinite(raw) ? raw : null;+ const n = Number(raw);+ return Number.isFinite(n) ? n : null;+}++/** processMonitors evaluates every claimed monitor, collecting the completions to persist and the webhook inputs to publish. */+function processMonitors(args: {+ monitors: Monitor[];+ metrics: MetricMap;+ triggers: TriggerDomainWithActions[];+ now: Date;+ runAt: Date;+ publishedAt: Date;+}): [MonitorCompletion[], MonitorWebhookInput[]] {+ const completions: MonitorCompletion[] = [];+ const monitorWebhookInputs: MonitorWebhookInput[] = [];+ for (const monitor of args.monitors) {+ const [completion, inputs] = processMonitor({+ monitor,+ metrics: args.metrics,+ triggers: args.triggers,+ now: args.now,+ runAt: args.runAt,+ publishedAt: args.publishedAt,+ });+ completions.push(completion);+ monitorWebhookInputs.push(...inputs);+ }+ return [completions, monitorWebhookInputs];+}++/** processMonitor evaluates one monitor and returns its lifecycle completion plus any webhook inputs to publish; a bad-query metric short-circuits to an ERROR_BAD_QUERY completion with no alert. */+function processMonitor(args: {+ monitor: Monitor;+ metrics: MetricMap;+ triggers: TriggerDomainWithActions[];+ now: Date;+ runAt: Date;+ publishedAt: Date;+}): [MonitorCompletion, MonitorWebhookInput[]] {+ const { monitor, metrics, triggers, now, runAt, publishedAt } = args;+ const value = getMetricValue(metrics, monitor.metric);+ if (value === ErrorBadQuery) {+ return [+ {+ monitorId: monitor.id,+ lastClaimedAt: now,+ lastCompletedAt: now,+ publishedAt,+ status: "ERROR_BAD_QUERY",+ severity: "PAUSED",+ severityChangedAt: now,+ alertedAt: monitor.alertedAt,+ },+ [],+ ];+ }++ const severity = computeSeverity({+ value,+ operator: monitor.thresholdOperator,+ alertThreshold: monitor.alertThreshold,+ warningThreshold: monitor.warningThreshold ?? null,+ });++ const { completion, emit } = applyStateMachine({+ prev: monitor,+ next: { severity },+ now,+ publishedAt,+ });+ if (!emit) return [completion, []];++ const automations = getAutomations({ monitor, completion, triggers });+ if (automations.length === 0) return [completion, []];++ const alert = buildAlert({ prev: monitor, next: completion, runAt });+ return [completion, toMonitorWebhookInputs({ alert, automations, now })];+}++/** getMetricValue reads a monitor's scalar result from the metrics map, returning the ErrorBadQuery sentinel before the zero-count NO_DATA gate so a rejected metric flips rather than reads NO_DATA. */+function getMetricValue(+ metrics: MetricMap,+ metric: Monitor["metric"],+): MetricValue {+ const value = metrics[metricKey(metric)];+ if (value === ErrorBadQuery) return ErrorBadQuery;+ if (metrics["count_count"] === 0) return null;+ return value ?? null;+}++/** getAutomations returns the automations under every trigger that consumes this alert. */+function getAutomations(args: {+ monitor: Monitor;+ completion: MonitorCompletion;+ triggers: TriggerDomainWithActions[];+}): TriggerDomainWithActions["automations"] {+ const filterData = {+ severity: args.completion.severity,+ triggerIds: args.monitor.triggerIds,+ };+ return args.triggers+ .filter((trigger) => matchesTriggerFilter(filterData, trigger))+ .flatMap((trigger) => trigger.automations);+}++/** buildAlert assembles the MonitorAlert payload from the monitor row and state-machine completion. */+function buildAlert(args: {+ prev: Monitor;+ next: MonitorCompletion;+ runAt: Date;+}): MonitorAlert {+ const { prev, next, runAt } = args;+ const { fromTimestamp, toTimestamp } = evaluationWindow(prev.window, runAt);+ return {+ monitorId: prev.id,+ projectId: prev.projectId,+ severity: next.severity,+ timestamp: runAt,+ fromTimestamp,+ toTimestamp,+ permalink: buildPermalink(prev.projectId, prev.id),+ message: renderAlertMessage({ monitor: prev, completion: next }),+ view: prev.view,+ filters: prev.filters,+ window: prev.window,+ };+}++/** buildPermalink composes the absolute Langfuse URL for a monitor, or undefined when NEXTAUTH_URL is unset. */+export function buildPermalink(+ projectId: string,+ monitorId: string,+): string | undefined {+ if (!env.NEXTAUTH_URL) return undefined;+ const base = env.NEXTAUTH_URL.replace(/\/$/, "");+ return `${base}/project/${projectId}/monitors/${monitorId}`;+}++/** toMonitorWebhookInputs fans an alert out to one webhook input per matched automation. */+function toMonitorWebhookInputs(args: {+ alert: MonitorAlert;+ automations: TriggerDomainWithActions["automations"];+ now: Date;+}): MonitorWebhookInput[] {+ return args.automations.map((automation) => {+ const executionId = randomUUID();+ return {+ projectId: args.alert.projectId,+ automationId: automation.id,+ executionId,+ payload: {+ id: executionId,+ timestamp: args.now,+ type: "monitor-alert",+ apiVersion: "v1",+ payload: args.alert,+ },+ };+ });+}++/** buildCompleteQuery builds the bulk UPDATE that lands every monitor's post-evaluation stamps. */+function buildCompleteQuery(args: {+ projectId: string;+ completions: MonitorCompletion[];+}): Prisma.Sql {+ const valueRows = Prisma.join(+ args.completions.map(+ (c) =>+ Prisma.sql`(${c.monitorId}, ${c.lastClaimedAt}::timestamptz, ${c.lastCompletedAt}::timestamptz, ${c.publishedAt}::timestamptz, ${c.status}::"MonitorStatus", ${c.severity}::"MonitorSeverity", ${c.severityChangedAt}::timestamptz, ${c.alertedAt}::timestamptz)`,+ ),+ ", ",+ );+ return Prisma.sql`+ UPDATE monitors AS m+ SET+ last_completed_at = data.last_completed_at,+ status = data.status,+ severity = data.severity,+ severity_changed_at = data.severity_changed_at,+ alerted_at = data.alerted_at+ FROM (VALUES ${valueRows}) AS data(+ id,+ last_claimed_at,+ last_completed_at,+ published_at,+ status,+ severity,+ severity_changed_at,+ alerted_at+ )+ WHERE m.id = data.id+ AND m.project_id = ${args.projectId}+ AND m.last_claimed_at = data.last_claimed_at -- no-op if another worker re-claimed since+ AND m.status = 'ACTIVE' -- no-op if the user paused since claim+ AND m.last_published_at = data.published_at -- no-op if the scheduler rescued/republished since claim+ `;+}++/** MetricValue is one metric's evaluated result: a number, null (missing/non-finite), or the ErrorBadQuery sentinel. */+export type MetricValue = number | null | typeof ErrorBadQuery;++/** MetricMap keys each metric's MetricValue by `${aggregation}_${measure}`. */+type MetricMap = Record<string, MetricValue>;++/** MonitorPublisher publishes one MonitorWebhookInput onto the webhook queue. */+export type MonitorPublisher = (input: MonitorWebhookInput) => Promise<void>;++/** QueryExecutor runs a monitor's ClickHouse query. */+export type QueryExecutor = typeof defaultExecuteQuery;++/** GetTriggerConfigurations loads the trigger configurations matching a filter. */+export type GetTriggerConfigurations = typeof defaultGetTriggerConfigurations;diff --git a/packages/shared/src/features/monitors/processor/renderAlertMessage.test.ts b/packages/shared/src/features/monitors/processor/renderAlertMessage.test.tsnew file mode 100644index 0000000000..e4c4c4d86b--- /dev/null+++ b/packages/shared/src/features/monitors/processor/renderAlertMessage.test.ts@@ -0,0 +1,156 @@+import { describe, it, expect } from "vitest";++import type { Monitor, MonitorSeverity } from "../types";+import type { MonitorCompletion } from "./applyStateMachine";+import { renderAlertMessage } from "./renderAlertMessage";++const t0 = new Date("2024-01-01T00:00:00.000Z");++/** baseMonitor supplies the Monitor fields each case overrides. */+const baseMonitor: Monitor = {+ id: "m_test",+ createdAt: t0,+ updatedAt: t0,+ createdBy: null,+ updatedBy: null,+ projectId: "p_test",+ view: "observations",+ filters: [],+ metric: { measure: "latency", aggregation: "p95" },+ window: "5m",+ thresholdOperator: "GT",+ alertThreshold: 100,+ warningThreshold: 50,+ noData: { mode: "SILENT" },+ renotify: { mode: "OFF" },+ name: "Latency monitor",+ tags: [],+ triggerIds: [],+ severity: "OK",+ severityChangedAt: null,+ alertedAt: null,+ status: "ACTIVE",+ nextRunAt: null,+ lastPublishedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,+};++/** completion builds a MonitorCompletion for a given severity. */+const completion = (severity: MonitorSeverity): MonitorCompletion => ({+ monitorId: baseMonitor.id,+ lastClaimedAt: t0,+ lastCompletedAt: t0,+ publishedAt: t0,+ status: "ACTIVE",+ severity,+ severityChangedAt: null,+ alertedAt: null,+});++/** Case is one renderAlertMessage table row. */+type Case = {+ name: string;+ monitor: Partial<Monitor>;+ next: MonitorSeverity;+ expected: { title: string; body: string };+};++/** metricRef is the rendered metric reference for baseMonitor's metric. */+const metricRef = "`p95(observations.latency)`";++/** cases covers the body-shape branches. */+const cases: Case[] = [+ {+ name: "NO_DATA: body reports no data over the window",+ monitor: { severity: "OK", window: "1h" },+ next: "NO_DATA",+ expected: {+ title: "[NO_DATA] Latency monitor",+ body: `${metricRef} has no data over the last **1h**`,+ },+ },+ {+ name: "NO_DATA -> OK: body reports recovery and data again",+ monitor: { severity: "NO_DATA" },+ next: "OK",+ expected: {+ title: "[OK] Latency monitor",+ body: `${metricRef} recovered and is reporting data again`,+ },+ },+ {+ name: "OK from a threshold severity: body reports recovery",+ monitor: { severity: "ALERT" },+ next: "OK",+ expected: {+ title: "[OK] Latency monitor",+ body: `${metricRef} recovered`,+ },+ },+ {+ name: "ALERT: body uses alert threshold",+ monitor: { severity: "OK", thresholdOperator: "GT", alertThreshold: 100 },+ next: "ALERT",+ expected: {+ title: "[ALERT] Latency monitor",+ body: `${metricRef} is **above** \`100\``,+ },+ },+ {+ name: "WARNING with warning band: body uses warning threshold",+ monitor: { severity: "OK", alertThreshold: 100, warningThreshold: 50 },+ next: "WARNING",+ expected: {+ title: "[WARNING] Latency monitor",+ body: `${metricRef} is **above** \`50\``,+ },+ },+ {+ name: "WARNING with null warning band: falls back to alert threshold",+ monitor: { severity: "OK", alertThreshold: 100, warningThreshold: null },+ next: "WARNING",+ expected: {+ title: "[WARNING] Latency monitor",+ body: `${metricRef} is **above** \`100\``,+ },+ },+];++describe("renderAlertMessage", () => {+ it.each(cases)("$name", ({ monitor, next, expected }) => {+ const result = renderAlertMessage({+ monitor: { ...baseMonitor, ...monitor },+ completion: completion(next),+ });+ expect(result).toEqual(expected);+ });++ /** OperatorCase pairs a threshold operator with its rendered word. */+ type OperatorCase = { op: Monitor["thresholdOperator"]; word: string };+ /** operatorCases covers every operator's rendered word. */+ const operatorCases: OperatorCase[] = [+ { op: "GT", word: "above" },+ { op: "GTE", word: "at or above" },+ { op: "LT", word: "below" },+ { op: "LTE", word: "at or below" },+ { op: "EQ", word: "equal to" },+ { op: "NEQ", word: "not equal to" },+ ];++ it.each(operatorCases)(+ "$op: body renders operator as '$word'",+ ({ op, word }) => {+ const result = renderAlertMessage({+ monitor: {+ ...baseMonitor,+ severity: "OK",+ thresholdOperator: op,+ alertThreshold: 100,+ },+ completion: completion("ALERT"),+ });+ expect(result.body).toBe(`${metricRef} is **${word}** \`100\``);+ },+ );+});diff --git a/packages/shared/src/features/monitors/processor/renderAlertMessage.ts b/packages/shared/src/features/monitors/processor/renderAlertMessage.tsnew file mode 100644index 0000000000..adcfd7bdf6--- /dev/null+++ b/packages/shared/src/features/monitors/processor/renderAlertMessage.ts@@ -0,0 +1,65 @@+import type {+ MonitorSeverity,+ MonitorThresholdOperator,+ Monitor,+} from "../types";+import type { MonitorCompletion } from "./applyStateMachine";++/** renderAlertMessage builds the human-readable title/body for a MonitorAlert. The body distinguishes no-data alerts from threshold-crossing alerts. */+export function renderAlertMessage(args: {+ monitor: Monitor;+ completion: MonitorCompletion;+}): { title: string; body: string } {+ const { monitor, completion } = args;+ const prevSeverity = monitor.severity;+ const severity = completion.severity;+ const title = `[${severity}] ${monitor.name}`;+ // standard markdown; the Slack builder later runs it through slackify-markdown+ const metricRef = `\`${monitor.metric.aggregation}(${monitor.view}.${monitor.metric.measure})\``;+ let body: string;+ if (severity === "NO_DATA") {+ body = `${metricRef} has no data over the last **${monitor.window}**`;+ } else if (prevSeverity === "NO_DATA" && severity === "OK") {+ body = `${metricRef} recovered and is reporting data again`;+ } else if (severity === "OK") {+ body = `${metricRef} recovered`;+ } else {+ const threshold = selectThreshold(+ severity,+ monitor.alertThreshold,+ monitor.warningThreshold ?? null,+ );+ body = `${metricRef} is **${operatorWord(monitor.thresholdOperator)}** \`${threshold}\``;+ }+ return { title, body };+}++/** operatorWord returns the human-readable form of a threshold operator. */+function operatorWord(op: MonitorThresholdOperator): string {+ switch (op) {+ case "GT":+ return "above";+ case "GTE":+ return "at or above";+ case "LT":+ return "below";+ case "LTE":+ return "at or below";+ case "EQ":+ return "equal to";+ case "NEQ":+ return "not equal to";+ }+}++/** selectThreshold picks the threshold relevant to the current severity (warning band for WARNING, alert for everything else). */+function selectThreshold(+ severity: MonitorSeverity,+ alertThreshold: number,+ warningThreshold: number | null,+): number {+ if (severity === "WARNING" && warningThreshold !== null) {+ return warningThreshold;+ }+ return alertThreshold;+}diff --git a/packages/shared/src/features/monitors/scheduler/scheduler.ts b/packages/shared/src/features/monitors/scheduler/scheduler.tsnew file mode 100644index 0000000000..9c639e764a--- /dev/null+++ b/packages/shared/src/features/monitors/scheduler/scheduler.ts@@ -0,0 +1,213 @@+import type { MonitorView as PrismaMonitorView } from "@prisma/client";+import type { z } from "zod";++import { Prisma, type PrismaClient } from "../../../db";+import type { singleFilter } from "../../../interfaces/filters";+import type { metric as MetricSchema } from "../../query/types";+import { viewFromPrisma, windowFromMs } from "../service/helpers";+import type { MonitorQueueEventInput } from "./types";++/** monitorProcessorTtl bounds how long a published run can be in flight before the scheduler republishes it. */+export const monitorProcessorTtl = 5 * 60 * 1000;++/** MonitorScheduler claims and publishes due monitors for its scheduler slot. */+export class MonitorScheduler {+ private readonly schedulerId: number;+ private readonly totalSchedulers: number;+ private readonly db: PrismaClient;+ private readonly publish: PublishMonitorEvent;++ constructor(deps: {+ schedulerId: number;+ totalSchedulers: number;+ db: PrismaClient;+ publish: PublishMonitorEvent;+ }) {+ this.schedulerId = deps.schedulerId;+ this.totalSchedulers = deps.totalSchedulers;+ this.db = deps.db;+ this.publish = deps.publish;+ }++ /**+ * schedule returns messages to queue for the current due monitors and+ * advances the schedule to the next run.+ */+ async schedule(scheduledAt: Date): Promise<number> {+ const results = await this.db.$queryRaw<MonitorBatchResult[]>(+ buildScheduleQuery({+ tick: scheduledAt,+ schedulerId: this.schedulerId,+ totalSchedulers: this.totalSchedulers,+ }),+ );++ if (results.length === 0) return 0;++ await Promise.all(+ results.map((result) => {+ let event = toMonitorQueueEvent(result, scheduledAt);+ return this.publish(event);+ }),+ );++ return results.length;+ }+}++/** toMonitorQueueEvent converts a MonitorBatchResult into its JSON-safe wire shape. */+function toMonitorQueueEvent(+ row: MonitorBatchResult,+ publishedAt: Date,+): MonitorQueueEventInput {+ return {+ projectId: row.project_id,+ schedulerBatchId: row.scheduler_batch_id.toString(),+ runAt: row.run_at,+ publishedAt,+ view: viewFromPrisma(row.view),+ filters: row.filters,+ window: windowFromMs(row.window_ms),+ metrics: row.metrics,+ monitors: row.monitors,+ };+}++/** buildScheduleQuery returns the SQL that claims due monitors, advances next_run_at, and aggregates published rows by (project_id, scheduler_batch_id). */+function buildScheduleQuery({+ tick,+ schedulerId,+ totalSchedulers,+}: {+ tick: Date;+ schedulerId: number;+ totalSchedulers: number;+}): Prisma.Sql {+ /** calculateRunAt returns the deterministic cadence boundary at or before tick for the given source. */+ const calculateRunAt = (source: "monitors" | "due"): Prisma.Sql => Prisma.sql`+ TIMESTAMPTZ 'epoch' + (+ (+ ((EXTRACT(EPOCH FROM ${tick}::timestamptz) * 1000)::bigint+ - (${Prisma.raw(source)}.scheduler_batch_id % 60) * 1000) -- ms since the beginning of time+ / ${Prisma.raw(source)}.cadence_ms * ${Prisma.raw(source)}.cadence_ms -- rounded down to the last cadence+ + (${Prisma.raw(source)}.scheduler_batch_id % 60) * 1000 -- plus some second jitter for better load distribution+ ) * INTERVAL '1 millisecond'+ )+ `;++ /** calculateNextRunAt is the next cadence boundary strictly after tick (snapshotted from due). */+ const calculateNextRunAt = Prisma.sql`+ ${calculateRunAt("due")} + due.cadence_ms * INTERVAL '1 millisecond'+ `;++ /** runIsPending is true when a prior publish has not completed within monitorProcessorTtl. */+ const runIsPending = Prisma.sql`+ due.last_published_at IS NOT NULL -- not the first run+ AND (+ due.last_completed_at IS NULL -- worker never reported completion+ OR due.last_completed_at < due.last_published_at -- last run still in flight+ )+ AND ${tick}::timestamptz - due.last_published_at+ <= ${monitorProcessorTtl} * INTERVAL '1 millisecond' -- before TTL+ `;++ return Prisma.sql`+ WITH due AS (+ SELECT+ id,+ project_id,+ scheduler_batch_id,+ cadence_ms,+ view,+ filters,+ window_ms,+ metric,+ last_published_at,+ last_completed_at,+ status,+ CASE+ WHEN next_run_at IS NULL THEN ${tick}::timestamptz+ ELSE ${calculateRunAt("monitors")}+ END AS run_at+ FROM monitors+ WHERE (scheduler_batch_id % ${totalSchedulers}::bigint) = ${schedulerId}::bigint+ AND status = 'ACTIVE'+ AND (+ -- due+ next_run_at IS NULL+ OR next_run_at <= ${tick}+ -- last run expired+ OR (+ last_published_at IS NOT NULL+ AND (+ last_completed_at IS NULL+ OR last_completed_at < last_published_at+ )+ AND ${tick}::timestamptz - last_published_at+ > ${monitorProcessorTtl} * INTERVAL '1 millisecond'+ )+ )+ ORDER BY next_run_at ASC NULLS FIRST+ FOR UPDATE SKIP LOCKED+ ),+ updated AS (+ UPDATE monitors+ SET+ next_run_at = ${calculateNextRunAt},+ last_published_at = CASE+ WHEN ${runIsPending} THEN monitors.last_published_at+ ELSE ${tick}::timestamptz+ END+ FROM due+ WHERE monitors.id = due.id+ RETURNING+ monitors.id,+ due.project_id,+ due.scheduler_batch_id,+ due.run_at,+ due.view,+ due.filters,+ due.window_ms,+ due.metric,+ NOT (${runIsPending}) AS was_published+ )+ -- Rollup published runs into a message queue event+ SELECT+ project_id,+ scheduler_batch_id,+ MAX(run_at) AS run_at,+ (array_agg(view))[1] AS view,+ (array_agg(filters))[1] AS filters,+ (array_agg(window_ms))[1] AS window_ms,+ array_agg(DISTINCT metric) AS metrics,+ array_agg(+ jsonb_build_object(+ 'monitorId', id,+ 'metricName', concat(metric->>'aggregation', '_', metric->>'measure')+ )+ ORDER BY id+ ) AS monitors+ FROM updated+ WHERE was_published = true+ GROUP BY project_id, scheduler_batch_id+ ORDER BY MAX(run_at) ASC+ `;+}++type Metric = z.infer<typeof MetricSchema>;+type FilterState = z.infer<typeof singleFilter>[];++/** PublishMonitorEvent publishes a monitor queue event. */+type PublishMonitorEvent = (event: MonitorQueueEventInput) => Promise<void>;++/** MonitorBatchResult is one published batch keyed by (project_id, scheduler_batch_id). */+type MonitorBatchResult = {+ project_id: string;+ scheduler_batch_id: bigint;+ run_at: Date;+ view: PrismaMonitorView;+ filters: FilterState;+ window_ms: bigint;+ metrics: Metric[];+ monitors: { monitorId: string; metricName: string }[];+};diff --git a/packages/shared/src/features/monitors/scheduler/types.test.ts b/packages/shared/src/features/monitors/scheduler/types.test.tsindex 9fed80c593..af72e7eacf 100644--- a/packages/shared/src/features/monitors/scheduler/types.test.ts+++ b/packages/shared/src/features/monitors/scheduler/types.test.ts@@ -9,7 +9,8 @@ describe("MonitorQueueEventSchema", () => {const validQueueEvent = {projectId: "proj_01",schedulerBatchId: 42n,- scheduledAt: new Date("2026-05-18T12:00:00.000Z"),+ runAt: new Date("2026-05-18T12:00:00.000Z"),+ publishedAt: new Date("2026-05-18T12:00:00.500Z"),view: "observations" as const,filters: [],window: "5m" as const,@@ -22,13 +23,13 @@ describe("MonitorQueueEventSchema", () => {expect(result.success).toBe(true);});- it("coerces a string scheduledAt to a Date", () => {+ it("coerces a string runAt to a Date", () => {const result = MonitorQueueEventSchema.safeParse({...validQueueEvent,- scheduledAt: "2026-05-18T12:00:00.000Z",+ runAt: "2026-05-18T12:00:00.000Z",});expect(result.success).toBe(true);- if (result.success) expect(result.data.scheduledAt).toBeInstanceOf(Date);+ if (result.success) expect(result.data.runAt).toBeInstanceOf(Date);});it("coerces a string schedulerBatchId to a bigint", () => {@@ -41,6 +42,19 @@ describe("MonitorQueueEventSchema", () => {expect(typeof result.data.schedulerBatchId).toBe("bigint");});+ it("preserves full precision when coercing a large bigint string wire value", () => {+ const huge = 123456789012345678901234567890n;+ const result = MonitorQueueEventSchema.safeParse({+ ...validQueueEvent,+ schedulerBatchId: huge.toString(),+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(typeof result.data.schedulerBatchId).toBe("bigint");+ expect(result.data.schedulerBatchId).toBe(huge);+ }+ });+it("rejects a window outside the MonitorWindow tier set", () => {expect(MonitorQueueEventSchema.safeParse({@@ -51,10 +65,6 @@ describe("MonitorQueueEventSchema", () => {});it("rejects a negative schedulerBatchId", () => {- // `calculateSchedulerBatchId` masks the sha256 high 8 bytes with- // `& (2^63 - 1)`, so the producer can never emit a negative value. Guard- // the wire boundary so anything else looks like an obvious validator- // failure rather than corrupted data.expect(MonitorQueueEventSchema.safeParse({...validQueueEvent,@@ -64,9 +74,6 @@ describe("MonitorQueueEventSchema", () => {});it("accepts zero as a schedulerBatchId", () => {- // Cryptographically improbable but mathematically possible; the- // refinement is `.nonnegative()`, not `.positive()`, to match the- // producer's contract.expect(MonitorQueueEventSchema.safeParse({...validQueueEvent,@@ -76,8 +83,6 @@ describe("MonitorQueueEventSchema", () => {});it("accepts an empty monitors array", () => {- // Scheduler may publish with zero monitors if everything in the batch was- // filtered out — schema should not block; downstream worker handles it.expect(MonitorQueueEventSchema.safeParse({ ...validQueueEvent, monitors: [] }).success,@@ -87,14 +92,18 @@ describe("MonitorQueueEventSchema", () => {describe("MonitorWebhookQueueEventSchema", () => {const validEnvelope = {+ id: "exe_01",+ timestamp: new Date("2026-05-18T12:01:00.000Z"),type: "monitor-alert" as const,- version: "v1" as const,+ apiVersion: "v1" as const,payload: {monitorId: "mon_01",projectId: "proj_01",- severity: "alert" as const,+ severity: "ALERT" as const,permalink: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",timestamp: new Date("2026-05-18T12:01:00.000Z"),+ fromTimestamp: new Date("2026-05-18T11:55:30.000Z"),+ toTimestamp: new Date("2026-05-18T12:00:30.000Z"),message: { title: "High error rate", body: "errors > 100" },view: "observations" as const,filters: [],@@ -117,22 +126,40 @@ describe("MonitorWebhookQueueEventSchema", () => {).toBe(false);});- it("rejects a wrong version literal", () => {+ it("rejects a wrong apiVersion literal", () => {expect(MonitorWebhookQueueEventSchema.safeParse({...validEnvelope,- version: "v2",+ apiVersion: "v2",}).success,).toBe(false);});++ it("requires id", () => {+ const { id: _unused, ...withoutId } = validEnvelope;+ expect(MonitorWebhookQueueEventSchema.safeParse(withoutId).success).toBe(+ false,+ );+ });++ it("requires timestamp", () => {+ const { timestamp: _unused, ...withoutTs } = validEnvelope;+ expect(MonitorWebhookQueueEventSchema.safeParse(withoutTs).success).toBe(+ false,+ );+ });++ it("coerces a string timestamp to a Date", () => {+ const result = MonitorWebhookQueueEventSchema.safeParse({+ ...validEnvelope,+ timestamp: "2026-05-18T12:01:00.000Z",+ });+ expect(result.success).toBe(true);+ if (result.success) expect(result.data.timestamp).toBeInstanceOf(Date);+ });});describe("scheduler DTO JSON round-trip (wire contract)", () => {- // BigInt and Date can't be JSON-stringified natively; the wire schemas use- // `z.coerce.*` to recover them on the consumer side. These tests lock that- // contract: produce → JSON.stringify → JSON.parse → schema.parse must- // round-trip successfully.-const stringifyWithBigInt = (value: unknown) =>JSON.stringify(value, (_key, v) =>typeof v === "bigint" ? v.toString() : v,@@ -142,7 +169,8 @@ describe("scheduler DTO JSON round-trip (wire contract)", () => {const event = {projectId: "proj_01",schedulerBatchId: 42n,- scheduledAt: new Date("2026-05-18T12:00:00.000Z"),+ runAt: new Date("2026-05-18T12:00:00.000Z"),+ publishedAt: new Date("2026-05-18T12:00:00.500Z"),view: "observations" as const,filters: [],window: "5m" as const,@@ -154,21 +182,25 @@ describe("scheduler DTO JSON round-trip (wire contract)", () => {expect(result.success).toBe(true);if (result.success) {expect(typeof result.data.schedulerBatchId).toBe("bigint");- expect(result.data.scheduledAt).toBeInstanceOf(Date);+ expect(result.data.runAt).toBeInstanceOf(Date);expect(result.data.window).toBe("5m");}});it("round-trips a MonitorWebhookQueueEvent envelope through JSON", () => {const envelope = {+ id: "exe_01",+ timestamp: new Date("2026-05-18T12:01:00.000Z"),type: "monitor-alert" as const,- version: "v1" as const,+ apiVersion: "v1" as const,payload: {monitorId: "mon_01",projectId: "proj_01",- severity: "alert" as const,+ severity: "ALERT" as const,permalink: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",timestamp: new Date("2026-05-18T12:01:00.000Z"),+ fromTimestamp: new Date("2026-05-18T11:55:30.000Z"),+ toTimestamp: new Date("2026-05-18T12:00:30.000Z"),message: { title: "High error rate", body: "errors > 100" },view: "observations" as const,filters: [],@@ -179,6 +211,7 @@ describe("scheduler DTO JSON round-trip (wire contract)", () => {const result = MonitorWebhookQueueEventSchema.safeParse(wire);expect(result.success).toBe(true);if (result.success) {+ expect(result.data.timestamp).toBeInstanceOf(Date);expect(result.data.payload.timestamp).toBeInstanceOf(Date);}});diff --git a/packages/shared/src/features/monitors/scheduler/types.ts b/packages/shared/src/features/monitors/scheduler/types.tsindex 90ed8edcbe..a113e91ec2 100644--- a/packages/shared/src/features/monitors/scheduler/types.ts+++ b/packages/shared/src/features/monitors/scheduler/types.ts@@ -1,6 +1,3 @@-/** scheduler/types.ts contains the transport DTOs the scheduler/worker- * publish on BullMQ. These are wire-shaped (coerced primitives) and not- * domain entities. */import { z } from "zod";import { metric as MetricSchema } from "../../query/types";@@ -12,43 +9,52 @@ import {MonitorWindowSchema,} from "../types";-/**- * MonitorQueueEventSchema represents a batch of monitors that can be- * evaluated together using the same set of parameters.- *- * All monitors in `monitors[]` share `view` / `filters` / `window`, so the- * worker runs one ClickHouse query for the whole batch.- */+/** MonitorQueueEventSchema validates a batch of monitors evaluated together with shared query parameters. */export const MonitorQueueEventSchema = z.object({projectId: z.string(),- // Fingerprint of (projectId, view, filters, window)+ // Fingerprint of (projectId, view, filters, window).schedulerBatchId: z.coerce.bigint().nonnegative(),- // Scheduler tick time- scheduledAt: z.coerce.date(),+ // CH window anchor.+ runAt: z.coerce.date(),++ // Publish identifier for the processor's claim/complete CAS.+ publishedAt: z.coerce.date(),- // Shared query primitives — every monitor in this batch agrees on these.view: MonitorViewSchema,filters: MonitorFiltersSchema,window: MonitorWindowSchema,metrics: z.array(MetricSchema),- // Monitors map to metricNames returned by the above query paramsmonitors: z.array(z.object({ monitorId: z.string(), metricName: z.string() }),),});++/** MonitorQueueEvent is the parsed shape of MonitorQueueEventSchema. */export type MonitorQueueEvent = z.infer<typeof MonitorQueueEventSchema>;-/**- * MonitorWebhookQueueEventSchema is the transport envelope wrapping- * `MonitorAlertSchema` for the `WebhookQueue`.- */+/** MonitorQueueEventInput is the unparsed input shape of MonitorQueueEventSchema. */+export type MonitorQueueEventInput = z.input<typeof MonitorQueueEventSchema>;++/** MonitorWebhookQueueEventSchema validates the envelope published onto WebhookQueue and posted to customer webhooks. */export const MonitorWebhookQueueEventSchema = z.object({+ id: z.string(),+ timestamp: z.coerce.date(),type: z.literal("monitor-alert"),- version: z.literal("v1"),+ apiVersion: z.literal("v1"),payload: MonitorAlertSchema,});++/** MonitorWebhookQueueEvent is the parsed shape of MonitorWebhookQueueEventSchema. */export type MonitorWebhookQueueEvent = z.infer<typeof MonitorWebhookQueueEventSchema>;++/** MonitorWebhookInput is the routing head plus monitor envelope the processor publishes onto WebhookQueue. */+export type MonitorWebhookInput = {+ projectId: string;+ automationId: string;+ executionId: string;+ payload: MonitorWebhookQueueEvent;+};diff --git a/packages/shared/src/features/monitors/server.ts b/packages/shared/src/features/monitors/server.tsindex db6f73c2ca..c8ee1b7ff4 100644--- a/packages/shared/src/features/monitors/server.ts+++ b/packages/shared/src/features/monitors/server.ts@@ -4,3 +4,5 @@export * from "./index";export * from "./service";export * from "./scheduler/types";+export * from "./scheduler/scheduler";+export * from "./processor/processor";diff --git a/packages/shared/src/features/monitors/service/helpers.test.ts b/packages/shared/src/features/monitors/service/helpers.test.tsindex 366e656a37..2700d760e8 100644--- a/packages/shared/src/features/monitors/service/helpers.test.ts+++ b/packages/shared/src/features/monitors/service/helpers.test.ts@@ -1,41 +1,27 @@-import {- MonitorSeverity as PrismaMonitorSeverity,- MonitorStatus as PrismaMonitorStatus,- MonitorThresholdOperator as PrismaMonitorThresholdOperator,- MonitorView as PrismaMonitorView,- Prisma,-} from "@prisma/client";+import { MonitorView as PrismaMonitorView, Prisma } from "@prisma/client";import { describe, it, expect } from "vitest";import { z } from "zod";import { InvalidRequestError, LangfuseNotFoundError } from "../../../errors";import { singleFilter } from "../../../interfaces/filters";-import {- MonitorSeveritySchema,- MonitorStatusSchema,- MonitorThresholdOperatorSchema,- MonitorViewSchema,- MonitorWindowSchema,-} from "../types";+import { MonitorViewSchema, MonitorWindowSchema } from "../types";import { DAY, HOUR, MINUTE, WEEK } from "../helpers";import {calculateCadence,- calculateLastRunAt,calculateSchedulerBatchId,decimalToPrisma,errorFromPrisma,monitorFromPrisma,- severityFromPrisma,sortFiltersCanonically,- statusFromPrisma,- statusToPrisma,- thresholdOperatorFromPrisma,- thresholdOperatorToPrisma,+ toPrismaWhere,+ updateSchedulerProperties,+ updateStatusAndSeverity,viewFromPrisma,viewToPrisma,windowFromMs,windowToMs,} from "./helpers";+import { type ListMonitorFilter } from "./types";type Filter = z.infer<typeof singleFilter>;@@ -137,6 +123,101 @@ describe("sortFiltersCanonically", () => {});});+describe("toPrismaWhere", () => {+ it("scopes by projectId with no AND clauses for undefined or empty filter", () => {+ expect(toPrismaWhere("proj_01", undefined)).toEqual({+ projectId: "proj_01",+ AND: [],+ });+ expect(toPrismaWhere("proj_01", [])).toEqual({+ projectId: "proj_01",+ AND: [],+ });+ });++ it("translates severity `any of` into a Prisma `in` clause", () => {+ const filter: ListMonitorFilter = [+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["ALERT", "WARNING"],+ },+ ];+ expect(toPrismaWhere("proj_01", filter)).toEqual({+ projectId: "proj_01",+ AND: [{ severity: { in: ["ALERT", "WARNING"] } }],+ });+ });++ it("translates severity `none of` into a negated `in` clause", () => {+ const filter: ListMonitorFilter = [+ {+ type: "stringOptions",+ column: "severity",+ operator: "none of",+ value: ["PAUSED"],+ },+ ];+ expect(toPrismaWhere("proj_01", filter)).toEqual({+ projectId: "proj_01",+ AND: [{ NOT: { severity: { in: ["PAUSED"] } } }],+ });+ });++ it("translates tags operators to Prisma array predicates", () => {+ const filter: ListMonitorFilter = [+ {+ type: "arrayOptions",+ column: "tags",+ operator: "any of",+ value: ["prod"],+ },+ {+ type: "arrayOptions",+ column: "tags",+ operator: "all of",+ value: ["prod", "latency"],+ },+ {+ type: "arrayOptions",+ column: "tags",+ operator: "none of",+ value: ["legacy"],+ },+ ];+ expect(toPrismaWhere("proj_01", filter)).toEqual({+ projectId: "proj_01",+ AND: [+ { tags: { hasSome: ["prod"] } },+ { tags: { hasEvery: ["prod", "latency"] } },+ { NOT: { tags: { hasSome: ["legacy"] } } },+ ],+ });+ });++ it("skips empty tag-value rows", () => {+ const filter: ListMonitorFilter = [+ {+ type: "arrayOptions",+ column: "tags",+ operator: "all of",+ value: [],+ },+ {+ type: "arrayOptions",+ column: "tags",+ operator: "none of",+ value: [],+ },+ ];+ expect(toPrismaWhere("proj_01", filter)).toEqual({+ projectId: "proj_01",+ AND: [],+ });+ });+});+describe("calculateCadence", () => {it("returns 1 minute for sub-day windows", () => {expect(calculateCadence(5n * 60_000n)).toBe(MINUTE);@@ -318,94 +399,6 @@ describe("calculateSchedulerBatchId", () => {});});-describe("calculateLastRunAt", () => {- const ONE_MINUTE = 60n * 1000n;- const THIRTY_MIN = 30n * ONE_MINUTE;- const FORTY_EIGHT_HOURS = 48n * 60n * ONE_MINUTE;-- it("returns a Date strictly at or before now", () => {- const now = new Date("2026-05-19T12:34:56.789Z");- const result = calculateLastRunAt(now, ONE_MINUTE, 17n);- expect(result.getTime()).toBeLessThanOrEqual(now.getTime());- });-- it("places the result on the (boundary + offset) slot", () => {- // schedulerBatchId % 60 = 17 → offset = 17_000ms- const now = new Date("2026-05-19T12:34:56.789Z");- const result = calculateLastRunAt(now, ONE_MINUTE, 17n);-- // result is exactly (boundary + 17s); the seconds-component is 17- expect(result.getUTCSeconds()).toBe(17);- expect(result.getUTCMilliseconds()).toBe(0);- });-- it("is deterministic per (schedulerBatchId, cadence) inside one cadence", () => {- const cadence = ONE_MINUTE;- const batchId = 42n;-- // two `now`s within the same minute-after-offset window- const a = calculateLastRunAt(- new Date("2026-05-19T12:34:50.000Z"),- cadence,- batchId,- );- const b = calculateLastRunAt(- new Date("2026-05-19T12:34:55.123Z"),- cadence,- batchId,- );- expect(a.getTime()).toBe(b.getTime());- });-- it("computes a deterministic slot for the 30-minute cadence", () => {- const result = calculateLastRunAt(- new Date("2026-05-19T12:45:00.000Z"),- THIRTY_MIN,- 45n,- );- // most recent boundary <= 12:45:00 with offset=45s is 12:30:45- expect(result.toISOString()).toBe("2026-05-19T12:30:45.000Z");- });-- it("computes a deterministic slot for the 48-hour cadence", () => {- // epoch 0 is a 48h boundary; 48h slots align at multiples of 172_800_000ms from epoch.- const now = new Date("2026-05-19T12:00:00.000Z");- const result = calculateLastRunAt(now, FORTY_EIGHT_HOURS, 7n);-- const cadenceMs = Number(FORTY_EIGHT_HOURS);- const offsetMs = 7 * 1000;- const expected =- Math.floor((now.getTime() - offsetMs) / cadenceMs) * cadenceMs + offsetMs;- expect(result.getTime()).toBe(expected);- expect(result.getTime()).toBeLessThanOrEqual(now.getTime());- });-- it("preserves the same in-cadence offset for the same batchId across different `now`s", () => {- // Two monitors with the same schedulerBatchId created at different `now`s- // produce different initial lastRunAt values (off by a cadence), but each- // is on the same `(boundary + offset)` slot — the scheduler converges them- // by advancing each by +cadence on every tick where due.- const cadence = ONE_MINUTE;- const batchId = 30n;-- const a = calculateLastRunAt(- new Date("2026-05-19T12:00:10.000Z"),- cadence,- batchId,- );- const b = calculateLastRunAt(- new Date("2026-05-19T12:00:40.000Z"),- cadence,- batchId,- );-- const cadenceMs = Number(cadence);- const offsetMs = Number(batchId % 60n) * 1000;- expect(a.getTime() % cadenceMs).toBe(offsetMs);- expect(b.getTime() % cadenceMs).toBe(offsetMs);- });-});-describe("windowToMs / windowFromMs", () => {it.each(MonitorWindowSchema.options)("round-trips %s", (window) => {expect(windowFromMs(windowToMs(window))).toBe(window);@@ -426,46 +419,6 @@ describe("viewToPrisma / viewFromPrisma", () => {});});-describe("statusToPrisma / statusFromPrisma", () => {- it.each(MonitorStatusSchema.options)("round-trips %s", (status) => {- expect(statusFromPrisma(statusToPrisma(status))).toBe(status);- });-- it.each(Object.values(PrismaMonitorStatus))(- "round-trips Prisma %s",- (status) => {- expect(statusToPrisma(statusFromPrisma(status))).toBe(status);- },- );-});--describe("severityFromPrisma", () => {- // No `severityToPrisma`: severity is owned by the scheduler/worker, never by- // a caller submitting an input. Only the reverse mapping is needed.- it.each(Object.values(PrismaMonitorSeverity))(- "maps Prisma %s to a valid MonitorSeverity",- (severity) => {- const mapped = severityFromPrisma(severity);- expect(MonitorSeveritySchema.options).toContain(mapped);- },- );-});--describe("thresholdOperatorToPrisma / thresholdOperatorFromPrisma", () => {- it.each(MonitorThresholdOperatorSchema.options)("round-trips %s", (op) => {- expect(thresholdOperatorFromPrisma(thresholdOperatorToPrisma(op))).toBe(op);- });-- it.each(Object.values(PrismaMonitorThresholdOperator))(- "round-trips Prisma %s",- (op) => {- expect(thresholdOperatorToPrisma(thresholdOperatorFromPrisma(op))).toBe(- op,- );- },- );-});-describe("decimalToPrisma", () => {it("returns null for a null input", () => {expect(decimalToPrisma(null)).toBeNull();@@ -520,28 +473,30 @@ describe("monitorFromPrisma", () => {windowMs: 5n * 60_000n,cadenceMs: 60_000n,schedulerBatchId: 42n,- thresholdOperator: PrismaMonitorThresholdOperator.GT,+ thresholdOperator: "GT" as const,alertThreshold: new Prisma.Decimal(100),warningThreshold: null,noData: { mode: "SILENT" as const },renotify: { mode: "OFF" as const },- severity: PrismaMonitorSeverity.UNKNOWN,+ severity: "UNKNOWN" as const,severityChangedAt: null,alertedAt: null,- status: PrismaMonitorStatus.ACTIVE,+ status: "ACTIVE" as const,nextRunAt: new Date("2026-05-18T00:01:00.000Z"),- lastPublishedRunAt: null,- lastCompletedRunAt: null,+ lastPublishedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,name: "High error rate",tags: [] as string[],+ triggerIds: [] as string[],};it("translates a representative row to the domain shape", () => {const monitor = monitorFromPrisma(prismaRow);expect(monitor.view).toBe("observations");- expect(monitor.status).toBe("active");- expect(monitor.severity).toBe("unknown");- expect(monitor.thresholdOperator).toBe("gt");+ expect(monitor.status).toBe("ACTIVE");+ expect(monitor.severity).toBe("UNKNOWN");+ expect(monitor.thresholdOperator).toBe("GT");expect(monitor.window).toBe("5m");expect(monitor.alertThreshold).toBe(100);expect(monitor.warningThreshold).toBeNull();@@ -561,3 +516,76 @@ describe("monitorFromPrisma", () => {).toThrow(InvalidRequestError);});});++describe("updateStatusAndSeverity", () => {+ it("emits PAUSED with a timestamp when status leaves ACTIVE", () => {+ const result = updateStatusAndSeverity("ACTIVE", "PAUSED");+ expect(result.status).toBe("PAUSED");+ expect(result.severity).toBe("PAUSED");+ expect(result.severityChangedAt).toBeInstanceOf(Date);+ });++ it("emits UNKNOWN with a timestamp when status returns to ACTIVE", () => {+ const result = updateStatusAndSeverity("PAUSED", "ACTIVE");+ expect(result.status).toBe("ACTIVE");+ expect(result.severity).toBe("UNKNOWN");+ expect(result.severityChangedAt).toBeInstanceOf(Date);+ });++ it("resets the publish lifecycle stamps when status returns to ACTIVE", () => {+ const result = updateStatusAndSeverity("PAUSED", "ACTIVE");+ expect(result.nextRunAt).toBeNull();+ expect(result.lastPublishedAt).toBeNull();+ expect(result.lastCompletedAt).toBeNull();+ expect(result.lastClaimedAt).toBeNull();+ expect(result.alertedAt).toBeNull();+ });++ it("emits UNKNOWN when recovering from ERROR_BAD_QUERY to ACTIVE", () => {+ const result = updateStatusAndSeverity("ERROR_BAD_QUERY", "ACTIVE");+ expect(result.status).toBe("ACTIVE");+ expect(result.severity).toBe("UNKNOWN");+ expect(result.severityChangedAt).toBeInstanceOf(Date);+ });++ it("emits PAUSED when going from ACTIVE to ERROR_BAD_QUERY", () => {+ const result = updateStatusAndSeverity("ACTIVE", "ERROR_BAD_QUERY");+ expect(result.status).toBe("ERROR_BAD_QUERY");+ expect(result.severity).toBe("PAUSED");+ expect(result.severityChangedAt).toBeInstanceOf(Date);+ });++ it("writes only status when it does not change", () => {+ expect(updateStatusAndSeverity("ACTIVE", "ACTIVE")).toEqual({+ status: "ACTIVE",+ });+ expect(updateStatusAndSeverity("PAUSED", "PAUSED")).toEqual({+ status: "PAUSED",+ });+ });++ it("writes only status when transitioning between two non-ACTIVE states", () => {+ expect(updateStatusAndSeverity("PAUSED", "ERROR_BAD_QUERY")).toEqual({+ status: "ERROR_BAD_QUERY",+ });+ expect(updateStatusAndSeverity("ERROR_BAD_QUERY", "PAUSED")).toEqual({+ status: "PAUSED",+ });+ });+});++describe("updateSchedulerProperties", () => {+ it("resets the publish lifecycle stamps when the batch id changes", () => {+ expect(updateSchedulerProperties(1n, 2n)).toEqual({+ schedulerBatchId: 2n,+ nextRunAt: null,+ lastPublishedAt: null,+ lastCompletedAt: null,+ lastClaimedAt: null,+ });+ });++ it("is a no-op when the batch id is unchanged", () => {+ expect(updateSchedulerProperties(42n, 42n)).toEqual({});+ });+});diff --git a/packages/shared/src/features/monitors/service/helpers.ts b/packages/shared/src/features/monitors/service/helpers.tsindex de90685e12..c03308b296 100644--- a/packages/shared/src/features/monitors/service/helpers.ts+++ b/packages/shared/src/features/monitors/service/helpers.ts@@ -5,10 +5,8 @@import { createHash } from "node:crypto";import {type Monitor as PrismaMonitor,- MonitorSeverity as PrismaMonitorSeverity,- MonitorStatus as PrismaMonitorStatus,- MonitorThresholdOperator as PrismaMonitorThresholdOperator,MonitorView as PrismaMonitorView,+ MonitorSeverity as PrismaMonitorSeverity,Prisma,} from "@prisma/client";@@ -20,20 +18,67 @@ import {type MonitorFilters,type MonitorSeverity,type MonitorStatus,- type MonitorThresholdOperator,type MonitorView,type MonitorWindow,MonitorSchema,+ MonitorStatusSchema,} from "../types";-import { MonitorNotFoundError, type MonitorListOrderBy } from "./types";+import {+ MonitorNotFoundError,+ type ListMonitorFilter,+ type ListMonitors,+ type MonitorListOrderBy,+} from "./types";/** nullableOrderColumns is the list of sortable columns that are nullable. */-export const nullableOrderColumns: ReadonlySet<MonitorListOrderBy> = new Set([+const nullableOrderColumns: ReadonlySet<MonitorListOrderBy> = new Set(["severityChangedAt","alertedAt",]);+/** toPrismaOrderBy builds the Prisma orderBy clause for MonitorService.list. */+export const toPrismaOrderBy = (+ orderBy: ListMonitors["orderBy"],+): Prisma.MonitorOrderByWithRelationInput[] => {+ if (!orderBy) return [{ severity: "desc" }, { id: "asc" }];+ const sort = orderBy.order.toLowerCase() as Prisma.SortOrder;+ const isNullable = nullableOrderColumns.has(orderBy.column);+ return [+ {+ [orderBy.column]: isNullable ? { sort, nulls: "last" } : sort,+ },+ { id: "asc" },+ ];+};++/** toPrismaWhere builds the Prisma where clause for a project-scoped ListMonitorFilter. */+export const toPrismaWhere = (+ projectId: string,+ filter: ListMonitorFilter | undefined,+): Prisma.MonitorWhereInput => {+ const and: Prisma.MonitorWhereInput[] = [];+ for (const f of filter ?? []) {+ if (f.type === "stringOptions") {+ and.push(+ f.operator === "any of"+ ? { [f.column]: { in: f.value } }+ : { NOT: { [f.column]: { in: f.value } } },+ );+ continue;+ }+ if (f.value.length === 0) continue;+ and.push(+ f.operator === "any of"+ ? { [f.column]: { hasSome: f.value } }+ : f.operator === "all of"+ ? { [f.column]: { hasEvery: f.value } }+ : { NOT: { [f.column]: { hasSome: f.value } } },+ );+ }+ return { projectId, AND: and };+};+/*** canonicalizeFilter normalizes a single filter for canonical comparison.* For the set-semantics filter variants (`stringOptions` / `categoryOptions` /@@ -113,24 +158,6 @@ export const calculateSchedulerBatchId = (params: {return digest.readBigUInt64BE(0) & ((1n << 63n) - 1n);};-/**- * calculateLastRunAt picks the most recent cadence boundary at or before- * `now`, offset by `(schedulerBatchId % 60) * 1000` ms. Persisted as- * `monitor.nextRunAt` on create/update so the scheduler picks the monitor up- * on its very next tick and advances it onto the deterministic slot.- */-export const calculateLastRunAt = (- now: Date,- cadenceMs: bigint,- schedulerBatchId: bigint,-): Date => {- const cadence = Number(cadenceMs);- const offset = Number(schedulerBatchId % 60n) * 1000;- const aligned =- Math.floor((now.getTime() - offset) / cadence) * cadence + offset;- return new Date(aligned);-};-/** viewToPrisma converts the MonitorView api enum to the Prisma MonitorView enum. */export const viewToPrisma = (view: MonitorView): PrismaMonitorView => {switch (view) {@@ -155,88 +182,6 @@ export const viewFromPrisma = (view: PrismaMonitorView): MonitorView => {}};-/** severityFromPrisma converts the Prisma MonitorSeverity enum to the MonitorSeverity api enum. */-export const severityFromPrisma = (- s: PrismaMonitorSeverity,-): MonitorSeverity => {- switch (s) {- case PrismaMonitorSeverity.UNKNOWN:- return "unknown";- case PrismaMonitorSeverity.NO_DATA:- return "no-data";- case PrismaMonitorSeverity.OK:- return "ok";- case PrismaMonitorSeverity.WARNING:- return "warning";- case PrismaMonitorSeverity.ALERT:- return "alert";- }-};--/** statusToPrisma converts the MonitorStatus api enum to the Prisma MonitorStatus enum. */-export const statusToPrisma = (s: MonitorStatus): PrismaMonitorStatus => {- switch (s) {- case "paused":- return PrismaMonitorStatus.PAUSED;- case "active":- return PrismaMonitorStatus.ACTIVE;- case "error-bad-query":- return PrismaMonitorStatus.ERROR_BAD_QUERY;- }-};--/** statusFromPrisma converts the Prisma MonitorStatus enum to the MonitorStatus api enum. */-export const statusFromPrisma = (s: PrismaMonitorStatus): MonitorStatus => {- switch (s) {- case PrismaMonitorStatus.PAUSED:- return "paused";- case PrismaMonitorStatus.ACTIVE:- return "active";- case PrismaMonitorStatus.ERROR_BAD_QUERY:- return "error-bad-query";- }-};--/** thresholdOperatorToPrisma converts the MonitorThresholdOperator api enum to the Prisma MonitorThresholdOperator enum. */-export const thresholdOperatorToPrisma = (- o: MonitorThresholdOperator,-): PrismaMonitorThresholdOperator => {- switch (o) {- case "gt":- return PrismaMonitorThresholdOperator.GT;- case "gte":- return PrismaMonitorThresholdOperator.GTE;- case "lt":- return PrismaMonitorThresholdOperator.LT;- case "lte":- return PrismaMonitorThresholdOperator.LTE;- case "eq":- return PrismaMonitorThresholdOperator.EQ;- case "neq":- return PrismaMonitorThresholdOperator.NEQ;- }-};--/** thresholdOperatorFromPrisma converts the Prisma MonitorThresholdOperator enum to the MonitorThresholdOperator api enum. */-export const thresholdOperatorFromPrisma = (- o: PrismaMonitorThresholdOperator,-): MonitorThresholdOperator => {- switch (o) {- case PrismaMonitorThresholdOperator.GT:- return "gt";- case PrismaMonitorThresholdOperator.GTE:- return "gte";- case PrismaMonitorThresholdOperator.LT:- return "lt";- case PrismaMonitorThresholdOperator.LTE:- return "lte";- case PrismaMonitorThresholdOperator.EQ:- return "eq";- case PrismaMonitorThresholdOperator.NEQ:- return "neq";- }-};-/** windowToMs converts the MonitorWindow api enum to a bigint of milliseconds. */export const windowToMs = (w: MonitorWindow): bigint => {switch (w) {@@ -298,9 +243,6 @@ export const monitorFromPrisma = (monitor: PrismaMonitor): Monitor =>MonitorSchema.parse({...monitor,view: viewFromPrisma(monitor.view),- severity: severityFromPrisma(monitor.severity),- status: statusFromPrisma(monitor.status),- thresholdOperator: thresholdOperatorFromPrisma(monitor.thresholdOperator),window: windowFromMs(monitor.windowMs),alertThreshold: monitor.alertThreshold.toNumber(),warningThreshold: monitor.warningThreshold?.toNumber() ?? null,@@ -310,6 +252,74 @@ export const monitorFromPrisma = (monitor: PrismaMonitor): Monitor =>export const decimalToPrisma = (n: number | null): Prisma.Decimal | null =>n == null ? null : new Prisma.Decimal(n);+/** updateStatusAndSeverity returns the status write and its derived severity transition. */+export const updateStatusAndSeverity = (+ current: MonitorStatus,+ next: MonitorStatus | undefined,+): {+ status?: MonitorStatus;+ severity?: MonitorSeverity;+ severityChangedAt?: Date;+ nextRunAt?: null;+ lastPublishedAt?: null;+ lastCompletedAt?: null;+ lastClaimedAt?: null;+ alertedAt?: null;+} => {+ if (!next) return {};+ const fromActive = current === MonitorStatusSchema.enum.ACTIVE;+ const toActive = next === MonitorStatusSchema.enum.ACTIVE;+ const toPaused = fromActive && !toActive;+ if (toPaused)+ return {+ status: next,+ severity: PrismaMonitorSeverity.PAUSED,+ severityChangedAt: new Date(),+ };+ if (!fromActive && toActive)+ return {+ status: next,+ severity: PrismaMonitorSeverity.UNKNOWN,+ severityChangedAt: new Date(),+ nextRunAt: null,+ lastPublishedAt: null,+ lastCompletedAt: null,+ lastClaimedAt: null,+ alertedAt: null,+ };+ // No Severity Change (eg ACTIVE -> ACTIVE, ERROR_* -> PAUSED)+ return { status: next };+};++/** updateSchedulerProperties returns the new schedulerBatchId and reset publish lifecycle stamps when the query-shape fingerprint changes; otherwise an empty object. */+export const updateSchedulerProperties = (+ current: bigint,+ next: bigint,+): {+ schedulerBatchId?: bigint;+ nextRunAt?: null;+ lastPublishedAt?: null;+ lastCompletedAt?: null;+ lastClaimedAt?: null;+} => {+ if (current === next) return {};+ return {+ schedulerBatchId: next,+ nextRunAt: null,+ lastPublishedAt: null,+ lastCompletedAt: null,+ lastClaimedAt: null, // void the complete() CAS guard for an in-flight worker on the old query shape+ };+};++/** initSeverity maps a MonitorStatus its initial severity value */+export const initSeverity = (status: MonitorStatus) => {+ if (status === MonitorStatusSchema.enum.ACTIVE) {+ return PrismaMonitorSeverity.UNKNOWN;+ }+ return PrismaMonitorSeverity.PAUSED;+};+/** errorFromPrisma converts a Prisma row-not-found error to MonitorNotFoundError. */export const errorFromPrisma = (id: string,diff --git a/packages/shared/src/features/monitors/service/service.test.ts b/packages/shared/src/features/monitors/service/service.test.tsnew file mode 100644index 0000000000..a635bbc626--- /dev/null+++ b/packages/shared/src/features/monitors/service/service.test.ts@@ -0,0 +1,113 @@+import { vi, describe, it, expect, beforeEach } from "vitest";++vi.mock("../../../db", async () => {+ const { Prisma } = await import("@prisma/client");+ return {+ Prisma,+ prisma: {+ monitor: {+ findFirst: vi.fn(),+ update: vi.fn(),+ },+ },+ };+});++import { prisma } from "../../../db";+import { calculateSchedulerBatchId } from "./helpers";+import { MonitorService } from "./service";+import { type SessionContext, type UpdateMonitor } from "./types";++const unchangedBatchId = calculateSchedulerBatchId({+ projectId: "proj_01",+ view: "observations",+ filters: [],+ windowMs: 300000n,+});++const session: SessionContext = { userId: "user_01" };++const input: UpdateMonitor = {+ id: "mon_01",+ projectId: "proj_01",+ view: "observations",+ filters: [],+ metric: { measure: "count", aggregation: "count" },+ window: "5m",+ thresholdOperator: "GT",+ alertThreshold: 100,+ warningThreshold: null,+ noData: { mode: "SILENT" },+ renotify: { mode: "OFF" },+ status: "ACTIVE",+ name: "High error rate",+ tags: [],+ triggerIds: [],+};++const prismaRow = {+ id: "mon_01",+ createdAt: new Date(),+ updatedAt: new Date(),+ createdBy: "user_01",+ updatedBy: "user_01",+ projectId: "proj_01",+ view: "OBSERVATIONS",+ filters: [],+ metric: { measure: "count", aggregation: "count" },+ windowMs: 300000n,+ cadenceMs: 60000n,+ thresholdOperator: "GT",+ alertThreshold: { toNumber: () => 100 },+ warningThreshold: null,+ severity: "UNKNOWN",+ severityChangedAt: null,+ noData: { mode: "SILENT" },+ renotify: { mode: "OFF" },+ status: "ACTIVE",+ schedulerBatchId: 42n,+ nextRunAt: null,+ lastPublishedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,+ name: "High error rate",+ tags: [],+ triggerIds: [],+ alertedAt: null,+};++describe("MonitorService.update", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (prisma.monitor.findFirst as any).mockResolvedValue(prismaRow);+ (prisma.monitor.update as any).mockResolvedValue(prismaRow);+ });++ it("pre-update read is scoped by projectId", async () => {+ await MonitorService.update(session, input);++ expect(prisma.monitor.findFirst).toHaveBeenCalledWith({+ where: { id: input.id, projectId: input.projectId },+ });+ });++ it("resume PAUSED->ACTIVE resets next_run_at and lifecycle stamps", async () => {+ (prisma.monitor.findFirst as any).mockResolvedValue({+ ...prismaRow,+ status: "PAUSED",+ schedulerBatchId: unchangedBatchId,+ nextRunAt: new Date("2026-05-01T00:00:00.000Z"),+ lastPublishedAt: new Date("2026-05-01T00:00:00.000Z"),+ lastCompletedAt: new Date("2026-05-01T00:00:00.000Z"),+ lastClaimedAt: new Date("2026-05-01T00:00:00.000Z"),+ });++ await MonitorService.update(session, { ...input, status: "ACTIVE" });++ const data = (prisma.monitor.update as any).mock.calls[0][0].data;+ expect(data.nextRunAt).toBeNull();+ expect(data.lastPublishedAt).toBeNull();+ expect(data.lastCompletedAt).toBeNull();+ expect(data.lastClaimedAt).toBeNull();+ });+});diff --git a/packages/shared/src/features/monitors/service/service.ts b/packages/shared/src/features/monitors/service/service.tsindex a4da66b0e2..bd5c96275b 100644--- a/packages/shared/src/features/monitors/service/service.ts+++ b/packages/shared/src/features/monitors/service/service.ts@@ -5,15 +5,16 @@ import { type Monitor } from "../types";import {calculateCadence,- calculateLastRunAt,calculateSchedulerBatchId,decimalToPrisma,errorFromPrisma,monitorFromPrisma,- nullableOrderColumns,sortFiltersCanonically,- statusToPrisma,- thresholdOperatorToPrisma,+ toPrismaOrderBy,+ toPrismaWhere,+ updateSchedulerProperties,+ updateStatusAndSeverity,+ initSeverity,viewToPrisma,windowToMs,} from "./helpers";@@ -21,6 +22,7 @@ import {type CreateMonitor,type DeleteMonitor,type GetMonitorById,+ type GetMonitorFilterOptions,type ListMonitors,MonitorNotFoundError,type SessionContext,@@ -54,11 +56,6 @@ export class MonitorService {filters,windowMs,});- const nextRunAt = calculateLastRunAt(- new Date(),- cadenceMs,- schedulerBatchId,- );const created = await prisma.monitor.create({data: {@@ -70,16 +67,18 @@ export class MonitorService {metric: input.metric,windowMs,cadenceMs,- thresholdOperator: thresholdOperatorToPrisma(input.thresholdOperator),+ thresholdOperator: input.thresholdOperator,alertThreshold: new Prisma.Decimal(input.alertThreshold),warningThreshold: decimalToPrisma(input.warningThreshold),noData: input.noData,renotify: input.renotify,- status: statusToPrisma(input.status),+ status: input.status,+ severity: initSeverity(input.status),schedulerBatchId,- nextRunAt,+ nextRunAt: null,name: input.name,tags: input.tags,+ triggerIds: input.triggerIds,},});return monitorFromPrisma(created);@@ -98,15 +97,15 @@ export class MonitorService {filters,windowMs,});- const nextRunAt = calculateLastRunAt(- new Date(),- cadenceMs,- schedulerBatchId,- );- // Scheduler and QueueProcessor columns are intentionally not touched- // (eg. severity, severityChangedAt, alertedAt, lastPublishedRunAt, lastCompletedRunAt).try {+ const current = await prisma.monitor.findFirst({+ where: { id: input.id, projectId: input.projectId },+ });+ if (!current) {+ throw new MonitorNotFoundError(input.id, input.projectId);+ }+const updated = await prisma.monitor.update({where: { id: input.id, projectId: input.projectId },data: {@@ -116,16 +115,19 @@ export class MonitorService {metric: input.metric,windowMs,cadenceMs,- thresholdOperator: thresholdOperatorToPrisma(input.thresholdOperator),+ thresholdOperator: input.thresholdOperator,alertThreshold: new Prisma.Decimal(input.alertThreshold),warningThreshold: decimalToPrisma(input.warningThreshold),noData: input.noData,renotify: input.renotify,- status: statusToPrisma(input.status),- schedulerBatchId,- nextRunAt,+ ...updateStatusAndSeverity(current.status, input.status),+ ...updateSchedulerProperties(+ current.schedulerBatchId,+ schedulerBatchId,+ ),name: input.name,tags: input.tags,+ triggerIds: input.triggerIds,},});return monitorFromPrisma(updated);@@ -153,27 +155,35 @@ export class MonitorService {): Promise<{ monitors: Monitor[]; totalCount: number }> {const skip =input.page && input.limit ? (input.page - 1) * input.limit : undefined;+ const where = toPrismaWhere(input.projectId, input.filter);- const sortOrder = input.orderBy?.order.toLowerCase();- const orderByValue =- input.orderBy && nullableOrderColumns.has(input.orderBy.column)- ? { sort: sortOrder, nulls: "last" as const }- : sortOrder;const [monitors, totalCount] = await Promise.all([prisma.monitor.findMany({- where: { projectId: input.projectId },- orderBy: input.orderBy- ? [{ [input.orderBy.column]: orderByValue }, { id: "asc" }]- : [{ severity: "desc" }, { id: "asc" }],+ where,+ orderBy: toPrismaOrderBy(input.orderBy),skip,take: input.limit,}),- prisma.monitor.count({ where: { projectId: input.projectId } }),+ prisma.monitor.count({ where }),]);return { monitors: monitors.map(monitorFromPrisma), totalCount };}+ public static async getFilterOptions(+ _session: SessionContext,+ input: GetMonitorFilterOptions,+ ): Promise<{ tags: { value: string }[] }> {+ const rows = await prisma.$queryRaw<{ value: string }[]>`+ SELECT tags.tag AS value+ FROM monitors, UNNEST(monitors.tags) AS tags(tag)+ WHERE monitors.project_id = ${input.projectId}+ GROUP BY tags.tag+ ORDER BY tags.tag ASC;+ `;+ return { tags: rows };+ }+public static async delete(_session: SessionContext,input: DeleteMonitor,diff --git a/packages/shared/src/features/monitors/service/types.test.ts b/packages/shared/src/features/monitors/service/types.test.tsindex 11324c51dd..66816d8a47 100644--- a/packages/shared/src/features/monitors/service/types.test.ts+++ b/packages/shared/src/features/monitors/service/types.test.ts@@ -2,9 +2,16 @@ import { describe, it, expect } from "vitest";import {CreateMonitorSchema,+ ErrorListMonitorFilterDuplicateColumn,+ ListMonitorFilterSchema,ListMonitorsSchema,UpdateMonitorSchema,} from "./types";+import {+ ErrorAlertThresholdRequired,+ ErrorAtLeastOneTrigger,+ ErrorNameRequired,+} from "../types";// Minimal valid `CreateMonitorSchema` payload. Tests override one field// at a time to exercise the refinements wired onto the input schema.@@ -16,15 +23,16 @@ const validCreateInput = {metric: { measure: "count", aggregation: "count" as const },window: "5m" as const,- thresholdOperator: "gt" as const,+ thresholdOperator: "GT" as const,alertThreshold: 100,warningThreshold: null,noData: { mode: "SILENT" as const },renotify: { mode: "OFF" as const },- status: "active" as const,+ status: "ACTIVE" as const,name: "High error rate",tags: [],+ triggerIds: ["trig_01"],};const validUpdateInput = {@@ -40,14 +48,14 @@ describe("CreateMonitorSchema", () => {it("rejects warning >= alert for gt (validateThresholdOrder is wired)", () => {const result = CreateMonitorSchema.safeParse({...validCreateInput,- thresholdOperator: "gt" as const,+ thresholdOperator: "GT" as const,alertThreshold: 100,warningThreshold: 100,});expect(result.success).toBe(false);});- it.each(["gt", "gte"] as const)(+ it.each(["GT", "GTE"] as const)("%s emits a `>` strict-ordering message (not the operator name)",(op) => {const result = CreateMonitorSchema.safeParse({@@ -67,7 +75,7 @@ describe("CreateMonitorSchema", () => {},);- it.each(["lt", "lte"] as const)(+ it.each(["LT", "LTE"] as const)("%s emits a `<` strict-ordering message (not the operator name)",(op) => {const result = CreateMonitorSchema.safeParse({@@ -93,13 +101,76 @@ describe("CreateMonitorSchema", () => {expect(result.success).toBe(false);});+ it("emits a friendly message when name is missing", () => {+ const { name: _name, ...rest } = validCreateInput;+ const result = CreateMonitorSchema.safeParse(rest);+ expect(result.success).toBe(false);+ if (!result.success) {+ const nameIssue = result.error.issues.find(+ (i) => i.path.join(".") === "name",+ );+ expect(nameIssue?.message).toBe(ErrorNameRequired);+ }+ });++ it("emits a friendly message when alertThreshold is missing", () => {+ const { alertThreshold: _t, ...rest } = validCreateInput;+ const result = CreateMonitorSchema.safeParse(rest);+ expect(result.success).toBe(false);+ if (!result.success) {+ const issue = result.error.issues.find(+ (i) => i.path.join(".") === "alertThreshold",+ );+ expect(issue?.message).toBe(ErrorAlertThresholdRequired);+ }+ });+it("rejects status `error-bad-query` on create (scheduler-owned)", () => {const result = CreateMonitorSchema.safeParse({...validCreateInput,- status: "error-bad-query",+ status: "ERROR_BAD_QUERY",});expect(result.success).toBe(false);});++ describe("triggerIds", () => {+ it("rejects an empty list with ErrorAtLeastOneTrigger on path triggerIds", () => {+ const result = CreateMonitorSchema.safeParse({+ ...validCreateInput,+ triggerIds: [],+ });+ expect(result.success).toBe(false);+ if (!result.success) {+ const issue = result.error.issues.find(+ (i) => i.path.join(".") === "triggerIds",+ );+ expect(issue?.message).toBe(ErrorAtLeastOneTrigger);+ }+ });++ it("rejects an omitted list with ErrorAtLeastOneTrigger on path triggerIds", () => {+ const { triggerIds: _t, ...rest } = validCreateInput;+ const result = CreateMonitorSchema.safeParse(rest);+ expect(result.success).toBe(false);+ if (!result.success) {+ const issue = result.error.issues.find(+ (i) => i.path.join(".") === "triggerIds",+ );+ expect(issue?.message).toBe(ErrorAtLeastOneTrigger);+ }+ });++ it("accepts a list of ids", () => {+ const result = CreateMonitorSchema.safeParse({+ ...validCreateInput,+ triggerIds: ["trig_01", "trig_02"],+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.triggerIds).toEqual(["trig_01", "trig_02"]);+ }+ });+ });});describe("UpdateMonitorSchema", () => {@@ -110,20 +181,20 @@ describe("UpdateMonitorSchema", () => {it("rejects warning <= alert for lt (validateThresholdOrder is wired)", () => {const result = UpdateMonitorSchema.safeParse({...validUpdateInput,- thresholdOperator: "lt" as const,+ thresholdOperator: "LT" as const,alertThreshold: 100,warningThreshold: 100,});expect(result.success).toBe(false);});- it("rejects an unknown filter column (validateQuery is wired)", () => {+ it("rejects a disallowed filter column (validateQuery is wired)", () => {const result = UpdateMonitorSchema.safeParse({...validUpdateInput,filters: [{type: "string",- column: "not_a_dimension",+ column: "metadata",operator: "=",value: "x",},@@ -138,10 +209,58 @@ describe("UpdateMonitorSchema", () => {// directly — narrowing the input DTO to active/paused enforces that.const result = UpdateMonitorSchema.safeParse({...validUpdateInput,- status: "error-bad-query",+ status: "ERROR_BAD_QUERY",});expect(result.success).toBe(false);});++ it("leaves status undefined when omitted so a save can't change it", () => {+ const { status, ...withoutStatus } = validUpdateInput;+ const result = UpdateMonitorSchema.safeParse(withoutStatus);+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.status).toBeUndefined();+ }+ });++ describe("triggerIds", () => {+ it("rejects an empty list with ErrorAtLeastOneTrigger on path triggerIds", () => {+ const result = UpdateMonitorSchema.safeParse({+ ...validUpdateInput,+ triggerIds: [],+ });+ expect(result.success).toBe(false);+ if (!result.success) {+ const issue = result.error.issues.find(+ (i) => i.path.join(".") === "triggerIds",+ );+ expect(issue?.message).toBe(ErrorAtLeastOneTrigger);+ }+ });++ it("rejects an omitted list with ErrorAtLeastOneTrigger on path triggerIds", () => {+ const { triggerIds: _t, ...rest } = validUpdateInput;+ const result = UpdateMonitorSchema.safeParse(rest);+ expect(result.success).toBe(false);+ if (!result.success) {+ const issue = result.error.issues.find(+ (i) => i.path.join(".") === "triggerIds",+ );+ expect(issue?.message).toBe(ErrorAtLeastOneTrigger);+ }+ });++ it("accepts a list of ids", () => {+ const result = UpdateMonitorSchema.safeParse({+ ...validUpdateInput,+ triggerIds: ["trig_01", "trig_02"],+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.triggerIds).toEqual(["trig_01", "trig_02"]);+ }+ });+ });});describe("ListMonitorsSchema", () => {@@ -196,3 +315,50 @@ describe("ListMonitorsSchema", () => {expect(result.success).toBe(false);});});++describe("ListMonitorFilterSchema", () => {+ it("parses an empty filter", () => {+ expect(ListMonitorFilterSchema.safeParse([]).success).toBe(true);+ });++ it("parses one severity row and one tags row", () => {+ const result = ListMonitorFilterSchema.safeParse([+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["ALERT"],+ },+ {+ type: "arrayOptions",+ column: "tags",+ operator: "any of",+ value: ["prod"],+ },+ ]);+ expect(result.success).toBe(true);+ });++ it("rejects two rows on the same column with ErrorListMonitorFilterDuplicateColumn", () => {+ const result = ListMonitorFilterSchema.safeParse([+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["ALERT"],+ },+ {+ type: "stringOptions",+ column: "severity",+ operator: "none of",+ value: ["PAUSED"],+ },+ ]);+ expect(result.success).toBe(false);+ if (!result.success) {+ expect(result.error.issues[0].message).toBe(+ ErrorListMonitorFilterDuplicateColumn,+ );+ }+ });+});diff --git a/packages/shared/src/features/monitors/service/types.ts b/packages/shared/src/features/monitors/service/types.tsindex fc4b5ca7f4..c59e0dbfd9 100644--- a/packages/shared/src/features/monitors/service/types.ts+++ b/packages/shared/src/features/monitors/service/types.ts@@ -6,8 +6,10 @@ import { paginationZod } from "../../../utils/zod";import {MonitorSchema,+ MonitorSeveritySchema,MonitorWriteStatusSchema,- validateQuery,+ validateAtLeastOneTrigger,+ validateMonitorQuery,validateThresholdOrder,} from "../types";@@ -34,8 +36,9 @@ const omitOnWrite = {severityChangedAt: true,alertedAt: true,nextRunAt: true,- lastPublishedRunAt: true,- lastCompletedRunAt: true,+ lastPublishedAt: true,+ lastClaimedAt: true,+ lastCompletedAt: true,} as const;/** CreateMonitorSchema is the input for MonitorService.create. */@@ -43,16 +46,19 @@ export const CreateMonitorSchema = MonitorSchema.omit({...omitOnWrite,id: true,})- .extend({ status: MonitorWriteStatusSchema.default("active") })- .superRefine(validateQuery)- .superRefine(validateThresholdOrder);+ .extend({ status: MonitorWriteStatusSchema.default("ACTIVE") })+ .superRefine(validateMonitorQuery)+ .superRefine(validateThresholdOrder)+ .superRefine(validateAtLeastOneTrigger);export type CreateMonitor = z.infer<typeof CreateMonitorSchema>;/** UpdateMonitorSchema is the input for MonitorService.update. */export const UpdateMonitorSchema = MonitorSchema.omit(omitOnWrite)- .extend({ status: MonitorWriteStatusSchema.default("active") })- .superRefine(validateQuery)- .superRefine(validateThresholdOrder);+ // status has no default: a default would un-pause a monitor on a form save.+ .extend({ status: MonitorWriteStatusSchema.optional() })+ .superRefine(validateMonitorQuery)+ .superRefine(validateThresholdOrder)+ .superRefine(validateAtLeastOneTrigger);export type UpdateMonitor = z.infer<typeof UpdateMonitorSchema>;/** GetMonitorByIdSchema is the input for MonitorService.getById. */@@ -69,6 +75,14 @@ export const DeleteMonitorSchema = z.object({});export type DeleteMonitor = z.infer<typeof DeleteMonitorSchema>;+/** GetMonitorFilterOptionsSchema is the input for MonitorService.getFilterOptions. */+export const GetMonitorFilterOptionsSchema = z.object({+ projectId: z.string(),+});+export type GetMonitorFilterOptions = z.infer<+ typeof GetMonitorFilterOptionsSchema+>;+/** MonitorListOrderBySchema is the set of columns MonitorService.list can sort by. */export const MonitorListOrderBySchema = z.enum(["name",@@ -81,6 +95,43 @@ export const MonitorListOrderBySchema = z.enum([]);export type MonitorListOrderBy = z.infer<typeof MonitorListOrderBySchema>;+/** ListMonitorSeverityFilterSchema is the severity row of a ListMonitorFilter. */+export const ListMonitorSeverityFilterSchema = z.object({+ type: z.literal("stringOptions"),+ column: z.literal("severity"),+ operator: z.enum(["any of", "none of"]),+ value: z.array(MonitorSeveritySchema).min(1),+});+export type ListMonitorSeverityFilter = z.infer<+ typeof ListMonitorSeverityFilterSchema+>;++/** ListMonitorTagsFilterSchema is the tags row of a ListMonitorFilter. */+export const ListMonitorTagsFilterSchema = z.object({+ type: z.literal("arrayOptions"),+ column: z.literal("tags"),+ operator: z.enum(["any of", "all of", "none of"]),+ value: z.array(z.string()),+});+export type ListMonitorTagsFilter = z.infer<typeof ListMonitorTagsFilterSchema>;++/** ErrorListMonitorFilterDuplicateColumn is the message for a repeated column. */+export const ErrorListMonitorFilterDuplicateColumn =+ "Each column may appear at most once in a ListMonitorFilter";++/** ListMonitorFilterSchema is the typed subset of `singleFilter[]` accepted by MonitorService.list. */+export const ListMonitorFilterSchema = z+ .array(+ z.discriminatedUnion("column", [+ ListMonitorSeverityFilterSchema,+ ListMonitorTagsFilterSchema,+ ]),+ )+ .refine((rows) => new Set(rows.map((r) => r.column)).size === rows.length, {+ message: ErrorListMonitorFilterDuplicateColumn,+ });+export type ListMonitorFilter = z.infer<typeof ListMonitorFilterSchema>;+/** ListMonitorsSchema is the input for MonitorService.list. */export const ListMonitorsSchema = z.object({projectId: z.string(),@@ -90,6 +141,7 @@ export const ListMonitorsSchema = z.object({order: z.enum(["ASC", "DESC"]),}).nullable(),+ filter: ListMonitorFilterSchema.optional(),...paginationZod,});export type ListMonitors = z.infer<typeof ListMonitorsSchema>;diff --git a/packages/shared/src/features/monitors/types.test.ts b/packages/shared/src/features/monitors/types.test.tsindex ae6b507447..7c2dfdc94c 100644--- a/packages/shared/src/features/monitors/types.test.ts+++ b/packages/shared/src/features/monitors/types.test.ts@@ -22,20 +22,21 @@ const validMonitorBase = {metric: { measure: "count", aggregation: "count" as const },window: "5m" as const,- thresholdOperator: "gt" as const,+ thresholdOperator: "GT" as const,alertThreshold: 100,warningThreshold: null,- severity: "unknown" as const,+ severity: "UNKNOWN" as const,severityChangedAt: null,noData: { mode: "SILENT" as const },renotify: { mode: "OFF" as const },- status: "active" as const,+ status: "ACTIVE" as const,nextRunAt: new Date("2026-05-18T00:01:00.000Z"),- lastPublishedRunAt: null,- lastCompletedRunAt: null,+ lastPublishedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,name: "High error rate",tags: [],@@ -153,13 +154,33 @@ describe("MonitorSchema", () => {});});+describe("MonitorSchema.triggerIds", () => {+ it("defaults to [] when omitted", () => {+ const result = MonitorSchema.safeParse(validMonitorBase);+ expect(result.success).toBe(true);+ if (result.success) expect(result.data.triggerIds).toEqual([]);+ });++ it("accepts a list of trigger IDs", () => {+ const result = MonitorSchema.safeParse({+ ...validMonitorBase,+ triggerIds: ["trig-a", "trig-b"],+ });+ expect(result.success).toBe(true);+ if (result.success)+ expect(result.data.triggerIds).toEqual(["trig-a", "trig-b"]);+ });+});+describe("MonitorAlertSchema", () => {const validAlert = {monitorId: "mon_01",projectId: "proj_01",- severity: "alert" as const,+ severity: "ALERT" as const,permalink: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",timestamp: new Date("2026-05-18T12:01:00.000Z"),+ fromTimestamp: new Date("2026-05-18T11:55:30.000Z"),+ toTimestamp: new Date("2026-05-18T12:00:30.000Z"),message: { title: "High error rate", body: "errors > 100" },view: "observations" as const,filters: [],@@ -170,10 +191,17 @@ describe("MonitorAlertSchema", () => {expect(MonitorAlertSchema.safeParse(validAlert).success).toBe(true);});- it("rejects a non-URL permalink", () => {+ it("accepts an omitted permalink (self-hosted without NEXTAUTH_URL)", () => {+ const { permalink: _permalink, ...withoutPermalink } = validAlert;+ expect(MonitorAlertSchema.safeParse(withoutPermalink).success).toBe(true);+ });++ it("rejects a relative (path-only) permalink", () => {expect(- MonitorAlertSchema.safeParse({ ...validAlert, permalink: "not-a-url" })- .success,+ MonitorAlertSchema.safeParse({+ ...validAlert,+ permalink: "/project/proj_01/monitors/mon_01",+ }).success,).toBe(false);});@@ -198,4 +226,27 @@ describe("MonitorAlertSchema", () => {expect(result.success).toBe(true);if (result.success) expect(result.data.timestamp).toBeInstanceOf(Date);});++ it("rejects an alert missing fromTimestamp", () => {+ const { fromTimestamp: _unused, ...withoutFrom } = validAlert;+ expect(MonitorAlertSchema.safeParse(withoutFrom).success).toBe(false);+ });++ it("rejects an alert missing toTimestamp", () => {+ const { toTimestamp: _unused, ...withoutTo } = validAlert;+ expect(MonitorAlertSchema.safeParse(withoutTo).success).toBe(false);+ });++ it("coerces fromTimestamp/toTimestamp strings to Dates", () => {+ const result = MonitorAlertSchema.safeParse({+ ...validAlert,+ fromTimestamp: "2026-05-18T11:55:30.000Z",+ toTimestamp: "2026-05-18T12:00:30.000Z",+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.fromTimestamp).toBeInstanceOf(Date);+ expect(result.data.toTimestamp).toBeInstanceOf(Date);+ }+ });});diff --git a/packages/shared/src/features/monitors/types.ts b/packages/shared/src/features/monitors/types.tsindex ad499ba33b..636b0971c5 100644--- a/packages/shared/src/features/monitors/types.ts+++ b/packages/shared/src/features/monitors/types.ts@@ -1,5 +1,10 @@/** types.ts contains the monitor domain — schemas, types, and the* `validate*` refinements consumed by the input schemas. */+import {+ MonitorSeverity as PrismaMonitorSeverity,+ MonitorStatus as PrismaMonitorStatus,+ MonitorThresholdOperator as PrismaMonitorThresholdOperator,+} from "@prisma/client";import { z } from "zod";import { singleFilter } from "../../interfaces/filters";@@ -8,6 +13,16 @@ import { metric as MetricSchema, viewsV2 } from "../query/types";import { isValidQuery } from "./isValidQuery";import { isValidThresholdOrder } from "./isValidThresholdOrder";+/** ErrorNameRequired is the message emitted when the Monitor name is missing or empty. */+export const ErrorNameRequired = "Name is a required field";++/** ErrorAlertThresholdRequired is the message emitted when alertThreshold is missing. */+export const ErrorAlertThresholdRequired =+ "Alert threshold is a required field";++/** ErrorAtLeastOneTrigger is the message emitted when a Monitor has no automations. */+export const ErrorAtLeastOneTrigger = "At least one automation is required";+/*** MonitorFiltersSchema is the array of filters applied to a Monitor's* underlying query — a thin alias over `singleFilter[]` so all Monitor@@ -16,53 +31,25 @@ import { isValidThresholdOrder } from "./isValidThresholdOrder";export const MonitorFiltersSchema = z.array(singleFilter);export type MonitorFilters = z.infer<typeof MonitorFiltersSchema>;-/**- * MonitorSeveritySchema is the kebab-case wire form of Prisma's- * `MonitorSeverity` enum. The service translates between this and Prisma at- * the persistence boundary.- */-export const MonitorSeveritySchema = z.enum([- "unknown",- "no-data",- "ok",- "warning",- "alert",-]);+/** MonitorSeveritySchema is the wire form of Prisma's `MonitorSeverity` enum. */+export const MonitorSeveritySchema = z.enum(PrismaMonitorSeverity);export type MonitorSeverity = z.infer<typeof MonitorSeveritySchema>;-/**- * MonitorStatusSchema is the kebab-case wire form of Prisma's `MonitorStatus`- * enum.- */-export const MonitorStatusSchema = z.enum([- "paused",- "active",- "error-bad-query",-]);+/** MonitorStatusSchema is the wire form of Prisma's `MonitorStatus` enum. */+export const MonitorStatusSchema = z.enum(PrismaMonitorStatus);export type MonitorStatus = z.infer<typeof MonitorStatusSchema>;-/**- * MonitorWriteStatusSchema is the subset of `MonitorStatusSchema` callers may- * submit on create/update. `error-bad-query` is owned by the scheduler/worker- * (flipped when a monitor's query fails to evaluate); accepting it on inputs- * would let callers forge a broken state or clear a legitimately broken- * monitor without scheduler revalidation.- */-export const MonitorWriteStatusSchema = z.enum(["active", "paused"]);+/** MonitorWriteStatusSchema is the subset of MonitorStatusSchema callers may submit on create/update. */+export const MonitorWriteStatusSchema = z.enum([+ PrismaMonitorStatus.ACTIVE,+ PrismaMonitorStatus.PAUSED,+]);export type MonitorWriteStatus = z.infer<typeof MonitorWriteStatusSchema>;-/**- * MonitorThresholdOperatorSchema is the kebab-case wire form of Prisma's- * `MonitorThresholdOperator` enum.- */-export const MonitorThresholdOperatorSchema = z.enum([- "gt",- "gte",- "lt",- "lte",- "eq",- "neq",-]);+/** MonitorThresholdOperatorSchema is the wire form of Prisma's `MonitorThresholdOperator` enum. */+export const MonitorThresholdOperatorSchema = z.enum(+ PrismaMonitorThresholdOperator,+);export type MonitorThresholdOperator = z.infer<typeof MonitorThresholdOperatorSchema>;@@ -112,8 +99,9 @@ export type MonitorRenotify = z.infer<typeof MonitorRenotifySchema>;/*** MonitorNoDataSchema describes behavior when a Monitor query returns no rows.- * `SILENT` only alerts on recovery; `NOTIFY` also alerts after- * `intervalMinutes` of sustained NO_DATA.+ * `SILENT` suppresses all NO_DATA notifications (entry, persistence, recovery);+ * `NOTIFY` alerts on entry after `intervalMinutes` of sustained NO_DATA,+ * re-fires per the renotify cadence, and alerts on recovery.*/export const MonitorNoDataSchema = z.discriminatedUnion("mode", [z.object({ mode: z.literal("SILENT") }),@@ -128,10 +116,7 @@ export const MonitorNoDataSchema = z.discriminatedUnion("mode", []);export type MonitorNoData = z.infer<typeof MonitorNoDataSchema>;-/**- * validateThresholdOrder enforces correct warning/alert threshold ordering on- * the Monitor input schemas.- */+/** validateThresholdOrder enforces correct warning/alert threshold ordering on the Monitor input schemas. */export const validateThresholdOrder = (input: {thresholdOperator: MonitorThresholdOperator;@@ -140,25 +125,35 @@ export const validateThresholdOrder = (},ctx: z.RefinementCtx,): void => {- if (!isValidThresholdOrder(input)) {- // For gt/gte the predicate requires `warning < alert` (strict);- // for lt/lte it requires `warning > alert` (strict). Map to the actual- // required relation symbol so the error message doesn't claim the- // non-strict variant for `gte`/`lte`.- const symbol = input.thresholdOperator.startsWith("g") ? ">" : "<";+ const result = isValidThresholdOrder(input);+ if (!result.valid) {ctx.addIssue({code: "custom",- message: `alertThreshold must be ${symbol} warningThreshold`,+ message: result.reason,path: ["threshold"],});}};+/** validateAtLeastOneTrigger enforces that a Monitor has at least one automation on the input schemas. */+export const validateAtLeastOneTrigger = (+ input: { triggerIds: string[] },+ ctx: z.RefinementCtx,+): void => {+ if (input.triggerIds.length < 1) {+ ctx.addIssue({+ code: "custom",+ message: ErrorAtLeastOneTrigger,+ path: ["triggerIds"],+ });+ }+};+/**- * validateQuery enforces a valid (view, metric, filters) shape on the Monitor- * input schemas.+ * validateMonitorQuery enforces a valid (view, metric, filters) shape on the+ * Monitor input schemas.*/-export const validateQuery = (+export const validateMonitorQuery = (input: {view: z.infer<typeof viewsV2>;metric: z.infer<typeof MetricSchema>;@@ -168,7 +163,7 @@ export const validateQuery = (): void => {const result = isValidQuery({view: input.view,- metric: input.metric,+ metrics: [input.metric],filters: input.filters,});if (!result.valid) {@@ -200,40 +195,47 @@ export const MonitorSchema = z.object({// Monitor Configwindow: MonitorWindowSchema,thresholdOperator: MonitorThresholdOperatorSchema,- alertThreshold: z.number(),+ alertThreshold: z.number({ message: ErrorAlertThresholdRequired }),warningThreshold: z.number().nullable(),noData: MonitorNoDataSchema.default({ mode: "SILENT" }),renotify: MonitorRenotifySchema.default({ mode: "OFF" }),// MonitorAlert Config- name: z.string().min(1).max(200),+ name: z+ .string({ message: ErrorNameRequired })+ .min(1, ErrorNameRequired)+ .max(200),tags: z.array(z.string().max(60)).max(20).default([]),+ triggerIds: z.array(z.string()).default([]),// Monitor State- severity: MonitorSeveritySchema.default("unknown"),+ severity: MonitorSeveritySchema.default("UNKNOWN"),severityChangedAt: z.date().nullable(),alertedAt: z.date().nullable(),// MonitorScheduler State- status: MonitorStatusSchema.default("active"),- nextRunAt: z.date(),- lastPublishedRunAt: z.date().nullable(),- lastCompletedRunAt: z.date().nullable(),+ status: MonitorStatusSchema.default("ACTIVE"),+ nextRunAt: z.date().nullable(),+ lastPublishedAt: z.date().nullable(),+ lastClaimedAt: z.date().nullable(),+ lastCompletedAt: z.date().nullable(),});export type Monitor = z.infer<typeof MonitorSchema>;/**- * MonitorAlertSchema is emitted when a monitor alerts. It carries the query- * shape (`view` / `filters` / `window`) alongside the rendered message so- * that recipients can reconstruct the underlying observations / scores query.+ * MonitorAlertSchema is emitted when a monitor alerts.+ * It carries enough information to query events that occurred+ * during the evaluation window of the monitor.*/export const MonitorAlertSchema = z.object({monitorId: z.string(),projectId: z.string(),- permalink: z.url(),+ permalink: z.url().optional(),message: z.object({ title: z.string(), body: z.string() }),severity: MonitorSeveritySchema,timestamp: z.coerce.date(),+ fromTimestamp: z.coerce.date(),+ toTimestamp: z.coerce.date(),view: MonitorViewSchema,filters: MonitorFiltersSchema,window: MonitorWindowSchema,diff --git a/packages/shared/src/features/query/types.ts b/packages/shared/src/features/query/types.tsindex 76c2821a31..8724ed5c72 100644--- a/packages/shared/src/features/query/types.ts+++ b/packages/shared/src/features/query/types.ts@@ -120,11 +120,10 @@ export const metricAggregations = z.enum(["uniq",]);-/**- * Returns the subset of aggregations that are valid for a given measure type.- * Whitelists known numeric types; unknown or missing types default to the- * restrictive count/uniq set to surface missing type annotations early.- */+/** MeasureDefinition is a single `measures` entry on a ViewDeclaration. */+export type MeasureDefinition = ViewDeclarationType["measures"][string];++/** getValidAggregationsForMeasureType returns the aggregations valid for a measure type: every aggregation for numeric types, or `count`/`uniq` otherwise. */export function getValidAggregationsForMeasureType(measureType: string | undefined,): z.infer<typeof metricAggregations>[] {diff --git a/packages/shared/src/server/automations.test.ts b/packages/shared/src/server/automations.test.tsindex 50e7f1989c..95cbedc12e 100644--- a/packages/shared/src/server/automations.test.ts+++ b/packages/shared/src/server/automations.test.ts@@ -7,8 +7,8 @@ describe("matchesTriggerFilter", () => {it("returns true when the filter is empty and eventActions is empty", () => {expect(matchesTriggerFilter(- { Name: "anything" },- { filter: [], eventActions: [] },+ { Name: "anything", triggerIds: ["trig-test"] },+ { id: "trig-test", filter: [], eventActions: [] },),).toBe(true);});@@ -18,7 +18,10 @@ describe("matchesTriggerFilter", () => {{ type: "string", column: "Name", operator: "=", value: "p95" },];expect(- matchesTriggerFilter({ Name: "p95" }, { filter, eventActions: [] }),+ matchesTriggerFilter(+ { Name: "p95", triggerIds: ["trig-test"] },+ { id: "trig-test", filter, eventActions: [] },+ ),).toBe(true);});@@ -28,8 +31,8 @@ describe("matchesTriggerFilter", () => {];expect(matchesTriggerFilter(- { Name: "error rate" },- { filter, eventActions: [] },+ { Name: "error rate", triggerIds: ["trig-test"] },+ { id: "trig-test", filter, eventActions: [] },),).toBe(false);});@@ -38,9 +41,12 @@ describe("matchesTriggerFilter", () => {const filter: FilterState = [{ type: "string", column: "Name", operator: "=", value: "p95" },];- expect(matchesTriggerFilter({}, { filter, eventActions: [] })).toBe(- false,- );+ expect(+ matchesTriggerFilter(+ { triggerIds: ["trig-test"] },+ { id: "trig-test", filter, eventActions: [] },+ ),+ ).toBe(false);});});@@ -48,8 +54,12 @@ describe("matchesTriggerFilter", () => {it("matches when data.action is in eventActions", () => {expect(matchesTriggerFilter(- { action: "created" },- { filter: [], eventActions: ["created", "updated"] },+ { action: "created", triggerIds: ["trig-test"] },+ {+ id: "trig-test",+ filter: [],+ eventActions: ["created", "updated"],+ },),).toBe(true);});@@ -57,15 +67,22 @@ describe("matchesTriggerFilter", () => {it("rejects when data.action is not in eventActions", () => {expect(matchesTriggerFilter(- { action: "deleted" },- { filter: [], eventActions: ["created", "updated"] },+ { action: "deleted", triggerIds: ["trig-test"] },+ {+ id: "trig-test",+ filter: [],+ eventActions: ["created", "updated"],+ },),).toBe(false);});it("rejects when data has no action and eventActions is non-empty", () => {expect(- matchesTriggerFilter({}, { filter: [], eventActions: ["created"] }),+ matchesTriggerFilter(+ { triggerIds: ["trig-test"] },+ { id: "trig-test", filter: [], eventActions: ["created"] },+ ),).toBe(false);});@@ -73,8 +90,8 @@ describe("matchesTriggerFilter", () => {// No synthetic condition appended, so data without an action still matches.expect(matchesTriggerFilter(- { action: "anything" },- { filter: [], eventActions: [] },+ { action: "anything", triggerIds: ["trig-test"] },+ { id: "trig-test", filter: [], eventActions: [] },),).toBe(true);});@@ -86,26 +103,99 @@ describe("matchesTriggerFilter", () => {expect(matchesTriggerFilter(- { Name: "p95", action: "created" },- { filter, eventActions: ["created"] },+ { Name: "p95", action: "created", triggerIds: ["trig-test"] },+ { id: "trig-test", filter, eventActions: ["created"] },),).toBe(true);// Filter matches but action doesn't → rejectedexpect(matchesTriggerFilter(- { Name: "p95", action: "updated" },- { filter, eventActions: ["created"] },+ { Name: "p95", action: "updated", triggerIds: ["trig-test"] },+ { id: "trig-test", filter, eventActions: ["created"] },),).toBe(false);// Action matches but filter doesn't → rejectedexpect(matchesTriggerFilter(- { Name: "other", action: "created" },- { filter, eventActions: ["created"] },+ { Name: "other", action: "created", triggerIds: ["trig-test"] },+ { id: "trig-test", filter, eventActions: ["created"] },),).toBe(false);});});++ describe("synthetic triggerIds clause (opt-in when data carries the field)", () => {+ it("matches when data.triggerIds contains trigger.id", () => {+ expect(+ matchesTriggerFilter(+ { triggerIds: ["trig-test"] },+ { id: "trig-test", filter: [], eventActions: [] },+ ),+ ).toBe(true);+ });++ it("rejects when data.triggerIds does not contain trigger.id", () => {+ expect(+ matchesTriggerFilter(+ { triggerIds: ["other-trigger"] },+ { id: "trig-test", filter: [], eventActions: [] },+ ),+ ).toBe(false);+ });++ it("rejects when data.triggerIds is an empty array (opted-in mechanism, nothing listed)", () => {+ expect(+ matchesTriggerFilter(+ { triggerIds: [] },+ { id: "trig-test", filter: [], eventActions: [] },+ ),+ ).toBe(false);+ });++ it("skips the triggerIds clause when data has no triggerIds field at all", () => {+ // Regression: prompt-version events do not carry a triggerIds field, so+ // the synthetic clause must not gate them.+ expect(+ matchesTriggerFilter(+ { Name: "my-prompt", action: "created" },+ { id: "trig-prompt", filter: [], eventActions: ["created"] },+ ),+ ).toBe(true);+ });++ it("treats non-array triggerIds the same as missing (clause is skipped)", () => {+ expect(+ matchesTriggerFilter(+ { triggerIds: "trig-test" },+ { id: "trig-test", filter: [], eventActions: [] },+ ),+ ).toBe(true);+ });++ it("ANDs with user-supplied filter: rejects when filter does not match even if triggerIds matches", () => {+ const filter: FilterState = [+ { type: "string", column: "Name", operator: "=", value: "p95" },+ ];+ expect(+ matchesTriggerFilter(+ { Name: "error rate", triggerIds: ["trig-test"] },+ { id: "trig-test", filter, eventActions: [] },+ ),+ ).toBe(false);+ });++ it("ANDs with user-supplied filter: matches when both filter and triggerIds match", () => {+ const filter: FilterState = [+ { type: "string", column: "Name", operator: "=", value: "p95" },+ ];+ expect(+ matchesTriggerFilter(+ { Name: "p95", triggerIds: ["trig-test"] },+ { id: "trig-test", filter, eventActions: [] },+ ),+ ).toBe(true);+ });+ });});diff --git a/packages/shared/src/server/automations.ts b/packages/shared/src/server/automations.tsindex 9659359a0b..3edbd6faf1 100644--- a/packages/shared/src/server/automations.ts+++ b/packages/shared/src/server/automations.ts@@ -1,24 +1,36 @@-import { type TriggerDomain } from "../domain/automations";import { FilterState } from "../types";+import { type TriggerDomain } from "../domain/automations";import { InMemoryFilterService } from "./services/InMemoryFilterService";-/** matchesTriggerFilter returns true when data satisfies a trigger's filter, treating `trigger.eventActions` as a synthetic "action" condition appended to the filter. */+/** matchesTriggerFilter returns true when data satisfies a trigger's filter. Appends a synthetic "action" clause (from eventActions) and, when the event data carries a triggerIds array, a synthetic "triggerIds any-of [id]" clause so the data can opt into a trigger by listing its ID. */export const matchesTriggerFilter = (data: Record<string, unknown>,- trigger: Pick<TriggerDomain, "filter" | "eventActions">,+ trigger: Pick<TriggerDomain, "id" | "filter" | "eventActions">,): boolean => {- const mergedFilter: FilterState =- trigger.eventActions.length > 0- ? [- ...trigger.filter,- {- column: "action",- operator: "any of",- type: "stringOptions",- value: trigger.eventActions,- },- ]- : trigger.filter;+ const synthetic: FilterState = [];++ if (trigger.eventActions.length > 0) {+ synthetic.push({+ column: "action",+ operator: "any of",+ type: "stringOptions",+ value: trigger.eventActions,+ });+ }++ // Data-side opt-in: if the event publishes a triggerIds array, gate by it.+ // Sources that don't publish the field (eg. prompt-version events) skip it.+ if (Array.isArray(data.triggerIds)) {+ synthetic.push({+ column: "triggerIds",+ operator: "any of",+ type: "arrayOptions",+ value: [trigger.id],+ });+ }++ const mergedFilter: FilterState = [...trigger.filter, ...synthetic];+return InMemoryFilterService.evaluateFilter(data,mergedFilter,diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 3c71b22a88..2bc918ff5e 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -69,6 +69,7 @@ export * from "./redis/cloudSpendAlertQueue";export * from "./redis/cloudFreeTierUsageThresholdQueue";export * from "./redis/getQueue";export * from "./redis/webhookQueue";+export * from "./redis/monitorQueue";export * from "./redis/traceDelete";export * from "./redis/projectDelete";export * from "./redis/scoreDelete";@@ -121,7 +122,6 @@ export * from "./redis/codeEvalExecutionQueue";export * from "./services/sessions-ui-table-service";export * from "./services/sessions-ui-table-events-service";export * from "./services/DashboardService";-export * from "../features/monitors/server";export * from "./services/TableViewService";export * from "./services/DefaultViewService";export * from "./services/DefaultEvaluationModelService";diff --git a/packages/shared/src/server/queues.test.ts b/packages/shared/src/server/queues.test.tsnew file mode 100644index 0000000000..906aa4af4e--- /dev/null+++ b/packages/shared/src/server/queues.test.ts@@ -0,0 +1,47 @@+import { describe, it, expect } from "vitest";++import { WebhookOutboundEnvelopeSchema } from "./queues";++const validMonitorEnvelope = {+ id: "exe_01",+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ type: "monitor-alert" as const,+ apiVersion: "v1" as const,+ payload: {+ monitorId: "mon_01",+ projectId: "proj_01",+ permalink: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",+ message: { title: "[ALERT] err", body: "errors > 100" },+ severity: "ALERT" as const,+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ fromTimestamp: new Date("2026-05-18T11:55:30.000Z"),+ toTimestamp: new Date("2026-05-18T12:00:30.000Z"),+ view: "observations" as const,+ filters: [],+ window: "5m" as const,+ },+};++describe("WebhookOutboundEnvelopeSchema (discriminated union)", () => {+ it("parses a monitor-alert envelope", () => {+ const parsed =+ WebhookOutboundEnvelopeSchema.safeParse(validMonitorEnvelope);+ expect(parsed.success).toBe(true);+ if (parsed.success && parsed.data.type === "monitor-alert") {+ expect(parsed.data.payload.severity).toBe("ALERT");+ }+ });++ it("rejects an unknown discriminator", () => {+ expect(+ WebhookOutboundEnvelopeSchema.safeParse({ type: "bogus" }).success,+ ).toBe(false);+ });++ it("rejects a monitor-alert envelope with missing payload", () => {+ const { payload: _unused, ...withoutPayload } = validMonitorEnvelope;+ expect(+ WebhookOutboundEnvelopeSchema.safeParse(withoutPayload).success,+ ).toBe(false);+ });+});diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex 638da55354..b43af3736e 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -11,6 +11,12 @@ import { PromptDomainSchema } from "../domain/prompts";import { ObservationAddToDatasetConfigSchema } from "../features/batchAction/addToDatasetTypes";import { EvalTargetObjectSchema } from "../features/evals/types";import { JobConfigExecutionMode } from "../features/evals/evalConfigBlocking";+import {+ type MonitorQueueEvent,+ MonitorWebhookQueueEventSchema,+} from "../features/monitors/scheduler/types";++export type { MonitorQueueEvent };export const IngestionEvent = z.object({data: z.object({@@ -232,10 +238,10 @@ export const NotificationEventSchema = z.discriminatedUnion("type", [// Future notification types can be added here]);-export const WebhookOutboundEnvelopeSchema = z.object({+export const promptVersionWebhookEnvelopeSchema = z.object({+ type: z.literal("prompt-version"),prompt: PromptDomainSchema,action: EventActionSchema,- type: z.literal("prompt-version"),user: z.object({id: z.string(),@@ -245,6 +251,12 @@ export const WebhookOutboundEnvelopeSchema = z.object({.optional(),});+/** WebhookOutboundEnvelopeSchema is the WebhookInput.payload contract: a discriminated union over `type`. The monitor-alert variant is the unified envelope (queue payload = HTTP outbound body); the prompt-version variant keeps its original dispatch-time wrap. */+export const WebhookOutboundEnvelopeSchema = z.discriminatedUnion("type", [+ promptVersionWebhookEnvelopeSchema,+ MonitorWebhookQueueEventSchema,+]);+export const WebhookInputSchema = z.object({projectId: z.string(),automationId: z.string(),@@ -358,6 +370,7 @@ export enum QueueName {EntityChangeQueue = "entity-change-queue",EventPropagationQueue = "event-propagation-queue",NotificationQueue = "notification-queue",+ MonitorQueue = "monitor-queue",}export enum QueueJobs {@@ -394,6 +407,7 @@ export enum QueueJobs {EntityChangeJob = "entity-change-job",EventPropagationJob = "event-propagation-job",NotificationJob = "notification-job",+ MonitorJob = "monitor-job",}export type TQueueJobTypes = {@@ -575,4 +589,10 @@ export type TQueueJobTypes = {payload: NotificationEventType;name: QueueJobs.NotificationJob;};+ [QueueName.MonitorQueue]: {+ timestamp: Date;+ id: string;+ payload: MonitorQueueEvent;+ name: QueueJobs.MonitorJob;+ };};diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.tsindex 52e44332b5..428a9f4751 100644--- a/packages/shared/src/server/redis/getQueue.ts+++ b/packages/shared/src/server/redis/getQueue.ts@@ -27,6 +27,7 @@ import { EntityChangeQueue } from "./entityChangeQueue";import { DatasetDeleteQueue } from "./datasetDelete";import { EventPropagationQueue } from "./eventPropagationQueue";import { NotificationQueue } from "./notificationQueue";+import { MonitorQueue } from "./monitorQueue";// Sharded queues require a sharding key.// Use the queue class directly, for example IngestionQueue.getInstance({ shardingKey }).@@ -99,6 +100,8 @@ export function getQueue(return EventPropagationQueue.getInstance();case QueueName.NotificationQueue:return NotificationQueue.getInstance();+ case QueueName.MonitorQueue:+ return MonitorQueue.getInstance();default: {const _exhaustiveCheckDefault: never = queueName;throw new Error(`Queue ${queueName} not found`);diff --git a/packages/shared/src/server/redis/monitorQueue.ts b/packages/shared/src/server/redis/monitorQueue.tsnew file mode 100644index 0000000000..1f0070ff5e--- /dev/null+++ b/packages/shared/src/server/redis/monitorQueue.ts@@ -0,0 +1,39 @@+import { Queue } from "bullmq";+import { QueueName, type MonitorQueueEvent } from "../queues";+import {+ createNewRedisInstance,+ redisQueueRetryOptions,+ getQueuePrefix,+} from "./redis";+import { logger } from "../logger";++export class MonitorQueue {+ private static instance: Queue | null = null;++ public static getInstance(): Queue | null {+ if (MonitorQueue.instance) return MonitorQueue.instance;++ const newRedis = createNewRedisInstance({+ enableOfflineQueue: false,+ ...redisQueueRetryOptions,+ });++ MonitorQueue.instance = newRedis+ ? new Queue<MonitorQueueEvent>(QueueName.MonitorQueue, {+ connection: newRedis,+ prefix: getQueuePrefix(QueueName.MonitorQueue),+ defaultJobOptions: {+ removeOnComplete: true,+ removeOnFail: 100,+ attempts: 1,+ },+ })+ : null;++ MonitorQueue.instance?.on("error", (err) => {+ logger.error("MonitorQueue error", err);+ });++ return MonitorQueue.instance;+ }+}diff --git a/packages/shared/src/server/repositories/automation-repository.ts b/packages/shared/src/server/repositories/automation-repository.tsindex ca1a5b92b0..fe7e9c3fad 100644--- a/packages/shared/src/server/repositories/automation-repository.ts+++ b/packages/shared/src/server/repositories/automation-repository.ts@@ -21,7 +21,6 @@ import {} from "../../domain/automations";import { FilterState } from "../../types";import { decryptSecretHeaders, mergeHeaders } from "../utils/headerUtils";-import { matchesTriggerFilter } from "../automations";export const getActionByIdWithSecrets = async ({projectId,@@ -101,7 +100,10 @@ export const getActionById = async ({return actionDomain;};-export type TriggerDomainWithActions = TriggerDomain & { actionIds: string[] };+export type TriggerDomainWithActions = TriggerDomain & {+ actionIds: string[];+ automations: { id: string; actionId: string }[];+};export const getTriggerConfigurations = async ({projectId,@@ -130,6 +132,10 @@ export const getTriggerConfigurations = async ({const triggerConfigurations = triggers.map((trigger) => ({...convertTriggerToDomain(trigger),actionIds: trigger.automations.map((automation) => automation.action.id),+ automations: trigger.automations.map((automation) => ({+ id: automation.id,+ actionId: automation.action.id,+ })),}));return triggerConfigurations;@@ -212,13 +218,11 @@ export const getAutomations = async ({triggerId,actionId,eventSource,- matches,}: {projectId: string;triggerId?: string;actionId?: string;eventSource?: TriggerEventSource;- matches?: Record<string, unknown>;}): Promise<AutomationDomain[]> => {const automations = await prisma.automation.findMany({where: {@@ -243,10 +247,7 @@ export const getAutomations = async ({action: convertActionToDomain(automation.action),}));- if (!matches) return domains;- return domains.filter((automation) =>- matchesTriggerFilter(matches, automation.trigger),- );+ return domains;};export const getConsecutiveAutomationFailures = async ({diff --git a/packages/shared/src/server/services/SlackService.ts b/packages/shared/src/server/services/SlackService.tsindex ae6c9c7814..361dd4499f 100644--- a/packages/shared/src/server/services/SlackService.ts+++ b/packages/shared/src/server/services/SlackService.ts@@ -54,6 +54,7 @@ export interface SlackMessageParams {channelId: string;blocks: any[];text?: string;+ attachments?: unknown[];}export interface SlackMessageResponse {@@ -463,6 +464,7 @@ export class SlackService {const result = await params.client.chat.postMessage({channel: params.channelId,blocks: params.blocks,+ attachments: params.attachments as any,text: params.text || "Langfuse Notification",unfurl_links: false,unfurl_media: false,diff --git a/packages/shared/src/tableDefinitions/index.ts b/packages/shared/src/tableDefinitions/index.tsindex fbaead008e..cdb0a9a381 100644--- a/packages/shared/src/tableDefinitions/index.ts+++ b/packages/shared/src/tableDefinitions/index.ts@@ -1,6 +1,7 @@export * from "./sessionsView";export * from "./types";export * from "./mapDashboards";+export * from "./monitorsTable";export * from "./promptsTable";export * from "./datasetItemsTable";export * from "./mapDatasetRunsTable";diff --git a/packages/shared/src/tableDefinitions/monitorsTable.ts b/packages/shared/src/tableDefinitions/monitorsTable.tsnew file mode 100644index 0000000000..936c0a0c68--- /dev/null+++ b/packages/shared/src/tableDefinitions/monitorsTable.ts@@ -0,0 +1,37 @@+import {+ MonitorSeveritySchema,+ MonitorStatusSchema,+} from "../features/monitors";++import { ColumnDefinition } from "./types";++/** monitorsTableCols defines the columns the monitors list filter sidebar narrows by. */+export const monitorsTableCols: ColumnDefinition[] = [+ {+ name: "Severity",+ id: "severity",+ type: "stringOptions",+ internal: 'm."severity"',+ options: MonitorSeveritySchema.options.map((value) => ({ value })),+ },+ {+ name: "Name",+ id: "name",+ type: "string",+ internal: 'm."name"',+ },+ {+ name: "Status",+ id: "status",+ type: "stringOptions",+ internal: 'm."status"',+ options: MonitorStatusSchema.options.map((value) => ({ value })),+ },+ {+ name: "Tags",+ id: "tags",+ type: "arrayOptions",+ internal: 'm."tags"',+ options: [],+ },+];diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d2c6d5c212..5ec2767ebc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1017,6 +1017,9 @@ importers:posthog-node:specifier: ^5.32.0version: 5.32.0([email protected])+ slackify-markdown:+ specifier: ^5.0.0+ version: 5.0.0stripe:specifier: ^17.4.0version: 17.4.0@@ -10450,6 +10453,10 @@ packages:resolution: {integrity: sha512-kUMbT1oBJCpgrnKoSr0o6wPtvRWT9W9UKvGLwfJYO2WuahZRHOpEyL1ckyMGgMWh0UdpmaoFqKKD29WTomNEGA==}engines: {node: '>=8'}+ resolution: {integrity: sha512-jTWvwjOYGAqS0NNyhTm+9H8S0/tux2anPEwyeIBCayH14jGHIrN70yj4afUYP2zq54aUwEFkASdXytjO/5GA+A==}+ engines: {node: '>=22'}+resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==}engines: {node: '>= 6.0.0', npm: '>= 3.0.0'}@@ -11041,6 +11048,9 @@ packages:resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}+ resolution: {integrity: sha512-b4gokeGId57UVRX/eVKej5gXqGlc9+trkORhFJpu9raqZkZhU0zm8Doi05+HaiBsMEIJowL+2WtQ5ItjsngPXg==}+resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}@@ -22763,6 +22773,18 @@ snapshots:dependencies:unicode-emoji-modifier-base: 1.0.0+ dependencies:+ mdast-util-to-markdown: 2.1.2+ remark-gfm: 4.0.1+ remark-parse: 11.0.0+ remark-stringify: 11.0.0+ unified: 11.0.5+ unist-util-remove: 4.0.0+ unist-util-visit: 5.0.0+ transitivePeerDependencies:+ - supports-color+@@ -23367,6 +23389,12 @@ snapshots:dependencies:'@types/unist': 3.0.3+ dependencies:+ '@types/unist': 3.0.3+ unist-util-is: 6.0.0+ unist-util-visit-parents: 6.0.1+dependencies:'@types/unist': 3.0.3diff --git a/web/src/__tests__/server/automations-trpc.servertest.ts b/web/src/__tests__/server/automations-trpc.servertest.tsindex 9dc6de2213..a3289ad658 100644--- a/web/src/__tests__/server/automations-trpc.servertest.ts+++ b/web/src/__tests__/server/automations-trpc.servertest.ts@@ -292,7 +292,7 @@ describe("automations trpc", () => {expect(response).toEqual([]);});- describe("eventSource + matches narrowing", () => {+ describe("eventSource narrowing", () => {async function createAutomation(opts: {projectId: string;name: string;@@ -363,132 +363,6 @@ describe("automations trpc", () => {});expect(prompt.map((a) => a.name)).toEqual(["prompt-automation"]);});-- it("merges trigger.eventActions into the filter as a synthetic action condition", async () => {- const { project, caller } = await prepare();-- await createAutomation({- projectId: project.id,- name: "created-only-automation",- eventSource: "prompt",- filter: [],- eventActions: ["created"],- });-- const created = await caller.automations.getAutomations({- projectId: project.id,- eventSource: "prompt",- matches: { action: "created" },- });- expect(created.map((a) => a.name)).toEqual(["created-only-automation"]);-- const updated = await caller.automations.getAutomations({- projectId: project.id,- eventSource: "prompt",- matches: { action: "updated" },- });- expect(updated).toEqual([]);- });-- it("returns triggers as-is when matches is omitted", async () => {- const { project, caller } = await prepare();-- await createAutomation({- projectId: project.id,- name: "monitor-automation",- eventSource: "monitor",- filter: [- {- type: "string",- column: "severity",- operator: "=",- value: "warning",- },- ],- });-- const response = await caller.automations.getAutomations({- projectId: project.id,- eventSource: "monitor",- });-- expect(response.map((a) => a.name)).toEqual(["monitor-automation"]);- });-- it.each([- {- label: "severity",- filter: {- type: "string",- column: "severity",- operator: "=",- value: "warning",- },- matching: { severity: "warning" },- nonMatching: { severity: "ok" },- },- {- label: "monitorId",- filter: {- type: "string",- column: "monitorId",- operator: "=",- value: "monitor-123",- },- matching: { monitorId: "monitor-123" },- nonMatching: { monitorId: "monitor-999" },- },- {- label: "monitorName",- filter: {- type: "string",- column: "monitorName",- operator: "contains",- value: "p95",- },- matching: { monitorName: "API p95 latency" },- nonMatching: { monitorName: "error rate" },- },- {- label: "tags",- filter: {- type: "arrayOptions",- column: "tags",- operator: "any of",- value: ["prod", "edge"],- },- matching: { tags: ["prod"] },- nonMatching: { tags: ["staging"] },- },- ])(- "monitor: $label filter matches and rejects",- async ({ filter, matching, nonMatching }) => {- const { project, caller } = await prepare();-- await createAutomation({- projectId: project.id,- name: "filtered-monitor-automation",- eventSource: "monitor",- filter: [filter],- });-- const matched = await caller.automations.getAutomations({- projectId: project.id,- eventSource: "monitor",- matches: matching,- });- expect(matched.map((a) => a.name)).toEqual([- "filtered-monitor-automation",- ]);-- const rejected = await caller.automations.getAutomations({- projectId: project.id,- eventSource: "monitor",- matches: nonMatching,- });- expect(rejected).toEqual([]);- },- );});});diff --git a/web/src/__tests__/server/monitorService.servertest.ts b/web/src/__tests__/server/monitorService.servertest.tsindex 81eae3078f..2b6e819f78 100644--- a/web/src/__tests__/server/monitorService.servertest.ts+++ b/web/src/__tests__/server/monitorService.servertest.ts@@ -1,9 +1,9 @@import { v4 as uuidv4 } from "uuid";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";import {- createOrgProjectAndApiKey,MonitorService,type SessionContext,-} from "@langfuse/shared/src/server";+} from "@langfuse/shared/monitors/server";import { prisma } from "@langfuse/shared/src/db";import { LangfuseNotFoundError } from "@langfuse/shared";@@ -13,12 +13,12 @@ const baseMonitorInput = (projectId: string) => ({filters: [],metric: { measure: "count", aggregation: "count" as const },window: "5m" as const,- thresholdOperator: "gt" as const,+ thresholdOperator: "GT" as const,alertThreshold: 100,warningThreshold: null,noData: { mode: "SILENT" as const },renotify: { mode: "OFF" as const },- status: "active" as const,+ status: "ACTIVE" as const,name: "High error rate",tags: [],});@@ -68,7 +68,7 @@ describe("MonitorService (integration)", () => {// "5m" is a sub-day window → 1-minute cadence.expect(row!.cadenceMs).toBe(60_000n);expect(row!.schedulerBatchId).toBeGreaterThan(0n);- expect(row!.nextRunAt.getTime()).toBeLessThanOrEqual(Date.now());+ expect(row!.nextRunAt).toBeNull();expect(row!.severity).toBe("UNKNOWN");expect(row!.createdBy).toBe(creator.userId);expect(row!.updatedBy).toBe(creator.userId);@@ -142,7 +142,7 @@ describe("MonitorService (integration)", () => {severity: "ALERT",severityChangedAt: new Date(),alertedAt: new Date(),- lastCompletedRunAt: new Date(),+ lastCompletedAt: new Date(),},});@@ -153,10 +153,10 @@ describe("MonitorService (integration)", () => {});expect(updated.name).toBe("Renamed");- expect(updated.severity).toBe("alert");+ expect(updated.severity).toBe("ALERT");expect(updated.severityChangedAt).not.toBeNull();expect(updated.alertedAt).not.toBeNull();- expect(updated.lastCompletedRunAt).not.toBeNull();+ expect(updated.lastCompletedAt).not.toBeNull();const row = await prisma.monitor.findUnique({where: { id: created.id },@@ -173,6 +173,131 @@ describe("MonitorService (integration)", () => {}),).rejects.toBeInstanceOf(LangfuseNotFoundError);});++ it("flips severity to PAUSED when status leaves ACTIVE", async () => {+ const created = await MonitorService.create(+ creator,+ baseMonitorInput(projectId),+ );+ expect(created.severity).toBe("UNKNOWN");++ const updated = await MonitorService.update(editor, {+ ...baseMonitorInput(projectId),+ id: created.id,+ status: "PAUSED",+ });++ expect(updated.severity).toBe("PAUSED");+ expect(updated.severityChangedAt).not.toBeNull();+ });++ it("flips severity to UNKNOWN when status returns to ACTIVE", async () => {+ const created = await MonitorService.create(creator, {+ ...baseMonitorInput(projectId),+ status: "PAUSED",+ });+ expect(created.severity).toBe("PAUSED");++ const updated = await MonitorService.update(editor, {+ ...baseMonitorInput(projectId),+ id: created.id,+ status: "ACTIVE",+ });++ expect(updated.severity).toBe("UNKNOWN");+ expect(updated.severityChangedAt).not.toBeNull();+ });++ it("leaves status and worker-owned severity untouched when status is omitted", async () => {+ const created = await MonitorService.create(+ creator,+ baseMonitorInput(projectId),+ );+ await prisma.monitor.update({+ where: { id: created.id },+ data: { severity: "ALERT", severityChangedAt: new Date() },+ });++ const { status, ...withoutStatus } = baseMonitorInput(projectId);+ const updated = await MonitorService.update(editor, {+ ...withoutStatus,+ id: created.id,+ name: "Renamed",+ });++ expect(updated.name).toBe("Renamed");+ expect(updated.status).toBe("ACTIVE");+ expect(updated.severity).toBe("ALERT");+ });++ it("does not resurrect a paused monitor when status is omitted", async () => {+ const created = await MonitorService.create(creator, {+ ...baseMonitorInput(projectId),+ status: "PAUSED",+ });+ expect(created.severity).toBe("PAUSED");++ const { status, ...withoutStatus } = baseMonitorInput(projectId);+ const updated = await MonitorService.update(editor, {+ ...withoutStatus,+ id: created.id,+ name: "Renamed",+ });++ expect(updated.status).toBe("PAUSED");+ expect(updated.severity).toBe("PAUSED");+ });++ it("preserves worker-owned severity when status does not change", async () => {+ const created = await MonitorService.create(+ creator,+ baseMonitorInput(projectId),+ );+ await prisma.monitor.update({+ where: { id: created.id },+ data: { severity: "ALERT", severityChangedAt: new Date() },+ });++ const updated = await MonitorService.update(editor, {+ ...baseMonitorInput(projectId),+ id: created.id,+ name: "Renamed",+ });++ expect(updated.severity).toBe("ALERT");+ });++ it("clears worker lifecycle stamps when update changes schedulerBatchId", async () => {+ const created = await MonitorService.create(+ creator,+ baseMonitorInput(projectId),+ );++ await prisma.monitor.update({+ where: { id: created.id },+ data: {+ lastPublishedAt: new Date("2026-05-27T11:58:30.000Z"),+ lastCompletedAt: null,+ },+ });++ const updated = await MonitorService.update(editor, {+ ...baseMonitorInput(projectId),+ id: created.id,+ filters: [+ {+ column: "environment" as const,+ operator: "=" as const,+ value: "production",+ type: "string" as const,+ },+ ],+ });++ expect(updated.nextRunAt).toBeNull();+ expect(updated.lastPublishedAt).toBeNull();+ expect(updated.lastCompletedAt).toBeNull();+ });});describe("getById / list / delete", () => {diff --git a/web/src/__tests__/server/monitors.servertest.ts b/web/src/__tests__/server/monitors.servertest.tsindex 26f834ec7b..7070933fad 100644--- a/web/src/__tests__/server/monitors.servertest.ts+++ b/web/src/__tests__/server/monitors.servertest.ts@@ -103,16 +103,30 @@ const validMonitorInput = (projectId: string) => ({filters: [],metric: { measure: "count", aggregation: "count" as const },window: "5m" as const,- thresholdOperator: "gt" as const,+ thresholdOperator: "GT" as const,alertThreshold: 100,warningThreshold: null,noData: { mode: "SILENT" as const },renotify: { mode: "OFF" as const },- status: "active" as const,+ status: "ACTIVE" as const,name: "High error rate",tags: [],+ triggerIds: ["trig_01"],});+const seedMonitors = async (+ caller: ReturnType<typeof appRouter.createCaller>,+ projectId: string,+ count: number,+) => {+ for (let i = 0; i < count; i++) {+ await caller.monitors.create({+ ...validMonitorInput(projectId),+ name: `Seeded monitor ${i + 1}`,+ });+ }+};+describe("monitors trpc", () => {afterAll(async () => {if (orgIds.length > 0) {@@ -140,6 +154,8 @@ describe("monitors trpc", () => {const list = await caller.monitors.all({projectId: project.id,orderBy: null,+ page: 1,+ limit: 50,});expect(list.totalCount).toBe(1);expect(list.monitors.map((m) => m.id)).toContain(created.id);@@ -163,7 +179,7 @@ describe("monitors trpc", () => {projectId: project.id,id: created.id,});- expect(fetched.status).toBe("error-bad-query");+ expect(fetched.status).toBe("ERROR_BAD_QUERY");});});@@ -191,6 +207,8 @@ describe("monitors trpc", () => {const list = await caller.monitors.all({projectId: project.id,orderBy: null,+ page: 1,+ limit: 50,});expect(list.totalCount).toBe(0);});@@ -203,7 +221,7 @@ describe("monitors trpc", () => {await expect(caller.monitors.create({...validMonitorInput(project.id),- thresholdOperator: "gt",+ thresholdOperator: "GT",alertThreshold: 100,warningThreshold: 100,}),@@ -255,7 +273,12 @@ describe("monitors trpc", () => {it("rejects monitors.all when the flag is off", async () => {const { project, caller } = await prepare({ monitorsFlag: false });await expect(- caller.monitors.all({ projectId: project.id, orderBy: null }),+ caller.monitors.all({+ projectId: project.id,+ orderBy: null,+ page: 1,+ limit: 50,+ }),).rejects.toThrow(/monitors/i);});});@@ -295,4 +318,310 @@ describe("monitors trpc", () => {).rejects.toThrow(/not found/i);});});++ describe("list filter sidebar", () => {+ it("filters by severity (any of)", async () => {+ const { project, caller } = await prepare();+ const a = await caller.monitors.create({+ ...validMonitorInput(project.id),+ name: "A",+ });+ await caller.monitors.create({+ ...validMonitorInput(project.id),+ name: "B",+ });+ await prisma.monitor.update({+ where: { id: a.id },+ data: { severity: "ALERT" },+ });++ const result = await caller.monitors.all({+ projectId: project.id,+ orderBy: null,+ page: 1,+ limit: 50,+ filter: [+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["ALERT"],+ },+ ],+ });+ expect(result.totalCount).toBe(1);+ expect(result.monitors.map((m) => m.name)).toEqual(["A"]);+ });++ it("filters by severity (none of PAUSED) hides paused monitors", async () => {+ // Pausing via the service writes severity = PAUSED; a severity-filter+ // with `none of [PAUSED]` then naturally excludes those rows.+ const { project, caller } = await prepare();+ const a = await caller.monitors.create({+ ...validMonitorInput(project.id),+ name: "A",+ });+ await caller.monitors.create({+ ...validMonitorInput(project.id),+ name: "B",+ });+ await caller.monitors.update({+ ...validMonitorInput(project.id),+ id: a.id,+ status: "PAUSED",+ });++ const result = await caller.monitors.all({+ projectId: project.id,+ orderBy: null,+ page: 1,+ limit: 50,+ filter: [+ {+ type: "stringOptions",+ column: "severity",+ operator: "none of",+ value: ["PAUSED"],+ },+ ],+ });+ expect(result.totalCount).toBe(1);+ expect(result.monitors.map((m) => m.name)).toEqual(["B"]);+ });++ it("flipping status ACTIVE → PAUSED via update writes severity = PAUSED", async () => {+ const { project, caller } = await prepare();+ const created = await caller.monitors.create(+ validMonitorInput(project.id),+ );+ expect(created.severity).toBe("UNKNOWN");++ const paused = await caller.monitors.update({+ ...validMonitorInput(project.id),+ id: created.id,+ status: "PAUSED",+ });+ expect(paused.status).toBe("PAUSED");+ expect(paused.severity).toBe("PAUSED");+ });++ it("flipping status PAUSED → ACTIVE via update resets severity to UNKNOWN", async () => {+ const { project, caller } = await prepare();+ const created = await caller.monitors.create({+ ...validMonitorInput(project.id),+ status: "PAUSED",+ });+ expect(created.severity).toBe("PAUSED");++ const resumed = await caller.monitors.update({+ ...validMonitorInput(project.id),+ id: created.id,+ status: "ACTIVE",+ });+ expect(resumed.status).toBe("ACTIVE");+ expect(resumed.severity).toBe("UNKNOWN");+ });++ it("filters by tags (any of)", async () => {+ const { project, caller } = await prepare();+ await caller.monitors.create({+ ...validMonitorInput(project.id),+ name: "Tagged",+ tags: ["prod", "latency"],+ });+ await caller.monitors.create({+ ...validMonitorInput(project.id),+ name: "Untagged",+ });++ const result = await caller.monitors.all({+ projectId: project.id,+ orderBy: null,+ page: 1,+ limit: 50,+ filter: [+ {+ type: "arrayOptions",+ column: "tags",+ operator: "any of",+ value: ["prod"],+ },+ ],+ });+ expect(result.totalCount).toBe(1);+ expect(result.monitors.map((m) => m.name)).toEqual(["Tagged"]);+ });++ it("filterOptions returns distinct tags for the project", async () => {+ const { project, caller } = await prepare();+ await caller.monitors.create({+ ...validMonitorInput(project.id),+ name: "A",+ tags: ["prod", "latency"],+ });+ await caller.monitors.create({+ ...validMonitorInput(project.id),+ name: "B",+ tags: ["prod"],+ });++ const opts = await caller.monitors.getFilterOptions({+ projectId: project.id,+ });+ expect(opts.tags.map((t) => t.value).sort()).toEqual(["latency", "prod"]);+ });+ });++ describe("entitlement limit", () => {+ it("rejects monitors.create when org is at the monitor-count limit", async () => {+ const { project, caller } = await prepare();+ await seedMonitors(caller, project.id, 10);++ await expect(+ caller.monitors.create({+ ...validMonitorInput(project.id),+ name: "Eleventh monitor",+ }),+ ).rejects.toThrow(/monitor-count/i);+ });++ it("counts monitors with non-ACTIVE status toward the limit", async () => {+ const { project, caller } = await prepare();+ await seedMonitors(caller, project.id, 10);++ const seeded = await prisma.monitor.findMany({+ where: { projectId: project.id },+ take: 2,+ });+ await prisma.monitor.update({+ where: { id: seeded[0].id },+ data: { status: "PAUSED" },+ });+ await prisma.monitor.update({+ where: { id: seeded[1].id },+ data: { status: "ERROR_BAD_QUERY" },+ });++ await expect(+ caller.monitors.create({+ ...validMonitorInput(project.id),+ name: "Eleventh monitor",+ }),+ ).rejects.toThrow(/monitor-count/i);+ });++ it("allows monitors.update when at the limit", async () => {+ const { project, caller } = await prepare();+ await seedMonitors(caller, project.id, 10);++ const [first] = await prisma.monitor.findMany({+ where: { projectId: project.id },+ take: 1,+ });++ const updated = await caller.monitors.update({+ ...validMonitorInput(project.id),+ id: first.id,+ name: "Renamed at limit",+ });+ expect(updated.name).toBe("Renamed at limit");+ });++ it("monitors.count is scoped to the caller's org", async () => {+ // Two independent orgs prove the count is org-scoped, not global.+ const orgA = await prepare();+ const orgB = await prepare();++ await seedMonitors(orgA.caller, orgA.project.id, 3);+ await seedMonitors(orgB.caller, orgB.project.id, 2);++ const resultA = await orgA.caller.monitors.count({+ projectId: orgA.project.id,+ });+ const resultB = await orgB.caller.monitors.count({+ projectId: orgB.project.id,+ });++ expect(resultA.count).toBe(3);+ expect(resultB.count).toBe(2);+ });+ });++ describe("hasAny", () => {+ it("returns false on an empty project", async () => {+ const { project, caller } = await prepare();+ const result = await caller.monitors.hasAny({ projectId: project.id });+ expect(result).toBe(false);+ });++ it("returns true once a monitor has been created", async () => {+ const { project, caller } = await prepare();+ await caller.monitors.create(validMonitorInput(project.id));+ const result = await caller.monitors.hasAny({ projectId: project.id });+ expect(result).toBe(true);+ });++ it("is project-scoped, not org-scoped", async () => {+ // Two projects in the same org: a monitor in project A must not flip+ // hasAny for project B, which is the read on which the empty-state+ // splash is gated.+ const {+ org,+ project: projectA,+ session: sessionA,+ caller: callerA,+ } = await prepare();++ const projectB = await prisma.project.create({+ data: {+ name: `sibling-${v4().substring(0, 8)}`,+ orgId: org.id,+ },+ });++ // Re-issue the session with projectB added so the caller has RBAC+ // access to read it; the procedure itself enforces project-scoped+ // RBAC, not org-scoped.+ const sessionUser = sessionA.user!;+ const orgA = sessionUser.organizations[0];+ const sessionAB = {+ ...sessionA,+ user: {+ ...sessionUser,+ organizations: [+ {+ ...orgA,+ projects: [+ ...orgA.projects,+ {+ id: projectB.id,+ role: "ADMIN",+ retentionDays: 30,+ deletedAt: null,+ name: projectB.name,+ metadata: {},+ hasTraces: false,+ createdAt: new Date().toISOString(),+ },+ ],+ },+ ],+ },+ } as Session;+ const ctxAB = createInnerTRPCContext({ session: sessionAB, headers: {} });+ const callerAB = appRouter.createCaller({ ...ctxAB, prisma });++ await callerA.monitors.create(validMonitorInput(projectA.id));++ const hasAnyA = await callerAB.monitors.hasAny({+ projectId: projectA.id,+ });+ const hasAnyB = await callerAB.monitors.hasAny({+ projectId: projectB.id,+ });++ expect(hasAnyA).toBe(true);+ expect(hasAnyB).toBe(false);+ });+ });});diff --git a/web/src/__tests__/server/queryBuilder.servertest.ts b/web/src/__tests__/server/queryBuilder.servertest.tsindex 756b98feea..9fb80b5691 100644--- a/web/src/__tests__/server/queryBuilder.servertest.ts+++ b/web/src/__tests__/server/queryBuilder.servertest.ts@@ -4517,7 +4517,7 @@ describe("getValidAggregationsForMeasureType", () => {expect(valid).toHaveLength(expectedLength);});- it("restricted set contains only count and uniq", () => {+ it("restricted set contains only count and uniq for string measures", () => {expect(getValidAggregationsForMeasureType("string")).toEqual(restricted);});});diff --git a/web/src/components/deleteButton.tsx b/web/src/components/deleteButton.tsxindex c328a1b3bd..daadd13b7a 100644--- a/web/src/components/deleteButton.tsx+++ b/web/src/components/deleteButton.tsx@@ -26,6 +26,9 @@ export type DeleteButtonProps = {deleteConfirmation?: string;icon?: boolean;enabled?: boolean;+ variant?: ButtonProps["variant"];+ title?: string;+ className?: string;};type BaseDeleteButtonProps = Omit<DeleteButtonProps, "itemId"> & {@@ -58,6 +61,8 @@ export function DeleteButton({deleteConfirmation,icon = false,enabled = true,+ title,+ className,captureDeleteOpen,captureDeleteSuccess,entityToDeleteName,@@ -95,6 +100,8 @@ export function DeleteButton({<Buttonvariant={variant ?? (icon ? "outline-solid" : "ghost")}size={icon ? "icon" : "default"}+ title={title}+ className={className}disabled={!hasAccess || !enabled}onClick={(e) => {e.stopPropagation();@@ -292,6 +299,57 @@ export function DeleteDashboardButton(props: DeleteButtonProps) {);}+/** DeleteMonitorButton deletes a monitor through the shared confirm-then-delete pattern. */+export function DeleteMonitorButton(props: DeleteButtonProps) {+ const utils = api.useUtils();+ const {+ itemId,+ projectId,+ scope = "monitors:CUD",+ invalidateFunc = () => utils.monitors.invalidate(),+ } = props;+ const monitorMutation = api.monitors.delete.useMutation({+ onSuccess: () => {+ showSuccessToast({+ title: "Monitor deleted",+ description: "The monitor has been deleted successfully",+ });+ utils.monitors.invalidate();+ },+ });++ const executeDeleteMutation = async (onSuccess: () => void) => {+ try {+ await monitorMutation.mutateAsync({ id: itemId, projectId });+ } catch (error) {+ return Promise.reject(error);+ }+ onSuccess();+ };++ return (+ <DeleteButton+ {...props}+ scope={scope}+ invalidateFunc={invalidateFunc}+ captureDeleteOpen={(capture, isTableAction) =>+ capture("monitors:delete_form_open", {+ source: isTableAction ? "table-single-row" : "monitor",+ })+ }+ captureDeleteSuccess={(capture, isTableAction) =>+ capture("monitors:delete_monitor_button_click", {+ source: isTableAction ? "table-single-row" : "monitor",+ })+ }+ entityToDeleteName="monitor"+ customDeletePrompt="This action cannot be undone. It stops all evaluations and removes the monitor's alert history."+ executeDeleteMutation={executeDeleteMutation}+ isDeleteMutationLoading={monitorMutation.isPending}+ />+ );+}+export function DeleteEvalConfigButton(props: DeleteButtonProps) {const utils = api.useUtils();const {diff --git a/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.ts b/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.tsindex 3f6b83d0a0..4b13b8a7e3 100644--- a/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.ts+++ b/web/src/components/layouts/app-layout/hooks/useFilteredNavigation.ts@@ -83,7 +83,7 @@ export function useFilteredNavigation(const router = useRouter();const entitlements = useEntitlements();const uiCustomization = useUiCustomization();- const { isLangfuseCloud, region } = useLangfuseCloudRegion();+ const { isLangfuseCloud } = useLangfuseCloudRegion();const routerProjectId = router.query.projectId as string | undefined;const routerOrganizationId = router.query.organizationId as@@ -98,9 +98,7 @@ export function useFilteredNavigation(session,enableExperimentalFeatures:session?.environment?.enableExperimentalFeatures ?? false,- cloudAdmin: Boolean(- session?.user?.admin && isLangfuseCloud && region !== "DEV",- ),+ cloudAdmin: Boolean(session?.user?.admin && isLangfuseCloud),entitlements,uiCustomization,isLangfuseCloud,@@ -114,7 +112,6 @@ export function useFilteredNavigation(uiCustomization,router.asPath,isLangfuseCloud,- region,],);diff --git a/web/src/components/layouts/routes.tsx b/web/src/components/layouts/routes.tsxindex b1e0129fba..399118f1cc 100644--- a/web/src/components/layouts/routes.tsx+++ b/web/src/components/layouts/routes.tsx@@ -1,6 +1,7 @@import { type Flag } from "@/src/features/feature-flags/types";import { type ProjectScope } from "@/src/features/rbac/constants/projectAccessRights";import {+ BellRing,Database,LayoutDashboard,LifeBuoy,@@ -125,6 +126,17 @@ export const ROUTES: Route[] = [group: RouteGroup.Observability,section: RouteSection.Main,},+ {+ title: "Monitors",+ pathname: "/project/[projectId]/monitors",+ icon: BellRing,+ projectRbacScopes: ["monitors:read"],+ featureFlag: "monitors",+ show: ({ isLangfuseCloud }) => isLangfuseCloud,+ group: RouteGroup.Observability,+ section: RouteSection.Main,+ label: "Beta",+ },{title: "Prompts",pathname: "/project/[projectId]/prompts",diff --git a/web/src/components/table/FilterToggleButton.tsx b/web/src/components/table/FilterToggleButton.tsxnew file mode 100644index 0000000000..c6cd59dcbb--- /dev/null+++ b/web/src/components/table/FilterToggleButton.tsx@@ -0,0 +1,35 @@+import { PanelLeftClose, PanelLeftOpen } from "lucide-react";++import { useDataTableControls } from "@/src/components/table/data-table-controls";+import { Badge } from "@/src/components/ui/badge";+import { Button } from "@/src/components/ui/button";+import { type FilterState } from "@langfuse/shared";++/** FilterToggleButton shows / hides the table's sidebar filter panel and exposes the active filter count. */+export function FilterToggleButton({+ filterState,+}: {+ filterState?: FilterState;+}) {+ const { open, setOpen } = useDataTableControls();+ return (+ <Button+ variant="outline"+ size="sm"+ onClick={() => setOpen(!open)}+ className="flex h-8 items-center gap-2 text-sm"+ >+ {open ? (+ <PanelLeftClose className="h-4 w-4" />+ ) : (+ <PanelLeftOpen className="h-4 w-4" />+ )}+ <span>{open ? "Hide" : "Show"} filters</span>+ {filterState && filterState.length > 0 && (+ <Badge variant="secondary" className="ml-1 h-5 px-1.5 text-xs">+ {filterState.length}+ </Badge>+ )}+ </Button>+ );+}diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsxindex 0ee4ae3726..9226d2d0fe 100644--- a/web/src/components/table/data-table-controls.tsx+++ b/web/src/components/table/data-table-controls.tsx@@ -67,6 +67,13 @@ export function DataTableControlsProvider({const defaultOpen = isDesktop ? !defaultSidebarCollapsed : false;const [open, setOpen] = useSessionStorage(storageKey, defaultOpen);+ // sessionStorage may carry a previously-open state from a wider viewport.+ // On mobile, force the sidebar closed on each (re)mount so the filter+ // panel doesn't cover the table by default.+ useEffect(() => {+ if (!isDesktop) setOpen(false);+ }, [isDesktop, setOpen]);+return (<ControlsContext.Provider value={{ open, setOpen, tableName }}><div@@ -596,6 +603,8 @@ export function CategoricalFacet({[textFilters, onTextFilterRemove, onChange],);+ const { tableName = "data" } = useContext(ControlsContext) ?? {};+const MAX_VISIBLE_OPTIONS = 12;const visibleOptionValues = Array.from(new Set([...options, ...value.filter((option) => option.length > 0)]),@@ -657,6 +666,7 @@ export function CategoricalFacet({- Traces: tags- Sessions: userIds, tags- Prompts: labels, tags+ - Monitors: tags*/}{onOperatorChange && (<div className="mb-1.5 flex items-center gap-1.5 px-2">@@ -722,8 +732,8 @@ export function CategoricalFacet({<div className="text-muted-foreground py-1 text-xs">{filterKey === "sessionId" ? (<span>- Sessions group traces together, which is useful for tracing- multi-step workflows.{" "}+ Sessions group {tableName} together, which is useful for+ tracing multi-step workflows.{" "}<ahref="https://langfuse.com/docs/observability/features/sessions"target="_blank"@@ -732,14 +742,16 @@ export function CategoricalFacet({>See docs</a>{" "}- to learn how to add sessions to your traces.+ to learn how to add sessions to your {tableName}.</span>) : filterKey === "name" ? (- <span>No trace names found in the given time range.</span>+ <span>+ No {tableName} names found in the given time range.+ </span>) : filterKey === "tags" ? (<span>- Tags let you filter traces according to custom categories- (e.g. feature flags).{" "}+ Tags let you filter {tableName} according to custom+ categories (e.g. feature flags).{" "}<ahref="https://langfuse.com/docs/observability/features/tags"target="_blank"@@ -748,7 +760,7 @@ export function CategoricalFacet({>See docs</a>{" "}- to learn how to add tags to your traces.+ to learn how to add tags to your {tableName}.</span>) : ("No options found"@@ -830,7 +842,7 @@ export function CategoricalFacet({>See docs</a>{" "}- on how to add environments to your traces.+ on how to add environments to your {tableName}.</div>) : null}</>diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsxindex 07ae3b1572..f08cffdb4b 100644--- a/web/src/components/table/data-table-toolbar.tsx+++ b/web/src/components/table/data-table-toolbar.tsx@@ -2,6 +2,7 @@ import { Button } from "@/src/components/ui/button";import React, { type Dispatch, type SetStateAction, useState } from "react";import { Input } from "@/src/components/ui/input";import { DataTableColumnVisibilityFilter } from "@/src/components/table/data-table-column-visibility-filter";+import { FilterToggleButton } from "@/src/components/table/FilterToggleButton";import { PopoverFilterBuilder } from "@/src/features/filters/components/filter-builder";import {type FilterState,@@ -21,13 +22,7 @@ import {DataTableRowHeightSwitch,type RowHeight,} from "@/src/components/table/data-table-row-height-switch";-import {- Search,- ChevronDown,- PanelLeftClose,- PanelLeftOpen,-} from "lucide-react";-import { Badge } from "@/src/components/ui/badge";+import { Search, ChevronDown } from "lucide-react";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { TimeRangePicker } from "@/src/components/date-picker";import {@@ -51,7 +46,6 @@ import {DropdownMenuSubTrigger,DropdownMenuSubContent,} from "@/src/components/ui/dropdown-menu";-import { useDataTableControls } from "@/src/components/table/data-table-controls";import { MultiSelect as MultiSelectFilter } from "@/src/features/filters/components/multi-select";import {DataTableRefreshButton,@@ -213,8 +207,6 @@ export function DataTableToolbar<TData, TValue>({);const capture = usePostHogClientCapture();- const { open: controlsPanelOpen, setOpen: setControlsPanelOpen } =- useDataTableControls();const showSearchTypeSelector = Boolean(searchConfig?.setSearchType && searchConfig.tableAllowsFullTextSearch,);@@ -234,26 +226,7 @@ export function DataTableToolbar<TData, TValue>({return (<div className={cn("grid h-fit w-full gap-0 px-2", className)}><div className="@container my-2 flex flex-wrap items-center gap-2">- {hasNewSidebar && (- <Button- variant="outline"- size="sm"- onClick={() => setControlsPanelOpen(!controlsPanelOpen)}- className="flex h-8 items-center gap-2 text-sm"- >- {controlsPanelOpen ? (- <PanelLeftClose className="h-4 w-4" />- ) : (- <PanelLeftOpen className="h-4 w-4" />- )}- <span>{controlsPanelOpen ? "Hide" : "Show"} filters</span>- {filterState && filterState.length > 0 && (- <Badge variant="secondary" className="ml-1 h-5 px-1.5 text-xs">- {filterState.length}- </Badge>- )}- </Button>- )}+ {hasNewSidebar && <FilterToggleButton filterState={filterState} />}{!!columnVisibility && !!columnOrder && !!viewConfig && (<TableViewPresetsDrawerviewConfig={viewConfig}diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsxindex b19b11971f..8860c29980 100644--- a/web/src/components/table/data-table.tsx+++ b/web/src/components/table/data-table.tsx@@ -334,12 +334,14 @@ export function DataTable<TData extends object, TValue>({const sortingEnabled = columnDef.enableSorting;// if the header id does not translate to a valid css variable name, default to 150px as width// may only happen for dynamic columns, as column names are user defined- const width = isValidCssVariableName({- name: header.id,- includesHyphens: false,- })- ? `calc(var(--header-${header.id}-size) * 1px)`- : 150;+ const width = columnDef.isFlexWidth+ ? "auto"+ : isValidCssVariableName({+ name: header.id,+ includesHyphens: false,+ })+ ? `calc(var(--header-${header.id}-size) * 1px)`+ : 150;return header.column.getIsVisible() ? (<TableHead@@ -350,8 +352,8 @@ export function DataTable<TData extends object, TValue>({getPinningClasses(header.column),)}style={{- width,...getCommonPinningStyles(header.column),+ width,}}onClick={(event) => {event.preventDefault();@@ -608,8 +610,10 @@ function TableBodyComponent<TData>({getPinningClasses(column),)}style={{- width: `calc(var(--col-${column.id}-size) * 1px)`,...getCommonPinningStyles(column),+ width: columnDef.isFlexWidth+ ? "auto"+ : `calc(var(--col-${column.id}-size) * 1px)`,}}><div@@ -679,8 +683,10 @@ function TableBodyComponent<TData>({getPinningClasses(cell.column),)}style={{- width: `calc(var(--col-${cell.column.id}-size) * 1px)`,...getCommonPinningStyles(cell.column),+ width: columnDef.isFlexWidth+ ? "auto"+ : `calc(var(--col-${cell.column.id}-size) * 1px)`,}}><divdiff --git a/web/src/components/table/resizable-filter-layout.tsx b/web/src/components/table/resizable-filter-layout.tsxindex 3c4e952261..d98e26b437 100644--- a/web/src/components/table/resizable-filter-layout.tsx+++ b/web/src/components/table/resizable-filter-layout.tsx@@ -23,9 +23,15 @@ export function ResizableFilterLayout({ children }: PropsWithChildren) {? childrenArray.slice(1): childrenArray;- // On mobile, render children as-is (stacked layout)+ // On mobile, honor the open state so the hide/show toggle works the same as+ // on desktop — collapsed by default, expandable via the controls button.if (!isDesktop) {- return <div className="flex flex-1 overflow-hidden">{children}</div>;+ return (+ <div className="flex flex-1 overflow-hidden">+ {open ? filterSidebar : null}+ {tableContent}+ </div>+ );}const filterDefault = 15;diff --git a/web/src/components/table/types.ts b/web/src/components/table/types.tsindex 6bd1c4c79f..7a507e5577 100644--- a/web/src/components/table/types.ts+++ b/web/src/components/table/types.ts@@ -19,6 +19,7 @@ declare module "@tanstack/react-table" {};isFixedPosition?: boolean; // if true, column cannot be reorderedisPinnedLeft?: boolean; // if true, column will be pinned to left side+ isFlexWidth?: boolean; // if true, column absorbs leftover space (one per table)loadingCell?: React.ReactNode | (() => React.ReactNode);cellPadding?: DataTableCellPadding;}diff --git a/web/src/components/ui/popover.tsx b/web/src/components/ui/popover.tsxindex 7e132455a7..9fed3485ef 100644--- a/web/src/components/ui/popover.tsx+++ b/web/src/components/ui/popover.tsx@@ -30,4 +30,6 @@ PopoverContent.displayName = PopoverPrimitive.Content.displayName;const PopoverClose = PopoverPrimitive.Close;-export { Popover, PopoverTrigger, PopoverContent, PopoverClose };+const PopoverAnchor = PopoverPrimitive.Anchor;++export { Popover, PopoverTrigger, PopoverContent, PopoverClose, PopoverAnchor };diff --git a/web/src/features/automations/components/AutomationDetails.tsx b/web/src/features/automations/components/AutomationDetails.tsxindex 17ea284036..fb50ee55cf 100644--- a/web/src/features/automations/components/AutomationDetails.tsx+++ b/web/src/features/automations/components/AutomationDetails.tsx@@ -8,7 +8,7 @@ import { AutomationFailureBanner } from "./AutomationFailureBanner";import {type AutomationDomain,JobConfigState,- type TriggerEventSource,+ TriggerEventSource,} from "@langfuse/shared";import {TabsBar,@@ -137,37 +137,45 @@ export const AutomationDetails: React.FC<AutomationDetailsProps> = ({automationId={automationId}/>- <TabsBar- value={activeTab}- onValueChange={setActiveTab}- className="w-full"- >- <TabsBarList>- <TabsBarTrigger value="executions">- Execution History- </TabsBarTrigger>- <TabsBarTrigger value="configuration">- Configuration- </TabsBarTrigger>- </TabsBarList>+ {automation.trigger.eventSource === TriggerEventSource.Monitor ? (+ <AutomationForm+ projectId={projectId}+ automation={automationForForm}+ isEditing={false}+ />+ ) : (+ <TabsBar+ value={activeTab}+ onValueChange={setActiveTab}+ className="w-full"+ >+ <TabsBarList>+ <TabsBarTrigger value="executions">+ Execution History+ </TabsBarTrigger>+ <TabsBarTrigger value="configuration">+ Configuration+ </TabsBarTrigger>+ </TabsBarList>- <TabsBarContent value="executions" className="mt-6">- <SettingsTableCard>- <AutomationExecutionsTable+ <TabsBarContent value="executions" className="mt-6">+ <SettingsTableCard>+ <AutomationExecutionsTable+ projectId={projectId}+ automationId={automationId}+ />+ </SettingsTableCard>+ </TabsBarContent>++ <TabsBarContent value="configuration" className="mt-6">+ <AutomationFormprojectId={projectId}- automationId={automationId}+ automation={automationForForm}+ isEditing={false}/>- </SettingsTableCard>- </TabsBarContent>-- <TabsBarContent value="configuration" className="mt-6">- <AutomationForm- projectId={projectId}- automation={automationForForm}- isEditing={false}- />- </TabsBarContent>- </TabsBar>+ </TabsBarContent>+ </TabsBar>+ )}</>)}</div>diff --git a/web/src/features/automations/components/actions/BaseActionHandler.ts b/web/src/features/automations/components/actions/BaseActionHandler.tsindex 6ef26d3139..15c976d7ef 100644--- a/web/src/features/automations/components/actions/BaseActionHandler.ts+++ b/web/src/features/automations/components/actions/BaseActionHandler.ts@@ -4,6 +4,7 @@ import {type ActionDomain,type ActionType,type AutomationDomain,+ type TriggerEventSource,} from "@langfuse/shared";export interface BaseActionHandler<@@ -12,7 +13,10 @@ export interface BaseActionHandler<actionType: ActionType;// Get default values for this action type- getDefaultValues(automation?: AutomationDomain): TFormData;+ getDefaultValues(+ automation?: AutomationDomain,+ eventSource?: TriggerEventSource,+ ): TFormData;// Validate the form data for this action typevalidateFormData(formData: TFormData): {diff --git a/web/src/features/automations/components/actions/WebhookActionHandler.clienttest.ts b/web/src/features/automations/components/actions/WebhookActionHandler.clienttest.tsnew file mode 100644index 0000000000..bab9cbe01d--- /dev/null+++ b/web/src/features/automations/components/actions/WebhookActionHandler.clienttest.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from "vitest";++import { type AutomationDomain, TriggerEventSource } from "@langfuse/shared";+import { WebhookActionHandler } from "./WebhookActionHandler";++const handler = new WebhookActionHandler();++const webhookAutomation = (+ apiVersion: Record<string, "v1">,+): AutomationDomain =>+ ({+ id: "automation-1",+ name: "test",+ trigger: {+ id: "trigger-1",+ eventSource: TriggerEventSource.Monitor,+ eventActions: ["created"],+ filter: [],+ status: "ACTIVE",+ },+ action: {+ id: "action-1",+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: "https://example.com",+ apiVersion,+ displaySecretKey: "sk_...abcd",+ },+ },+ }) as unknown as AutomationDomain;++describe("WebhookActionHandler.getDefaultValues", () => {+ it("monitor-source new automation: seeds apiVersion { monitor: v1 }", () => {+ expect(+ handler.getDefaultValues(undefined, TriggerEventSource.Monitor).webhook+ .apiVersion,+ ).toEqual({ monitor: "v1" });+ });++ it("prompt-source new automation: seeds apiVersion { prompt: v1 }", () => {+ expect(+ handler.getDefaultValues(undefined, TriggerEventSource.Prompt).webhook+ .apiVersion,+ ).toEqual({ prompt: "v1" });+ });++ it("no eventSource: seeds apiVersion { prompt: v1 }", () => {+ expect(handler.getDefaultValues(undefined).webhook.apiVersion).toEqual({+ prompt: "v1",+ });+ });++ it("editing existing config: stored apiVersion wins over eventSource", () => {+ expect(+ handler.getDefaultValues(+ webhookAutomation({ monitor: "v1" }),+ TriggerEventSource.Prompt,+ ).webhook.apiVersion,+ ).toEqual({ monitor: "v1" });+ });+});diff --git a/web/src/features/automations/components/actions/WebhookActionHandler.tsx b/web/src/features/automations/components/actions/WebhookActionHandler.tsxindex f71e283460..de291a6146 100644--- a/web/src/features/automations/components/actions/WebhookActionHandler.tsx+++ b/web/src/features/automations/components/actions/WebhookActionHandler.tsx@@ -6,6 +6,7 @@ import {type AutomationDomain,AvailableWebhookApiSchema,WebhookDefaultHeaders,+ TriggerEventSource,type ActionCreate,type ActionDomain,} from "@langfuse/shared";@@ -72,9 +73,15 @@ export class WebhookActionHandler implements BaseActionHandler<WebhookActionFormreturn [];}- getDefaultValues(automation?: AutomationDomain): WebhookActionFormData {+ getDefaultValues(+ automation?: AutomationDomain,+ eventSource?: TriggerEventSource,+ ): WebhookActionFormData {// Extract apiVersion from existing config- let apiVersion = { prompt: "v1" } as const;+ let apiVersion: z.infer<typeof AvailableWebhookApiSchema> =+ eventSource === TriggerEventSource.Monitor+ ? { monitor: "v1" }+ : { prompt: "v1" };if (automation?.action?.type === "WEBHOOK" &&automation?.action?.config &&diff --git a/web/src/features/automations/components/automationForm.clienttest.tsx b/web/src/features/automations/components/automationForm.clienttest.tsxnew file mode 100644index 0000000000..3e78cac289--- /dev/null+++ b/web/src/features/automations/components/automationForm.clienttest.tsx@@ -0,0 +1,99 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { TriggerEventSource } from "@langfuse/shared";++const createAutomationMutateAsync = vi.fn().mockResolvedValue({+ automation: { id: "auto-1" },+ webhookSecret: "secret",+});++vi.mock("@/src/utils/api", () => ({+ api: {+ useUtils: () => ({ automations: { invalidate: vi.fn() } }),+ automations: {+ createAutomation: {+ useMutation: () => ({ mutateAsync: createAutomationMutateAsync }),+ },+ updateAutomation: {+ useMutation: () => ({ mutateAsync: vi.fn() }),+ },+ regenerateWebhookSecret: {+ useMutation: () => ({ mutateAsync: vi.fn() }),+ },+ },+ slack: {+ getIntegrationStatus: {+ useQuery: () => ({ data: undefined }),+ },+ },+ },+}));++vi.mock("next/router", () => ({+ useRouter: () => ({ asPath: "/", push: vi.fn() }),+}));++vi.mock("@/src/features/rbac/utils/checkProjectAccess", () => ({+ useHasProjectAccess: () => true,+}));++vi.mock("@/src/features/feature-flags/hooks/useIsFeatureEnabled", () => ({+ default: () => true,+}));++import { AutomationForm } from "./automationForm";++describe("AutomationForm handleActionTypeChange", () => {+ beforeAll(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ Element.prototype.scrollIntoView = vi.fn();+ Element.prototype.hasPointerCapture = vi.fn();+ Element.prototype.releasePointerCapture = vi.fn();+ });++ beforeEach(() => {+ createAutomationMutateAsync.mockClear();+ });++ it("monitor-source trigger: switching action type away and back to WEBHOOK keeps apiVersion monitor", async () => {+ render(+ <AutomationForm+ projectId="p1"+ isEditing={true}+ prefill={{+ eventSource: TriggerEventSource.Monitor,+ actionType: "WEBHOOK",+ }}+ />,+ );++ // comboboxes: [0] eventSource, [1] actionType, [2] webhook apiVersion.+ fireEvent.click(screen.getAllByRole("combobox")[1]);+ fireEvent.click(await screen.findByRole("option", { name: "Slack" }));++ fireEvent.click(screen.getAllByRole("combobox")[1]);+ fireEvent.click(await screen.findByRole("option", { name: "Webhook" }));++ fireEvent.change(screen.getByPlaceholderText(/automation name/i), {+ target: { value: "My automation" },+ });+ fireEvent.change(screen.getByPlaceholderText(/https/i), {+ target: { value: "https://example.com/hook" },+ });++ fireEvent.click(screen.getByRole("button", { name: /save automation/i }));++ await waitFor(() => {+ expect(createAutomationMutateAsync).toHaveBeenCalledTimes(1);+ });++ const payload = createAutomationMutateAsync.mock.calls[0][0];+ expect(payload.actionConfig.apiVersion).toEqual({ monitor: "v1" });+ });+});diff --git a/web/src/features/automations/components/automationForm.tsx b/web/src/features/automations/components/automationForm.tsxindex 2f3bb5d772..5fd6fed96b 100644--- a/web/src/features/automations/components/automationForm.tsx+++ b/web/src/features/automations/components/automationForm.tsx@@ -1,4 +1,4 @@-import React, { useState, useEffect } from "react";+import React from "react";import {Card,CardContent,@@ -19,7 +19,7 @@ import { Separator } from "@/src/components/ui/separator";import { Switch } from "@/src/components/ui/switch";import { useRouter } from "next/router";import { z } from "zod";-import { useForm } from "react-hook-form";+import { type Control, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import {Form,@@ -34,17 +34,25 @@ import { api } from "@/src/utils/api";import {type AutomationDomain,type ActionTypes,+ ActionTypeSchema,+ type FilterState,type JobConfigState,+ TriggerEventSource,+ TriggerEventSourceSchema,webhookActionFilterOptions,} from "@langfuse/shared";import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";import { DeleteAutomationButton } from "./DeleteAutomationButton";+import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { ActionHandlerRegistry } from "./actions";import { webhookSchema } from "./actions/WebhookActionForm";import { MultiSelect } from "@/src/features/filters/components/multi-select";+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";+import Link from "next/link";+import { Info } from "lucide-react";// Define Slack action schemaconst slackSchema = z.object({@@ -61,39 +69,276 @@ const githubDispatchSchema = z.object({displayGitHubToken: z.string().optional(),});-// Define the TriggerEventSource enum directly in this file to match the backend-enum TriggerEventSource {- Prompt = "prompt",-}+/** promptEventActionDefaults is the default eventAction set for a fresh prompt-source automation. */+const promptEventActionDefaults: string[] = ["created", "updated", "deleted"];++/** CreateAutomationPrefill pre-fills the create-automation form from a deep link. */+export type CreateAutomationPrefill = {+ eventSource?: TriggerEventSource;+ filter?: FilterState;+ actionType?: ActionTypes;+ /** redirectUrl is a same-origin path the caller wants to return to after the automation is saved. */+ redirectUrl?: string;+};++/** isSameOriginRedirect resolves a candidate URL against the current Next-rendered origin and accepts it only if the resulting origin still matches; falls back to path-only validation during SSR where `window` is absent. */+const isSameOriginRedirect = (url: string): boolean => {+ if (url.startsWith("//")) return false;+ if (typeof window === "undefined") {+ // Without window we cannot resolve absolute URLs; trust relative paths only.+ return url.startsWith("/") && !url.includes("\\");+ }+ try {+ const resolved = new URL(url, window.location.origin);+ return resolved.origin === window.location.origin;+ } catch {+ return false;+ }+};++/** safeRedirectPath defends against open-redirect by requiring the URL to resolve back to the current origin. */+const safeRedirectPath = z.string().refine(isSameOriginRedirect, {+ message: "redirectUrl must resolve to the same origin",+});++/** createAutomationPrefillSchema validates a decoded prefill payload. */+const createAutomationPrefillSchema = z.object({+ eventSource: TriggerEventSourceSchema.optional(),+ filter: z.array(z.any()).optional(),+ actionType: ActionTypeSchema.optional(),+ redirectUrl: safeRedirectPath.optional(),+});++/** parseCreateAutomationPrefill decodes a base64url JSON blob into a typed prefill; returns {} when absent or malformed. */+export const parseCreateAutomationPrefill = (+ raw: string | null | undefined,+): CreateAutomationPrefill => {+ if (!raw) return {};+ try {+ const padded = raw.replace(/-/g, "+").replace(/_/g, "/");+ const binary = atob(padded);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);+ const decoded = new TextDecoder().decode(bytes);+ const result = createAutomationPrefillSchema.safeParse(JSON.parse(decoded));+ return result.success ? (result.data as CreateAutomationPrefill) : {};+ } catch {+ return {};+ }+};++/** serializeCreateAutomationPrefill encodes a typed prefill as a base64url JSON blob for a single URL query param, UTF-8-safe so non-ASCII tags don't throw at btoa. */+const serializeCreateAutomationPrefill = (+ prefill: CreateAutomationPrefill,+): string => {+ const bytes = new TextEncoder().encode(JSON.stringify(prefill));+ let binary = "";+ for (let i = 0; i < bytes.length; i++)+ binary += String.fromCharCode(bytes[i]);+ return btoa(binary)+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=+$/, "");+};++/** automationCreateHref builds the deep-link to the automations create form, prefilling eventSource as Monitor and (optionally) the chosen actionType + a same-origin redirectUrl to return to after save. */+export const automationCreateHref = (+ projectId: string,+ actionType?: ActionTypes,+ redirectUrl?: string,+): string => {+ const prefill = serializeCreateAutomationPrefill({+ eventSource: TriggerEventSource.Monitor,+ ...(actionType ? { actionType } : {}),+ ...(redirectUrl ? { redirectUrl } : {}),+ });+ const params = new URLSearchParams({ view: "create", prefill });+ return `/project/${projectId}/automations?${params.toString()}`;+};// Define schemas for form validationconst baseFormSchema = z.object({name: z.string().min(1, "Name is required").max(100),eventSource: z.string().min(1, "Event source is required"),- eventAction: z- .array(z.string())- .min(1, "At least one event action is required"),+ eventAction: z.array(z.string()),status: z.enum(["ACTIVE", "INACTIVE"]),filter: z.array(z.any()).optional(),});-const formSchema = z.discriminatedUnion("actionType", [- baseFormSchema.extend({- actionType: z.literal("WEBHOOK"),- webhook: webhookSchema,- }),- baseFormSchema.extend({- actionType: z.literal("SLACK"),- slack: slackSchema,- }),- baseFormSchema.extend({- actionType: z.literal("GITHUB_DISPATCH"),- githubDispatch: githubDispatchSchema,- }),-]);+const formSchema = z+ .discriminatedUnion("actionType", [+ baseFormSchema.extend({+ actionType: z.literal("WEBHOOK"),+ webhook: webhookSchema,+ }),+ baseFormSchema.extend({+ actionType: z.literal("SLACK"),+ slack: slackSchema,+ }),+ baseFormSchema.extend({+ actionType: z.literal("GITHUB_DISPATCH"),+ githubDispatch: githubDispatchSchema,+ }),+ ])+ .superRefine((data, ctx) => {+ // Prompt-source triggers require at least one event action; monitor-source triggers don't use this field.+ if (+ data.eventSource === TriggerEventSource.Prompt &&+ data.eventAction.length === 0+ ) {+ ctx.addIssue({+ code: "custom",+ path: ["eventAction"],+ message: "At least one event action is required",+ });+ }+ });type FormValues = z.infer<typeof formSchema>;+/** EventSourceField renders the trigger source picker and routes changes through onSourceChange so the parent can reset dependent fields. */+const EventSourceField = ({+ control,+ onSourceChange,+ disabled,+}: {+ control: Control<FormValues>;+ onSourceChange: (value: TriggerEventSource) => void;+ disabled: boolean;+}) => {+ const isMonitorsEnabled = useIsFeatureEnabled("monitors");+ return (+ <FormField+ control={control}+ name="eventSource"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Event Source</FormLabel>+ <Select+ onValueChange={(value) =>+ onSourceChange(value as TriggerEventSource)+ }+ value={field.value}+ disabled={disabled}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue placeholder="Select an event source" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ <SelectItem value={TriggerEventSource.Prompt}>Prompt</SelectItem>+ {(isMonitorsEnabled ||+ field.value === TriggerEventSource.Monitor) && (+ <SelectItem value={TriggerEventSource.Monitor}>+ Monitor+ </SelectItem>+ )}+ <SelectItem disabled={true} value="planned">+ More coming soon...+ </SelectItem>+ </SelectContent>+ </Select>+ <FormDescription>+ The event that triggers this automation.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ );+};++/** PromptTriggerFields renders the eventAction picker and inline filter builder for prompt-source automations. */+const PromptTriggerFields = ({+ control,+ disabled,+}: {+ control: Control<FormValues>;+ disabled: boolean;+}) => (+ <>+ <FormField+ control={control}+ name="eventAction"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Event Action</FormLabel>+ <FormControl>+ <MultiSelect+ title="Event Actions"+ label="Actions"+ values={field.value}+ onValueChange={field.onChange}+ options={[+ {+ value: "created",+ description: "Whenever a new prompt version is created",+ },+ {+ value: "updated",+ description:+ "Whenever tags or labels on a prompt version are updated",+ },+ {+ value: "deleted",+ description: "Whenever a prompt version is deleted",+ },+ ]}+ className="my-0 w-auto overflow-hidden"+ disabled={disabled}+ labelTruncateCutOff={4}+ />+ </FormControl>+ <FormDescription>+ The actions on the event source that trigger this automation.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={control}+ name="filter"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Filter</FormLabel>+ <FormControl>+ <InlineFilterBuilder+ columns={webhookActionFilterOptions()}+ filterState={field.value || []}+ onChange={field.onChange}+ disabled={disabled}+ />+ </FormControl>+ <FormDescription>+ Add conditions to narrow down when this trigger fires.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </>+);++/** MonitorTriggerFields renders an info card explaining that monitors connect to this automation via the create-monitor page. */+const MonitorTriggerFields = ({ projectId }: { projectId: string }) => (+ <Alert>+ <Info className="h-4 w-4" />+ <AlertTitle>How Monitors Connect</AlertTitle>+ <AlertDescription>+ Add this automation to a monitor from the{" "}+ <Link+ href={`/project/${projectId}/monitors/new`}+ className="text-primary underline underline-offset-2"+ >+ create monitors page+ </Link>+ .+ </AlertDescription>+ </Alert>+);+interface AutomationFormProps {projectId: string;onSuccess?: (@@ -102,8 +347,11 @@ interface AutomationFormProps {actionType?: "WEBHOOK" | "GITHUB_DISPATCH",) => void;onCancel?: () => void;+ /** automation is the existing record being edited. Mutually exclusive with prefill in practice. */automation?: AutomationDomain;isEditing?: boolean;+ /** prefill is the pre-parsed deep-link payload (decoded by the caller). Ignored when automation is set. */+ prefill?: CreateAutomationPrefill | null;}export const AutomationForm = ({@@ -112,9 +360,9 @@ export const AutomationForm = ({onCancel,automation,isEditing = false,+ prefill,}: AutomationFormProps) => {const router = useRouter();- const [activeTab, setActiveTab] = useState<string>("webhook");const hasAccess = useHasProjectAccess({projectId,scope: "automations:CUD",@@ -140,42 +388,55 @@ export const AutomationForm = ({},);+ // Prefill is empty when editing an existing automation; otherwise the caller-decoded payload is used directly.+ const parsedPrefill: CreateAutomationPrefill = automation+ ? {}+ : (prefill ?? {});+// Get the action type for the form when editing- const getActionType = () => {- if (automation?.action?.type) {- return automation.action.type as ActionTypes;- }- return "WEBHOOK";- };+ const getActionType = (): ActionTypes =>+ (automation?.action.type as ActionTypes | undefined) ??+ parsedPrefill.actionType ??+ "WEBHOOK";// Get default values based on action typeconst getDefaultValues = (): FormValues => {const actionType = getActionType();- const today = new Date().toLocaleString("sv").split("T")[0]; // YYYY-MM-DD++ const resolvedEventSource: TriggerEventSource =+ automation?.trigger.eventSource ??+ parsedPrefill.eventSource ??+ TriggerEventSource.Prompt;++ const resolvedEventAction: string[] =+ automation?.trigger.eventActions ??+ (resolvedEventSource === TriggerEventSource.Monitor+ ? []+ : promptEventActionDefaults);++ const resolvedFilter: FilterState =+ automation?.trigger.filter ?? parsedPrefill.filter ?? [];const baseValues = {- name:- isEditing && automation ? automation.name : `${actionType} ${today}`,- eventSource: automation- ? automation.trigger.eventSource- : TriggerEventSource.Prompt,- eventAction: automation- ? automation.trigger.eventActions- : ["created", "updated", "deleted"],+ name: isEditing && automation ? automation.name : "",+ eventSource: resolvedEventSource,+ eventAction: resolvedEventAction,status: (isEditing && automation? automation.trigger.status: "ACTIVE") as "ACTIVE" | "INACTIVE",- filter: automation ? automation.trigger.filter || [] : [],+ filter: resolvedFilter,};if (actionType === "WEBHOOK") {// Use action handler to get default values with proper typingconst handler = ActionHandlerRegistry.getHandler("WEBHOOK");- const webhookDefaults = handler.getDefaultValues(automation);+ const webhookDefaults = handler.getDefaultValues(+ automation,+ resolvedEventSource,+ );return {...baseValues,actionType: "WEBHOOK" as const,- eventSource: TriggerEventSource.Prompt,webhook: {url: webhookDefaults.webhook.url || "",headers: webhookDefaults.webhook.headers || [],@@ -191,7 +452,6 @@ export const AutomationForm = ({return {...baseValues,actionType: "SLACK" as const,- eventSource: TriggerEventSource.Prompt,slack: {channelId: slackDefaults.slack.channelId || "",channelName: slackDefaults.slack.channelName || "",@@ -205,7 +465,6 @@ export const AutomationForm = ({return {...baseValues,actionType: "GITHUB_DISPATCH" as const,- eventSource: TriggerEventSource.Prompt,githubDispatch: {url: githubDefaults.githubDispatch.url || "",eventType: githubDefaults.githubDispatch.eventType || "",@@ -225,13 +484,6 @@ export const AutomationForm = ({defaultValues: getDefaultValues(),});- // Set the active tab based on the action type- useEffect(() => {- if (isEditing && automation?.action?.type) {- setActiveTab(automation.action.type.toLowerCase());- }- }, [isEditing, automation]);-// Handle form submissionconst onSubmit = async (data: FormValues) => {if (!hasAccess) {@@ -308,12 +560,14 @@ export const AutomationForm = ({// Update required fields based on action typeconst handleActionTypeChange = (value: ActionTypes) => {- setActiveTab(value.toLowerCase());form.setValue("actionType", value);if (value === "WEBHOOK") {const handler = ActionHandlerRegistry.getHandler("WEBHOOK");- const defaultValues = handler.getDefaultValues();+ const defaultValues = handler.getDefaultValues(+ undefined,+ form.getValues("eventSource") as TriggerEventSource,+ );form.setValue("webhook", defaultValues.webhook);} else if (value === "SLACK") {const handler = ActionHandlerRegistry.getHandler("SLACK");@@ -324,12 +578,6 @@ export const AutomationForm = ({const defaultValues = handler.getDefaultValues();form.setValue("githubDispatch", defaultValues.githubDispatch);}-- // If we are creating a new automation, update the default name- if (!automation) {- const today = new Date().toLocaleString("sv").split("T")[0];- form.setValue("name", `${value} ${today}`);- }};// Handle cancel button click@@ -354,9 +602,23 @@ export const AutomationForm = ({const currentActionHandler = getCurrentActionHandler();+ /** watchedEventSource drives the conditional trigger UI (prompt → filter builder, monitor → tag picker). */+ const watchedEventSource = form.watch("eventSource") as TriggerEventSource;++ /** handleEventSourceChange resets eventAction + filter to defaults appropriate for the picked source. */+ const handleEventSourceChange = (value: TriggerEventSource) => {+ form.setValue("eventSource", value);+ if (value === TriggerEventSource.Monitor) {+ form.setValue("eventAction", []);+ } else {+ form.setValue("eventAction", promptEventActionDefaults);+ }+ form.setValue("filter", []);+ };+return (<Form {...form}>- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 pb-6">{isEditing && (<div className="mb-6 flex items-center gap-4"><div className="flex-1">@@ -370,6 +632,7 @@ export const AutomationForm = ({<Inputplaceholder="Automation name"{...field}+ autoFocus={!automation}disabled={!hasAccess || !isEditing}className="border-border rounded-none border-0 border-b bg-transparent px-0 text-2xl font-semibold focus-visible:ring-0 focus-visible:ring-offset-0"/>@@ -409,104 +672,19 @@ export const AutomationForm = ({</CardDescription></CardHeader><CardContent className="space-y-4">- <FormField- control={form.control}- name="eventSource"- render={({ field }) => (- <FormItem>- <FormLabel>Event Source</FormLabel>- <Select- onValueChange={field.onChange}- value={field.value}- disabled={!hasAccess || !isEditing}- >- <FormControl>- <SelectTrigger>- <SelectValue placeholder="Select an event source" />- </SelectTrigger>- </FormControl>- <SelectContent>- <SelectItem value={TriggerEventSource.Prompt}>- Prompt- </SelectItem>- <SelectItem disabled={true} value="planned">- More coming soon...- </SelectItem>- </SelectContent>- </Select>- <FormDescription>- The event that triggers this automation.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="eventAction"- render={({ field }) => (- <FormItem>- <FormLabel>Event Action</FormLabel>- <FormControl>- <MultiSelect- title="Event Actions"- label="Actions"- values={field.value}- onValueChange={field.onChange}- options={[- {- value: "created",- description:- "Whenever a new prompt version is created",- },- {- value: "updated",- description:- "Whenever tags or labels on a prompt version are updated",- },- {- value: "deleted",- description: "Whenever a prompt version is deleted",- },- ]}- className="my-0 w-auto overflow-hidden"- disabled={!hasAccess || !isEditing}- labelTruncateCutOff={4}- />- </FormControl>- <FormDescription>- The actions on the event source that trigger this- automation.- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField+ <EventSourceFieldcontrol={form.control}- name="filter"- render={({ field }) => (- <FormItem>- <FormLabel>Filter</FormLabel>- <FormControl>- <InlineFilterBuilder- columns={webhookActionFilterOptions()}- filterState={field.value || []}- onChange={field.onChange}- disabled={- activeTab === "annotation_queue" ||- !hasAccess ||- !isEditing- }- />- </FormControl>- <FormDescription>- Add conditions to narrow down when this trigger fires.- </FormDescription>- <FormMessage />- </FormItem>- )}+ onSourceChange={handleEventSourceChange}+ disabled={!hasAccess || !isEditing}/>+ {watchedEventSource === TriggerEventSource.Monitor ? (+ <MonitorTriggerFields projectId={projectId} />+ ) : (+ <PromptTriggerFields+ control={form.control}+ disabled={!hasAccess || !isEditing}+ />+ )}</CardContent></Card>diff --git a/web/src/features/automations/components/automations.tsx b/web/src/features/automations/components/automations.tsxindex d6aaf2c61c..36b4b17452 100644--- a/web/src/features/automations/components/automations.tsx+++ b/web/src/features/automations/components/automations.tsx@@ -1,7 +1,10 @@import { useRouter } from "next/router";import { AutomationSidebar } from "@/src/features/automations/components/AutomationSidebar";import { AutomationDetails } from "@/src/features/automations/components/AutomationDetails";-import { AutomationForm } from "@/src/features/automations/components/automationForm";+import {+ AutomationForm,+ parseCreateAutomationPrefill,+} from "@/src/features/automations/components/automationForm";import { WebhookSecretRender } from "@/src/features/automations/components/WebhookSecretRender";import { Button } from "@/src/components/ui/button";import { Plus } from "lucide-react";@@ -28,15 +31,26 @@ export default function AutomationsPage() {const projectId = router.query.projectId as string;const [webhookSecret, setWebhookSecret] = useState<string | null>(null);const [showSecretDialog, setShowSecretDialog] = useState(false);+ /** pendingAutomationId is the id to select once the webhook-secret dialog dismisses, when no prefill.redirectUrl is set. */+ const [pendingAutomationId, setPendingAutomationId] = useState<string | null>(+ null,+ );const [urlParams, setUrlParams] = useQueryParams({view: withDefault(StringParam, "list"),automationId: StringParam,tab: withDefault(StringParam, "executions"),+ prefill: StringParam,});const { view, automationId } = urlParams;+ /** parsedPrefill decodes the deep-link blob once; the form receives the parsed object and the create-success path reads its redirectUrl. */+ const parsedPrefill = useMemo(+ () => parseCreateAutomationPrefill(urlParams.prefill),+ [urlParams.prefill],+ );+const selectedAutomation = useMemo(() => (automationId ? { automationId } : undefined),[automationId],@@ -80,6 +94,10 @@ export default function AutomationsPage() {if (updates.view !== undefined) {params.set("view", updates.view);+ // The prefill blob is scoped to view=create; drop it on any other view.+ if (updates.view !== "create") {+ params.delete("prefill");+ }}if (updates.automationId !== undefined) {if (updates.automationId) {@@ -140,6 +158,7 @@ export default function AutomationsPage() {view: "create",automationId: undefined,tab: urlParams.tab,+ prefill: undefined,});};@@ -151,11 +170,40 @@ export default function AutomationsPage() {});};- const handleReturnToList = () => {- // Use router.replace to avoid creating history entry when canceling+ /** finishFlow returns the user to parsedPrefill.redirectUrl when present; otherwise invokes the caller-supplied fallback, defaulting to the automations list view with no selection. */+ const finishFlow = useCallback(+ (fallback?: () => void) => {+ if (parsedPrefill.redirectUrl) {+ router.push(parsedPrefill.redirectUrl);+ return;+ }+ if (fallback) {+ fallback();+ } else {+ navigateWithoutHistory({ view: "list" });+ }+ },+ [parsedPrefill.redirectUrl, router, navigateWithoutHistory],+ );++ /** selectAutomationFallback navigates back to the automations list with the given id selected; used as the fallback after a successful create when no redirectUrl is set. */+ const selectAutomationFallback = (id: string) => () =>navigateWithoutHistory({view: "list",+ automationId: id,+ tab: urlParams.tab,});++ const dismissSecretDialog = () => {+ setShowSecretDialog(false);+ setWebhookSecret(null);+ const id = pendingAutomationId;+ setPendingAutomationId(null);+ finishFlow(id ? selectAutomationFallback(id) : undefined);+ };++ const handleReturnToList = () => {+ finishFlow();};const handleCreateSuccess = (@@ -166,20 +214,13 @@ export default function AutomationsPage() {if (webhookSecret && actionType === "WEBHOOK") {setWebhookSecret(webhookSecret);setShowSecretDialog(true);+ setPendingAutomationId(automationId ?? null);+ return;}- // Navigate to the newly created automation detail page without history entry- if (automationId) {- navigateWithoutHistory({- view: "list",- automationId,- tab: urlParams.tab,- });- } else {- navigateWithoutHistory({- view: "list",- });- }+ finishFlow(+ automationId ? selectAutomationFallback(automationId) : undefined,+ );};const handleEditSuccess = () => {@@ -280,6 +321,7 @@ export default function AutomationsPage() {onSuccess={handleCreateSuccess}onCancel={handleReturnToList}isEditing={true}+ prefill={parsedPrefill}/></div>);@@ -358,7 +400,16 @@ export default function AutomationsPage() {</div></div>{/* Webhook Secret Dialog */}- <Dialog open={showSecretDialog} onOpenChange={setShowSecretDialog}>+ <Dialog+ open={showSecretDialog}+ onOpenChange={(open) => {+ if (open) {+ setShowSecretDialog(true);+ } else {+ dismissSecretDialog();+ }+ }}+ ><DialogContent className="max-w-4xl"><DialogHeader><DialogTitle>Webhook Secret Created</DialogTitle>@@ -373,12 +424,7 @@ export default function AutomationsPage() {)}</DialogBody><DialogFooter>- <Button- onClick={() => {- setShowSecretDialog(false);- setWebhookSecret(null);- }}- >+ <Button onClick={dismissSecretDialog}>{"I've saved the secret"}</Button></DialogFooter>diff --git a/web/src/features/automations/server/router.ts b/web/src/features/automations/server/router.tsindex 0111ba7c60..af7cb2c045 100644--- a/web/src/features/automations/server/router.ts+++ b/web/src/features/automations/server/router.ts@@ -144,7 +144,6 @@ export const automationsRouter = createTRPCRouter({z.object({projectId: z.string(),eventSource: TriggerEventSourceSchema.optional(),- matches: z.record(z.string(), z.unknown()).optional(),}),).query(async ({ ctx, input }) => {@@ -158,7 +157,6 @@ export const automationsRouter = createTRPCRouter({return await getAutomations({projectId: input.projectId,eventSource: input.eventSource,- matches: input.matches,});}),diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.tsindex b077fcfdbd..e322feb28f 100644--- a/web/src/features/entitlements/constants/entitlements.ts+++ b/web/src/features/entitlements/constants/entitlements.ts@@ -39,6 +39,7 @@ export const entitlementLimits = ["data-access-days","model-based-evaluations-count-evaluators","prompt-management-count-prompts",+ "monitor-count",] as const;export type EntitlementLimit = (typeof entitlementLimits)[number];@@ -63,6 +64,7 @@ export const entitlementAccess: Record<"annotation-queue-count": 1,"model-based-evaluations-count-evaluators": false,"prompt-management-count-prompts": false,+ "monitor-count": 10,},},"cloud:core": {@@ -73,6 +75,7 @@ export const entitlementAccess: Record<"annotation-queue-count": 3,"model-based-evaluations-count-evaluators": false,"prompt-management-count-prompts": false,+ "monitor-count": 10,},},"cloud:pro": {@@ -87,6 +90,7 @@ export const entitlementAccess: Record<"data-access-days": false,"model-based-evaluations-count-evaluators": false,"prompt-management-count-prompts": false,+ "monitor-count": 10,},},"cloud:team": {@@ -107,6 +111,7 @@ export const entitlementAccess: Record<"data-access-days": false,"model-based-evaluations-count-evaluators": false,"prompt-management-count-prompts": false,+ "monitor-count": 10,},},"cloud:enterprise": {@@ -127,6 +132,7 @@ export const entitlementAccess: Record<"data-access-days": false,"model-based-evaluations-count-evaluators": false,"prompt-management-count-prompts": false,+ "monitor-count": 10,},},oss: {@@ -137,6 +143,7 @@ export const entitlementAccess: Record<"data-access-days": false,"model-based-evaluations-count-evaluators": false,"prompt-management-count-prompts": false,+ "monitor-count": 10,},},"self-hosted:pro": {@@ -147,6 +154,7 @@ export const entitlementAccess: Record<"data-access-days": false,"model-based-evaluations-count-evaluators": false,"prompt-management-count-prompts": false,+ "monitor-count": 10,},},"self-hosted:enterprise": {@@ -166,6 +174,7 @@ export const entitlementAccess: Record<"data-access-days": false,"model-based-evaluations-count-evaluators": false,"prompt-management-count-prompts": false,+ "monitor-count": 10,},},};diff --git a/web/src/features/filters/config/monitors-config.ts b/web/src/features/filters/config/monitors-config.tsnew file mode 100644index 0000000000..845377065f--- /dev/null+++ b/web/src/features/filters/config/monitors-config.ts@@ -0,0 +1,26 @@+import { monitorsTableCols } from "@langfuse/shared";+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";++export const monitorFilterConfig: FilterConfig = {+ tableName: "monitors",++ columnDefinitions: monitorsTableCols,++ defaultExpanded: ["severity", "tags"],++ defaultSidebarCollapsed: false,++ facets: [+ {+ type: "categorical" as const,+ column: "severity",+ label: "Severity",+ disableTextFilter: true,+ },+ {+ type: "categorical" as const,+ column: "tags",+ label: "Tags",+ },+ ],+};diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsxindex 7efe78e094..0815353282 100644--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx@@ -1540,6 +1540,8 @@ export function useSidebarFilterState((c) => c.id === facet.column,);const isArrayOptions = colDef?.type === "arrayOptions";+ const textFilterDisabled =+ facet.type === "categorical" && facet.disableTextFilter === true;// Get the checkbox filter (stringOptions/arrayOptions) for this columnconst checkboxFilter = filterState.find(@@ -1684,14 +1686,18 @@ export function useSidebarFilterState(updateOperator(facet.column, op): undefined,// Text filter support - ONLY for stringOptions, NOT arrayOptions or boolean- textFilters: !isArrayOptions ? textFilters : undefined,- onTextFilterAdd: !isArrayOptions- ? (op, val) => addTextFilter(facet.column, op, val)- : undefined,- onTextFilterRemove: !isArrayOptions- ? (op, val) => removeTextFilter(facet.column, op, val)- : undefined,- hasTextFilters: !isArrayOptions ? hasTextFilters : undefined,+ textFilters:+ !isArrayOptions && !textFilterDisabled ? textFilters : undefined,+ onTextFilterAdd:+ !isArrayOptions && !textFilterDisabled+ ? (op, val) => addTextFilter(facet.column, op, val)+ : undefined,+ onTextFilterRemove:+ !isArrayOptions && !textFilterDisabled+ ? (op, val) => removeTextFilter(facet.column, op, val)+ : undefined,+ hasTextFilters:+ !isArrayOptions && !textFilterDisabled ? hasTextFilters : undefined,hasCheckboxSelections,};})diff --git a/web/src/features/filters/lib/filter-config.ts b/web/src/features/filters/lib/filter-config.tsindex 919571a40e..6059c4a526 100644--- a/web/src/features/filters/lib/filter-config.ts+++ b/web/src/features/filters/lib/filter-config.ts@@ -13,6 +13,8 @@ interface CategoricalFacet extends BaseFacet {type: "categorical";/** Optional function to render an icon next to filter option labels */renderIcon?: (value: string) => React.ReactNode;+ /** When true, the sidebar hides the contains/does-not-contain text filter mode for this facet. */+ disableTextFilter?: boolean;}interface BooleanFacet extends BaseFacet {diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.access.clienttest.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.access.clienttest.tsxnew file mode 100644index 0000000000..a6efff8c41--- /dev/null+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.access.clienttest.tsx@@ -0,0 +1,82 @@+import { fireEvent, render, screen } from "@testing-library/react";++const automationRow = {+ id: "auto-1",+ name: "Ping webhook",+ trigger: { id: "trig-1" },+ action: { type: "WEBHOOK" },+};++vi.mock("@/src/utils/api", () => ({+ api: {+ automations: {+ getAutomations: {+ useQuery: () => ({ data: [automationRow], isSuccess: true }),+ },+ },+ },+}));++vi.mock("next/router", () => ({+ useRouter: () => ({ asPath: "/", push: vi.fn() }),+}));++import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";++describe("MonitorAutomationsPanel access gating", () => {+ it("read-only access: clicking a row does not toggle the trigger", () => {+ const onTriggerIdsChange = vi.fn();+ render(+ <MonitorAutomationsPanel+ projectId="p1"+ hasAccess={false}+ triggerIds={[]}+ onTriggerIdsChange={onTriggerIdsChange}+ />,+ );++ fireEvent.click(screen.getByRole("button", { name: /ping webhook/i }));+ expect(onTriggerIdsChange).not.toHaveBeenCalled();+ });++ it("write access: clicking a row toggles the trigger", () => {+ const onTriggerIdsChange = vi.fn();+ render(+ <MonitorAutomationsPanel+ projectId="p1"+ hasAccess={true}+ triggerIds={[]}+ onTriggerIdsChange={onTriggerIdsChange}+ />,+ );++ fireEvent.click(screen.getByRole("button", { name: /ping webhook/i }));+ expect(onTriggerIdsChange).toHaveBeenCalledTimes(1);+ });++ it("read-only access: the add-automation trigger is disabled", () => {+ render(+ <MonitorAutomationsPanel+ projectId="p1"+ hasAccess={false}+ triggerIds={[]}+ onTriggerIdsChange={vi.fn()}+ />,+ );+ expect(screen.getByRole("button", { name: /automation/i })).toBeDisabled();+ });++ it("write access: the add-automation trigger is enabled", () => {+ render(+ <MonitorAutomationsPanel+ projectId="p1"+ hasAccess={true}+ triggerIds={[]}+ onTriggerIdsChange={vi.fn()}+ />,+ );+ expect(+ screen.getByRole("button", { name: /automation/i }),+ ).not.toBeDisabled();+ });+});diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.clienttest.ts b/web/src/features/monitors/components/MonitorAutomationsPanel.clienttest.tsnew file mode 100644index 0000000000..a0e48db639--- /dev/null+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.clienttest.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";++import { __test } from "./MonitorAutomationsPanel";++const { computeSelectedSet, toggle } = __test;++describe("computeSelectedSet", () => {+ it("pre-checks rows whose trigger.id is in triggerIds", () => {+ const liveIds = ["t1", "t2", "t3"];+ const selected = computeSelectedSet(["t1", "t3"], liveIds);+ expect(selected.has("t1")).toBe(true);+ expect(selected.has("t2")).toBe(false);+ expect(selected.has("t3")).toBe(true);+ });++ it("drops stale IDs that are no longer in liveTriggerIds", () => {+ const liveIds = ["t1", "t2"];+ const selected = computeSelectedSet(["t1", "t99-stale"], liveIds);+ expect(selected.has("t1")).toBe(true);+ expect(selected.has("t99-stale")).toBe(false);+ expect(selected.size).toBe(1);+ });+});++describe("toggle", () => {+ it("toggle-on appends the id to the selected set and returns the new array", () => {+ const liveIds = ["t1", "t2", "t3"];+ const current = ["t1"];+ const next = toggle("t2", current, liveIds);+ expect(next).toContain("t1");+ expect(next).toContain("t2");+ expect(next).not.toContain("t3");+ });++ it("toggle-off removes the id from the selected set and returns the new array", () => {+ const liveIds = ["t1", "t2", "t3"];+ const current = ["t1", "t2"];+ const next = toggle("t2", current, liveIds);+ expect(next).toContain("t1");+ expect(next).not.toContain("t2");+ });++ it("stale IDs are dropped during a toggle-on (lazy cleanup)", () => {+ const liveIds = ["t1", "t2"];+ // t99 is stale — not in liveIds; t2 is being toggled on+ const current = ["t1", "t99-stale"];+ const next = toggle("t2", current, liveIds);+ expect(next).toContain("t1");+ expect(next).toContain("t2");+ expect(next).not.toContain("t99-stale");+ });+});diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsxnew file mode 100644index 0000000000..985c36cff8--- /dev/null+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsx@@ -0,0 +1,68 @@+import { render } from "@testing-library/react";++const automationRow = {+ id: "auto-1",+ name: "Ping webhook",+ trigger: { id: "trig-1" },+ action: { type: "WEBHOOK" },+};++const useQueryMock = vi.fn();++vi.mock("@/src/utils/api", () => ({+ api: {+ automations: {+ getAutomations: {+ useQuery: () => useQueryMock(),+ },+ },+ },+}));++vi.mock("next/router", () => ({+ useRouter: () => ({ asPath: "/", push: vi.fn() }),+}));++import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";++describe("MonitorAutomationsPanel auto-prune", () => {+ it("does not prune while the query is loading", () => {+ useQueryMock.mockReturnValue({ data: undefined, isSuccess: false });+ const onTriggerIdsChange = vi.fn();+ render(+ <MonitorAutomationsPanel+ projectId="p1"+ triggerIds={["trig-stale"]}+ onTriggerIdsChange={onTriggerIdsChange}+ />,+ );+ expect(onTriggerIdsChange).not.toHaveBeenCalled();+ });++ it("prunes a stale ID once loaded, calling onChange once with the pruned array", () => {+ useQueryMock.mockReturnValue({ data: [automationRow], isSuccess: true });+ const onTriggerIdsChange = vi.fn();+ render(+ <MonitorAutomationsPanel+ projectId="p1"+ triggerIds={["trig-1", "trig-stale"]}+ onTriggerIdsChange={onTriggerIdsChange}+ />,+ );+ expect(onTriggerIdsChange).toHaveBeenCalledTimes(1);+ expect(onTriggerIdsChange).toHaveBeenCalledWith(["trig-1"]);+ });++ it("does not write back when the selection already matches the live set", () => {+ useQueryMock.mockReturnValue({ data: [automationRow], isSuccess: true });+ const onTriggerIdsChange = vi.fn();+ render(+ <MonitorAutomationsPanel+ projectId="p1"+ triggerIds={["trig-1"]}+ onTriggerIdsChange={onTriggerIdsChange}+ />,+ );+ expect(onTriggerIdsChange).not.toHaveBeenCalled();+ });+});diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.tsxnew file mode 100644index 0000000000..af890de812--- /dev/null+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.tsx@@ -0,0 +1,262 @@+import { useEffect, useMemo } from "react";+import Link from "next/link";+import { useRouter } from "next/router";+import {+ Check,+ Webhook as WebhookIcon,+ Github,+ Plus,+ Slack,+} from "lucide-react";++import { api } from "@/src/utils/api";+import { Button } from "@/src/components/ui/button";+import { Card, CardContent } from "@/src/components/ui/card";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import {+ ActionTypeSchema,+ type ActionTypes,+ TriggerEventSource,+} from "@langfuse/shared";+import { automationCreateHref } from "@/src/features/automations/components/automationForm";+import { cn } from "@/src/utils/tailwind";++/** actionLabel maps each automation action type to its display name. */+const actionLabel: Record<ActionTypes, string> = {+ WEBHOOK: "Webhook",+ SLACK: "Slack",+ GITHUB_DISPATCH: "GitHub Dispatch",+};++/** MonitorAutomationsPanel lets the user select which automations fire for a monitor via explicit trigger IDs. */+export const MonitorAutomationsPanel = ({+ projectId,+ triggerIds,+ onTriggerIdsChange,+ hasAccess = true,+}: {+ projectId: string;+ triggerIds: string[];+ onTriggerIdsChange: (next: string[]) => void;+ hasAccess?: boolean;+}) => {+ const automations = api.automations.getAutomations.useQuery(+ {+ projectId,+ eventSource: TriggerEventSource.Monitor,+ },+ {+ trpc: { context: { skipBatch: true } },+ refetchOnWindowFocus: false,+ },+ );++ /** liveTriggerIds is the set of trigger IDs that exist in the current project. */+ const liveTriggerIds = useMemo(+ () => (automations.data ?? []).map((a) => a.trigger.id),+ [automations.data],+ );++ /** selectedSet is the intersection of triggerIds with liveTriggerIds — stale IDs fall out automatically. */+ const selectedSet = useMemo(+ () => computeSelectedSet(triggerIds, liveTriggerIds),+ [triggerIds, liveTriggerIds],+ );++ // Write the pruned selection back once the live set is known; gating on+ // isSuccess avoids wiping a real selection while liveIds is still [].+ useEffect(() => {+ if (!automations.isSuccess) return;+ const pruned = Array.from(selectedSet);+ if (pruned.length !== triggerIds.length) onTriggerIdsChange(pruned);+ }, [automations.isSuccess, selectedSet, triggerIds, onTriggerIdsChange]);++ /** handleToggle flips membership for a trigger ID and calls onTriggerIdsChange with the new array. */+ const handleToggle = (triggerId: string) => {+ if (!hasAccess) return;+ onTriggerIdsChange(toggle(triggerId, triggerIds, liveTriggerIds));+ };++ // Only show the empty splash after the query has actually resolved with no+ // rows; otherwise loading or errored requests would flash the splash and+ // make linked automations look like they have vanished.+ const showEmptyState = automations.isSuccess && automations.data.length === 0;++ return (+ <div className="space-y-3">+ <Card>+ <CardContent className="space-y-3 pt-4">+ {showEmptyState ? (+ <>+ <p className="text-muted-foreground px-4 py-6 text-center text-base">+ Set up Slack, Webhook, and Github Action Automations to Receive+ Alerts+ </p>+ <AddAutomationDropdown+ projectId={projectId}+ fullWidth+ hasAccess={hasAccess}+ />+ </>+ ) : (+ <>+ <ul className="space-y-1">+ {(automations.data ?? []).map((automation) => {+ const checked = selectedSet.has(automation.trigger.id);+ const handleClick = () => handleToggle(automation.trigger.id);+ return (+ <li key={automation.id}>+ <div+ role="button"+ tabIndex={hasAccess ? 0 : -1}+ aria-pressed={checked}+ aria-disabled={!hasAccess}+ onClick={handleClick}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ handleClick();+ }+ }}+ className={cn(+ "hover:bg-muted/60 focus-visible:ring-ring flex cursor-pointer items-center gap-2 rounded-md border p-2 text-xs outline-hidden transition-colors focus-visible:ring-2",+ !hasAccess && "pointer-events-none opacity-50",+ )}+ >+ <RowCheckbox checked={checked} />+ <ActionIcon+ type={automation.action.type as ActionTypes}+ className="h-3.5 w-3.5 shrink-0"+ />+ <span className="truncate">{automation.name}</span>+ </div>+ </li>+ );+ })}+ </ul>+ <AddAutomationDropdown+ projectId={projectId}+ fullWidth+ hasAccess={hasAccess}+ />+ </>+ )}+ </CardContent>+ </Card>+ </div>+ );+};++/** RowCheckbox is a non-interactive visual stand-in for a checkbox. */+const RowCheckbox = ({ checked }: { checked: boolean }) => (+ <span+ aria-hidden+ className={cn(+ "border-primary flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border",+ checked && "bg-primary text-primary-foreground",+ )}+ >+ {checked && <Check className="h-3.5 w-3.5" />}+ </span>+);++/** ActionIcon renders the lucide icon for a given automation action type. */+const ActionIcon = ({+ type,+ className,+}: {+ type: ActionTypes;+ className?: string;+}) => {+ switch (type) {+ case "WEBHOOK":+ return <WebhookIcon className={className} />;+ case "SLACK":+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- see import note.+ return <Slack className={className} />;+ case "GITHUB_DISPATCH":+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- see import note.+ return <Github className={className} />;+ }+};++/** AddAutomationDropdown renders the "+ Automation" CTA used in both the empty state and the populated-list footer. Threads the current route through `redirectUrl` so the create-automation flow returns the user here on save. */+const AddAutomationDropdown = ({+ projectId,+ fullWidth,+ hasAccess = true,+}: {+ projectId: string;+ fullWidth?: boolean;+ hasAccess?: boolean;+}) => {+ const router = useRouter();+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="outline"+ size="lg"+ disabled={!hasAccess}+ className={fullWidth ? "w-full" : undefined}+ >+ <Plus className="mr-2 h-4 w-4" />+ Automation+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuItem asChild>+ <Link+ href={automationCreateHref(projectId, undefined, router.asPath)}+ >+ <Plus className="mr-2 h-3.5 w-3.5" />+ New automation+ </Link>+ </DropdownMenuItem>+ {ActionTypeSchema.options.map((t) => (+ <DropdownMenuItem key={t} asChild>+ <Link href={automationCreateHref(projectId, t, router.asPath)}>+ <ActionIcon type={t} className="mr-2 h-3.5 w-3.5" />+ {actionLabel[t]}+ </Link>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+};++/** computeSelectedSet returns the intersection of triggerIds with liveTriggerIds, dropping stale IDs. */+const computeSelectedSet = (+ triggerIds: string[],+ liveTriggerIds: string[],+): Set<string> => {+ const liveSet = new Set(liveTriggerIds);+ return new Set(triggerIds.filter((id) => liveSet.has(id)));+};++/** toggle flips membership of triggerId in the current selection (after dropping stale IDs) and returns the new array. */+const toggle = (+ triggerId: string,+ currentTriggerIds: string[],+ liveTriggerIds: string[],+): string[] => {+ const next = computeSelectedSet(currentTriggerIds, liveTriggerIds);+ if (next.has(triggerId)) {+ next.delete(triggerId);+ } else {+ next.add(triggerId);+ }+ return Array.from(next);+};++/** __test exposes private helpers to co-located tests without widening the module API. */+export const __test = {+ computeSelectedSet,+ toggle,+};diff --git a/web/src/features/monitors/components/MonitorChartPreview.tsx b/web/src/features/monitors/components/MonitorChartPreview.tsxnew file mode 100644index 0000000000..4b47e1df8d--- /dev/null+++ b/web/src/features/monitors/components/MonitorChartPreview.tsx@@ -0,0 +1,191 @@+import { useMemo, useState } from "react";+import { type z } from "zod";++import { api } from "@/src/utils/api";+import { Card, CardContent } from "@/src/components/ui/card";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import { Chart } from "@/src/features/widgets/chart-library/Chart";+import { ChartLoadingState } from "@/src/features/widgets/chart-library/ChartLoadingState";+import { type DataPoint } from "@/src/features/widgets/chart-library/chart-props";+import { getWidgetMetricPresentation } from "@/src/features/widgets/utils";+import {+ type FilterState,+ type metricAggregations,+ RESOURCE_LIMIT_ERROR_MESSAGE,+} from "@langfuse/shared";+import {+ type MonitorThresholdOperator,+ type MonitorView,+} from "@langfuse/shared/monitors";+import { TIME_RANGES } from "@/src/utils/date-range-utils";++/** previewRangePresets lists the time ranges offered in the preview picker. */+const previewRangePresets = [+ "last1Hour",+ "last6Hours",+ "last1Day",+ "last7Days",+ "last30Days",+] as const satisfies ReadonlyArray<keyof typeof TIME_RANGES>;++type PreviewRangePreset = (typeof previewRangePresets)[number];++/** MonitorChartPreview renders the live time-series preview with alert/warning threshold bands for a monitor draft. */+export const MonitorChartPreview = ({+ projectId,+ view,+ filters,+ measure,+ aggregation,+ thresholdOperator,+ alertThreshold,+ warningThreshold,+}: {+ projectId: string;+ view: MonitorView;+ filters: FilterState;+ measure: string;+ aggregation: z.infer<typeof metricAggregations>;+ thresholdOperator: MonitorThresholdOperator;+ alertThreshold: number | null | undefined;+ warningThreshold: number | null | undefined;+}) => {+ /** rangePreset is the currently selected preview window key. */+ const [rangePreset, setRangePreset] =+ useState<PreviewRangePreset>("last1Day");++ /** fromTimestamp and toTimestamp bound the preview query to the picked range, anchored to now. */+ const { fromTimestamp, toTimestamp } = useMemo(() => {+ const now = Date.now();+ const minutes = TIME_RANGES[rangePreset].minutes ?? 24 * 60;+ return {+ toTimestamp: new Date(now).toISOString(),+ fromTimestamp: new Date(now - minutes * 60_000).toISOString(),+ };+ }, [rangePreset]);++ /** queryResult runs the preview query for the draft monitor. */+ const queryResult = api.dashboard.executeQuery.useQuery(+ {+ projectId,+ version: "v2",+ query: {+ view,+ dimensions: [],+ metrics: [{ measure, aggregation }],+ filters,+ timeDimension: { granularity: "auto" },+ fromTimestamp,+ toTimestamp,+ orderBy: null,+ chartConfig: { type: "LINE_TIME_SERIES" },+ },+ },+ {+ trpc: { context: { skipBatch: true } },+ meta: { silentHttpCodes: [422] },+ refetchOnWindowFocus: false,+ },+ );++ /** data reshapes the query rows into chart points. */+ const data: DataPoint[] = useMemo(() => {+ const rows = (queryResult.data ?? []) as Array<Record<string, unknown>>;+ const metricField = `${aggregation}_${measure}`;+ return rows.map((row) => {+ const value = row[metricField];+ return {+ time_dimension: row["time_dimension"] as string | undefined,+ dimension: "metric",+ metric: typeof value === "number" ? value : 0,+ } satisfies DataPoint;+ });+ }, [queryResult.data, measure, aggregation]);++ /** thresholds lists the warning and alert bands to draw on the chart. */+ const thresholds = useMemo(() => {+ const ordered = [];+ if (warningThreshold != null && Number.isFinite(warningThreshold)) {+ ordered.push({+ value: warningThreshold,+ operator: thresholdOperator,+ color: "yellow" as const,+ label: "Warning",+ });+ }+ if (alertThreshold != null && Number.isFinite(alertThreshold)) {+ ordered.push({+ value: alertThreshold,+ operator: thresholdOperator,+ color: "red" as const,+ label: "Alert",+ });+ }+ return ordered;+ }, [warningThreshold, alertThreshold, thresholdOperator]);++ // Why: without the measure's unit, cost charts render as raw numbers+ // instead of dollar amounts.+ /** metricFormatter formats chart values with the measure's unit. */+ const { metricFormatter } = useMemo(+ () =>+ getWidgetMetricPresentation({+ metric: { measure, agg: aggregation },+ view,+ version: "v2",+ }),+ [measure, aggregation, view],+ );++ return (+ <Card className="h-full">+ <CardContent className="flex h-full flex-col pt-4">+ <div className="mb-4 flex items-center justify-between">+ <h3 className="text-lg font-bold tracking-tight">Live Preview</h3>+ <Select+ value={rangePreset}+ onValueChange={(value) =>+ setRangePreset(value as PreviewRangePreset)+ }+ >+ <SelectTrigger className="h-8 w-auto gap-2 text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent align="end">+ {previewRangePresets.map((preset) => (+ <SelectItem key={preset} value={preset} className="text-xs">+ {TIME_RANGES[preset].label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="relative min-h-0 flex-1">+ <Chart+ chartType="LINE_TIME_SERIES"+ data={data}+ rowLimit={1000}+ thresholds={thresholds}+ metricFormatter={metricFormatter}+ />+ <ChartLoadingState+ isLoading={queryResult.isError}+ showSpinner={false}+ showHintImmediately+ layout="compact"+ hintText={+ queryResult.error?.message ?? RESOURCE_LIMIT_ERROR_MESSAGE+ }+ className="bg-background/80 absolute inset-0 z-20 backdrop-blur-xs"+ />+ </div>+ </CardContent>+ </Card>+ );+};diff --git a/web/src/features/monitors/components/MonitorForm.clienttest.ts b/web/src/features/monitors/components/MonitorForm.clienttest.tsnew file mode 100644index 0000000000..d85c6bb9d5--- /dev/null+++ b/web/src/features/monitors/components/MonitorForm.clienttest.ts@@ -0,0 +1,121 @@+import { describe, expect, it } from "vitest";++import {+ CreateMonitorSchema,+ ErrorAtLeastOneTrigger,+ type Monitor,+} from "@langfuse/shared/monitors";++import { __test } from "./MonitorForm";++const { createDefaults, monitorToDefaults, nameOrPlaceholder } = __test;++describe("createDefaults", () => {+ it("only surfaces name + alertThreshold as missing base fields (no hidden missing fields)", () => {+ const defaults = createDefaults("project-1");+ const result = CreateMonitorSchema.safeParse(defaults);+ expect(result.success).toBe(false);+ if (result.success) return;++ const paths = result.error.issues.map((i) => i.path.join("."));+ expect(paths).toContain("name");+ expect(paths).toContain("alertThreshold");+ // Anything else has no error UI in the form, so the submit would silently+ // reject and the user would see the create button "do nothing". Defaults+ // must cover these fields with schema-valid values.+ expect(paths).not.toContain("warningThreshold");+ expect(paths).not.toContain("filters");+ expect(paths).not.toContain("tags");+ });++ it("requires at least one automation once the base fields parse", () => {+ const defaults = createDefaults("project-1");+ const result = CreateMonitorSchema.safeParse({+ ...defaults,+ name: "Test Monitor",+ alertThreshold: 5,+ });+ expect(result.success).toBe(false);+ if (result.success) return;+ const issue = result.error.issues.find(+ (i) => i.path.join(".") === "triggerIds",+ );+ expect(issue?.message).toBe(ErrorAtLeastOneTrigger);+ });++ it("becomes schema-valid once name + alertThreshold + an automation are filled in", () => {+ const defaults = createDefaults("project-1");+ const result = CreateMonitorSchema.safeParse({+ ...defaults,+ name: "Test Monitor",+ alertThreshold: 5,+ triggerIds: ["t1"],+ });+ if (!result.success) {+ throw new Error(+ `expected schema-valid, got: ${JSON.stringify(result.error.issues, null, 2)}`,+ );+ }+ expect(result.success).toBe(true);+ });++ it("triggerIds defaults to empty array", () => {+ const defaults = createDefaults("project-1");+ expect(defaults.triggerIds).toEqual([]);+ });+});++describe("nameOrPlaceholder", () => {+ const placeholder = "Count of Observations > 0";++ it("empty string: falls back to the placeholder", () => {+ expect(nameOrPlaceholder("", placeholder)).toBe(placeholder);+ });++ it("undefined: falls back to the placeholder", () => {+ expect(nameOrPlaceholder(undefined, placeholder)).toBe(placeholder);+ });++ it("whitespace-only: preserved as typed, not the placeholder", () => {+ expect(nameOrPlaceholder(" ", placeholder)).toBe(" ");+ });++ it("non-blank name: wins over the placeholder", () => {+ expect(nameOrPlaceholder("My Monitor", placeholder)).toBe("My Monitor");+ });+});++describe("monitorToDefaults", () => {+ it("maps monitor.triggerIds into the form defaults", () => {+ const monitor: Monitor = {+ id: "mon-1",+ projectId: "project-1",+ view: "observations",+ filters: [],+ metric: { measure: "count", aggregation: "count" },+ window: "5m",+ thresholdOperator: "GT",+ alertThreshold: 10,+ warningThreshold: null,+ noData: { mode: "SILENT" },+ renotify: { mode: "OFF" },+ name: "My Monitor",+ tags: [],+ triggerIds: ["t-a", "t-b"],+ status: "ACTIVE",+ severity: "UNKNOWN",+ severityChangedAt: null,+ alertedAt: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ createdBy: null,+ updatedBy: null,+ nextRunAt: new Date(),+ lastPublishedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,+ };+ const defaults = monitorToDefaults(monitor);+ expect(defaults.triggerIds).toEqual(["t-a", "t-b"]);+ });+});diff --git a/web/src/features/monitors/components/MonitorForm.tsx b/web/src/features/monitors/components/MonitorForm.tsxnew file mode 100644index 0000000000..55d9ba43d7--- /dev/null+++ b/web/src/features/monitors/components/MonitorForm.tsx@@ -0,0 +1,1081 @@+import React, { useEffect, useMemo, useRef } from "react";+import { useRouter } from "next/router";+import { type LucideIcon, Plus } from "lucide-react";+import { useForm, useWatch } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { startCase } from "lodash";++import { api } from "@/src/utils/api";+import { Button } from "@/src/components/ui/button";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/src/components/ui/accordion";+import {+ Card,+ 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 { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import {+ mapWidgetUiTableFilterToView,+ normalizeStoredWidgetFiltersForEditor,+} from "@/src/features/dashboard/lib/dashboardUiTableToViewMapping";+import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";+import { WidgetPropertySelectItem } from "@/src/features/widgets/components/WidgetPropertySelectItem";+import {+ getWidgetColumnsWithCustomSelect,+ getWidgetFilterColumns,+} from "@/src/features/widgets/components/widgetFilterColumns";+import { normalizeSingleValueOptions } from "@/src/features/filters/lib/filter-transform";+import { cn } from "@/src/utils/tailwind";++import {+ CreateMonitorSchema,+ type CreateMonitor,+ getValidMonitorAggregationsForMeasure,+ getValidMonitorFilterColumns,+ type Monitor,+ type MonitorNoData,+ type MonitorRenotify,+ type MonitorThresholdOperator,+ type MonitorView,+ MonitorViewSchema,+ type MonitorWindow,+ MonitorWindowSchema,+ UpdateMonitorSchema,+ type UpdateMonitor,+} from "@langfuse/shared/monitors";+import { viewDeclarations, type FilterState } from "@langfuse/shared";++import TagManager from "@/src/features/tag/components/TagManager";++import { MonitorChartPreview } from "./MonitorChartPreview";+import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";+import { MonitorSeverityBadge } from "./MonitorSeverityBadge";++/** windowLabels maps each MonitorWindow enum value to a human label. */+const windowLabels: Record<MonitorWindow, string> = {+ "5m": "5 minutes",+ "10m": "10 minutes",+ "15m": "15 minutes",+ "30m": "30 minutes",+ "1h": "1 hour",+ "2h": "2 hours",+ "4h": "4 hours",+ "1d": "1 day",+ "2d": "2 days",+ "1w": "1 week",+};++/** operatorLabels maps each MonitorThresholdOperator to a natural-language label. */+const operatorLabels: Record<MonitorThresholdOperator, string> = {+ GT: "above",+ GTE: "above or equal to",+ LT: "below",+ LTE: "below or equal to",+ EQ: "equal to",+ NEQ: "not equal to",+};++/** triggerOperatorOptions lists the MonitorThresholdOperators shown in the trigger-condition dropdown. */+const triggerOperatorOptions: ReadonlyArray<MonitorThresholdOperator> = [+ "GT",+ "LT",+ "GTE",+ "LTE",+ "EQ",+ "NEQ",+];++/** operatorSymbol maps each MonitorThresholdOperator to a single math glyph. */+const operatorSymbol: Record<MonitorThresholdOperator, string> = {+ GT: ">",+ GTE: "≥",+ LT: "<",+ LTE: "≤",+ EQ: "=",+ NEQ: "≠",+};++/** viewLabels maps each MonitorView to a human label. */+const viewLabels: Record<MonitorView, string> = {+ observations: "Observations",+ "scores-numeric": "Scores (numeric)",+ "scores-categorical": "Scores (categorical)",+};++/** createDefaults returns the form defaults for a brand-new monitor. */+const createDefaults = (projectId: string): Partial<CreateMonitor> => ({+ projectId,+ view: "observations",+ filters: [],+ metric: { measure: "count", aggregation: "count" },+ window: "5m",+ thresholdOperator: "GT",+ warningThreshold: null,+ noData: { mode: "SILENT" },+ renotify: { mode: "OFF" },+ tags: [],+ triggerIds: [],+ status: "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,+ // Stored filters use the view's dimension names (e.g. "environment"); the+ // InlineFilterBuilder works in UI-table column space (e.g. "Environment").+ // Translate on load so the builder shows the right rows.+ filters: normalizeStoredWidgetFiltersForEditor(monitor.view, monitor.filters)+ .editorFilters,+ 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;++/** MonitorForm renders the create/edit form for a Monitor. */+export const MonitorForm = ({+ projectId,+ monitor,+ onNameChange,+}: {+ projectId: string;+ monitor?: Monitor;+ /** onNameChange fires on every form change so the host (e.g. the edit page header) can mirror the live name. */+ onNameChange?: (name: string) => void;+}) => {+ /** router is the Next router used to redirect after a successful create. */+ const router = useRouter();+ /** isEdit is true when the form is bound to an existing monitor. */+ const isEdit = Boolean(monitor);+ /** hasAccess gates write controls behind the monitors:CUD RBAC scope. */+ const hasAccess = useHasProjectAccess({ projectId, scope: "monitors: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);++ /** namePlaceholderRef holds the latest computed name placeholder for the resolver. */+ const namePlaceholderRef = useRef("");++ /** resolver wraps zodResolver, mapping filter columns into view-space and 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 {+ view: MonitorView;+ filters?: FilterState;+ name?: string;+ };+ const mapped = {+ ...values,+ name: nameOrPlaceholder(v.name, namePlaceholderRef.current),+ filters: mapWidgetUiTableFilterToView(v.view, v.filters ?? []),+ };+ 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",+ });++ /** 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();+ showSuccessToast({+ title: "Monitor created",+ description: `"${variables.name}" is now active.`,+ });+ router.replace(`/project/${projectId}/monitors`);+ },+ onError: (e) => showErrorToast("Failed to create monitor", e.message),+ });++ /** 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({+ title: "Monitor saved",+ description: `Your changes to "${variables.name}" have been applied.`,+ });+ router.replace(`/project/${projectId}/monitors`);+ },+ onError: (e) => showErrorToast("Failed to save monitor", e.message),+ });++ /** onSubmit normalizes filter columns into view-space and dispatches the create or update mutation. */+ const onSubmit = form.handleSubmit(+ /** onValid normalize filter values before updating or saving the monitor */+ (values) => {+ const normalizedValues = {+ ...values,+ filters: mapWidgetUiTableFilterToView(+ values.view as Parameters<typeof mapWidgetUiTableFilterToView>[0],+ (values.filters ?? []) as FilterState,+ ),+ } 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 });++ // Push the live name up to the host (e.g. the edit page header) so the page+ // title can mirror it as the user types instead of waiting for save.+ useEffect(() => {+ onNameChange?.(watched.name ?? "");+ }, [watched.name, onNameChange]);++ /** eventsFilterOptions loads the events v2 filter dictionary (environments, tags, models, …) for the picked view. */+ const eventsFilterOptions = api.events.filterOptions.useQuery(+ { projectId },+ {+ trpc: { context: { skipBatch: true } },+ staleTime: Infinity,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ },+ );++ /** datasets loads dataset metadata for the project; used to label experiment-dataset filter options. */+ const datasets = api.datasets.allDatasetMeta.useQuery({ projectId });++ /** 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 },+ );++ /** filterColumnsParams collects the filter-column descriptor for InlineFilterBuilder, derived from the picked view and live option dictionaries. */+ const filterColumnsParams = useMemo(() => {+ const data = eventsFilterOptions.data;+ return {+ selectedView: (watched.view ?? "observations") as+ | "traces"+ | "observations"+ | "scores-numeric"+ | "scores-categorical",+ viewVersion: "v2" as const,+ environmentOptions: data?.environment ?? [],+ nameOptions: normalizeSingleValueOptions(data?.traceName),+ tagsOptions: data?.traceTags ?? [],+ modelOptions: data?.providedModelName ?? [],+ toolNamesOptions: data?.toolNames ?? [],+ calledToolNamesOptions: data?.calledToolNames ?? [],+ observationLevelOptions: [],+ experimentNameOptions: data?.experimentName ?? [],+ experimentDatasetOptions: (() => {+ const ids = new Set(+ (data?.experimentDatasetId ?? []).map((e) => e.value),+ );+ return (+ datasets.data+ ?.filter((d: { id: string }) => ids.has(d.id))+ .map((d: { id: string; name: string }) => ({+ value: d.id,+ displayValue: d.name,+ })) ?? []+ );+ })(),+ observationTypeOptions: [],+ };+ }, [eventsFilterOptions.data, datasets.data, watched.view]);++ /** filterColumns is the InlineFilterBuilder column schema for the picked view. */+ const filterColumns = useMemo(+ () =>+ getValidMonitorFilterColumns(getWidgetFilterColumns(filterColumnsParams)),+ [filterColumnsParams],+ );++ /** customSelectColumnIds is the set of filter columns that render a custom select control. */+ const customSelectColumnIds = useMemo(+ () => getWidgetColumnsWithCustomSelect(filterColumnsParams),+ [filterColumnsParams],+ );++ /** 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. "Count of Observations > 0"). */+ const namePlaceholder = useMemo(() => {+ const view = (watched.view ?? "observations") as MonitorView;+ const measure = watched.metric?.measure ?? "count";+ const aggregation = watched.metric?.aggregation ?? "count";+ const op = (watched.thresholdOperator ?? "GT") as MonitorThresholdOperator;+ const threshold = watched.alertThreshold;+ const aggLabel = startCase(aggregation);+ const viewLabel = viewLabels[view];+ const base =+ measure === "count"+ ? `${aggLabel} of ${viewLabel}`+ : `${aggLabel} of ${viewLabel} ${startCase(measure)}`;+ const value =+ threshold != null && Number.isFinite(threshold) ? threshold : 0;+ return `${base} ${operatorSymbol[op]} ${value}`;+ }, [+ watched.view,+ watched.metric?.measure,+ watched.metric?.aggregation,+ watched.thresholdOperator,+ watched.alertThreshold,+ ]);++ namePlaceholderRef.current = namePlaceholder;++ /** previewFilters translates the UI-table column filters into the view's dimension space for the preview query. */+ const previewFilters = useMemo<FilterState>(+ () =>+ mapWidgetUiTableFilterToView(+ (watched.view ?? "observations") as Parameters<+ typeof mapWidgetUiTableFilterToView+ >[0],+ (watched.filters ?? []) as FilterState,+ ),+ [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;++ 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">+ <CardHeader>+ <CardTitle>Monitor Configuration</CardTitle>+ <CardDescription>+ Receive notifications when a metric crosses a threshold. (eg.+ “sudden cost increase”, “accuracy has+ dropped”)+ </CardDescription>+ </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);+ // Reset the metric whenever the view changes: the+ // selected measure may not exist on the new view,+ // which would leave the form in an unsubmittable+ // state until the user manually picks one. "count"+ // is always present and is the safe default.+ const view =+ next as keyof (typeof viewDeclarations)["v2"];+ const measures =+ viewDeclarations.v2[view]?.measures ?? {};+ const currentMeasure =+ form.getValues("metric.measure");+ if (!(currentMeasure in measures)) {+ form.setValue(+ "metric",+ { measure: "count", aggregation: "count" },+ { shouldValidate: true },+ );+ }+ // Clear filters too — UI-cased column ids only resolve+ // against the view that's currently selected.+ form.setValue("filters", [], {+ 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}>+ {startCase(a)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />+ )}+ <FormField+ control={form.control}+ name="filters"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Filters</FormLabel>+ <FormControl>+ <InlineFilterBuilder+ columns={filterColumns}+ filterState={(field.value ?? []) as FilterState}+ onChange={(next: FilterState) => field.onChange(next)}+ columnsWithCustomSelect={customSelectColumnIds}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ {formError.query && (+ <p className="text-destructive text-xs">+ {formError.query.message}+ </p>+ )}+ </Section>++ <Section title="Alert Conditions" step={2}>+ <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 === "NEQ") {+ form.setValue("warningThreshold", null, {+ shouldValidate: true,+ });+ }+ }}+ disabled={!hasAccess}+ >+ <FormControl>+ <SelectTrigger className="w-auto">+ <SelectValue />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {triggerOperatorOptions.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="ALERT" />+ <span className="text-sm whitespace-nowrap">+ Threshold+ </span>+ <span className="mr-1.5 ml-1 font-mono text-xs font-semibold">+ {+ operatorSymbol[+ (watched.thresholdOperator ??+ "GT") as keyof typeof operatorSymbol+ ]+ }+ </span>+ <FormControl>+ <Input+ type="number"+ className="flex-1"+ placeholder="0"+ value={field.value ?? ""}+ onChange={(e) => {+ const raw = e.target.value;+ field.onChange(+ raw === "" ? undefined : Number(raw),+ );+ }}+ disabled={!hasAccess}+ />+ </FormControl>+ </div>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="warningThreshold"+ render={({ field }) => (+ <FormItem hidden={watched.thresholdOperator === "NEQ"}>+ <div className="flex items-center gap-2">+ <MonitorSeverityBadge severity="WARNING" />+ <span className="text-sm whitespace-nowrap">+ Threshold+ </span>+ <span className="mr-1.5 ml-1 font-mono text-xs font-semibold">+ {+ operatorSymbol[+ (watched.thresholdOperator ??+ "GT") as keyof typeof operatorSymbol+ ]+ }+ </span>+ <FormControl>+ <Input+ type="number"+ className="flex-1"+ 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>+ )}+ />+ <Accordion type="single" collapsible>+ <AccordionItem value="advanced" className="border-b-0">+ <AccordionTrigger className="justify-start gap-2 py-2 text-sm font-medium [&>svg]:order-first [&>svg]:-rotate-90 [&[data-state=open]>svg]:rotate-0">+ Advanced Options+ </AccordionTrigger>+ <AccordionContent className="space-y-6 pt-2">+ <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>+ )}+ />+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ </Section>++ <Section title="Notifications" step={3} className="pb-2">+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Name</FormLabel>+ <FormControl>+ <Input+ maxLength={200}+ placeholder={namePlaceholder}+ disabled={!hasAccess}+ {...field}+ value={field.value ?? ""}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="tags"+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <TagManager+ itemName="monitor"+ 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 className="h-3 w-3" />+ 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>+ </CardContent>+ <CardFooter className="mt-auto">+ <div className="flex-inherit w-full items-center pt-4">+ <Button+ type="submit"+ size="lg"+ className="w-full"+ disabled={!hasAccess || submitting}+ >+ {isEdit ? "Save Monitor" : "Create Monitor"}+ </Button>+ </div>+ </CardFooter>+ </Card>+ </div>++ <div className="hidden h-full w-2/3 min-w-107.5 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"]+ }+ thresholdOperator={+ (watched.thresholdOperator ?? "GT") as MonitorThresholdOperator+ }+ alertThreshold={watched.alertThreshold}+ warningThreshold={watched.warningThreshold ?? null}+ />+ </div>+ </form>+ </Form>+ );+};++/** Header pins a section title to the top of the scrolling CardContent. */+const Header = ({+ title,+ step,+ icon: Icon,+}: {+ title: string;+ step?: number;+ icon?: LucideIcon;+}) => (+ <div className="bg-card sticky top-0 z-10">+ <h3 className="flex items-center gap-2 py-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-semibold">+ {step}+ </span>+ ) : null}+ {Icon ? <Icon className="h-5 w-5" aria-hidden="true" /> : null}+ {title}+ </h3>+ </div>+);++/** Section wraps a Header and its body in the layout used by every MonitorForm section. */+const Section = ({+ title,+ step,+ icon,+ children,+ className,+}: {+ title: string;+ step?: number;+ icon?: LucideIcon;+ children: React.ReactNode;+ className?: string;+}) => (+ <div>+ <Header title={title} step={step} icon={icon} />+ <div className={cn("space-y-4 px-2 pb-4", className)}>{children}</div>+ </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>On no data</Label>+ <Select+ value={value.mode}+ onValueChange={(mode) =>+ onChange(+ mode === "NOTIFY"+ ? { mode: "NOTIFY", intervalMinutes: 60 }+ : { mode: "SILENT" },+ )+ }+ disabled={disabled}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="SILENT">Silent</SelectItem>+ <SelectItem value="NOTIFY">Notify after sustained no-data</SelectItem>+ </SelectContent>+ </Select>+ {value.mode === "NOTIFY" && (+ <div className="flex items-center gap-2">+ <Label className="text-muted-foreground text-xs">+ Notify every (minutes)+ </Label>+ <Input+ type="number"+ min={1}+ max={60 * 24}+ value={value.intervalMinutes}+ onChange={(e) =>+ onChange({+ mode: "NOTIFY",+ intervalMinutes: Math.max(1, Number(e.target.value) || 1),+ })+ }+ disabled={disabled}+ className="w-32"+ />+ </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>+);++/** __test exposes private helpers to co-located tests without widening the module API. */+export const __test = {+ createDefaults,+ monitorToDefaults,+ nameOrPlaceholder,+};diff --git a/web/src/features/monitors/components/MonitorPagePermissions.tsx b/web/src/features/monitors/components/MonitorPagePermissions.tsxnew file mode 100644index 0000000000..5683b3de6b--- /dev/null+++ b/web/src/features/monitors/components/MonitorPagePermissions.tsx@@ -0,0 +1,35 @@+import { type ReactNode } from "react";++import { ErrorPage } from "@/src/components/error-page";+import { SupportOrUpgradePage } from "@/src/ee/features/billing/components/SupportOrUpgradePage";+import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";+import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";++/** MonitorScope is the RBAC scope a monitor page can require for entry. */+type MonitorScope = "monitors:read" | "monitors:CUD";++/** MonitorPagePermissions gates a monitor page on the `monitors` feature flag and a project RBAC scope. */+export function MonitorPagePermissions({+ scope,+ children,+}: {+ scope: MonitorScope;+ children: ReactNode;+}) {+ const projectId = useProjectIdFromURL();+ const isEnabled = useIsFeatureEnabled("monitors");+ const { isLangfuseCloud } = useLangfuseCloudRegion();+ const hasAccess = useHasProjectAccess({ projectId, scope });++ if (!isEnabled || !isLangfuseCloud) {+ return <ErrorPage title="Not found" message="This page does not exist." />;+ }++ if (!hasAccess) {+ return <SupportOrUpgradePage />;+ }++ return <>{children}</>;+}diff --git a/web/src/features/monitors/components/MonitorRowActions.clienttest.tsx b/web/src/features/monitors/components/MonitorRowActions.clienttest.tsxnew file mode 100644index 0000000000..a2a41ab3ca--- /dev/null+++ b/web/src/features/monitors/components/MonitorRowActions.clienttest.tsx@@ -0,0 +1,94 @@+import { fireEvent, render, screen } from "@testing-library/react";++import { type Monitor } from "@langfuse/shared/monitors";++vi.mock("@/src/components/deleteButton", () => ({+ DeleteMonitorButton: (props: { itemId: string }) => (+ <button type="button" data-testid="delete-monitor">+ delete {props.itemId}+ </button>+ ),+}));++import { __test } from "./MonitorsTable";++const { MonitorRowActions } = __test;++const PROJECT_ID = "proj_test123";++/** monitorRow builds a minimal monitor row with the given id and status. */+const monitorRow = (status: Monitor["status"]): Monitor =>+ ({ id: "mon-1", status }) as Monitor;++describe("MonitorRowActions", () => {+ it("write access: edit links to monitors/<id> and pause click toggles status", () => {+ const onToggleStatus = vi.fn();+ render(+ <MonitorRowActions+ monitor={monitorRow("ACTIVE")}+ projectId={PROJECT_ID}+ hasCUDAccess={true}+ collapsed={false}+ isStatusPending={false}+ onToggleStatus={onToggleStatus}+ />,+ );++ const editLink = screen.getByRole("link");+ expect(editLink.getAttribute("href")).toBe(+ `/project/${PROJECT_ID}/monitors/mon-1`,+ );++ fireEvent.click(screen.getByRole("button", { name: /pause/i }));+ expect(onToggleStatus).toHaveBeenCalledTimes(1);+ });++ it("paused monitor: shows a Resume control", () => {+ render(+ <MonitorRowActions+ monitor={monitorRow("PAUSED")}+ projectId={PROJECT_ID}+ hasCUDAccess={true}+ collapsed={false}+ isStatusPending={false}+ onToggleStatus={vi.fn()}+ />,+ );++ expect(screen.getByRole("button", { name: /resume/i })).toBeInTheDocument();+ });++ it("read-only access: pause and edit controls are disabled", () => {+ render(+ <MonitorRowActions+ monitor={monitorRow("ACTIVE")}+ projectId={PROJECT_ID}+ hasCUDAccess={false}+ collapsed={false}+ isStatusPending={false}+ onToggleStatus={vi.fn()}+ />,+ );++ expect(screen.getByRole("button", { name: /pause/i })).toBeDisabled();+ expect(screen.getByRole("link")).toHaveAttribute("disabled");+ });++ it("collapsed: actions hide behind a kebab menu trigger", () => {+ render(+ <MonitorRowActions+ monitor={monitorRow("ACTIVE")}+ projectId={PROJECT_ID}+ hasCUDAccess={true}+ collapsed={true}+ isStatusPending={false}+ onToggleStatus={vi.fn()}+ />,+ );++ expect(+ screen.getByRole("button", { name: /monitor actions/i }),+ ).toBeInTheDocument();+ expect(screen.queryByRole("link")).not.toBeInTheDocument();+ });+});diff --git a/web/src/features/monitors/components/MonitorSeverityBadge.tsx b/web/src/features/monitors/components/MonitorSeverityBadge.tsxnew file mode 100644index 0000000000..af5265bc9e--- /dev/null+++ b/web/src/features/monitors/components/MonitorSeverityBadge.tsx@@ -0,0 +1,72 @@+import { PauseCircle } from "lucide-react";++import { Badge, type BadgeProps } from "@/src/components/ui/badge";+import { cn } from "@/src/utils/tailwind";+import { type MonitorSeverity } from "@langfuse/shared/monitors";++/** severityVariant maps each MonitorSeverity to the underlying Badge variant. */+const severityVariant: Record<MonitorSeverity, BadgeProps["variant"]> = {+ UNKNOWN: "outline",+ NO_DATA: "secondary",+ PAUSED: "outline",+ OK: "default",+ WARNING: "default",+ ALERT: "default",+};++/** severityClassName maps each MonitorSeverity to its badge tailwind classes. */+const severityClassName: Record<MonitorSeverity, string> = {+ UNKNOWN: "text-gray-400",+ NO_DATA: "",+ PAUSED: "text-gray-400",+ OK: "bg-emerald-500 text-white hover:bg-emerald-500",+ WARNING: "bg-amber-600 text-white hover:bg-amber-600",+ ALERT: "bg-orange-600 text-white hover:bg-orange-600",+};++/** severityLabel maps each MonitorSeverity to its display text. */+const severityLabel: Record<MonitorSeverity, string> = {+ UNKNOWN: "PENDING",+ NO_DATA: "NO DATA",+ PAUSED: "PAUSED",+ OK: "OK",+ WARNING: "WARNING",+ ALERT: "ALERT",+};++/** MonitorSeverityBadge displays the Monitor's severity, including loading states for pending monitors. */+export function MonitorSeverityBadge({+ severity,+ className,+}: {+ severity: MonitorSeverity;+ className?: string;+}) {+ return (+ <Badge+ variant={severityVariant[severity]}+ className={cn(+ "w-20 justify-center py-1",+ severityClassName[severity],+ className,+ )}+ >+ {severity === "PAUSED" ? (+ <span className="inline-flex items-center gap-1">+ <PauseCircle className="h-4 w-4" />+ {severityLabel.PAUSED}+ </span>+ ) : severity === "UNKNOWN" ? (+ <span className="inline-flex items-center gap-1.5">+ <span+ className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-gray-200 border-t-gray-400"+ aria-hidden="true"+ />+ {severityLabel.UNKNOWN}+ </span>+ ) : (+ severityLabel[severity]+ )}+ </Badge>+ );+}diff --git a/web/src/features/monitors/components/MonitorsOnboarding.clienttest.tsx b/web/src/features/monitors/components/MonitorsOnboarding.clienttest.tsxnew file mode 100644index 0000000000..5417540492--- /dev/null+++ b/web/src/features/monitors/components/MonitorsOnboarding.clienttest.tsx@@ -0,0 +1,77 @@+import { render, screen } from "@testing-library/react";++import { MonitorsOnboarding } from "./MonitorsOnboarding";++const PROJECT_ID = "proj_test123";++/** parsePrefill decodes the `prefill` query param into the same shape the form's serializer produced. */+const parsePrefill = (+ href: string,+): { eventSource?: string; actionType?: string; redirectUrl?: string } => {+ const url = new URL(href, "http://localhost");+ const raw = url.searchParams.get("prefill");+ if (!raw) return {};+ const padded = raw.replace(/-/g, "+").replace(/_/g, "/");+ const binary = atob(padded);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);+ return JSON.parse(new TextDecoder().decode(bytes));+};++describe("MonitorsOnboarding", () => {+ it("renders the splash header, step titles, and four CTAs", () => {+ render(<MonitorsOnboarding projectId={PROJECT_ID} hasCUDAccess={true} />);++ expect(+ screen.getByText("Catch issues before they impact your users"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("Choose where alerts should go"),+ ).toBeInTheDocument();+ expect(screen.getByText("Decide what to monitor")).toBeInTheDocument();++ expect(+ screen.getByRole("link", { name: /Connect Slack/i }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: /Connect Webhooks/i }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: /Connect Github Actions/i }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: /Create Monitor/i }),+ ).toBeInTheDocument();+ });++ it("links each channel button to /automations?view=create with the matching prefill actionType", () => {+ render(<MonitorsOnboarding projectId={PROJECT_ID} hasCUDAccess={true} />);++ const cases: Array<{ label: RegExp; expected: string }> = [+ { label: /Connect Slack/i, expected: "SLACK" },+ { label: /Connect Webhooks/i, expected: "WEBHOOK" },+ { label: /Connect Github Actions/i, expected: "GITHUB_DISPATCH" },+ ];++ for (const { label, expected } of cases) {+ const link = screen.getByRole("link", { name: label });+ const href = link.getAttribute("href") ?? "";+ expect(href).toContain(`/project/${PROJECT_ID}/automations`);+ expect(href).toContain("view=create");++ const decoded = parsePrefill(href);+ expect(decoded.eventSource).toBe("monitor");+ expect(decoded.actionType).toBe(expected);+ expect(decoded.redirectUrl).toBe(`/project/${PROJECT_ID}/monitors`);+ }+ });++ it("links the Create Monitor CTA to the project's new-monitor route", () => {+ render(<MonitorsOnboarding projectId={PROJECT_ID} hasCUDAccess={true} />);++ const link = screen.getByRole("link", { name: /Create Monitor/i });+ expect(link.getAttribute("href")).toBe(+ `/project/${PROJECT_ID}/monitors/new`,+ );+ });+});diff --git a/web/src/features/monitors/components/MonitorsOnboarding.tsx b/web/src/features/monitors/components/MonitorsOnboarding.tsxnew file mode 100644index 0000000000..492ccc80e6--- /dev/null+++ b/web/src/features/monitors/components/MonitorsOnboarding.tsx@@ -0,0 +1,104 @@+import Link from "next/link";+import { ChevronRight, Github, Plus, Slack, Webhook } from "lucide-react";++import { ActionButton } from "@/src/components/ActionButton";+import { Button } from "@/src/components/ui/button";+import { SplashScreen } from "@/src/components/ui/splash-screen";+import { automationCreateHref } from "@/src/features/automations/components/automationForm";+import { type ActionTypes } from "@langfuse/shared";++/** OnboardingChannel describes one notification-channel CTA shown in step 1 of the splash. */+type OnboardingChannel = {+ actionType: ActionTypes;+ label: string;+ icon: React.ReactNode;+};++/** channels enumerates the three notification channels presented to a first-time user. */+const channels: OnboardingChannel[] = [+ {+ actionType: "SLACK",+ label: "Connect Slack",+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- brand icon retained for parity with MonitorAutomationsPanel.+ icon: <Slack className="h-4 w-4" aria-hidden="true" />,+ },+ {+ actionType: "WEBHOOK",+ label: "Connect Webhooks",+ icon: <Webhook className="h-4 w-4" aria-hidden="true" />,+ },+ {+ actionType: "GITHUB_DISPATCH",+ label: "Connect Github Actions",+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- see Slack note above.+ icon: <Github className="h-4 w-4" aria-hidden="true" />,+ },+];++/** MonitorsOnboarding renders the splash shown on /monitors when the project has no monitors yet. */+export function MonitorsOnboarding({+ projectId,+ hasCUDAccess,+}: {+ projectId: string;+ hasCUDAccess: boolean;+}) {+ return (+ <div className="mx-auto w-full max-w-xl pt-12">+ <SplashScreen+ title="Catch issues before they impact your users"+ description="Get notified when cost, quality, latency, or other key metrics move outside of expected ranges."+ steps={[+ {+ title: "Choose where alerts should go",+ description:+ "Send alerts to Slack, Webhooks, or GitHub Actions so your team and your workflows can respond automatically.",+ content: (+ <div className="flex flex-col gap-2">+ {channels.map((channel) => (+ <Button+ key={channel.actionType}+ asChild+ variant="outline"+ size="lg"+ className="w-full justify-between gap-2 px-6 py-5"+ >+ <Link+ href={automationCreateHref(+ projectId,+ channel.actionType,+ `/project/${projectId}/monitors`,+ )}+ >+ <span className="flex items-center gap-2">+ {channel.icon}+ {channel.label}+ </span>+ <ChevronRight className="h-4 w-4" aria-hidden="true" />+ </Link>+ </Button>+ ))}+ </div>+ ),+ },+ {+ title: "Decide what to monitor",+ description:+ "Create monitors for sudden cost spikes, quality drops, latency changes, or other important changes.",+ content: (+ <ActionButton+ hasAccess={hasCUDAccess}+ icon={<Plus className="h-4 w-4" aria-hidden="true" />}+ href={`/project/${projectId}/monitors/new`}+ variant="default"+ size="lg"+ >+ Create Monitor+ </ActionButton>+ ),+ },+ ]}+ />+ </div>+ );+}diff --git a/web/src/features/monitors/components/MonitorsTable.clienttest.ts b/web/src/features/monitors/components/MonitorsTable.clienttest.tsnew file mode 100644index 0000000000..1584f220a2--- /dev/null+++ b/web/src/features/monitors/components/MonitorsTable.clienttest.ts@@ -0,0 +1,199 @@+import { describe, expect, it } from "vitest";++import { type FilterState } from "@langfuse/shared";+import { type Monitor } from "@langfuse/shared/monitors";++import { __test } from "./MonitorsTable";++const { filterStateToListMonitorFilter, buildStatusToggleUpdate } = __test;++/** monitorFixture builds a full Monitor row with the given status. */+const monitorFixture = (status: Monitor["status"]): Monitor => ({+ id: "mon-1",+ projectId: "project-1",+ view: "observations",+ filters: [],+ metric: { measure: "count", aggregation: "count" },+ window: "5m",+ thresholdOperator: "GT",+ alertThreshold: 10,+ warningThreshold: null,+ noData: { mode: "SILENT" },+ renotify: { mode: "OFF" },+ name: "My Monitor",+ tags: ["prod"],+ triggerIds: ["t-a"],+ status,+ severity: "OK",+ severityChangedAt: null,+ alertedAt: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ createdBy: null,+ updatedBy: null,+ nextRunAt: new Date(),+ lastPublishedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,+});++describe("filterStateToListMonitorFilter", () => {+ it("passes severity `any of` through with values intact", () => {+ const state: FilterState = [+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["ALERT", "WARNING"],+ },+ ];+ expect(filterStateToListMonitorFilter(state)).toEqual([+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["ALERT", "WARNING"],+ },+ ]);+ });++ it("expands NO_DATA to (NO_DATA, UNKNOWN) on the severity column", () => {+ const state: FilterState = [+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["NO_DATA"],+ },+ ];+ expect(filterStateToListMonitorFilter(state)).toEqual([+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["NO_DATA", "UNKNOWN"],+ },+ ]);+ });++ it("expands NO_DATA on `none of` too", () => {+ const state: FilterState = [+ {+ type: "stringOptions",+ column: "severity",+ operator: "none of",+ value: ["NO_DATA"],+ },+ ];+ expect(filterStateToListMonitorFilter(state)).toEqual([+ {+ type: "stringOptions",+ column: "severity",+ operator: "none of",+ value: ["NO_DATA", "UNKNOWN"],+ },+ ]);+ });++ it("does not duplicate UNKNOWN when both NO_DATA and UNKNOWN are already present", () => {+ const state: FilterState = [+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["NO_DATA", "UNKNOWN", "ALERT"],+ },+ ];+ expect(filterStateToListMonitorFilter(state)).toEqual([+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["NO_DATA", "UNKNOWN", "ALERT"],+ },+ ]);+ });++ it("passes tags rows through unchanged", () => {+ const state: FilterState = [+ {+ type: "arrayOptions",+ column: "tags",+ operator: "any of",+ value: ["prod"],+ },+ ];+ expect(filterStateToListMonitorFilter(state)).toEqual(state);+ });++ it("collapses to no filter when a row has an unrecognized column", () => {+ const state: FilterState = [+ {+ type: "stringOptions",+ column: "bogus",+ operator: "any of",+ value: ["x"],+ },+ {+ type: "arrayOptions",+ column: "tags",+ operator: "any of",+ value: ["prod"],+ },+ ];+ expect(filterStateToListMonitorFilter(state)).toEqual([]);+ });++ it("collapses to no filter when a column is duplicated", () => {+ const state: FilterState = [+ {+ type: "stringOptions",+ column: "severity",+ operator: "any of",+ value: ["ALERT"],+ },+ {+ type: "stringOptions",+ column: "severity",+ operator: "none of",+ value: ["PAUSED"],+ },+ ];+ expect(filterStateToListMonitorFilter(state)).toEqual([]);+ });+});++describe("buildStatusToggleUpdate", () => {+ it("ACTIVE monitor: flips status to PAUSED", () => {+ expect(buildStatusToggleUpdate(monitorFixture("ACTIVE")).status).toBe(+ "PAUSED",+ );+ });++ it("PAUSED monitor: flips status to ACTIVE", () => {+ expect(buildStatusToggleUpdate(monitorFixture("PAUSED")).status).toBe(+ "ACTIVE",+ );+ });++ it("carries the full config so only status changes", () => {+ const monitor = monitorFixture("ACTIVE");+ expect(buildStatusToggleUpdate(monitor)).toEqual({+ 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: "PAUSED",+ });+ });+});diff --git a/web/src/features/monitors/components/MonitorsTable.tsx b/web/src/features/monitors/components/MonitorsTable.tsxnew file mode 100644index 0000000000..b241d4b063--- /dev/null+++ b/web/src/features/monitors/components/MonitorsTable.tsx@@ -0,0 +1,453 @@+import { MoreVertical, PauseCircle, PlayCircle, SquarePen } from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/router";+import { useEffect, useMemo } from "react";+import { useMediaQuery } from "react-responsive";++import { DeleteMonitorButton } from "@/src/components/deleteButton";+import { DataTable } from "@/src/components/table/data-table";+import { DataTableControls } from "@/src/components/table/data-table-controls";+import { TableBadgeLoadingCell } from "@/src/components/table/loading-cells";+import { ResizableFilterLayout } from "@/src/components/table/resizable-filter-layout";+import { type LangfuseColumnDef } from "@/src/components/table/types";+import { Button } from "@/src/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import { monitorFilterConfig } from "@/src/features/filters/config/monitors-config";+import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";+import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import TagList from "@/src/features/tag/components/TagList";+import { usePaginationState } from "@/src/hooks/usePaginationState";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { api, type RouterInputs, type RouterOutputs } from "@/src/utils/api";+import { cn } from "@/src/utils/tailwind";+import { type FilterState } from "@langfuse/shared";+import {+ type ListMonitorFilter,+ ListMonitorFilterSchema,+ type Monitor,+ MonitorSeveritySchema,+ type UpdateMonitor,+} from "@langfuse/shared/monitors";++import { MonitorSeverityBadge } from "./MonitorSeverityBadge";++/** monitorsRefetchInterval keeps the list's severity and paused state current without a manual reload. */+const monitorsRefetchInterval = 5_000;++/** rowActionIconColors ramps an inline row-action icon from faint to full foreground, scaling on its own hover. */+const rowActionIconColors =+ "text-foreground/40 transition-[color,transform] group-hover/monitor-row:text-foreground/70 hover:scale-110 hover:text-foreground";++/** MonitorRow is one row of the monitors list, shaped by the `monitors.all` tRPC output. */+type MonitorRow = RouterOutputs["monitors"]["all"]["monitors"][number];++/** MonitorsOrderBy is the order-by argument accepted by the `monitors.all` tRPC query. */+type MonitorsOrderBy = RouterInputs["monitors"]["all"]["orderBy"];++/** MonitorsTable renders the project's monitors as a sortable, filterable, paginated table with row navigation to the edit page. */+export function MonitorsTable() {+ const router = useRouter();+ const projectId = useProjectIdFromURL() ?? "";+ const { setDetailPageList } = useDetailPageLists();+ const utils = api.useUtils();+ /** hasCUDAccess gates the edit, pause/resume, and delete row actions behind the monitors:CUD RBAC scope. */+ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "monitors:CUD",+ });+ /** isWiderThanPhone is true at viewports wider than the main nav's drawer breakpoint (768px / Tailwind `md`), the threshold at which the Tags column appears. */+ const isWiderThanPhone = useMediaQuery({ query: "(min-width: 768px)" });++ /** statusMutation flips a monitor's status between ACTIVE and PAUSED from the row's pause/resume action. */+ const statusMutation = api.monitors.update.useMutation({+ onSuccess: async (_data, variables) => {+ await utils.monitors.invalidate();+ showSuccessToast({+ title:+ variables.status === "PAUSED" ? "Monitor paused" : "Monitor resumed",+ description:+ variables.status === "PAUSED"+ ? "Evaluations are halted until you resume."+ : "Evaluations have resumed.",+ });+ },+ onError: (e) =>+ showErrorToast("Failed to update monitor status", e.message),+ });++ /** paginationState is the bound page index + size, defaulting to 50 per page and synced to the `pageIndex`/`pageSize` URL params. */+ const [paginationState, setPaginationState] = usePaginationState(0, 50, {+ page: "pageIndex",+ limit: "pageSize",+ });++ /** orderByState is the bound table sort, defaulting to severity descending. */+ const [orderByState, setOrderByState] = useOrderByState({+ column: "severity",+ order: "DESC",+ });++ /** filterOptions loads the project's sidebar filter dictionary (severity values, tag list). */+ const filterOptions = api.monitors.getFilterOptions.useQuery(+ { projectId },+ {+ enabled: Boolean(projectId),+ trpc: { context: { skipBatch: true } },+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ staleTime: Infinity,+ },+ );++ /** newFilterOptions reshapes filterOptions into the {value, displayValue} rows the sidebar expects, hiding UNKNOWN so the user sees a single "NO DATA" choice. */+ const newFilterOptions = useMemo(+ () => ({+ severity: MonitorSeveritySchema.options+ // Hide UNKNOWN; it's merged with NO_DATA at the backend so the user+ // sees a single "NO DATA" checkbox.+ .filter((value) => value !== "UNKNOWN")+ .toReversed()+ .map((value) => ({+ value,+ displayValue: value.replace(/_/g, " "),+ })),+ tags: filterOptions.data?.tags.map((t) => ({ value: t.value })) ?? [],+ }),+ [filterOptions.data],+ );++ /** queryFilter is the bound sidebar filter state, synced to the URL and to session storage per project. */+ const queryFilter = useSidebarFilterState(+ monitorFilterConfig,+ newFilterOptions,+ {+ loading: filterOptions.isPending,+ stateLocation: "urlAndSessionStorage",+ sessionFilterContextId: projectId ?? null,+ },+ );++ const monitorFilter = useMemo(+ () => filterStateToListMonitorFilter(queryFilter.filterState),+ [queryFilter.filterState],+ );++ /** monitors loads the paginated, filtered, sorted page of monitors from the server. */+ const monitors = api.monitors.all.useQuery(+ {+ projectId,+ orderBy: orderByState as MonitorsOrderBy,+ filter: monitorFilter,+ page: paginationState.pageIndex + 1,+ limit: paginationState.pageSize,+ },+ {+ enabled: Boolean(projectId),+ trpc: { context: { skipBatch: true } },+ refetchInterval: monitorsRefetchInterval,+ },+ );++ useEffect(() => {+ if (monitors.isSuccess) {+ setDetailPageList(+ "monitors",+ monitors.data.monitors.map((m) => ({ id: m.id })),+ );+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [monitors.isSuccess, monitors.data]);++ /** columns is the DataTable column schema, conditionally including Tags on viewports wider than a phone. */+ const columns: LangfuseColumnDef<MonitorRow>[] = [+ {+ accessorKey: "severity",+ header: "Severity",+ id: "severity",+ enableSorting: true,+ enableResizing: false,+ size: 100,+ minSize: 100,+ maxSize: 100,+ loadingCell: <TableBadgeLoadingCell className="h-6 w-20" />,+ cell: ({ row }) => (+ <MonitorSeverityBadge severity={row.original.severity} />+ ),+ },+ {+ accessorKey: "name",+ header: "Name",+ id: "name",+ enableSorting: true,+ enableResizing: false,+ isFlexWidth: true,+ cell: ({ row }) => (+ <span+ className={cn(+ "text-sm font-medium",+ row.original.severity === "PAUSED" && "opacity-50",+ )}+ >+ {row.original.name}+ </span>+ ),+ },+ ...(isWiderThanPhone+ ? [+ {+ accessorKey: "tags",+ header: "Tags",+ id: "tags",+ enableSorting: false,+ enableResizing: false,+ size: 250,+ minSize: 250,+ maxSize: 250,+ cell: ({ row }) => (+ <div+ className={cn(+ "flex flex-wrap gap-1",+ row.original.severity === "PAUSED" && "opacity-50",+ )}+ >+ <TagList+ selectedTags={row.original.tags ?? []}+ isLoading={false}+ viewOnly+ isTableCell+ />+ </div>+ ),+ } satisfies LangfuseColumnDef<MonitorRow>,+ ]+ : []),+ {+ accessorKey: "actions",+ header: "Actions",+ id: "actions",+ enableSorting: false,+ enableResizing: false,+ size: 120,+ minSize: 120,+ maxSize: 120,+ cell: ({ row }) => (+ <MonitorRowActions+ monitor={row.original}+ projectId={projectId}+ hasCUDAccess={hasCUDAccess}+ collapsed={!isWiderThanPhone}+ isStatusPending={statusMutation.isPending}+ onToggleStatus={() =>+ statusMutation.mutate(buildStatusToggleUpdate(row.original))+ }+ />+ ),+ },+ ];++ return (+ <div className="flex h-full w-full flex-col">+ <ResizableFilterLayout>+ <DataTableControls queryFilter={queryFilter} />+ <div className="flex flex-1 flex-col overflow-hidden">+ <DataTable+ tableName="monitors"+ columns={columns}+ data={+ monitors.isLoading+ ? { isLoading: true, isError: false }+ : monitors.isError+ ? {+ isLoading: false,+ isError: true,+ error: monitors.error.message,+ }+ : {+ isLoading: false,+ isError: false,+ data: monitors.data?.monitors ?? [],+ }+ }+ orderBy={orderByState}+ setOrderBy={setOrderByState}+ pagination={{+ totalCount: monitors.data?.totalCount ?? null,+ onChange: setPaginationState,+ state: paginationState,+ }}+ onRowClick={(row) => {+ router.push(monitorHref(projectId, row.id));+ }}+ getRowClassName={() => "group/monitor-row"}+ cellPadding="comfortable"+ />+ </div>+ </ResizableFilterLayout>+ </div>+ );+}++/** MonitorRowActions renders the per-row edit, pause/resume, and delete controls, collapsing into a kebab menu on narrow viewports. */+function MonitorRowActions({+ monitor,+ projectId,+ hasCUDAccess,+ collapsed,+ isStatusPending,+ onToggleStatus,+}: {+ monitor: MonitorRow;+ projectId: string;+ hasCUDAccess: boolean;+ collapsed: boolean;+ isStatusPending: boolean;+ /** onToggleStatus flips the monitor between ACTIVE and PAUSED. */+ onToggleStatus: () => void;+}) {+ const isPaused = monitor.status === "PAUSED";++ const editButton = (+ <Button+ asChild+ variant="ghost"+ size={collapsed ? "default" : "icon"}+ disabled={!hasCUDAccess}+ aria-label="Edit monitor"+ title="Edit"+ className={cn(!collapsed && rowActionIconColors)}+ >+ <Link+ href={monitorHref(projectId, monitor.id)}+ onClick={(e) => e.stopPropagation()}+ >+ <SquarePen className="h-4 w-4" aria-hidden="true" />+ {collapsed ? <span className="ml-2">Edit</span> : null}+ </Link>+ </Button>+ );++ const pauseButton = (+ <Button+ variant="ghost"+ size={collapsed ? "default" : "icon"}+ disabled={!hasCUDAccess || isStatusPending}+ aria-label={isPaused ? "Resume monitor" : "Pause monitor"}+ title={isPaused ? "Resume" : "Pause"}+ className={cn(!collapsed && rowActionIconColors)}+ onClick={(e) => {+ e.stopPropagation();+ onToggleStatus();+ }}+ >+ {isPaused ? (+ <PlayCircle className="h-4.5 w-4.5" aria-hidden="true" />+ ) : (+ <PauseCircle className="h-4.5 w-4.5" aria-hidden="true" />+ )}+ {collapsed ? (+ <span className="ml-2">{isPaused ? "Resume" : "Pause"}</span>+ ) : null}+ </Button>+ );++ const deleteButton = (+ <DeleteMonitorButton+ itemId={monitor.id}+ projectId={projectId}+ isTableAction+ icon={!collapsed}+ variant="ghost"+ title="Delete"+ className={cn(!collapsed && rowActionIconColors)}+ />+ );++ if (collapsed) {+ return (+ <div onClick={(e) => e.stopPropagation()}>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button size="xs" variant="ghost" aria-label="Monitor actions">+ <MoreVertical className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="flex flex-col *:w-full *:justify-start">+ <DropdownMenuItem asChild>{pauseButton}</DropdownMenuItem>+ <DropdownMenuItem asChild>{editButton}</DropdownMenuItem>+ <DropdownMenuItem asChild>{deleteButton}</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+ }++ return (+ <div+ className="flex items-center gap-0"+ onClick={(e) => e.stopPropagation()}+ >+ {pauseButton}+ {editButton}+ {deleteButton}+ </div>+ );+}++/** filterStateToListMonitorFilter expands NO_DATA to (NO_DATA, UNKNOWN) on the severity column. */+const filterStateToListMonitorFilter = (+ state: FilterState,+): ListMonitorFilter => {+ const parsed = ListMonitorFilterSchema.safeParse(state);+ if (!parsed.success) return [];+ return parsed.data.map((row) => {+ if (+ row.column === "severity" &&+ row.value.includes("NO_DATA") &&+ !row.value.includes("UNKNOWN")+ ) {+ return { ...row, value: [...row.value, "UNKNOWN"] };+ }+ return row;+ });+};++/** monitorHref is the project-scoped path to a monitor's page, the row-click and edit-action target. */+const monitorHref = (projectId: string, monitorId: string): string =>+ `/project/${projectId}/monitors/${encodeURIComponent(monitorId)}`;++/** buildStatusToggleUpdate returns a full update payload with only the status flipped between ACTIVE and PAUSED. */+const buildStatusToggleUpdate = (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: monitor.status === "PAUSED" ? "ACTIVE" : "PAUSED",+});++export const __test = {+ filterStateToListMonitorFilter,+ buildStatusToggleUpdate,+ monitorHref,+ monitorsRefetchInterval,+ MonitorRowActions,+};diff --git a/web/src/features/monitors/index.ts b/web/src/features/monitors/index.tsnew file mode 100644index 0000000000..3f95154ffc--- /dev/null+++ b/web/src/features/monitors/index.ts@@ -0,0 +1 @@+export { MonitorForm } from "./components/MonitorForm";diff --git a/web/src/features/monitors/monitorRoutes.clienttest.ts b/web/src/features/monitors/monitorRoutes.clienttest.tsnew file mode 100644index 0000000000..f1755d995c--- /dev/null+++ b/web/src/features/monitors/monitorRoutes.clienttest.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from "vitest";++import EditMonitorPage from "@/src/features/monitors/pages/EditMonitorPage";++describe("monitors/<id> route", () => {+ it("index route renders the same component as the edit route", async () => {+ const indexRoute =+ await import("@/src/pages/project/[projectId]/monitors/[monitorId]/index");+ const editRoute =+ await import("@/src/pages/project/[projectId]/monitors/[monitorId]/edit");++ expect(indexRoute.default).toBe(EditMonitorPage);+ expect(indexRoute.default).toBe(editRoute.default);+ });+});diff --git a/web/src/features/monitors/pages/EditMonitorPage.tsx b/web/src/features/monitors/pages/EditMonitorPage.tsxnew file mode 100644index 0000000000..33891aaa12--- /dev/null+++ b/web/src/features/monitors/pages/EditMonitorPage.tsx@@ -0,0 +1,64 @@+import { useRouter } from "next/router";+import { useEffect, useState } from "react";++import { ErrorPage } from "@/src/components/error-page";+import Page from "@/src/components/layouts/page";+import { MonitorForm } from "@/src/features/monitors";+import { MonitorPagePermissions } from "@/src/features/monitors/components/MonitorPagePermissions";+import { api } from "@/src/utils/api";++/** EditMonitorPage gates the edit-monitor route and defers all data fetching to EditMonitorPageContent so blocked users never trigger the monitor query. */+export default function EditMonitorPage() {+ return (+ <MonitorPagePermissions scope="monitors:read">+ <EditMonitorPageContent />+ </MonitorPagePermissions>+ );+}++/** EditMonitorPageContent renders the edit form for a single monitor; runs only when the route gate has admitted the user. */+function EditMonitorPageContent() {+ const router = useRouter();+ const projectId = router.query.projectId as string;+ const monitorId = router.query.monitorId as string;++ const { data, error, isPending } = api.monitors.get.useQuery(+ { projectId, id: monitorId },+ { enabled: Boolean(monitorId) },+ );++ /** liveName mirrors the form's name so the page title updates as the user edits, without waiting for a save round-trip. */+ const [liveName, setLiveName] = useState("");+ useEffect(() => {+ setLiveName(data?.name ?? "");+ }, [data?.name]);++ if (error?.data?.code === "NOT_FOUND") {+ return (+ <ErrorPage+ title="Monitor not found"+ message="This monitor doesn't exist or has been deleted."+ />+ );+ }++ return (+ <Page+ withPadding+ headerProps={{+ title: liveName ? `Edit Monitor - ${liveName}` : "Edit Monitor",+ breadcrumb: [+ { name: "Monitors", href: `/project/${projectId}/monitors` },+ ],+ }}+ >+ {isPending ? null : data ? (+ <MonitorForm+ projectId={projectId}+ monitor={data}+ onNameChange={setLiveName}+ />+ ) : null}+ </Page>+ );+}diff --git a/web/src/features/monitors/pages/ListMonitorsPage.tsx b/web/src/features/monitors/pages/ListMonitorsPage.tsxnew file mode 100644index 0000000000..19729b431f--- /dev/null+++ b/web/src/features/monitors/pages/ListMonitorsPage.tsx@@ -0,0 +1,117 @@+import { PlusIcon } from "lucide-react";++import { ActionButton } from "@/src/components/ActionButton";+import Page from "@/src/components/layouts/page";+import { DataTableControlsProvider } from "@/src/components/table/data-table-controls";+import { FilterToggleButton } from "@/src/components/table/FilterToggleButton";+import { AutomationButton } from "@/src/features/automations/components/AutomationButton";+import { useEntitlementLimit } from "@/src/features/entitlements/hooks";+import { monitorFilterConfig } from "@/src/features/filters/config/monitors-config";+import { MonitorPagePermissions } from "@/src/features/monitors/components/MonitorPagePermissions";+import { MonitorsOnboarding } from "@/src/features/monitors/components/MonitorsOnboarding";+import { MonitorsTable } from "@/src/features/monitors/components/MonitorsTable";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { api } from "@/src/utils/api";++/** headerProps are shared by all of the ListMonitorPage headers */+const headerProps = {+ title: "Monitors",+ help: {+ description:+ "Monitors notify your team and automated workflows of sudden cost spikes, quality drops, latency changes, and other important changes on the system.",+ },+};++/** ListMonitorsPage displays the list of monitors for a project, or an onboarding splash when the project has none. */+export default function ListMonitorsPage() {+ const projectId = useProjectIdFromURL();++ const {+ isLoading,+ isSuccess,+ data: hasMonitors,+ } = api.monitors.hasAny.useQuery(+ { projectId: projectId ?? "" },+ { enabled: !!projectId },+ );++ return (+ <MonitorPagePermissions scope="monitors:read">+ {!projectId || isLoading ? (+ <EmptyPage />+ ) : isSuccess && hasMonitors ? (+ <MainPage projectId={projectId} />+ ) : (+ <OnboardingPage projectId={projectId} />+ )}+ </MonitorPagePermissions>+ );+}++/** EmptyPage is an empty monitor page */+const EmptyPage = () => <Page headerProps={headerProps}>{null}</Page>;++/** OnboardingPage shows the onboarding message */+const OnboardingPage = ({ projectId }: { projectId: string }) => {+ /** hasCUDAccess is true if the user has permission to create monitors */+ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "monitors:CUD",+ });++ return (+ <Page headerProps={headerProps}>+ <MonitorsOnboarding projectId={projectId} hasCUDAccess={hasCUDAccess} />+ </Page>+ );+};++/** MainPage loads and displays the list of monitors */+const MainPage = ({ projectId }: { projectId: string }) => {+ /** hasCUDAccess is true if the user has permission to create monitors */+ const hasCUDAccess = useHasProjectAccess({+ projectId,+ scope: "monitors:CUD",+ });++ /** monitorEntitlementLimit is the limit of the number of monitors that can be created for this org */+ const monitorEntitlementLimit = useEntitlementLimit("monitor-count");++ /** monitorCountQuery returns the total number of monitors created for this org */+ const monitorCountQuery = api.monitors.count.useQuery(+ { projectId: projectId },+ { enabled: hasCUDAccess },+ );++ return (+ <DataTableControlsProvider+ tableName={monitorFilterConfig.tableName}+ defaultSidebarCollapsed={monitorFilterConfig.defaultSidebarCollapsed}+ >+ <Page+ headerProps={{+ ...headerProps,+ actionButtonsRight: (+ <>+ <FilterToggleButton />+ <AutomationButton projectId={projectId} />+ <ActionButton+ icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}+ hasAccess={hasCUDAccess}+ limit={monitorEntitlementLimit}+ limitValue={monitorCountQuery.data?.count}+ href={`/project/${projectId}/monitors/new`}+ variant="default"+ >+ New Monitor+ </ActionButton>+ </>+ ),+ }}+ >+ <MonitorsTable />+ </Page>+ </DataTableControlsProvider>+ );+};diff --git a/web/src/features/monitors/pages/NewMonitorPage.tsx b/web/src/features/monitors/pages/NewMonitorPage.tsxnew file mode 100644index 0000000000..31564129f7--- /dev/null+++ b/web/src/features/monitors/pages/NewMonitorPage.tsx@@ -0,0 +1,27 @@+import { useRouter } from "next/router";++import Page from "@/src/components/layouts/page";+import { MonitorForm } from "@/src/features/monitors";+import { MonitorPagePermissions } from "@/src/features/monitors/components/MonitorPagePermissions";++/** NewMonitorPage renders the create-monitor form for a project. */+export default function NewMonitorPage() {+ const router = useRouter();+ const projectId = router.query.projectId as string;++ return (+ <MonitorPagePermissions scope="monitors:CUD">+ <Page+ withPadding+ headerProps={{+ title: "New Monitor",+ breadcrumb: [+ { name: "Monitors", href: `/project/${projectId}/monitors` },+ ],+ }}+ >+ <MonitorForm projectId={projectId} />+ </Page>+ </MonitorPagePermissions>+ );+}diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex f63143cf66..01f09f7f4b 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -131,6 +131,7 @@ export const events = {"delete_dashboard_form_open","delete_dashboard_button_click",],+ monitors: ["delete_form_open", "delete_monitor_button_click"],datasets: ["delete_form_open","delete_dataset_button_click",diff --git a/web/src/features/tag/components/TagManager.tsx b/web/src/features/tag/components/TagManager.tsxindex b5652f768e..08d8ff985e 100644--- a/web/src/features/tag/components/TagManager.tsx+++ b/web/src/features/tag/components/TagManager.tsx@@ -5,6 +5,7 @@ import TagList from "@/src/features/tag/components/TagList";import { useTagManager } from "@/src/features/tag/hooks/useTagManager";import {Popover,+ PopoverAnchor,PopoverTrigger,PopoverContent,} from "@/src/components/ui/popover";@@ -14,7 +15,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePosimport { Label } from "@/src/components/ui/label";type TagManagerProps = {- itemName: "prompt" | "trace";+ itemName: "prompt" | "trace" | "monitor";tags: string[];allTags: string[];hasAccess: boolean;@@ -23,6 +24,8 @@ type TagManagerProps = {className?: string;isTableCell?: boolean;allowTagRemoval?: boolean;+ triggerButton?: React.ReactNode;+ alignPopover?: "start" | "center" | "end";};const TagManager = ({@@ -35,6 +38,8 @@ const TagManager = ({className,isTableCell = false,allowTagRemoval = true,+ triggerButton,+ alignPopover,}: TagManagerProps) => {const {selectedTags,@@ -82,31 +87,51 @@ const TagManager = ({return (<Popover onOpenChange={(open) => handlePopoverChange(open)}>- <PopoverTrigger- className="select-none"- asChild- onClick={(e) => {- if (isTableCell) {- e.stopPropagation();- }- }}- >- <div- className={cn(- "flex gap-x-1 gap-y-1",- !isTableCell && "flex-wrap",- className,- )}+ {triggerButton ? (+ <PopoverTrigger className="select-none" asChild>+ <div+ className={cn("flex cursor-pointer items-start gap-1", className)}+ >+ <PopoverAnchor asChild>{triggerButton}</PopoverAnchor>+ {selectedTags.length > 0 && (+ <div className="flex flex-1 flex-wrap gap-1">+ <TagList+ selectedTags={selectedTags}+ isLoading={isLoading}+ isTableCell={isTableCell}+ />+ </div>+ )}+ </div>+ </PopoverTrigger>+ ) : (+ <PopoverTrigger+ className="select-none"+ asChild+ onClick={(e) => {+ if (isTableCell) {+ e.stopPropagation();+ }+ }}>- <TagList- selectedTags={selectedTags}- isLoading={isLoading}- isTableCell={isTableCell}- />- </div>- </PopoverTrigger>+ <div+ className={cn(+ "flex gap-x-1 gap-y-1",+ !isTableCell && "flex-wrap",+ className,+ )}+ >+ <TagList+ selectedTags={selectedTags}+ isLoading={isLoading}+ isTableCell={isTableCell}+ />+ </div>+ </PopoverTrigger>+ )}<PopoverContent- className="space-y-2"+ align={alignPopover}+ className="w-72 space-y-2"onClick={(e) => {if (isTableCell) {e.stopPropagation();diff --git a/web/src/features/tag/hooks/useTagManager.tsx b/web/src/features/tag/hooks/useTagManager.tsxindex c752b56bfe..dcd1d4a764 100644--- a/web/src/features/tag/hooks/useTagManager.tsx+++ b/web/src/features/tag/hooks/useTagManager.tsx@@ -1,5 +1,5 @@import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useState, useMemo } from "react";+import { useEffect, useState, useMemo } from "react";type UseTagManagerProps = {initialTags: string[];@@ -8,6 +8,7 @@ type UseTagManagerProps = {export function useTagManager({ initialTags, allTags }: UseTagManagerProps) {const [selectedTags, setSelectedTags] = useState(initialTags);+ useEffect(() => setSelectedTags(initialTags), [initialTags]);const [inputValue, setInputValue] = useState("");const availableTags = useMemo(() => allTags.filter((value) => !selectedTags.includes(value)),diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsxindex 12b0ba69f2..1b35b156c5 100644--- a/web/src/features/widgets/chart-library/Chart.tsx+++ b/web/src/features/widgets/chart-library/Chart.tsx@@ -3,6 +3,7 @@ import {type FormatMetricOptions,type MetricFormatterFunction,type DataPoint,+ type ChartThreshold,} from "@/src/features/widgets/chart-library/chart-props";import { formatMetric } from "@/src/features/widgets/chart-library/utils";import { CardContent } from "@/src/components/ui/card";@@ -38,6 +39,7 @@ export const Chart = ({legendPosition,overrideWarning = false,metricFormatter: metricFormatterOverride,+ thresholds,}: {chartType: DashboardWidgetChartType;data: DataPoint[];@@ -62,6 +64,7 @@ export const Chart = ({legendPosition?: "above" | "none";overrideWarning?: boolean;metricFormatter?: MetricFormatterFunction;+ thresholds?: ChartThreshold[];}) => {const [forceRender, setForceRender] = useState(overrideWarning);const shouldWarn = data.length > 2000 && !forceRender;@@ -137,6 +140,7 @@ export const Chart = ({metricFormatter={metricFormatter}legendPosition={legendPosition}showDataPointDots={chartConfig?.show_data_point_dots ?? true}+ thresholds={thresholds}/>);case "AREA_TIME_SERIES":diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsxindex 7c897aef32..5a3c55c03d 100644--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx@@ -5,8 +5,20 @@ import {ChartTooltip,ChartTooltipContent,} from "@/src/components/ui/chart";-import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";-import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";+import {+ CartesianGrid,+ Label,+ Line,+ LineChart,+ ReferenceArea,+ ReferenceLine,+ XAxis,+ YAxis,+} from "recharts";+import {+ type ChartProps,+ type ChartThreshold,+} from "@/src/features/widgets/chart-library/chart-props";import {formatMetric,getUniqueDimensions,@@ -15,6 +27,138 @@ import {} from "@/src/features/widgets/chart-library/utils";import { cn } from "@/src/utils/tailwind";+/** computeMetricExtent returns the [min, max] of all numeric metric values across the data, for sizing the eq/neq band. */+const computeMetricExtent = (+ data: ChartProps["data"],+): { min: number; max: number } | null => {+ let min = Infinity;+ let max = -Infinity;+ for (const point of data) {+ const m = point.metric;+ if (typeof m === "number" && Number.isFinite(m)) {+ if (m < min) min = m;+ if (m > max) max = m;+ }+ }+ return Number.isFinite(min) && Number.isFinite(max) ? { min, max } : null;+};++/** ThresholdOverlay returns the ReferenceLine + (operator-derived) ReferenceArea recharts elements for a single ChartThreshold. */+const ThresholdOverlay = ({+ threshold,+ extent,+}: {+ threshold: ChartThreshold;+ extent: { min: number; max: number } | null;+}) => {+ const stroke = `var(--color-${threshold.color}-600)`;+ const fill = `var(--color-${threshold.color}-500)`;+ const elements: React.ReactNode[] = [];++ switch (threshold.operator) {+ case "GT":+ case "GTE":+ elements.push(+ <ReferenceArea+ key={`area-${threshold.value}`}+ y2={threshold.value}+ ifOverflow="extendDomain"+ fill={fill}+ fillOpacity={0.14}+ stroke="none"+ />,+ );+ break;+ case "LT":+ case "LTE":+ elements.push(+ <ReferenceArea+ key={`area-${threshold.value}`}+ y1={threshold.value}+ ifOverflow="extendDomain"+ fill={fill}+ fillOpacity={0.14}+ stroke="none"+ />,+ );+ break;+ case "EQ":+ case "NEQ": {+ // Floor at 1 so threshold.value === 0 with no extent doesn't collapse+ // the band to a zero-height area (which Recharts then tiles across the+ // full chart).+ const bandEpsilon = Math.max(+ extent && extent.max > extent.min+ ? (extent.max - extent.min) * 0.01+ : Math.abs(threshold.value) * 0.01,+ 1,+ );+ if (threshold.operator === "EQ") {+ // The violation IS the band: a thin shaded region centered on value.+ elements.push(+ <ReferenceArea+ key={`area-${threshold.value}`}+ y1={threshold.value - bandEpsilon}+ y2={threshold.value + bandEpsilon}+ ifOverflow="extendDomain"+ fill={fill}+ fillOpacity={0.14}+ stroke="none"+ />,+ );+ } else {+ elements.push(+ <ReferenceArea+ key={`area-above-${threshold.value}`}+ y2={threshold.value + bandEpsilon}+ ifOverflow="extendDomain"+ fill={fill}+ fillOpacity={0.14}+ stroke="none"+ />,+ <ReferenceArea+ key={`area-below-${threshold.value}`}+ y1={threshold.value - bandEpsilon}+ ifOverflow="extendDomain"+ fill={fill}+ fillOpacity={0.14}+ stroke="none"+ />,+ );+ }+ break;+ }+ }++ // Inclusive operators get solid lines, exclusive operators get dashed lines+ const isInclusive =+ threshold.operator === "GTE" ||+ threshold.operator === "LTE" ||+ threshold.operator === "EQ";++ elements.push(+ <ReferenceLine+ key={`line-${threshold.value}`}+ y={threshold.value}+ stroke={stroke}+ strokeWidth={1.5}+ strokeDasharray={isInclusive ? undefined : "4 4"}+ ifOverflow="extendDomain"+ >+ {threshold.label && (+ <Label+ value={threshold.label}+ position="insideTopRight"+ fill={stroke}+ fontSize={11}+ />+ )}+ </ReferenceLine>,+ );++ return <>{elements}</>;+};+/*** LineChartTimeSeries component* @param data - Data to be displayed. Expects an array of objects with time_dimension, dimension, and metric properties.@@ -35,7 +179,9 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({metricFormatter = (value, options) => formatMetric(value, options),legendPosition = "none",showDataPointDots = true,+ thresholds,}) => {+ const metricExtent = useMemo(() => computeMetricExtent(data), [data]);const [highlightedDimension, setHighlightedDimension] = useState<string | null>(null);@@ -106,6 +252,7 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({fontSize={12}tickLine={false}axisLine={false}+ width="auto"niceTicks="auto"tickFormatter={(value) => tooltipFormatter(Number(value))}/>@@ -131,6 +278,13 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({/>);})}+ {thresholds?.map((threshold, i) => (+ <ThresholdOverlay+ key={`threshold-${i}-${threshold.value}`}+ threshold={threshold}+ extent={metricExtent}+ />+ ))}<ChartActiveReferenceLine /><ChartTooltipcontentStyle={{ backgroundColor: "hsl(var(--background))" }}diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.tsindex a302b00851..bcd8efa8bf 100644--- a/web/src/features/widgets/chart-library/chart-props.ts+++ b/web/src/features/widgets/chart-library/chart-props.ts@@ -1,4 +1,5 @@import { type ChartConfig } from "@/src/components/ui/chart";+import type tailwindColors from "tailwindcss/colors";export interface DataPoint {time_dimension: string | undefined;@@ -26,6 +27,28 @@ export type MetricFormatterFunction = (options: FormatMetricOptions,) => FormattedMetric;+/** ChartThresholdOperator picks the violation region a chart tints around a threshold. */+export type ChartThresholdOperator = "GT" | "GTE" | "LT" | "LTE" | "EQ" | "NEQ";++/** ChartThresholdColor is one of Tailwind's palette family names. */+export type ChartThresholdColor = {+ [K in keyof typeof tailwindColors]: (typeof tailwindColors)[K] extends Record<+ string,+ string+ >+ ? K+ : never;+}[keyof typeof tailwindColors] &+ string;++/** ChartThreshold renders a horizontal reference line plus an operator-derived tinted violation region. */+export interface ChartThreshold {+ value: number;+ operator: ChartThresholdOperator;+ color: ChartThresholdColor;+ label?: string;+}+export interface ChartProps {data: DataPoint[];config?: ChartConfig;@@ -35,4 +58,5 @@ export interface ChartProps {showValueLabels?: boolean;showDataPointDots?: boolean;subtleFill?: boolean;+ thresholds?: ChartThreshold[];}diff --git a/web/src/pages/project/[projectId]/monitors/[monitorId]/edit.tsx b/web/src/pages/project/[projectId]/monitors/[monitorId]/edit.tsxnew file mode 100644index 0000000000..81bd24f808--- /dev/null+++ b/web/src/pages/project/[projectId]/monitors/[monitorId]/edit.tsx@@ -0,0 +1 @@+export { default } from "@/src/features/monitors/pages/EditMonitorPage";diff --git a/web/src/pages/project/[projectId]/monitors/[monitorId]/index.tsx b/web/src/pages/project/[projectId]/monitors/[monitorId]/index.tsxnew file mode 100644index 0000000000..81bd24f808--- /dev/null+++ b/web/src/pages/project/[projectId]/monitors/[monitorId]/index.tsx@@ -0,0 +1 @@+export { default } from "@/src/features/monitors/pages/EditMonitorPage";diff --git a/web/src/pages/project/[projectId]/monitors/index.tsx b/web/src/pages/project/[projectId]/monitors/index.tsxnew file mode 100644index 0000000000..80b8ce4dd5--- /dev/null+++ b/web/src/pages/project/[projectId]/monitors/index.tsx@@ -0,0 +1 @@+export { default } from "@/src/features/monitors/pages/ListMonitorsPage";diff --git a/web/src/pages/project/[projectId]/monitors/new.tsx b/web/src/pages/project/[projectId]/monitors/new.tsxnew file mode 100644index 0000000000..7ad4e29fad--- /dev/null+++ b/web/src/pages/project/[projectId]/monitors/new.tsx@@ -0,0 +1 @@+export { default } from "@/src/features/monitors/pages/NewMonitorPage";diff --git a/web/src/server/api/routers/monitors.ts b/web/src/server/api/routers/monitors.tsindex fd0bd994c6..983859ad4d 100644--- a/web/src/server/api/routers/monitors.ts+++ b/web/src/server/api/routers/monitors.ts@@ -1,23 +1,28 @@+import { z } from "zod";+import {createTRPCRouter,protectedProjectProcedure,requireFeatureFlag,+ requireLangfuseCloud,} from "@/src/server/api/trpc";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { throwIfExceedsLimit } from "@/src/features/entitlements/server/hasEntitlementLimit";import {CreateMonitorSchema,DeleteMonitorSchema,GetMonitorByIdSchema,+ GetMonitorFilterOptionsSchema,ListMonitorsSchema,MonitorService,type SessionContext,UpdateMonitorSchema,-} from "@langfuse/shared/src/server";+} from "@langfuse/shared/monitors/server";-/** monitorsProcedure protects every monitors route behind the `monitors` flag. */-const monitorsProcedure = protectedProjectProcedure.use(- requireFeatureFlag("monitors"),-);+/** monitorsProcedure protects every monitors route behind a Langfuse Cloud check and the `monitors` flag. */+const monitorsProcedure = protectedProjectProcedure+ .use(requireLangfuseCloud)+ .use(requireFeatureFlag("monitors"));/** sessionContextFromCtx adapts a tRPC session into a MonitorService SessionContext. */const sessionContextFromCtx = (ctx: {@@ -33,6 +38,17 @@ export const monitorsRouter = createTRPCRouter({projectId: input.projectId,scope: "monitors:CUD",});++ const currentCount = await ctx.prisma.monitor.count({+ where: { project: { orgId: ctx.session.orgId, deletedAt: null } },+ });+ throwIfExceedsLimit({+ entitlementLimit: "monitor-count",+ sessionUser: ctx.session.user,+ orgId: ctx.session.orgId,+ currentUsage: currentCount,+ });+return MonitorService.create(sessionContextFromCtx(ctx), input);}),@@ -80,4 +96,45 @@ export const monitorsRouter = createTRPCRouter({});return MonitorService.list(sessionContextFromCtx(ctx), input);}),++ count: monitorsProcedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "monitors:read",+ });+ const count = await ctx.prisma.monitor.count({+ where: { project: { orgId: ctx.session.orgId, deletedAt: null } },+ });+ return { count };+ }),++ /** hasAny reports whether the project owns at least one monitor; drives the list-page onboarding splash. */+ hasAny: monitorsProcedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "monitors:read",+ });+ const monitor = await ctx.prisma.monitor.findFirst({+ where: { projectId: input.projectId },+ select: { id: true },+ });+ return monitor !== null;+ }),++ getFilterOptions: monitorsProcedure+ .input(GetMonitorFilterOptionsSchema)+ .query(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "monitors:read",+ });+ return MonitorService.getFilterOptions(sessionContextFromCtx(ctx), input);+ }),});diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex 3d0c295231..c1c1848ad8 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -386,6 +386,14 @@ export const requireFeatureFlag = (flag: Flag) =>return next();});+/** requireLangfuseCloud rejects calls from non-Langfuse-Cloud deployments. */+export const requireLangfuseCloud = t.middleware(({ next }) => {+ if (!isLangfuseCloud) {+ throw new TRPCError({ code: "NOT_FOUND", message: "Not found" });+ }+ return next();+});+export const protectedProjectProcedureWithoutTracing = t.procedure.use(withErrorHandling).use(enforceUserIsAuthedAndProjectMember);diff --git a/worker/package.json b/worker/package.jsonindex 11f6f42ecf..dd6e57cb63 100644--- a/worker/package.json+++ b/worker/package.json@@ -62,6 +62,7 @@"p-limit": "^7.3.0","pg": "^8.13.0","posthog-node": "^5.32.0",+ "slackify-markdown": "^5.0.0","stripe": "^17.4.0","tiktoken": "^1.0.20","uuid": "^14.0.0",diff --git a/worker/src/__tests__/__snapshots__/monitorProcessorScalarQuery.test.ts.snap b/worker/src/__tests__/__snapshots__/monitorProcessorScalarQuery.test.ts.snapnew file mode 100644index 0000000000..9c6c5d289a--- /dev/null+++ b/worker/src/__tests__/__snapshots__/monitorProcessorScalarQuery.test.ts.snap@@ -0,0 +1,222 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`monitor scalar query — empty project > verifies which parameters return zero and which return null 1`] = `+{+ "observations/costByType/avg": null,+ "observations/costByType/count": null,+ "observations/costByType/max": null,+ "observations/costByType/min": null,+ "observations/costByType/p50": null,+ "observations/costByType/p75": null,+ "observations/costByType/p90": null,+ "observations/costByType/p95": null,+ "observations/costByType/p99": null,+ "observations/costByType/sum": null,+ "observations/costByType/uniq": null,+ "observations/count/count": 0,+ "observations/countScores/avg": null,+ "observations/countScores/count": 0,+ "observations/countScores/max": 0,+ "observations/countScores/min": 0,+ "observations/countScores/p50": null,+ "observations/countScores/p75": null,+ "observations/countScores/p90": null,+ "observations/countScores/p95": null,+ "observations/countScores/p99": null,+ "observations/countScores/sum": 0,+ "observations/countScores/uniq": 0,+ "observations/inputCost/avg": null,+ "observations/inputCost/count": 0,+ "observations/inputCost/max": 0,+ "observations/inputCost/min": 0,+ "observations/inputCost/p50": 0,+ "observations/inputCost/p75": 0,+ "observations/inputCost/p90": 0,+ "observations/inputCost/p95": 0,+ "observations/inputCost/p99": 0,+ "observations/inputCost/sum": 0,+ "observations/inputCost/uniq": 0,+ "observations/inputTokens/avg": null,+ "observations/inputTokens/count": 0,+ "observations/inputTokens/max": 0,+ "observations/inputTokens/min": 0,+ "observations/inputTokens/p50": null,+ "observations/inputTokens/p75": null,+ "observations/inputTokens/p90": null,+ "observations/inputTokens/p95": null,+ "observations/inputTokens/p99": null,+ "observations/inputTokens/sum": 0,+ "observations/inputTokens/uniq": 0,+ "observations/latency/avg": null,+ "observations/latency/count": 0,+ "observations/latency/max": null,+ "observations/latency/min": null,+ "observations/latency/p50": null,+ "observations/latency/p75": null,+ "observations/latency/p90": null,+ "observations/latency/p95": null,+ "observations/latency/p99": null,+ "observations/latency/sum": null,+ "observations/latency/uniq": 0,+ "observations/outputCost/avg": null,+ "observations/outputCost/count": 0,+ "observations/outputCost/max": 0,+ "observations/outputCost/min": 0,+ "observations/outputCost/p50": 0,+ "observations/outputCost/p75": 0,+ "observations/outputCost/p90": 0,+ "observations/outputCost/p95": 0,+ "observations/outputCost/p99": 0,+ "observations/outputCost/sum": 0,+ "observations/outputCost/uniq": 0,+ "observations/outputTokens/avg": null,+ "observations/outputTokens/count": 0,+ "observations/outputTokens/max": 0,+ "observations/outputTokens/min": 0,+ "observations/outputTokens/p50": null,+ "observations/outputTokens/p75": null,+ "observations/outputTokens/p90": null,+ "observations/outputTokens/p95": null,+ "observations/outputTokens/p99": null,+ "observations/outputTokens/sum": 0,+ "observations/outputTokens/uniq": 0,+ "observations/outputTokensPerSecond/avg": null,+ "observations/outputTokensPerSecond/count": 0,+ "observations/outputTokensPerSecond/max": null,+ "observations/outputTokensPerSecond/min": null,+ "observations/outputTokensPerSecond/p50": null,+ "observations/outputTokensPerSecond/p75": null,+ "observations/outputTokensPerSecond/p90": null,+ "observations/outputTokensPerSecond/p95": null,+ "observations/outputTokensPerSecond/p99": null,+ "observations/outputTokensPerSecond/sum": null,+ "observations/outputTokensPerSecond/uniq": 0,+ "observations/streamingLatency/avg": null,+ "observations/streamingLatency/count": 0,+ "observations/streamingLatency/max": null,+ "observations/streamingLatency/min": null,+ "observations/streamingLatency/p50": null,+ "observations/streamingLatency/p75": null,+ "observations/streamingLatency/p90": null,+ "observations/streamingLatency/p95": null,+ "observations/streamingLatency/p99": null,+ "observations/streamingLatency/sum": null,+ "observations/streamingLatency/uniq": 0,+ "observations/timeToFirstToken/avg": null,+ "observations/timeToFirstToken/count": 0,+ "observations/timeToFirstToken/max": null,+ "observations/timeToFirstToken/min": null,+ "observations/timeToFirstToken/p50": null,+ "observations/timeToFirstToken/p75": null,+ "observations/timeToFirstToken/p90": null,+ "observations/timeToFirstToken/p95": null,+ "observations/timeToFirstToken/p99": null,+ "observations/timeToFirstToken/sum": null,+ "observations/timeToFirstToken/uniq": 0,+ "observations/tokensPerSecond/avg": null,+ "observations/tokensPerSecond/count": 0,+ "observations/tokensPerSecond/max": null,+ "observations/tokensPerSecond/min": null,+ "observations/tokensPerSecond/p50": null,+ "observations/tokensPerSecond/p75": null,+ "observations/tokensPerSecond/p90": null,+ "observations/tokensPerSecond/p95": null,+ "observations/tokensPerSecond/p99": null,+ "observations/tokensPerSecond/sum": null,+ "observations/tokensPerSecond/uniq": 0,+ "observations/toolCalls/avg": null,+ "observations/toolCalls/count": 0,+ "observations/toolCalls/max": null,+ "observations/toolCalls/min": null,+ "observations/toolCalls/p50": null,+ "observations/toolCalls/p75": null,+ "observations/toolCalls/p90": null,+ "observations/toolCalls/p95": null,+ "observations/toolCalls/p99": null,+ "observations/toolCalls/sum": null,+ "observations/toolCalls/uniq": 0,+ "observations/toolDefinitions/avg": null,+ "observations/toolDefinitions/count": 0,+ "observations/toolDefinitions/max": null,+ "observations/toolDefinitions/min": null,+ "observations/toolDefinitions/p50": null,+ "observations/toolDefinitions/p75": null,+ "observations/toolDefinitions/p90": null,+ "observations/toolDefinitions/p95": null,+ "observations/toolDefinitions/p99": null,+ "observations/toolDefinitions/sum": null,+ "observations/toolDefinitions/uniq": 0,+ "observations/totalCost/avg": null,+ "observations/totalCost/count": 0,+ "observations/totalCost/max": null,+ "observations/totalCost/min": null,+ "observations/totalCost/p50": null,+ "observations/totalCost/p75": null,+ "observations/totalCost/p90": null,+ "observations/totalCost/p95": null,+ "observations/totalCost/p99": null,+ "observations/totalCost/sum": null,+ "observations/totalCost/uniq": 0,+ "observations/totalTokens/avg": null,+ "observations/totalTokens/count": 0,+ "observations/totalTokens/max": 0,+ "observations/totalTokens/min": 0,+ "observations/totalTokens/p50": null,+ "observations/totalTokens/p75": null,+ "observations/totalTokens/p90": null,+ "observations/totalTokens/p95": null,+ "observations/totalTokens/p99": null,+ "observations/totalTokens/sum": 0,+ "observations/totalTokens/uniq": 0,+ "observations/traceId/count": 0,+ "observations/traceId/uniq": 0,+ "observations/uniqueSessionIds/count": 0,+ "observations/uniqueSessionIds/uniq": 0,+ "observations/uniqueUserIds/count": 0,+ "observations/uniqueUserIds/uniq": 0,+ "observations/usageByType/avg": null,+ "observations/usageByType/count": null,+ "observations/usageByType/max": null,+ "observations/usageByType/min": null,+ "observations/usageByType/p50": null,+ "observations/usageByType/p75": null,+ "observations/usageByType/p90": null,+ "observations/usageByType/p95": null,+ "observations/usageByType/p99": null,+ "observations/usageByType/sum": null,+ "observations/usageByType/uniq": null,+ "scores-categorical/count/avg": null,+ "scores-categorical/count/count": 0,+ "scores-categorical/count/max": 0,+ "scores-categorical/count/min": 0,+ "scores-categorical/count/p50": null,+ "scores-categorical/count/p75": null,+ "scores-categorical/count/p90": null,+ "scores-categorical/count/p95": null,+ "scores-categorical/count/p99": null,+ "scores-categorical/count/sum": 0,+ "scores-categorical/count/uniq": 0,+ "scores-numeric/count/avg": null,+ "scores-numeric/count/count": 0,+ "scores-numeric/count/max": 0,+ "scores-numeric/count/min": 0,+ "scores-numeric/count/p50": null,+ "scores-numeric/count/p75": null,+ "scores-numeric/count/p90": null,+ "scores-numeric/count/p95": null,+ "scores-numeric/count/p99": null,+ "scores-numeric/count/sum": 0,+ "scores-numeric/count/uniq": 0,+ "scores-numeric/value/avg": null,+ "scores-numeric/value/count": 0,+ "scores-numeric/value/max": 0,+ "scores-numeric/value/min": 0,+ "scores-numeric/value/p50": null,+ "scores-numeric/value/p75": null,+ "scores-numeric/value/p90": null,+ "scores-numeric/value/p95": null,+ "scores-numeric/value/p99": null,+ "scores-numeric/value/sum": 0,+ "scores-numeric/value/uniq": 0,+}+`;diff --git a/worker/src/__tests__/monitorProcessor.test.ts b/worker/src/__tests__/monitorProcessor.test.tsnew file mode 100644index 0000000000..0dda5d7899--- /dev/null+++ b/worker/src/__tests__/monitorProcessor.test.ts@@ -0,0 +1,1625 @@+import { v4 } from "uuid";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";++import { createOrgProjectAndApiKey, logger } from "@langfuse/shared/src/server";+import { InvalidRequestError } from "@langfuse/shared";+import {+ MonitorProcessor,+ type MonitorPublisher,+ type QueryExecutor,+ type MonitorQueueEvent,+ type MonitorQueueEventInput,+ type GetTriggerConfigurations,+} from "@langfuse/shared/monitors/server";+import { prisma } from "@langfuse/shared/src/db";+import type { Prisma, PrismaClient } from "@prisma/client";++type MonitorStatus = "ACTIVE" | "PAUSED" | "ERROR_BAD_QUERY";+type MonitorView = "OBSERVATIONS" | "SCORES_NUMERIC" | "SCORES_CATEGORICAL";+type MonitorSeverity =+ | "UNKNOWN"+ | "OK"+ | "WARNING"+ | "ALERT"+ | "NO_DATA"+ | "PAUSED";+type ThresholdOperator = "GT" | "GTE" | "LT" | "LTE" | "EQ" | "NEQ";++type Metric = { measure: string; aggregation: string };++type SeedOverrides = Partial<{+ schedulerBatchId: bigint;+ windowMs: bigint;+ status: MonitorStatus;+ view: MonitorView;+ metric: Metric;+ alertThreshold: number;+ warningThreshold: number | null;+ thresholdOperator: ThresholdOperator;+ noData: { mode: "SILENT" } | { mode: "NOTIFY"; intervalMinutes: number };+ renotify: { mode: "OFF" } | { mode: "EVERY"; intervalMinutes: number };+ severity: MonitorSeverity;+ severityChangedAt: Date | null;+ alertedAt: Date | null;+ tags: string[];+ triggerIds: string[];+ lastPublishedAt: Date | null;+ lastClaimedAt: Date | null;+ lastCompletedAt: Date | null;+}>;++type MonitorSeed = { id: string } & SeedOverrides;++type TriggerSeed = {+ filter: { column: string; operator: string; value: unknown; type: string }[];+ eventActions?: string[];+ automations?: { id: string; actionId: string }[];+};++type ExpectedRow = {+ id: string;+ status?: MonitorStatus;+ severity: MonitorSeverity;+ severityChangedAt: Date | null;+ alertedAt: Date | null;+ lastClaimedAt: Date | null;+ lastCompletedAt: Date | null;+};++type InjectErrorStage =+ | "claim"+ | "executeQuery"+ | "getTriggers"+ | "publish"+ | "complete";++type ProcessCase = {+ name: string;+ monitors: MonitorSeed[];+ triggers?: TriggerSeed[];+ ch?: Record<string, unknown>[];+ injectError?: {+ stage: InjectErrorStage;+ message: string;+ errorClass?: "invalid-request";+ };+ preempt?: { newClaimedAt: Date };+ preemptPause?: { at: Date };+ rescue?: { newPublishedAt: Date };+ expect: {+ throws?: string;+ publishCallCount: number;+ publishMatch?: Record<string, unknown>;+ publishCallsMatch?: Record<string, unknown>[];+ rows: ExpectedRow[];+ };+};++const oneMinuteMs = 60n * 1000n;+const fiveMinutesMs = 5n * oneMinuteMs;++const runAt = new Date("2026-05-27T12:00:00.000Z");+const justAfterRunAt = new Date("2026-05-27T12:00:01.000Z");+const tenMinutesAgo = new Date("2026-05-27T11:50:00.000Z");+const laterPublish = new Date("2026-05-27T12:01:00.000Z");+const pausedAt = new Date("2026-05-27T12:00:00.500Z");++const matchAnyAlertTrigger: TriggerSeed = {+ filter: [+ {+ column: "severity",+ operator: "any of",+ value: ["WARNING", "ALERT", "NO_DATA"],+ type: "stringOptions",+ },+ ],+};++const monitorAId = `m_a_${v4()}`;+const monitorBId = `m_b_${v4()}`;++/** seedMonitor writes one Monitor row from a seed; defaults align with a fresh ACTIVE monitor whose run was just published. */+async function seedMonitor(projectId: string, seed: MonitorSeed) {+ return prisma.monitor.create({+ data: {+ id: seed.id,+ projectId,+ view: seed.view ?? "OBSERVATIONS",+ filters: [] as unknown as Prisma.InputJsonValue,+ metric: (seed.metric ?? {+ measure: "count",+ aggregation: "count",+ }) as unknown as Prisma.InputJsonValue,+ windowMs: seed.windowMs ?? fiveMinutesMs,+ cadenceMs: oneMinuteMs,+ thresholdOperator: seed.thresholdOperator ?? "GT",+ alertThreshold: seed.alertThreshold ?? 100,+ warningThreshold: seed.warningThreshold ?? null,+ noData: (seed.noData ?? {+ mode: "SILENT",+ }) as unknown as Prisma.InputJsonValue,+ renotify: (seed.renotify ?? {+ mode: "OFF",+ }) as unknown as Prisma.InputJsonValue,+ status: seed.status ?? "ACTIVE",+ schedulerBatchId: seed.schedulerBatchId ?? 0n,+ nextRunAt: new Date("2099-01-01T00:00:00.000Z"),+ lastPublishedAt:+ seed.lastPublishedAt === undefined ? runAt : seed.lastPublishedAt,+ lastClaimedAt: seed.lastClaimedAt ?? null,+ lastCompletedAt: seed.lastCompletedAt ?? null,+ severity: seed.severity ?? "UNKNOWN",+ severityChangedAt: seed.severityChangedAt ?? null,+ alertedAt: seed.alertedAt ?? null,+ tags: seed.tags ?? [],+ triggerIds: seed.triggerIds ?? [],+ name: `Test ${seed.id}`,+ },+ });+}++/** makeEvent builds the MonitorQueueEvent for the seeded monitors, deduping each monitor's metric into the batch and keying metricName by `${aggregation}_${measure}`. */+function makeEvent(+ projectId: string,+ monitors: (string | { id: string; metric?: Metric })[],+): MonitorQueueEvent {+ const seeds = monitors.map((m) =>+ typeof m === "string" ? { id: m, metric: undefined } : m,+ );+ const metricOf = (m: (typeof seeds)[number]): Metric =>+ m.metric ?? { measure: "count", aggregation: "count" };+ const seen = new Set<string>();+ const metrics: Metric[] = [];+ for (const s of seeds) {+ const metric = metricOf(s);+ const key = `${metric.aggregation}_${metric.measure}`;+ if (seen.has(key)) continue;+ seen.add(key);+ metrics.push(metric);+ }+ return {+ projectId,+ schedulerBatchId: 0n,+ runAt,+ publishedAt: runAt,+ view: "observations",+ filters: [],+ window: "5m",+ metrics: metrics as MonitorQueueEvent["metrics"],+ monitors: seeds.map((s) => {+ const metric = metricOf(s);+ return {+ monitorId: s.id,+ metricName: `${metric.aggregation}_${metric.measure}`,+ };+ }),+ };+}++/** wrapDbToThrow returns a Proxy over `db` that rejects at the DB seam matching `stage`: claim intercepts `monitor.updateManyAndReturn`, complete intercepts `$executeRaw`. Lets the table inject failures without per-method seams on the processor. */+function wrapDbToThrow(+ db: PrismaClient,+ stage: "claim" | "complete",+ message: string,+): PrismaClient {+ if (stage === "complete") {+ return new Proxy(db, {+ get(target, prop, _receiver) {+ if (prop === "$executeRaw") {+ return () => Promise.reject(new Error(message));+ }+ return Reflect.get(target, prop, target);+ },+ }) as PrismaClient;+ }+ return new Proxy(db, {+ get(target, prop, _receiver) {+ if (prop === "monitor") {+ const delegate = Reflect.get(target, prop, target);+ return new Proxy(delegate, {+ get(dTarget, dProp, _dReceiver) {+ if (dProp === "updateManyAndReturn") {+ return () => Promise.reject(new Error(message));+ }+ return Reflect.get(dTarget, dProp, dTarget);+ },+ });+ }+ return Reflect.get(target, prop, target);+ },+ }) as PrismaClient;+}++/** wrapDbPreemptBeforeComplete simulates another worker re-claiming between this worker's claim and complete: the first `$executeRaw` (the complete) first bumps `lastClaimedAt` on the project's monitors so the complete-side CAS owner key no longer matches and the update no-ops. */+function wrapDbPreemptBeforeComplete(+ db: PrismaClient,+ projectId: string,+ newClaimedAt: Date,+): PrismaClient {+ let preempted = false;+ return new Proxy(db, {+ get(target, prop, _receiver) {+ if (prop === "$executeRaw") {+ return async (...args: unknown[]) => {+ if (!preempted) {+ preempted = true;+ await target.monitor.updateMany({+ where: { projectId },+ data: { lastClaimedAt: newClaimedAt },+ });+ }+ return (target.$executeRaw as (...a: unknown[]) => unknown)(...args);+ };+ }+ return Reflect.get(target, prop, target);+ },+ }) as PrismaClient;+}++/** wrapDbPauseBeforeComplete simulates a user pausing between this worker's claim and complete: the first `$executeRaw` (the complete) first flips the project's monitors to PAUSED without touching `lastClaimedAt`, so the complete-side CAS owner key still matches. */+function wrapDbPauseBeforeComplete(+ db: PrismaClient,+ projectId: string,+ at: Date,+): PrismaClient {+ let paused = false;+ return new Proxy(db, {+ get(target, prop, _receiver) {+ if (prop === "$executeRaw") {+ return async (...args: unknown[]) => {+ if (!paused) {+ paused = true;+ await target.monitor.updateMany({+ where: { projectId },+ data: {+ status: "PAUSED",+ severity: "PAUSED",+ severityChangedAt: at,+ },+ });+ }+ return (target.$executeRaw as (...a: unknown[]) => unknown)(...args);+ };+ }+ return Reflect.get(target, prop, target);+ },+ }) as PrismaClient;+}++/** wrapDbRescueBeforeComplete simulates the scheduler TTL-rescuing this worker's stale run between claim and complete: the first `$executeRaw` (the complete) first advances `lastPublishedAt` on the project's monitors — leaving `lastClaimedAt` and `lastCompletedAt` untouched, exactly as buildScheduleQuery does — so the complete-side CAS owner key still matches on `lastClaimedAt` but the new publish-identity clause no-ops. */+function wrapDbRescueBeforeComplete(+ db: PrismaClient,+ projectId: string,+ newPublishedAt: Date,+): PrismaClient {+ let rescued = false;+ return new Proxy(db, {+ get(target, prop, _receiver) {+ if (prop === "$executeRaw") {+ return async (...args: unknown[]) => {+ if (!rescued) {+ rescued = true;+ await target.monitor.updateMany({+ where: { projectId },+ data: { lastPublishedAt: newPublishedAt },+ });+ }+ return (target.$executeRaw as (...a: unknown[]) => unknown)(...args);+ };+ }+ return Reflect.get(target, prop, target);+ },+ }) as PrismaClient;+}++const cases: ProcessCase[] = [+ {+ name: "no severity change: claim, complete, no sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ },+ ],+ ch: [{ count_count: 50 }],+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "no triggers match: claim, complete, sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [+ {+ filter: [+ {+ column: "severity",+ operator: "any of",+ value: ["WARNING"],+ type: "stringOptions",+ },+ ],+ },+ ],+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: justAfterRunAt,+ alertedAt: justAfterRunAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "alert: claim, complete, sev change, emit",+ monitors: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 1,+ publishMatch: {+ projectId: expect.any(String),+ automationId: expect.any(String),+ executionId: expect.any(String),+ payload: {+ type: "monitor-alert",+ apiVersion: "v1",+ payload: {+ monitorId: monitorAId,+ severity: "ALERT",+ message: {+ title: `[ALERT] Test ${monitorAId}`,+ body: "`count(observations.count)` is **above** `100`",+ },+ view: "observations",+ window: "5m",+ },+ },+ },+ rows: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: justAfterRunAt,+ alertedAt: justAfterRunAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "renotify on: claim, complete, no sev change, emit",+ monitors: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: tenMinutesAgo,+ alertedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ renotify: { mode: "EVERY", intervalMinutes: 5 },+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 1,+ rows: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: tenMinutesAgo,+ alertedAt: justAfterRunAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "renotify off: claim, complete, no sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: tenMinutesAgo,+ alertedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ renotify: { mode: "OFF" },+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: tenMinutesAgo,+ alertedAt: tenMinutesAgo,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "count monitor empty window (count_count 0): NO_DATA, not OK",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ noData: { mode: "NOTIFY", intervalMinutes: 5 },+ },+ ],+ ch: [{ count_count: 0 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 1,+ rows: [+ {+ id: monitorAId,+ severity: "NO_DATA",+ severityChangedAt: justAfterRunAt,+ alertedAt: justAfterRunAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "count monitor non-empty window (count_count 5): evaluates normally",+ monitors: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ alertThreshold: 3,+ thresholdOperator: "GT",+ },+ ],+ ch: [{ count_count: 5 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 1,+ publishMatch: {+ payload: {+ type: "monitor-alert",+ apiVersion: "v1",+ payload: { monitorId: monitorAId, severity: "ALERT" },+ },+ },+ rows: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: justAfterRunAt,+ alertedAt: justAfterRunAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "nodata on: claim, complete, sev change, emit",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ noData: { mode: "NOTIFY", intervalMinutes: 5 },+ },+ ],+ ch: [{}],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 1,+ rows: [+ {+ id: monitorAId,+ severity: "NO_DATA",+ severityChangedAt: justAfterRunAt,+ alertedAt: justAfterRunAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "nodata off: claim, complete, sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ noData: { mode: "SILENT" },+ },+ ],+ ch: [{}],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "NO_DATA",+ severityChangedAt: justAfterRunAt,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "error on claim: no claim, no complete, no sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ },+ ],+ injectError: { stage: "claim", message: "PG down (claim)" },+ expect: {+ throws: "PG down (claim)",+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ alertedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "error on executeQuery: flips ERROR_BAD_QUERY, PAUSED, no throw, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ },+ ],+ injectError: { stage: "executeQuery", message: "CH timeout" },+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ status: "ERROR_BAD_QUERY",+ severity: "PAUSED",+ severityChangedAt: justAfterRunAt,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "InvalidRequestError on executeQuery: flips ERROR_BAD_QUERY, PAUSED, no throw, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ },+ ],+ injectError: {+ stage: "executeQuery",+ errorClass: "invalid-request",+ message: "Invalid filter column",+ },+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ status: "ERROR_BAD_QUERY",+ severity: "PAUSED",+ severityChangedAt: justAfterRunAt,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "error on getTriggers: claim, no complete, no sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ },+ ],+ injectError: { stage: "getTriggers", message: "trigger lookup failed" },+ expect: {+ throws: "trigger lookup failed",+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "InvalidRequestError on getTriggers: rethrows, stays ACTIVE, not ERROR_BAD_QUERY",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ },+ ],+ injectError: {+ stage: "getTriggers",+ errorClass: "invalid-request",+ message: "bad trigger filter",+ },+ expect: {+ throws: "bad trigger filter",+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ status: "ACTIVE",+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "error on publish: claim, no complete, no sev change, emit (publish fired before throwing)",+ monitors: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ injectError: { stage: "publish", message: "webhook queue rejected" },+ expect: {+ throws: "webhook queue rejected",+ publishCallCount: 1,+ rows: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ severityChangedAt: null,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "error on complete: claim, no complete, no sev change, emit (publish fired before throwing)",+ monitors: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ injectError: { stage: "complete", message: "PG down (complete)" },+ expect: {+ throws: "PG down (complete)",+ publishCallCount: 1,+ rows: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ severityChangedAt: null,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "partial claim: claim, complete, sev change, emit for claimable; no claim for already-completed",+ monitors: [+ // already-completed: claim's clause 2 rejects it (lastCompletedAt == lastPublishedAt)+ {+ id: monitorAId,+ schedulerBatchId: 7n,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ lastClaimedAt: runAt,+ lastCompletedAt: runAt,+ },+ // claimable: fresh, will emit ALERT+ {+ id: monitorBId,+ schedulerBatchId: 7n,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 1,+ publishMatch: {+ payload: {+ type: "monitor-alert",+ apiVersion: "v1",+ payload: {+ monitorId: monitorBId,+ severity: "ALERT",+ },+ },+ },+ rows: [+ // done: untouched+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ alertedAt: null,+ lastClaimedAt: runAt,+ lastCompletedAt: runAt,+ },+ // claimable: fully processed+ {+ id: monitorBId,+ severity: "ALERT",+ severityChangedAt: justAfterRunAt,+ alertedAt: justAfterRunAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "fan-out: 2 matching triggers → 2 publish calls, distinct executionIds + automationIds",+ monitors: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [+ {+ ...matchAnyAlertTrigger,+ automations: [{ id: "auto_fan_a", actionId: "act_fan_a" }],+ },+ {+ ...matchAnyAlertTrigger,+ automations: [{ id: "auto_fan_b", actionId: "act_fan_b" }],+ },+ ],+ expect: {+ publishCallCount: 2,+ publishCallsMatch: [+ {+ automationId: "auto_fan_a",+ payload: {+ type: "monitor-alert",+ apiVersion: "v1",+ payload: { monitorId: monitorAId, severity: "ALERT" },+ },+ },+ {+ automationId: "auto_fan_b",+ payload: {+ type: "monitor-alert",+ apiVersion: "v1",+ payload: { monitorId: monitorAId, severity: "ALERT" },+ },+ },+ ],+ rows: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: justAfterRunAt,+ alertedAt: justAfterRunAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "fan-out: 1 matched + 1 rejected → 1 publish for matched trigger",+ monitors: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [+ {+ ...matchAnyAlertTrigger,+ automations: [{ id: "auto_match", actionId: "act_match" }],+ },+ {+ filter: [+ {+ column: "severity",+ operator: "any of",+ value: ["WARNING"],+ type: "stringOptions",+ },+ ],+ automations: [{ id: "auto_reject", actionId: "act_reject" }],+ },+ ],+ expect: {+ publishCallCount: 1,+ publishMatch: {+ automationId: "auto_match",+ payload: {+ type: "monitor-alert",+ apiVersion: "v1",+ payload: { monitorId: monitorAId, severity: "ALERT" },+ },+ },+ rows: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: justAfterRunAt,+ alertedAt: justAfterRunAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "scheduler published a newer event: no claim, no complete, no sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: laterPublish,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ alertedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "scheduler never published this event: no claim, no complete, no sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: null,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ severityChangedAt: null,+ alertedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "processor claimed this event already: no claim, no complete, no sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: null,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ severityChangedAt: null,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "processor completed this event already: no claim, no complete, no sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ lastClaimedAt: runAt,+ lastCompletedAt: runAt,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ alertedAt: null,+ lastClaimedAt: runAt,+ lastCompletedAt: runAt,+ },+ ],+ },+ },+ {+ name: "another worker re-claims before complete: claim, no complete, no sev change, emit",+ monitors: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: tenMinutesAgo,+ alertedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ renotify: { mode: "EVERY", intervalMinutes: 5 },+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ preempt: { newClaimedAt: laterPublish },+ expect: {+ publishCallCount: 1,+ rows: [+ {+ id: monitorAId,+ severity: "ALERT",+ severityChangedAt: tenMinutesAgo,+ alertedAt: tenMinutesAgo,+ lastClaimedAt: laterPublish,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "user pauses after claim before complete: webhook fired (RFC §9), but PAUSED row not overwritten",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ alertedAt: null,+ lastPublishedAt: runAt,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ preemptPause: { at: pausedAt },+ expect: {+ publishCallCount: 1, // webhook fires pre-complete; separable per RFC §9+ rows: [+ {+ id: monitorAId,+ severity: "PAUSED",+ severityChangedAt: pausedAt,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: null, // complete CAS no-ops on the PAUSED row+ },+ ],+ },+ },+ {+ name: "scheduler rescues (advances last_published_at) before a stuck worker completes: webhook fired (RFC §9), but stale writeback blocked",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ alertedAt: null,+ lastPublishedAt: runAt, // worker claims event with publishedAt=runAt, stamps lastClaimedAt=justAfterRunAt+ },+ ],+ ch: [{ count_count: 200 }], // > alertThreshold 100 → computed ALERT+ triggers: [matchAnyAlertTrigger],+ rescue: { newPublishedAt: laterPublish }, // scheduler TTL rescue moved last_published_at forward+ expect: {+ publishCallCount: 1, // webhook fires pre-complete; separable per RFC §9+ rows: [+ {+ id: monitorAId,+ severity: "OK", // complete CAS no-ops → prior severity preserved+ severityChangedAt: tenMinutesAgo,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt, // worker's claim stamp, untouched by rescue+ lastCompletedAt: null, // CAS no-ops → not advanced → Worker B's claim stays unblocked+ },+ ],+ },+ },+ {+ name: "monitor paused before claim: no claim, no complete, no sev change, no emit",+ monitors: [+ {+ id: monitorAId,+ status: "PAUSED",+ severity: "PAUSED",+ lastPublishedAt: runAt,+ lastClaimedAt: null,+ lastCompletedAt: null,+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ severity: "PAUSED",+ severityChangedAt: null,+ alertedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "mixed metric batch: valid-metric monitor completes, invalid-metric monitor flips ERROR_BAD_QUERY only for itself",+ monitors: [+ {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ },+ {+ id: monitorBId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ metric: { measure: "bogus_measure", aggregation: "count" },+ },+ ],+ ch: [{ count_count: 200 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 1,+ publishMatch: {+ payload: {+ type: "monitor-alert",+ apiVersion: "v1",+ payload: { monitorId: monitorAId, severity: "ALERT" },+ },+ },+ rows: [+ {+ id: monitorAId,+ status: "ACTIVE",+ severity: "ALERT",+ severityChangedAt: justAfterRunAt,+ alertedAt: justAfterRunAt,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ {+ id: monitorBId,+ status: "ERROR_BAD_QUERY",+ severity: "PAUSED",+ severityChangedAt: justAfterRunAt,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+ {+ name: "rejected metric in a zero-count window: flips ERROR_BAD_QUERY, not NO_DATA",+ monitors: [+ {+ id: monitorAId,+ severity: "OK",+ severityChangedAt: tenMinutesAgo,+ lastPublishedAt: runAt,+ metric: { measure: "bogus_measure", aggregation: "count" },+ noData: { mode: "NOTIFY", intervalMinutes: 5 },+ },+ ],+ ch: [{ count_count: 0 }],+ triggers: [matchAnyAlertTrigger],+ expect: {+ publishCallCount: 0,+ rows: [+ {+ id: monitorAId,+ status: "ERROR_BAD_QUERY",+ severity: "PAUSED",+ severityChangedAt: justAfterRunAt,+ alertedAt: null,+ lastClaimedAt: justAfterRunAt,+ lastCompletedAt: justAfterRunAt,+ },+ ],+ },+ },+];++describe("MonitorProcessor.process (integration)", () => {+ let projectId: string;++ beforeAll(async () => {+ const org = await createOrgProjectAndApiKey();+ projectId = org.projectId;+ });++ afterEach(async () => {+ await prisma.monitor.deleteMany({ where: { projectId } });+ });++ it.each(cases)("$name", async (c) => {+ const triggerIds = (c.triggers ?? []).map((_, i) => `trig_${i}`);+ for (const m of c.monitors) {+ await seedMonitor(projectId, { ...m, triggerIds });+ }++ const publish = vi.fn<MonitorPublisher>(async () => {});+ if (c.injectError?.stage === "publish") {+ publish.mockRejectedValueOnce(new Error(c.injectError.message));+ }++ const executeQuery: QueryExecutor = async () => {+ if (c.injectError?.stage === "executeQuery") {+ if (c.injectError.errorClass === "invalid-request") {+ throw new InvalidRequestError(c.injectError.message);+ }+ throw new Error(c.injectError.message);+ }+ return c.ch ?? [{ count_count: 0 }];+ };++ const getTriggers: GetTriggerConfigurations = async () => {+ if (c.injectError?.stage === "getTriggers") {+ if (c.injectError.errorClass === "invalid-request") {+ throw new InvalidRequestError(c.injectError.message);+ }+ throw new Error(c.injectError.message);+ }+ // Trigger ids line up with the monitor's seeded triggerIds so the+ // triggerIds opt-in passes; the severity filter does the discriminating.+ return (c.triggers ?? []).map((t, i) => ({+ id: `trig_${i}`,+ filter: t.filter,+ eventActions: t.eventActions ?? [],+ automations: t.automations ?? [+ { id: `auto_default_${i}`, actionId: `act_default_${i}` },+ ],+ })) as unknown as Awaited<ReturnType<GetTriggerConfigurations>>;+ };++ let db: PrismaClient = prisma;+ if (c.injectError?.stage === "claim") {+ db = wrapDbToThrow(prisma, "claim", c.injectError.message);+ } else if (c.injectError?.stage === "complete") {+ db = wrapDbToThrow(prisma, "complete", c.injectError.message);+ } else if (c.preempt) {+ db = wrapDbPreemptBeforeComplete(+ prisma,+ projectId,+ c.preempt.newClaimedAt,+ );+ } else if (c.preemptPause) {+ db = wrapDbPauseBeforeComplete(prisma, projectId, c.preemptPause.at);+ } else if (c.rescue) {+ db = wrapDbRescueBeforeComplete(+ prisma,+ projectId,+ c.rescue.newPublishedAt,+ );+ }++ const processor = new MonitorProcessor(+ db,+ publish,+ executeQuery,+ getTriggers,+ );++ const event = makeEvent(+ projectId,+ c.monitors.map((m) => ({ id: m.id, metric: m.metric })),+ );+ if (c.expect.throws) {+ await expect(processor.process(event, justAfterRunAt)).rejects.toThrow(+ c.expect.throws,+ );+ } else {+ await processor.process(event, justAfterRunAt);+ }++ expect(publish).toHaveBeenCalledTimes(c.expect.publishCallCount);+ if (c.expect.publishMatch && c.expect.publishCallCount > 0) {+ expect(publish.mock.calls[0][0]).toMatchObject(c.expect.publishMatch);+ }+ if (c.expect.publishCallsMatch) {+ // Match each expected entry against any actual publish call using+ // toMatchObject semantics (deep-partial). Order-independent.+ const actual = publish.mock.calls.map((args) => args[0]);+ for (const expected of c.expect.publishCallsMatch) {+ const found = actual.some((call) => {+ try {+ expect(call).toMatchObject(expected);+ return true;+ } catch {+ return false;+ }+ });+ expect(+ found,+ `no publish call matched ${JSON.stringify(expected)}`,+ ).toBe(true);+ }+ // Assert distinct executionIds across calls.+ const executionIds = actual.map(+ (a) => (a as { executionId: string }).executionId,+ );+ expect(new Set(executionIds).size).toBe(executionIds.length);+ }++ for (const exp of c.expect.rows) {+ const row = await prisma.monitor.findUniqueOrThrow({+ where: { id: exp.id },+ });+ if (exp.status) expect(row.status).toBe(exp.status);+ expect(row.severity).toBe(exp.severity);+ expect(row.severityChangedAt?.toISOString() ?? null).toBe(+ exp.severityChangedAt?.toISOString() ?? null,+ );+ expect(row.alertedAt?.toISOString() ?? null).toBe(+ exp.alertedAt?.toISOString() ?? null,+ );+ expect(row.lastClaimedAt?.toISOString() ?? null).toBe(+ exp.lastClaimedAt?.toISOString() ?? null,+ );+ expect(row.lastCompletedAt?.toISOString() ?? null).toBe(+ exp.lastCompletedAt?.toISOString() ?? null,+ );+ }+ });+});++describe("MonitorProcessor.process evaluation offset", () => {+ let projectId: string;++ beforeAll(async () => {+ const org = await createOrgProjectAndApiKey();+ projectId = org.projectId;+ });++ afterEach(async () => {+ await prisma.monitor.deleteMany({ where: { projectId } });+ });++ it("shifts the CH query window back by 30s and stamps it onto the alert payload", async () => {+ const monitorId = `m_off_${v4()}`;+ await seedMonitor(projectId, {+ id: monitorId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ triggerIds: ["trig_off"],+ });++ let capturedQuery: { fromTimestamp: string; toTimestamp: string } | null =+ null;+ const publish = vi.fn<MonitorPublisher>(async () => {});+ const executeQuery: QueryExecutor = async (_p, query) => {+ capturedQuery = {+ fromTimestamp: query.fromTimestamp,+ toTimestamp: query.toTimestamp,+ };+ return [{ count_count: 200 }];+ };+ const getTriggers: GetTriggerConfigurations = async () =>+ [+ {+ id: "trig_off",+ filter: matchAnyAlertTrigger.filter,+ eventActions: [],+ automations: [{ id: "auto_off", actionId: "act_off" }],+ },+ ] as unknown as Awaited<ReturnType<GetTriggerConfigurations>>;++ const processor = new MonitorProcessor(+ prisma,+ publish,+ executeQuery,+ getTriggers,+ );++ const event = makeEvent(projectId, [monitorId]);+ await processor.process(event, justAfterRunAt);++ const offsetMs = 30_000;+ const windowMs = 5 * 60_000;+ const expectedTo = new Date(runAt.getTime() - offsetMs).toISOString();+ const expectedFrom = new Date(+ runAt.getTime() - offsetMs - windowMs,+ ).toISOString();++ expect(capturedQuery).toEqual({+ fromTimestamp: expectedFrom,+ toTimestamp: expectedTo,+ });++ expect(publish).toHaveBeenCalledTimes(1);+ const sent = publish.mock.calls[0][0].payload;+ if (sent.type !== "monitor-alert") throw new Error("unexpected envelope");+ expect(sent.payload.fromTimestamp.toISOString()).toBe(expectedFrom);+ expect(sent.payload.toTimestamp.toISOString()).toBe(expectedTo);+ // The cadence-boundary stamp stays unshifted — alerts say "fired at runAt".+ expect(sent.payload.timestamp.toISOString()).toBe(runAt.toISOString());+ });+});++describe("MonitorProcessor.process wire deserialization", () => {+ let projectId: string;++ beforeAll(async () => {+ const org = await createOrgProjectAndApiKey();+ projectId = org.projectId;+ });++ afterEach(async () => {+ await prisma.monitor.deleteMany({ where: { projectId } });+ });++ it("coerces a JSON round-tripped event (Redis wire shape) back to typed dates", async () => {+ const monitorId = `m_wire_${v4()}`;+ await seedMonitor(projectId, {+ id: monitorId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ triggerIds: ["trig_wire"],+ });++ let capturedQuery: { fromTimestamp: string; toTimestamp: string } | null =+ null;+ const publish = vi.fn<MonitorPublisher>(async () => {});+ const executeQuery: QueryExecutor = async (_p, query) => {+ capturedQuery = {+ fromTimestamp: query.fromTimestamp,+ toTimestamp: query.toTimestamp,+ };+ return [{ count_count: 200 }];+ };+ const getTriggers: GetTriggerConfigurations = async () =>+ [+ {+ id: "trig_wire",+ filter: matchAnyAlertTrigger.filter,+ eventActions: [],+ automations: [{ id: "auto_wire", actionId: "act_wire" }],+ },+ ] as unknown as Awaited<ReturnType<GetTriggerConfigurations>>;++ const processor = new MonitorProcessor(+ prisma,+ publish,+ executeQuery,+ getTriggers,+ );++ // Mirror BullMQ: the scheduler stringifies the bigint batch id, then Redis+ // round-trips the payload through JSON, turning runAt/publishedAt into ISO strings.+ const event = makeEvent(projectId, [monitorId]);+ const wire: MonitorQueueEventInput = JSON.parse(+ JSON.stringify({+ ...event,+ schedulerBatchId: event.schedulerBatchId.toString(),+ }),+ );++ await processor.process(wire, justAfterRunAt);++ const expectedTo = new Date(runAt.getTime() - 30_000).toISOString();+ const expectedFrom = new Date(+ runAt.getTime() - 30_000 - 5 * 60_000,+ ).toISOString();+ expect(capturedQuery).toEqual({+ fromTimestamp: expectedFrom,+ toTimestamp: expectedTo,+ });+ expect(publish).toHaveBeenCalledTimes(1);+ });+});++describe("MonitorProcessor.process count metric", () => {+ let projectId: string;++ beforeAll(async () => {+ const org = await createOrgProjectAndApiKey();+ projectId = org.projectId;+ });++ afterEach(async () => {+ await prisma.monitor.deleteMany({ where: { projectId } });+ });++ it("appends the count_count metric exactly once for a count monitor", async () => {+ const monitorId = `m_count_${v4()}`;+ await seedMonitor(projectId, {+ id: monitorId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ });++ let capturedMetrics: { measure: string; aggregation: string }[] = [];+ const publish = vi.fn<MonitorPublisher>(async () => {});+ const executeQuery: QueryExecutor = async (_p, query) => {+ capturedMetrics = query.metrics;+ return [{ count_count: 5 }];+ };+ const getTriggers: GetTriggerConfigurations = async () =>+ [] as unknown as Awaited<ReturnType<GetTriggerConfigurations>>;++ const processor = new MonitorProcessor(+ prisma,+ publish,+ executeQuery,+ getTriggers,+ );++ await processor.process(makeEvent(projectId, [monitorId]), justAfterRunAt);++ expect(+ capturedMetrics.filter(+ (m) => m.measure === "count" && m.aggregation === "count",+ ),+ ).toHaveLength(1);+ });+});++describe("MonitorProcessor.process executeQuery failure logging", () => {+ let projectId: string;++ beforeAll(async () => {+ const org = await createOrgProjectAndApiKey();+ projectId = org.projectId;+ });++ afterEach(async () => {+ await prisma.monitor.deleteMany({ where: { projectId } });+ });++ it("logs the batch context when executeQuery rejects", async () => {+ const errSpy = vi.spyOn(logger, "error").mockImplementation(() => logger);+ try {+ await seedMonitor(projectId, {+ id: monitorAId,+ severity: "UNKNOWN",+ lastPublishedAt: runAt,+ });++ const publish = vi.fn<MonitorPublisher>(async () => {});+ const executeQuery: QueryExecutor = async () => {+ throw new Error("CH timeout");+ };+ const getTriggers: GetTriggerConfigurations = async () =>+ [] as unknown as Awaited<ReturnType<GetTriggerConfigurations>>;++ const processor = new MonitorProcessor(+ prisma,+ publish,+ executeQuery,+ getTriggers,+ );++ await processor.process(+ makeEvent(projectId, [monitorAId]),+ justAfterRunAt,+ );++ expect(errSpy).toHaveBeenCalled();+ const meta = errSpy.mock.calls[0][1] as Record<string, unknown>;+ expect(meta.projectId).toBe(projectId);+ expect(meta.monitorIds).toEqual([monitorAId]);+ expect(typeof meta.schedulerBatchId).toBe("string");+ } finally {+ errSpy.mockRestore();+ }+ });+});diff --git a/worker/src/__tests__/monitorProcessorScalarQuery.test.ts b/worker/src/__tests__/monitorProcessorScalarQuery.test.tsnew file mode 100644index 0000000000..c56df34e62--- /dev/null+++ b/worker/src/__tests__/monitorProcessorScalarQuery.test.ts@@ -0,0 +1,73 @@+import { v4 } from "uuid";+import { beforeAll, describe, expect, it } from "vitest";++import { executeQuery } from "@langfuse/shared/query/server";+import {+ getViewDeclaration,+ viewsV2,+ type QueryType,+} from "@langfuse/shared/query";+import { getValidMonitorAggregationsForMeasure } from "@langfuse/shared/monitors";+import { queryClickhouse } from "@langfuse/shared/src/server";++/** eventsCoreAvailable reports whether the dev-only `events_core` table exists. */+async function eventsCoreAvailable(): Promise<boolean> {+ // events_core is created by ch:dev-tables, not migrations; absent in -azure/-redis-cluster CI legs.+ const rows = await queryClickhouse<Record<string, unknown>>({+ query: "EXISTS TABLE events_core",+ params: {},+ });+ return Number(Object.values(rows[0] ?? {})[0]) === 1;+}++/** parseNumericValue coerces a ClickHouse cell to number | null, mirroring the monitor processor. */+function parseNumericValue(raw: unknown): number | null {+ if (raw === null || raw === undefined) return null;+ if (typeof raw === "number") return Number.isFinite(raw) ? raw : null;+ const n = Number(raw);+ return Number.isFinite(n) ? n : null;+}++/** combos enumerates every (view, measure, aggregation) a monitor can run. */+const combos = viewsV2.options.flatMap((view) => {+ const declaration = getViewDeclaration(view, "v2");+ return Object.entries(declaration.measures).flatMap(([measure, def]) =>+ getValidMonitorAggregationsForMeasure(def).map((aggregation) => ({+ view,+ measure,+ aggregation,+ })),+ );+});++/** scalarValue runs one monitor scalar query against an empty project and returns its number | null. */+async function scalarValue(query: QueryType): Promise<number | null> {+ const rows = await executeQuery(v4(), query, "v2", true);+ const row = (rows[0] ?? {}) as Record<string, unknown>;+ return parseNumericValue(Object.values(row)[0]);+}++describe("monitor scalar query — empty project", () => {+ let hasEventsCore = false;+ beforeAll(async () => {+ hasEventsCore = await eventsCoreAvailable();+ });++ it("verifies which parameters return zero and which return null", async (ctx) => {+ if (!hasEventsCore) ctx.skip();+ const results: Record<string, number | null> = {};+ for (const { view, measure, aggregation } of combos) {+ results[`${view}/${measure}/${aggregation}`] = await scalarValue({+ view,+ dimensions: [],+ metrics: [{ measure, aggregation }],+ filters: [],+ timeDimension: null,+ fromTimestamp: "2025-01-01T00:00:00.000Z",+ toTimestamp: "2025-03-01T00:00:00.000Z",+ orderBy: null,+ });+ }+ expect(results).toMatchSnapshot();+ });+});diff --git a/worker/src/__tests__/monitorScheduler.test.ts b/worker/src/__tests__/monitorScheduler.test.tsnew file mode 100644index 0000000000..72d4a31e98--- /dev/null+++ b/worker/src/__tests__/monitorScheduler.test.ts@@ -0,0 +1,691 @@+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";++import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import {+ MonitorScheduler,+ type MonitorQueueEventInput,+} from "@langfuse/shared/monitors/server";+import { prisma } from "@langfuse/shared/src/db";+import type { Prisma } from "@prisma/client";++type MonitorStatus = "ACTIVE" | "PAUSED" | "ERROR_BAD_QUERY";+type MonitorView = "OBSERVATIONS" | "SCORES_NUMERIC" | "SCORES_CATEGORICAL";++type SeedOverrides = Partial<{+ id: string;+ schedulerBatchId: bigint;+ cadenceMs: bigint;+ windowMs: bigint;+ nextRunAt: Date | null;+ lastPublishedAt: Date | null;+ lastCompletedAt: Date | null;+ status: MonitorStatus;+ view: MonitorView;+ metric: { measure: string; aggregation: string };+}>;++type MonitorSeed = { id: string } & SeedOverrides;++type ExpectedEvent = {+ schedulerBatchId: string;+ runAt: Date;+ monitorIds: string[];+};++type ExpectedRow = {+ id: string;+ nextRunAt: Date | null;+ lastPublishedAt: Date | null;+ lastCompletedAt: Date | null;+};++type SchedulerCase = {+ name: string;+ scheduler?: { id: number; total: number };+ tick: Date;+ monitors: MonitorSeed[];+ expect: { events: ExpectedEvent[]; rows: ExpectedRow[] };+};++const oneMinuteMs = 60n * 1000n;+const thirtyMinutesMs = 30n * 60n * 1000n;++// Scheduler times+const now = new Date("2026-05-27T12:00:30.000Z");+const twoMinutesAgo = new Date("2026-05-27T11:58:30.000Z");+const threeMinutesAgo = new Date("2026-05-27T11:57:30.000Z");+const fourMinutesAgo = new Date("2026-05-27T11:56:30.000Z");+const sixMinutesAgo = new Date("2026-05-27T11:54:30.000Z");+const tenMinutesAgo = new Date("2026-05-27T11:50:30.000Z");+const oneMinuteFromNow = new Date("2026-05-27T12:01:30.000Z");+const prevCadence30m = new Date("2026-05-27T12:00:00.000Z");+const nextCadence30m = new Date("2026-05-27T12:30:00.000Z");++// Cadence-aligned boundaries (cadence=1m), offset by (batchId % 60) seconds.+const prevCadence = new Date("2026-05-27T12:00:00.000Z");+const nextCadence = new Date("2026-05-27T12:01:00.000Z");+const prevCadenceBatch1 = new Date("2026-05-27T12:00:01.000Z");+const nextCadenceBatch1 = new Date("2026-05-27T12:01:01.000Z");+const prevCadenceBatch2 = new Date("2026-05-27T12:00:02.000Z");+const nextCadenceBatch2 = new Date("2026-05-27T12:01:02.000Z");+const prevCadenceBatch5 = new Date("2026-05-27T12:00:05.000Z");+const nextCadenceBatch5 = new Date("2026-05-27T12:01:05.000Z");+const prevCadenceBatch7 = new Date("2026-05-27T12:00:07.000Z");+const nextCadenceBatch7 = new Date("2026-05-27T12:01:07.000Z");++async function seedMonitor(projectId: string, seed: MonitorSeed) {+ return prisma.monitor.create({+ data: {+ id: seed.id,+ projectId,+ view: seed.view ?? "OBSERVATIONS",+ filters: [] as unknown as Prisma.InputJsonValue,+ metric: (seed.metric ?? {+ measure: "count",+ aggregation: "count",+ }) as unknown as Prisma.InputJsonValue,+ windowMs: seed.windowMs ?? 5n * oneMinuteMs,+ cadenceMs: seed.cadenceMs ?? oneMinuteMs,+ thresholdOperator: "GT",+ alertThreshold: 100,+ warningThreshold: null,+ noData: { mode: "SILENT" } as unknown as Prisma.InputJsonValue,+ renotify: { mode: "OFF" } as unknown as Prisma.InputJsonValue,+ status: seed.status ?? "ACTIVE",+ schedulerBatchId: seed.schedulerBatchId ?? 0n,+ nextRunAt: seed.nextRunAt === undefined ? null : seed.nextRunAt,+ lastPublishedAt: seed.lastPublishedAt ?? null,+ lastCompletedAt: seed.lastCompletedAt ?? null,+ name: `Test ${seed.id}`,+ tags: [],+ },+ });+}++function makeScheduler(+ publish: (event: MonitorQueueEventInput) => Promise<void>,+ shard: { id: number; total: number } = { id: 0, total: 1 },+) {+ return new MonitorScheduler({+ schedulerId: shard.id,+ totalSchedulers: shard.total,+ db: prisma,+ publish,+ });+}++const cases: SchedulerCase[] = [+ {+ name: "no monitors on the system: schedule returns 0, publish not called",+ tick: now,+ monitors: [],+ expect: { events: [], rows: [] },+ },+ {+ name: "all monitors ahead: every row filtered by WHERE, nothing published or advanced",+ tick: now,+ monitors: [+ { id: "m_ahead_a", nextRunAt: oneMinuteFromNow },+ { id: "m_ahead_b", nextRunAt: oneMinuteFromNow },+ ],+ expect: {+ events: [],+ rows: [+ {+ id: "m_ahead_a",+ nextRunAt: oneMinuteFromNow,+ lastPublishedAt: null,+ lastCompletedAt: null,+ },+ {+ id: "m_ahead_b",+ nextRunAt: oneMinuteFromNow,+ lastPublishedAt: null,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "new monitor: publishes at tick, advances to next boundary",+ tick: now,+ monitors: [{ id: "m_new", nextRunAt: null }],+ expect: {+ events: [{ schedulerBatchId: "0", runAt: now, monitorIds: ["m_new"] }],+ rows: [+ {+ id: "m_new",+ nextRunAt: nextCadence,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "mixed batch: new monitor pulls existing sibling forward to tick",+ tick: now,+ monitors: [+ { id: "m_existing", nextRunAt: prevCadence },+ { id: "m_new", nextRunAt: null },+ ],+ expect: {+ events: [+ {+ schedulerBatchId: "0",+ runAt: now,+ monitorIds: ["m_existing", "m_new"],+ },+ ],+ rows: [+ {+ id: "m_existing",+ nextRunAt: nextCadence,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ {+ id: "m_new",+ nextRunAt: nextCadence,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "behind monitor: publishes at prior next_run_at, advances",+ tick: now,+ monitors: [{ id: "m_behind", nextRunAt: prevCadence }],+ expect: {+ events: [+ {+ schedulerBatchId: "0",+ runAt: prevCadence,+ monitorIds: ["m_behind"],+ },+ ],+ rows: [+ {+ id: "m_behind",+ nextRunAt: nextCadence,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "in-flight + last_completed=NULL within TTL: not published, advanced",+ tick: now,+ monitors: [+ {+ id: "m_pending",+ nextRunAt: prevCadence,+ lastPublishedAt: twoMinutesAgo,+ lastCompletedAt: null,+ },+ ],+ expect: {+ events: [],+ rows: [+ {+ id: "m_pending",+ nextRunAt: nextCadence,+ lastPublishedAt: twoMinutesAgo,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "in-flight + completed-before-published within TTL: not published, advanced",+ tick: now,+ monitors: [+ {+ id: "m_inflight_completed",+ nextRunAt: prevCadence,+ lastPublishedAt: twoMinutesAgo,+ lastCompletedAt: threeMinutesAgo,+ },+ ],+ expect: {+ events: [],+ rows: [+ {+ id: "m_inflight_completed",+ nextRunAt: nextCadence,+ lastPublishedAt: twoMinutesAgo,+ lastCompletedAt: threeMinutesAgo,+ },+ ],+ },+ },+ {+ name: "in-flight past TTL: republishes (rescue), advances",+ tick: now,+ monitors: [+ {+ id: "m_stuck",+ nextRunAt: prevCadence,+ lastPublishedAt: tenMinutesAgo,+ lastCompletedAt: null,+ },+ ],+ expect: {+ events: [+ {+ schedulerBatchId: "0",+ runAt: prevCadence,+ monitorIds: ["m_stuck"],+ },+ ],+ rows: [+ {+ id: "m_stuck",+ nextRunAt: nextCadence,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "long-cadence in-flight past TTL: rescue branch republishes",+ tick: now,+ monitors: [+ {+ id: "m_long_stuck",+ cadenceMs: thirtyMinutesMs,+ nextRunAt: nextCadence30m,+ lastPublishedAt: sixMinutesAgo,+ lastCompletedAt: null,+ },+ ],+ expect: {+ events: [+ {+ schedulerBatchId: "0",+ runAt: prevCadence30m,+ monitorIds: ["m_long_stuck"],+ },+ ],+ rows: [+ {+ id: "m_long_stuck",+ nextRunAt: nextCadence30m,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "long-cadence in-flight within TTL: rescue branch does not fire",+ tick: now,+ monitors: [+ {+ id: "m_long_pending",+ cadenceMs: thirtyMinutesMs,+ nextRunAt: nextCadence30m,+ lastPublishedAt: fourMinutesAgo,+ lastCompletedAt: null,+ },+ ],+ expect: {+ events: [],+ rows: [+ {+ id: "m_long_pending",+ nextRunAt: nextCadence30m,+ lastPublishedAt: fourMinutesAgo,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "very behind: snaps forward to most recent boundary, skips intermediates",+ tick: now,+ monitors: [{ id: "m_far_behind", nextRunAt: tenMinutesAgo }],+ expect: {+ events: [+ {+ schedulerBatchId: "0",+ runAt: prevCadence,+ monitorIds: ["m_far_behind"],+ },+ ],+ rows: [+ {+ id: "m_far_behind",+ nextRunAt: nextCadence,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "paused monitor: untouched",+ tick: now,+ monitors: [+ {+ id: "m_paused",+ status: "PAUSED",+ nextRunAt: prevCadence,+ },+ ],+ expect: {+ events: [],+ rows: [+ {+ id: "m_paused",+ nextRunAt: prevCadence,+ lastPublishedAt: null,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "error monitor: untouched",+ tick: now,+ monitors: [+ {+ id: "m_error",+ status: "ERROR_BAD_QUERY",+ nextRunAt: prevCadence,+ },+ ],+ expect: {+ events: [],+ rows: [+ {+ id: "m_error",+ nextRunAt: prevCadence,+ lastPublishedAt: null,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "multi-monitor batch: one event, both monitors, deduped metrics",+ tick: now,+ monitors: [+ {+ id: "m_a",+ schedulerBatchId: 7n,+ nextRunAt: prevCadence,+ metric: { measure: "count", aggregation: "count" },+ },+ {+ id: "m_b",+ schedulerBatchId: 7n,+ nextRunAt: prevCadence,+ metric: { measure: "latency", aggregation: "p95" },+ },+ ],+ expect: {+ events: [+ {+ schedulerBatchId: "7",+ runAt: prevCadenceBatch7,+ monitorIds: ["m_a", "m_b"],+ },+ ],+ rows: [+ {+ id: "m_a",+ nextRunAt: nextCadenceBatch7,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ {+ id: "m_b",+ nextRunAt: nextCadenceBatch7,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "5 monitors batched into 2 events (batching + ordering)",+ tick: now,+ monitors: [+ { id: "m_a1", schedulerBatchId: 1n, nextRunAt: twoMinutesAgo },+ { id: "m_a2", schedulerBatchId: 1n, nextRunAt: twoMinutesAgo },+ { id: "m_a3", schedulerBatchId: 1n, nextRunAt: twoMinutesAgo },+ { id: "m_b1", schedulerBatchId: 2n, nextRunAt: tenMinutesAgo },+ { id: "m_b2", schedulerBatchId: 2n, nextRunAt: tenMinutesAgo },+ ],+ expect: {+ events: [+ {+ schedulerBatchId: "1",+ runAt: prevCadenceBatch1,+ monitorIds: ["m_a1", "m_a2", "m_a3"],+ },+ {+ schedulerBatchId: "2",+ runAt: prevCadenceBatch2,+ monitorIds: ["m_b1", "m_b2"],+ },+ ],+ rows: [+ {+ id: "m_a1",+ nextRunAt: nextCadenceBatch1,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ {+ id: "m_a2",+ nextRunAt: nextCadenceBatch1,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ {+ id: "m_a3",+ nextRunAt: nextCadenceBatch1,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ {+ id: "m_b1",+ nextRunAt: nextCadenceBatch2,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ {+ id: "m_b2",+ nextRunAt: nextCadenceBatch2,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "sharding: only this scheduler's slot is claimed",+ scheduler: { id: 1, total: 4 },+ tick: now,+ monitors: [+ { id: "m_in", schedulerBatchId: 5n, nextRunAt: prevCadence },+ { id: "m_out", schedulerBatchId: 4n, nextRunAt: prevCadence },+ ],+ expect: {+ events: [+ {+ schedulerBatchId: "5",+ runAt: prevCadenceBatch5,+ monitorIds: ["m_in"],+ },+ ],+ rows: [+ {+ id: "m_in",+ nextRunAt: nextCadenceBatch5,+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ {+ id: "m_out",+ nextRunAt: prevCadence,+ lastPublishedAt: null,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "new monitor, 1m cadence: publishes at tick, advances to cadence-aligned + 17s slot",+ tick: now,+ monitors: [+ { id: "m_cadence_1m", schedulerBatchId: 17n, cadenceMs: oneMinuteMs },+ ],+ expect: {+ events: [+ { schedulerBatchId: "17", runAt: now, monitorIds: ["m_cadence_1m"] },+ ],+ rows: [+ {+ id: "m_cadence_1m",+ nextRunAt: new Date("2026-05-27T12:01:17.000Z"),+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "new monitor, 30m cadence: publishes at tick, advances to cadence-aligned + 17s slot",+ tick: now,+ monitors: [+ {+ id: "m_cadence_30m",+ schedulerBatchId: 17n,+ cadenceMs: thirtyMinutesMs,+ },+ ],+ expect: {+ events: [+ { schedulerBatchId: "17", runAt: now, monitorIds: ["m_cadence_30m"] },+ ],+ rows: [+ {+ id: "m_cadence_30m",+ nextRunAt: new Date("2026-05-27T12:30:17.000Z"),+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+ {+ name: "new monitor, 1d cadence: publishes at tick, advances to cadence-aligned + 17s slot",+ tick: now,+ monitors: [+ {+ id: "m_cadence_1d",+ schedulerBatchId: 17n,+ cadenceMs: 24n * 60n * 60n * 1000n,+ },+ ],+ expect: {+ events: [+ { schedulerBatchId: "17", runAt: now, monitorIds: ["m_cadence_1d"] },+ ],+ rows: [+ {+ id: "m_cadence_1d",+ nextRunAt: new Date("2026-05-28T00:00:17.000Z"),+ lastPublishedAt: now,+ lastCompletedAt: null,+ },+ ],+ },+ },+];++describe("MonitorScheduler (integration)", () => {+ let projectId: string;++ beforeAll(async () => {+ const org = await createOrgProjectAndApiKey();+ projectId = org.projectId;+ });++ afterEach(async () => {+ await prisma.monitor.deleteMany({ where: { projectId } });+ });++ it.each(cases)("$name", async (c) => {+ for (const m of c.monitors) {+ await seedMonitor(projectId, m);+ }++ const publish = vi.fn<(event: MonitorQueueEventInput) => Promise<void>>();+ await makeScheduler(publish, c.scheduler).schedule(c.tick);++ // Filter to this project's events — the scheduler is global, so concurrent+ // test files in the same shard can leak monitors into the publish call.+ const myEvents = publish.mock.calls+ .flatMap((call) => call[0])+ .filter((e) => e.projectId === projectId);++ expect(myEvents).toHaveLength(c.expect.events.length);+ myEvents.forEach((event, i) => {+ const exp = c.expect.events[i];+ expect(event.schedulerBatchId).toBe(exp.schedulerBatchId);+ expect(event.runAt).toEqual(exp.runAt);+ expect(event.monitors.map((m) => m.monitorId).sort()).toEqual(+ [...exp.monitorIds].sort(),+ );+ });++ for (const exp of c.expect.rows) {+ const row = await prisma.monitor.findUniqueOrThrow({+ where: { id: exp.id },+ });+ expect(row.nextRunAt?.toISOString() ?? null).toBe(+ exp.nextRunAt?.toISOString() ?? null,+ );+ expect(row.lastPublishedAt?.toISOString() ?? null).toBe(+ exp.lastPublishedAt?.toISOString() ?? null,+ );+ expect(row.lastCompletedAt?.toISOString() ?? null).toBe(+ exp.lastCompletedAt?.toISOString() ?? null,+ );+ }+ });++ it("computes the same next_run_at across two ticks with the same (cadence, schedulerBatchId)", async () => {+ await seedMonitor(projectId, {+ id: "m_det",+ schedulerBatchId: 17n,+ nextRunAt: prevCadence,+ });++ const publish1 = vi.fn<(event: MonitorQueueEventInput) => Promise<void>>();+ await makeScheduler(publish1).schedule(now);+ const firstNext = (+ await prisma.monitor.findUniqueOrThrow({ where: { id: "m_det" } })+ ).nextRunAt;++ await prisma.monitor.update({+ where: { id: "m_det" },+ data: { nextRunAt: prevCadence, lastPublishedAt: null },+ });++ const publish2 = vi.fn<(event: MonitorQueueEventInput) => Promise<void>>();+ await makeScheduler(publish2).schedule(now);+ const secondNext = (+ await prisma.monitor.findUniqueOrThrow({ where: { id: "m_det" } })+ ).nextRunAt;++ expect(firstNext?.toISOString()).toBe(secondNext?.toISOString());+ });+});diff --git a/worker/src/__tests__/monitorWorkerIntegration.test.ts b/worker/src/__tests__/monitorWorkerIntegration.test.tsnew file mode 100644index 0000000000..e30a42fe78--- /dev/null+++ b/worker/src/__tests__/monitorWorkerIntegration.test.ts@@ -0,0 +1,400 @@+/** monitorWorkerIntegration.test.ts drives the full scheduler → processor → webhook dispatch → webhook received flow;+ * BullMq and ClickHouse are mocked. Posgtgress is injected.+ */+import {+ describe,+ it,+ expect,+ beforeAll,+ beforeEach,+ afterAll,+ afterEach,+ vi,+} from "vitest";+import { v4 } from "uuid";+import { setupServer } from "msw/node";+import { http, HttpResponse } from "msw";+import { Prisma } from "@prisma/client";++import { JobConfigState } from "@langfuse/shared";+import {+ createOrgProjectAndApiKey,+ redis,+ type WebhookInput,+} from "@langfuse/shared/src/server";+import {+ MonitorProcessor,+ type MonitorQueueEvent,+ MonitorQueueEventSchema,+ MonitorScheduler,+} from "@langfuse/shared/monitors/server";+import { prisma } from "@langfuse/shared/src/db";+import { encrypt, generateWebhookSecret } from "@langfuse/shared/encryption";++import { executeWebhook } from "../queues/webhooks";++describe("monitor-alert e2e (scheduler → processor → dispatcher → webhook URL)", () => {+ let projectId: string;++ beforeAll(() => {+ webhookServer.setup();+ });++ beforeEach(async () => {+ webhookServer.reset();+ ({ projectId } = await createOrgProjectAndApiKey());+ });++ afterEach(async () => {+ vi.restoreAllMocks();+ await prisma.monitor.deleteMany({ where: { projectId } });+ webhookServer.reset();+ });++ afterAll(() => {+ webhookServer.teardown();+ });++ it("posts a monitor-alert envelope to the webhook URL", async () => {+ const { triggerId } = await seedWebhookAutomation({+ projectId,+ url: "https://webhook.example.com/monitor-e2e",+ triggerFilter: [+ {+ column: "severity",+ operator: "any of",+ value: ["ALERT"],+ type: "stringOptions",+ },+ ],+ });+ const monitorId = await seedMonitor({+ projectId,+ alertThreshold: 100,+ triggerIds: [triggerId],+ });+ // Capture now after seeding so the monitor's nextRunAt is strictly in the past.+ const now = new Date();++ // 1. Scheduler publishes monitor queue events for due Monitors+ let monitorQueueEvents: MonitorQueueEvent[] = [];+ const scheduler = new MonitorScheduler({+ schedulerId: 0,+ totalSchedulers: 1,+ db: prisma,+ publish: async (event) => {+ monitorQueueEvents.push(MonitorQueueEventSchema.parse(event));+ },+ });+ await scheduler.schedule(now);+ monitorQueueEvents = monitorQueueEvents.filter(+ (e) => e.projectId === projectId, // isolate the scheduler check to this test project+ );+ expect(monitorQueueEvents).toHaveLength(1);++ // 2. Processor executes the scheduled job (ClickHouse mocked above threshold).+ const webhookInputs: WebhookInput[] = [];+ const processor = new MonitorProcessor(+ prisma,+ async (event) => {+ webhookInputs.push(event);+ },+ async () => [{ count_count: 150 }],+ );+ await Promise.all(+ monitorQueueEvents.map((monitorQueueEvent) =>+ processor.process(monitorQueueEvent, now),+ ),+ );+ expect(webhookInputs).toHaveLength(1);++ // 3. Webhook processor executes the webhook inputs.+ for (const input of webhookInputs) {+ await executeWebhook(input, { skipValidation: true });+ }++ // 4. Webhook server receives one monitor-alert envelope per scheduled event.+ const requests = webhookServer.getReceivedRequests();+ expect(requests).toHaveLength(monitorQueueEvents.length);+ monitorQueueEvents.forEach((event, i) => {+ const body = JSON.parse(requests[i].body);+ // Window edges anchor to the scheduler's runAt (the cadence boundary), not now.+ const expectedTo = new Date(event.runAt.getTime() - 30_000).toISOString();+ const expectedFrom = new Date(+ event.runAt.getTime() - 30_000 - 5 * 60_000,+ ).toISOString();+ expect(body).toMatchObject({+ type: "monitor-alert",+ apiVersion: "v1",+ payload: {+ monitorId,+ severity: "ALERT",+ fromTimestamp: expectedFrom,+ toTimestamp: expectedTo,+ },+ });+ });+ });++ it("redis.del failure on a delivered monitor-alert webhook: does not increment the failure counter", async () => {+ const { triggerId } = await seedWebhookAutomation({+ projectId,+ url: "https://webhook.example.com/monitor-redis-del-fail",+ triggerFilter: [+ {+ column: "severity",+ operator: "any of",+ value: ["ALERT"],+ type: "stringOptions",+ },+ ],+ });+ const monitorId = await seedMonitor({+ projectId,+ alertThreshold: 100,+ triggerIds: [triggerId],+ });+ const now = new Date();++ const delSpy = vi+ .spyOn(redis!, "del")+ .mockRejectedValueOnce(new Error("READONLY simulated failover"));+ const multiSpy = vi.spyOn(redis!, "multi");++ const monitorQueueEvents: MonitorQueueEvent[] = [];+ const scheduler = new MonitorScheduler({+ schedulerId: 0,+ totalSchedulers: 1,+ db: prisma,+ publish: async (event) => {+ monitorQueueEvents.push(MonitorQueueEventSchema.parse(event));+ },+ });+ await scheduler.schedule(now);+ const projectEvents = monitorQueueEvents.filter(+ (e) => e.projectId === projectId,+ );+ expect(projectEvents).toHaveLength(1);++ const webhookInputs: WebhookInput[] = [];+ const processor = new MonitorProcessor(+ prisma,+ async (event) => {+ webhookInputs.push(event);+ },+ async () => [{ count_count: 150 }],+ );+ await Promise.all(+ projectEvents.map((event) => processor.process(event, now)),+ );+ expect(webhookInputs).toHaveLength(1);++ for (const input of webhookInputs) {+ await expect(+ executeWebhook(input, { skipValidation: true }),+ ).resolves.not.toThrow();+ }++ expect(delSpy).toHaveBeenCalled();+ expect(multiSpy).not.toHaveBeenCalled();++ const trigger = await prisma.trigger.findUnique({+ where: { id: triggerId, projectId },+ });+ expect(trigger?.status).toBe(JobConfigState.ACTIVE);+ expect(monitorId).toBeTruthy();+ });++ it("does not write AutomationExecution rows for monitor-alert dispatches", async () => {+ const now = new Date();+ const { triggerId } = await seedWebhookAutomation({+ projectId,+ url: "https://webhook.example.com/monitor-no-exec",+ triggerFilter: [+ {+ column: "severity",+ operator: "any of",+ value: ["ALERT"],+ type: "stringOptions",+ },+ ],+ });+ await seedMonitor({+ projectId,+ alertThreshold: 100,+ triggerIds: [triggerId],+ });++ const before = await prisma.automationExecution.count({+ where: { projectId },+ });++ const monitorQueueEvents: MonitorQueueEvent[] = [];+ const scheduler = new MonitorScheduler({+ schedulerId: 0,+ totalSchedulers: 1,+ db: prisma,+ publish: async (event) => {+ monitorQueueEvents.push(MonitorQueueEventSchema.parse(event));+ },+ });+ await scheduler.schedule(now);+ const projectEvents = monitorQueueEvents.filter(+ (e) => e.projectId === projectId,+ );+ expect(projectEvents).toHaveLength(1);++ const captured: WebhookInput[] = [];+ const processor = new MonitorProcessor(+ prisma,+ async (input) => {+ captured.push(input);+ },+ async () => [{ count_count: 150 }],+ );+ await Promise.all(+ projectEvents.map((event) => processor.process(event, now)),+ );+ expect(captured).toHaveLength(1);+ for (const input of captured) {+ await executeWebhook(input, { skipValidation: true });+ }++ const after = await prisma.automationExecution.count({+ where: { projectId },+ });+ expect(after).toBe(before);+ });+});++/** WebhookTestServer records webhook POSTs via MSW so tests can assert on them. */+class WebhookTestServer {+ private server;+ private receivedRequests: Array<{+ url: string;+ method: string;+ body: string;+ }> = [];++ constructor() {+ this.server = setupServer(+ http.post("https://webhook.example.com/*", async ({ request }) => {+ this.receivedRequests.push({+ url: request.url,+ method: request.method,+ body: JSON.stringify(await request.json()),+ });+ return HttpResponse.json({ success: true }, { status: 200 });+ }),+ );+ }++ setup() {+ this.server.listen();+ }+ reset() {+ this.receivedRequests = [];+ this.server.resetHandlers();+ }+ teardown() {+ this.server.close();+ }+ getReceivedRequests() {+ return this.receivedRequests;+ }+}++/** webhookServer is the suite-wide MSW capture server. */+const webhookServer = new WebhookTestServer();++/** seedWebhookAutomation creates a monitor-source trigger and webhook automation whose URL MSW captures, returning the created ids for assertions. */+async function seedWebhookAutomation(args: {+ projectId: string;+ url: string;+ triggerFilter: {+ column: string;+ operator: string;+ value: unknown;+ type: string;+ }[];+}) {+ const triggerId = v4();+ await prisma.trigger.create({+ data: {+ id: triggerId,+ projectId: args.projectId,+ eventSource: "monitor",+ eventActions: [],+ filter: args.triggerFilter as unknown as Prisma.InputJsonValue,+ status: JobConfigState.ACTIVE,+ },+ });++ const actionId = v4();+ const { secretKey, displaySecretKey } = generateWebhookSecret();+ await prisma.action.create({+ data: {+ id: actionId,+ projectId: args.projectId,+ type: "WEBHOOK",+ config: {+ type: "WEBHOOK",+ url: args.url,+ apiVersion: { monitor: "v1" },+ secretKey: encrypt(secretKey),+ displaySecretKey,+ },+ },+ });++ const automationId = v4();+ await prisma.automation.create({+ data: {+ id: automationId,+ projectId: args.projectId,+ triggerId,+ actionId,+ name: "Monitor e2e Automation",+ },+ });++ return { triggerId, actionId, automationId };+}++/** seedMonitor inserts a due monitor row; triggerIds gates which monitor-source triggers the processor routes its alerts to. */+async function seedMonitor(args: {+ projectId: string;+ alertThreshold: number;+ triggerIds?: string[];+}) {+ const id = `mon_${v4()}`;+ await prisma.monitor.create({+ data: {+ id,+ projectId: args.projectId,+ view: "OBSERVATIONS",+ filters: [],+ metric: { measure: "count", aggregation: "count" },+ windowMs: 5n * 60n * 1000n,+ cadenceMs: 60n * 1000n,+ thresholdOperator: "GT",+ alertThreshold: args.alertThreshold,+ warningThreshold: null,+ noData: { mode: "SILENT" },+ renotify: { mode: "OFF" },+ status: "ACTIVE",+ schedulerBatchId: 0n,+ nextRunAt: new Date(Date.now() - 1000),+ lastPublishedAt: null,+ lastClaimedAt: null,+ lastCompletedAt: null,+ severity: "UNKNOWN",+ severityChangedAt: null,+ alertedAt: null,+ tags: [],+ triggerIds: args.triggerIds ?? [],+ name: "e2e monitor",+ },+ });+ return id;+}diff --git a/worker/src/__tests__/slack-message-builder.test.ts b/worker/src/__tests__/slack-message-builder.test.tsindex f3ad8dd0be..7e07649b80 100644--- a/worker/src/__tests__/slack-message-builder.test.ts+++ b/worker/src/__tests__/slack-message-builder.test.ts@@ -266,11 +266,13 @@ describe("SlackMessageBuilder", () => {describe("buildMessage", () => {it("should route prompt-version events to prompt message builder", () => {- const blocks = SlackMessageBuilder.buildMessage(mockPromptPayload);+ const { blocks, attachments } =+ SlackMessageBuilder.buildMessage(mockPromptPayload);// Should be a full prompt message (5 blocks with commit message)expect(blocks).toHaveLength(5);expect(blocks[0].text.text).toContain("Prompt created");+ expect(attachments).toBeUndefined();});it("should route unknown events to fallback message builder", () => {@@ -279,7 +281,9 @@ describe("SlackMessageBuilder", () => {type: "trace-evaluation" as any,};- const blocks = SlackMessageBuilder.buildMessage(unknownPayload as any);+ const { blocks } = SlackMessageBuilder.buildMessage(+ unknownPayload as any,+ );// Should be a fallback message (1 block)expect(blocks).toHaveLength(1);@@ -294,11 +298,113 @@ describe("SlackMessageBuilder", () => {prompt: null, // This should cause an error} as any;- const blocks = SlackMessageBuilder.buildMessage(malformedPayload);+ const { blocks } = SlackMessageBuilder.buildMessage(malformedPayload);// Should fallback to simple messageexpect(blocks).toHaveLength(1);expect(blocks[0].text.text).toContain("Langfuse Notification");});});++ describe("buildMonitorMessage", () => {+ const mockMonitorEnvelope = {+ id: "exe_01",+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ type: "monitor-alert" as const,+ apiVersion: "v1" as const,+ payload: {+ monitorId: "mon_01",+ projectId: "proj_01",+ permalink: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",+ message: {+ title: "High error rate",+ body: "**count(observations.value)** is **above** `100`",+ },+ severity: "ALERT" as const,+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ fromTimestamp: new Date("2026-05-18T11:55:30.000Z"),+ toTimestamp: new Date("2026-05-18T12:00:30.000Z"),+ view: "observations" as const,+ filters: [],+ window: "5m" as const,+ },+ };++ it("ALERT: header is title only (no severity emoji); body converted to Slack mrkdwn; red attachment", () => {+ const { blocks, attachments } =+ SlackMessageBuilder.buildMonitorMessage(mockMonitorEnvelope);+ expect(blocks[0]).toMatchObject({+ type: "header",+ text: { type: "plain_text", text: "High error rate" },+ });+ // slackify-markdown converts **bold** → *bold* (Slack mrkdwn)+ expect(blocks[1]).toMatchObject({+ type: "section",+ text: { type: "mrkdwn" },+ });+ expect(blocks[1].text.text).toContain("*count(observations.value)*");+ expect(blocks[2]).toMatchObject({ type: "actions" });+ expect(blocks[2].elements[0]).toMatchObject({+ type: "button",+ url: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",+ });+ expect(blocks[3]).toMatchObject({ type: "context" });+ expect(attachments).toEqual([{ color: "#dc3545" }]);+ });++ it.each([+ ["WARNING", "#ffc107"],+ ["OK", "#28a745"],+ ["NO_DATA", "#6c757d"],+ ["UNKNOWN", "#6c757d"],+ ["PAUSED", "#6c757d"],+ ] as const)(+ "%s: header is title only, attachment color %s",+ (severity, color) => {+ const { blocks, attachments } = SlackMessageBuilder.buildMonitorMessage(+ {+ ...mockMonitorEnvelope,+ payload: { ...mockMonitorEnvelope.payload, severity },+ },+ );+ expect(blocks[0].text.text).toBe("High error rate");+ expect(attachments).toEqual([{ color }]);+ },+ );++ it("header has no severity emoji prefix", () => {+ const { blocks } =+ SlackMessageBuilder.buildMonitorMessage(mockMonitorEnvelope);+ expect(blocks[0].text.text).toBe("High error rate");+ });++ it("truncates a header longer than 150 chars to 150 with an ellipsis", () => {+ const longTitle = "[ALERT] " + "x".repeat(160);+ const { blocks } = SlackMessageBuilder.buildMonitorMessage({+ ...mockMonitorEnvelope,+ payload: {+ ...mockMonitorEnvelope.payload,+ message: { ...mockMonitorEnvelope.payload.message, title: longTitle },+ },+ });+ const headerText = blocks[0].text.text as string;+ expect(headerText.length).toBeLessThanOrEqual(150);+ expect(headerText.endsWith("…")).toBe(true);+ });++ it("omits the actions block when permalink is absent", () => {+ const { blocks } = SlackMessageBuilder.buildMonitorMessage({+ ...mockMonitorEnvelope,+ payload: { ...mockMonitorEnvelope.payload, permalink: undefined },+ });+ expect(blocks.every((b) => b.type !== "actions")).toBe(true);+ expect(blocks.some((b) => b.type === "context")).toBe(true);+ });++ it("buildMessage routes monitor-alert envelopes", () => {+ const result = SlackMessageBuilder.buildMessage(mockMonitorEnvelope);+ expect(result.attachments).toEqual([{ color: "#dc3545" }]);+ expect(result.blocks[0].text.text).toBe("High error rate");+ });+ });});diff --git a/worker/src/__tests__/slack-processor.test.ts b/worker/src/__tests__/slack-processor.test.tsindex c558290fc7..047574afa4 100644--- a/worker/src/__tests__/slack-processor.test.ts+++ b/worker/src/__tests__/slack-processor.test.ts@@ -28,6 +28,7 @@ vi.mock("@langfuse/shared/src/server", async () => {SlackService: {getInstance: vi.fn(),},+ getActionById: vi.fn(),};});@@ -42,7 +43,12 @@ describe("Slack Processor", () => {beforeAll(async () => {// Import mocked SlackService- const { SlackService } = await import("@langfuse/shared/src/server");+ const server = await import("@langfuse/shared/src/server");+ const { SlackService } = server;++ // getActionById delegates to the real impl so existing tests read real rows+ const actual = await vi.importActual<any>("@langfuse/shared/src/server");+ (server.getActionById as any).mockImplementation(actual.getActionById);// Create mock service instancemockSlackService = {@@ -68,6 +74,11 @@ describe("Slack Processor", () => {// Reset mocksvi.clearAllMocks();+ // clearAllMocks wipes call history but preserves the getActionById impl+ const actual = await vi.importActual<any>("@langfuse/shared/src/server");+ const server = await import("@langfuse/shared/src/server");+ (server.getActionById as any).mockImplementation(actual.getActionById);+// Create test project({ projectId } = await createOrgProjectAndApiKey());@@ -441,6 +452,165 @@ describe("Slack Processor", () => {expect(trigger?.status).toBe(JobConfigState.INACTIVE);});+ it("monitor-alert with a JSON-round-tripped (string) timestamp builds the full message, not the fallback", async () => {+ // Reconfigure the action as a monitor-alert SLACK action.+ await prisma.action.update({+ where: { id: actionId },+ data: {+ config: {+ type: "SLACK",+ channelId: "C123456",+ channelName: "general",+ } as SlackActionConfig,+ },+ });++ const monitorInput: WebhookInput = {+ projectId,+ automationId,+ executionId,+ payload: {+ id: executionId,+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ type: "monitor-alert",+ apiVersion: "v1",+ payload: {+ monitorId: "mon_01",+ projectId,+ severity: "ALERT",+ permalink:+ "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",+ message: { title: "High error rate", body: "errors > 100" },+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ fromTimestamp: new Date("2026-05-18T11:55:30.000Z"),+ toTimestamp: new Date("2026-05-18T12:00:30.000Z"),+ view: "observations",+ filters: [],+ window: "5m",+ },+ },+ };++ // Reproduce the BullMQ wire shape: Dates become ISO strings.+ const wireInput: WebhookInput = JSON.parse(JSON.stringify(monitorInput));++ await executeWebhook(wireInput, { skipValidation: true });++ expect(mockSlackService.sendMessage).toHaveBeenCalledTimes(1);+ const sent = mockSlackService.sendMessage.mock.calls[0][0];+ const blocks = sent.blocks;++ // Full monitor message: header block carries the alert title.+ expect(blocks[0].type).toBe("header");+ expect(blocks[0].text.text).toBe("High error rate");++ // Not the fallback: a single section block starting "*Langfuse Notification*".+ const isFallback =+ blocks.length === 1 &&+ blocks[0].type === "section" &&+ blocks[0].text?.text?.startsWith("*Langfuse Notification*");+ expect(isFallback).toBe(false);+ });++ it("monitor-alert: text fallback is the alert title, not the generic notification", async () => {+ await prisma.action.update({+ where: { id: actionId },+ data: {+ config: {+ type: "SLACK",+ channelId: "C123456",+ channelName: "general",+ } as SlackActionConfig,+ },+ });++ const monitorInput: WebhookInput = {+ projectId,+ automationId,+ executionId,+ payload: {+ id: executionId,+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ type: "monitor-alert",+ apiVersion: "v1",+ payload: {+ monitorId: "mon_01",+ projectId,+ severity: "ALERT",+ permalink:+ "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",+ message: { title: "[ALERT] High error rate", body: "errors > 100" },+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ fromTimestamp: new Date("2026-05-18T11:55:30.000Z"),+ toTimestamp: new Date("2026-05-18T12:00:30.000Z"),+ view: "observations",+ filters: [],+ window: "5m",+ },+ },+ };++ const wireInput: WebhookInput = JSON.parse(JSON.stringify(monitorInput));++ await executeWebhook(wireInput, { skipValidation: true });++ expect(mockSlackService.sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({ text: "[ALERT] High error rate" }),+ );+ });++ it("monitor-alert: text fallback escapes Slack mention tokens in the monitor name", async () => {+ await prisma.action.update({+ where: { id: actionId },+ data: {+ config: {+ type: "SLACK",+ channelId: "C123456",+ channelName: "general",+ } as SlackActionConfig,+ },+ });++ const monitorInput: WebhookInput = {+ projectId,+ automationId,+ executionId,+ payload: {+ id: executionId,+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ type: "monitor-alert",+ apiVersion: "v1",+ payload: {+ monitorId: "mon_01",+ projectId,+ severity: "ALERT",+ permalink:+ "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",+ message: {+ title: "[ALERT] <!channel> investigate",+ body: "errors > 100",+ },+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ fromTimestamp: new Date("2026-05-18T11:55:30.000Z"),+ toTimestamp: new Date("2026-05-18T12:00:30.000Z"),+ view: "observations",+ filters: [],+ window: "5m",+ },+ },+ };++ const wireInput: WebhookInput = JSON.parse(JSON.stringify(monitorInput));++ await executeWebhook(wireInput, { skipValidation: true });++ expect(mockSlackService.sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ text: "[ALERT] <!channel> investigate",+ }),+ );+ });+it("should handle SlackService errors gracefully", async () => {const { SlackService } = await import("@langfuse/shared/src/server");@@ -491,5 +661,54 @@ describe("Slack Processor", () => {expect(execution?.status).toBe(ActionExecutionStatus.ERROR);expect(execution?.error).toContain("Failed to get Slack client");});++ it("getActionById infra failure propagates for BullMQ retry instead of disabling the trigger", async () => {+ const server = await import("@langfuse/shared/src/server");+ (server.getActionById as any).mockRejectedValueOnce(+ new Error("P2024: connection pool timeout"),+ );++ const fullPrompt = await prisma.prompt.findUnique({+ where: { id: promptId },+ });++ const slackInput: WebhookInput = {+ projectId,+ automationId,+ executionId,+ payload: {+ prompt: fullPrompt as PromptDomain,+ action: "created",+ type: "prompt-version",+ user: {+ id: "user-123",+ name: "Test User",+ email: "[email protected]",+ },+ },+ };++ // Pre-create the execution row so the catch path can fully disable the+ // trigger pre-fix; post-fix the error propagates before the catch.+ await prisma.automationExecution.create({+ data: {+ id: executionId,+ projectId,+ triggerId,+ automationId,+ actionId,+ status: ActionExecutionStatus.PENDING,+ sourceId: executionId,+ input: slackInput,+ },+ });++ await expect(executeWebhook(slackInput)).rejects.toThrow();++ const trigger = await prisma.trigger.findUnique({+ where: { id: triggerId },+ });+ expect(trigger?.status).toBe(JobConfigState.ACTIVE);+ });});});diff --git a/worker/src/__tests__/webhooks.test.ts b/worker/src/__tests__/webhooks.test.tsindex 6342fdbdbd..b0a80b186c 100644--- a/worker/src/__tests__/webhooks.test.ts+++ b/worker/src/__tests__/webhooks.test.ts@@ -6,6 +6,7 @@ import {beforeAll,afterAll,afterEach,+ vi,} from "vitest";import { v4 } from "uuid";import {@@ -18,6 +19,7 @@ import {WebhookInput,createOrgProjectAndApiKey,getActionByIdWithSecrets,+ redis,} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";import {@@ -645,6 +647,133 @@ describe("Webhook Integration Tests", () => {);});+ it("clears the monitor-alert failure counter when auto-disabling the trigger", async () => {+ const action = await prisma.action.findUnique({+ where: { id: actionId },+ });+ if (!action) {+ throw new Error("Action not found");+ }++ await prisma.action.update({+ where: { id: actionId },+ data: {+ projectId,+ type: "WEBHOOK",+ config: {+ ...(action.config as WebhookActionConfigWithSecrets),+ url: "https://webhook-error.example.com/test",+ },+ },+ });++ const failureKey = `automation-failures:${projectId}:${automationId}`;+ await redis!.del(failureKey);++ for (let i = 0; i < 5; i++) {+ const webhookInput: WebhookInput = {+ projectId,+ automationId,+ executionId: v4(),+ payload: {+ id: v4(),+ timestamp: new Date(),+ type: "monitor-alert",+ apiVersion: "v1",+ payload: {+ monitorId: v4(),+ projectId,+ severity: "ALERT",+ permalink: `https://cloud.langfuse.com/project/${projectId}/monitors/mon`,+ timestamp: new Date(),+ fromTimestamp: new Date(Date.now() - 5 * 60_000),+ toTimestamp: new Date(),+ message: { title: "High error rate", body: "errors > 100" },+ view: "observations",+ filters: [],+ window: "5m",+ },+ },+ };++ await executeWebhook(webhookInput, { skipValidation: true });+ }++ const trigger = await prisma.trigger.findUnique({+ where: { id: triggerId },+ });+ expect(trigger?.status).toBe(JobConfigState.INACTIVE);++ expect(await redis!.get(failureKey)).toBeNull();+ });++ it("auto-disables despite a redis.del failure on the failure-side reset", async () => {+ const action = await prisma.action.findUnique({+ where: { id: actionId },+ });+ if (!action) {+ throw new Error("Action not found");+ }++ await prisma.action.update({+ where: { id: actionId },+ data: {+ projectId,+ type: "WEBHOOK",+ config: {+ ...(action.config as WebhookActionConfigWithSecrets),+ url: "https://webhook-error.example.com/test",+ },+ },+ });++ const failureKey = `automation-failures:${projectId}:${automationId}`;+ await redis!.del(failureKey);++ const buildInput = (): WebhookInput => ({+ projectId,+ automationId,+ executionId: v4(),+ payload: {+ id: v4(),+ timestamp: new Date(),+ type: "monitor-alert",+ apiVersion: "v1",+ payload: {+ monitorId: v4(),+ projectId,+ severity: "ALERT",+ permalink: `https://cloud.langfuse.com/project/${projectId}/monitors/mon`,+ timestamp: new Date(),+ fromTimestamp: new Date(Date.now() - 5 * 60_000),+ toTimestamp: new Date(),+ message: { title: "High error rate", body: "errors > 100" },+ view: "observations",+ filters: [],+ window: "5m",+ },+ },+ });++ for (let i = 0; i < 4; i++) {+ await executeWebhook(buildInput(), { skipValidation: true });+ }++ const delSpy = vi+ .spyOn(redis!, "del")+ .mockRejectedValue(new Error("READONLY during failover"));+ try {+ await executeWebhook(buildInput(), { skipValidation: true });+ } finally {+ delSpy.mockRestore();+ }++ const trigger = await prisma.trigger.findUnique({+ where: { id: triggerId },+ });+ expect(trigger?.status).toBe(JobConfigState.INACTIVE);+ });+it("should execute webhook with secret headers correctly", async () => {// Get the full prompt for the payloadconst fullPrompt = await prisma.prompt.findUnique({@@ -1599,5 +1728,100 @@ describe("Webhook Integration Tests", () => {const clientPayloadKeys = Object.keys(payload.client_payload);expect(clientPayloadKeys[clientPayloadKeys.length - 1]).toBe("prompt");});++ it("should truncate oversized GitHub dispatch monitor-alert filters", async () => {+ const ghActionId = v4();+ await prisma.action.create({+ data: {+ id: ghActionId,+ projectId,+ type: "GITHUB_DISPATCH",+ config: {+ type: "GITHUB_DISPATCH",+ url: "https://webhook.example.com/dispatches",+ eventType: "monitor-alert",+ githubToken: encrypt("ghp_test_token"),+ displayGitHubToken: "ghp_...n",+ },+ },+ });++ const ghAutomationId = v4();+ await prisma.automation.create({+ data: {+ id: ghAutomationId,+ projectId,+ triggerId,+ actionId: ghActionId,+ name: "GitHub Dispatch Monitor Automation",+ },+ });++ const ghExecutionId = v4();+ await prisma.automationExecution.create({+ data: {+ id: ghExecutionId,+ projectId,+ triggerId,+ automationId: ghAutomationId,+ actionId: ghActionId,+ status: ActionExecutionStatus.PENDING,+ sourceId: v4(),+ input: {},+ },+ });++ const webhookInput: WebhookInput = {+ projectId,+ automationId: ghAutomationId,+ executionId: ghExecutionId,+ payload: {+ id: v4(),+ timestamp: new Date(),+ type: "monitor-alert",+ apiVersion: "v1",+ payload: {+ monitorId: v4(),+ projectId,+ severity: "ALERT",+ permalink: `https://cloud.langfuse.com/project/${projectId}/monitors/mon`,+ timestamp: new Date(),+ fromTimestamp: new Date(Date.now() - 5 * 60_000),+ toTimestamp: new Date(),+ message: { title: "High error rate", body: "errors > 100" },+ view: "observations",+ filters: [+ {+ column: "metadata.user_id",+ operator: "any of",+ value: [+ "x".repeat(+ GITHUB_REPOSITORY_DISPATCH_MAX_PAYLOAD_BYTES + 1000,+ ),+ ],+ type: "stringOptions",+ },+ ],+ window: "5m",+ },+ },+ };++ await executeWebhook(webhookInput, { skipValidation: true });++ const requests = webhookServer.getReceivedRequests();+ expect(requests).toHaveLength(1);+ expect(Buffer.byteLength(requests[0].body, "utf8")).toBeLessThan(+ GITHUB_REPOSITORY_DISPATCH_MAX_PAYLOAD_BYTES,+ );++ const payload = JSON.parse(requests[0].body);+ expect(payload.event_type).toBe("monitor-alert");+ expect(payload.client_payload.payload.filters).toEqual([]);+ expect(payload.client_payload.truncation).toEqual({+ payloadTruncated: true,+ truncatedFields: ["payload.filters", "payload.message.body"],+ });+ });});});diff --git a/worker/src/app.ts b/worker/src/app.tsindex 855b113c15..4858e1506b 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -22,6 +22,7 @@ import helmet from "helmet";import { cloudUsageMeteringQueueProcessor } from "./queues/cloudUsageMeteringQueue";import { cloudSpendAlertQueueProcessor } from "./queues/cloudSpendAlertQueue";import { cloudFreeTierUsageThresholdQueueProcessor } from "./queues/cloudFreeTierUsageThresholdQueue";+import { monitorQueueProcessor } from "./queues/monitorQueue";import { WorkerManager } from "./queues/workerManager";import {CoreDataS3ExportQueue,@@ -46,6 +47,7 @@ import {LLMAsJudgeExecutionQueue,CodeEvalExecutionQueue,} from "@langfuse/shared/src/server";+import { monitorProcessorTtl } from "@langfuse/shared/monitors/server";import { env, v4WritesToEventsTable } from "./env";import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";import { BackgroundMigrationManager } from "./backgroundMigrations/backgroundMigrationManager";@@ -94,6 +96,7 @@ import { BatchTraceDeletionCleaner } from "./features/batch-trace-deletion-cleanimport { BatchProjectMediaCleaner } from "./features/batch-project-media-cleaner";import { BatchProjectBlobCleaner } from "./features/batch-project-blob-cleaner";import { QueueMetricsRunner } from "./features/queue-metrics-runner";+import { MonitorRunner } from "./features/monitor-runner";import { DeletedMaskCleaner } from "./features/deleted-mask-cleaner";const app = express();@@ -409,6 +412,16 @@ if ();}+if (env.QUEUE_CONSUMER_MONITOR_QUEUE_IS_ENABLED === "true") {+ WorkerManager.register(QueueName.MonitorQueue, monitorQueueProcessor, {+ concurrency: env.LANGFUSE_MONITOR_QUEUE_PROCESSING_CONCURRENCY,+ // Scheduler is the only source of redelivery; disable BullMQ's stalled+ // recovery so the unified TTL pacing is uncontested.+ lockDuration: monitorProcessorTtl + 60_000,+ maxStalledCount: 0,+ });+}+// Cloud Spend Alert Queue: Only enable in cloud environment with Stripeif (env.QUEUE_CONSUMER_CLOUD_SPEND_ALERT_QUEUE_IS_ENABLED === "true" &&@@ -724,6 +737,17 @@ if (env.LANGFUSE_QUEUE_METRICS_ENABLED === "true") {queueMetricsRunner.start();}+// Monitor runners — one per shard+export const monitorRunners: MonitorRunner[] = [];++if (env.LANGFUSE_MONITOR_SCHEDULER_ENABLED === "true") {+ for (let i = 0; i < env.LANGFUSE_MONITOR_SCHEDULERS; i++) {+ const runner = new MonitorRunner(i, env.LANGFUSE_MONITOR_SCHEDULERS);+ monitorRunners.push(runner);+ runner.start();+ }+}+process.on("SIGINT", () => onShutdown("SIGINT"));process.on("SIGTERM", () => onShutdown("SIGTERM"));diff --git a/worker/src/env.ts b/worker/src/env.tsindex 28d8704412..9fd110eff3 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -185,7 +185,13 @@ const EnvSchema = z.object({.optional().transform((s) => (s ? s.split(",").map((id) => id.trim()) : [])),+ LANGFUSE_MONITOR_SCHEDULER_ENABLED: z.enum(["true", "false"]).default("true"),+ LANGFUSE_MONITOR_SCHEDULERS: z.coerce.number().int().min(1).default(1),+// Flags to toggle queue consumers on or off.+ QUEUE_CONSUMER_MONITOR_QUEUE_IS_ENABLED: z+ .enum(["true", "false"])+ .default("true"),QUEUE_CONSUMER_CLOUD_USAGE_METERING_QUEUE_IS_ENABLED: z.enum(["true", "false"]).default("true"),@@ -467,6 +473,10 @@ const EnvSchema = z.object({.number().positive().default(2),+ LANGFUSE_MONITOR_QUEUE_PROCESSING_CONCURRENCY: z.coerce+ .number()+ .positive()+ .default(10),LANGFUSE_DELETE_BATCH_SIZE: z.coerce.number().positive().default(2000),LANGFUSE_TOKEN_COUNT_WORKER_POOL_SIZE: z.coerce.number()diff --git a/worker/src/features/monitor-runner/index.ts b/worker/src/features/monitor-runner/index.tsnew file mode 100644index 0000000000..8cfa0abf04--- /dev/null+++ b/worker/src/features/monitor-runner/index.ts@@ -0,0 +1,65 @@+import { logger, MonitorQueue, QueueJobs } from "@langfuse/shared/src/server";+import { MonitorScheduler } from "@langfuse/shared/monitors/server";+import { prisma } from "@langfuse/shared/src/db";+import { v4 } from "uuid";++import { PeriodicExclusiveRunner } from "../../utils/PeriodicExclusiveRunner";++const tickIntervalMs = 30_000;+const lockTtlSeconds = 90;++/** MonitorRunner ticks one shard of the MonitorScheduler. */+export class MonitorRunner extends PeriodicExclusiveRunner {+ private readonly schedulerId: number;+ private readonly totalSchedulers: number;+ private readonly scheduler: MonitorScheduler;++ protected get defaultIntervalMs(): number {+ return tickIntervalMs;+ }++ constructor(schedulerId: number, totalSchedulers: number) {+ super({+ name: `MonitorRunner(${schedulerId + 1}/${totalSchedulers})`,+ lockKey: `langfuse:monitor:${schedulerId}`,+ lockTtlSeconds,+ });+ this.schedulerId = schedulerId;+ this.totalSchedulers = totalSchedulers;+ const queue = MonitorQueue.getInstance();+ if (!queue) {+ throw new Error(+ `${this.instanceName}: MonitorQueue is unavailable; refusing to start without the ability to publish monitor events`,+ );+ }+ this.scheduler = new MonitorScheduler({+ schedulerId,+ totalSchedulers,+ db: prisma,+ publish: async (event) => {+ await queue.add(QueueJobs.MonitorJob, {+ timestamp: new Date(),+ id: v4(),+ payload: event,+ name: QueueJobs.MonitorJob,+ });+ },+ });+ }++ public override start(): void {+ logger.info(`Starting ${this.instanceName}`, {+ schedulerId: this.schedulerId,+ totalSchedulers: this.totalSchedulers,+ intervalMs: tickIntervalMs,+ });+ super.start();+ }++ protected async execute(): Promise<void> {+ await this.withLock(async () => {+ const count = await this.scheduler.schedule(new Date());+ logger.debug(`${this.instanceName}: published ${count} events`);+ });+ }+}diff --git a/worker/src/features/slack/slackMessageBuilder.ts b/worker/src/features/slack/slackMessageBuilder.tsindex 7d2370eb53..f6ad53af96 100644--- a/worker/src/features/slack/slackMessageBuilder.ts+++ b/worker/src/features/slack/slackMessageBuilder.ts@@ -1,16 +1,44 @@import { logger } from "@langfuse/shared/src/server";import type { WebhookInput } from "@langfuse/shared/src/server";+import type { MonitorSeverity } from "@langfuse/shared";+import type { MonitorWebhookQueueEvent } from "@langfuse/shared/monitors/server";+import { slackifyMarkdown } from "slackify-markdown";import { env } from "../../env";+/** severityVisual maps MonitorSeverity to its Slack emoji + attachment color per RFC §895-900. */+const severityVisual: Record<+ MonitorSeverity,+ { emoji: string; color: string }+> = {+ ALERT: { emoji: "🚨", color: "#dc3545" },+ WARNING: { emoji: "⚠️", color: "#ffc107" },+ OK: { emoji: "✅", color: "#28a745" },+ NO_DATA: { emoji: "❓", color: "#6c757d" },+ UNKNOWN: { emoji: "❓", color: "#6c757d" },+ PAUSED: { emoji: "⏸️", color: "#6c757d" },+};+/** Escape Slack mrkdwn special characters to prevent injection (e.g. <!channel>)* @see https://docs.slack.dev/messaging/formatting-message-text/#escaping */-function escapeSlackMrkdwn(text: string): string {+export function escapeSlackMrkdwn(text: string): string {return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");}+type WebhookInputPayload = WebhookInput["payload"];+type PromptVersionPayload = Extract<+ WebhookInputPayload,+ { type: "prompt-version" }+>;++/** SlackMessage is the shape returned by buildMessage: blocks for Block Kit, optional attachments for the legacy color bar (used by monitor-alert). */+export interface SlackMessage {+ blocks: any[];+ attachments?: { color: string }[];+}+/*** Builds Slack Block Kit messages for different Langfuse event types*/@@ -18,7 +46,7 @@ export class SlackMessageBuilder {/*** Build Block Kit message for prompt version events*/- static buildPromptVersionMessage(payload: WebhookInput["payload"]): any[] {+ static buildPromptVersionMessage(payload: PromptVersionPayload): any[] {const { action, prompt } = payload;// Determine action emoji and color@@ -109,16 +137,74 @@ export class SlackMessageBuilder {/*** Build a simple fallback message for unsupported event types*/- static buildFallbackMessage(payload: WebhookInput["payload"]): any[] {+ static buildFallbackMessage(payload: WebhookInputPayload): any[] {+ // Fallback handles malformed and not-yet-known payloads — narrow off the+ // discriminated union and read `.action` opportunistically.+ const action =+ (payload as { action?: string }).action ?? payload.type ?? "event";return [{type: "section",text: {type: "mrkdwn",- text: `*Langfuse Notification*\n${payload.type} event: *${payload.action}*`,+ text: `*Langfuse Notification*\n${payload.type} event: *${action}*`,+ },+ },+ ];+ }++ /** buildMonitorMessage renders a MonitorWebhookQueueEvent into Slack Block Kit per RFC §855-902. The processor emits standard markdown; we convert the body to Slack mrkdwn via slackify-markdown. */+ static buildMonitorMessage(envelope: MonitorWebhookQueueEvent): SlackMessage {+ const alert = envelope.payload;+ const { color } = severityVisual[alert.severity];+ // Slack hard-limits header plain_text to 150 chars and rejects longer+ // values with invalid_blocks; the [SEVERITY] prefix already conveys+ // severity, so the header carries the title alone (no severity emoji).+ const title = alert.message.title;+ const headerText = title.length > 150 ? `${title.slice(0, 149)}…` : title;+ const blocks: any[] = [+ {+ type: "header",+ text: {+ type: "plain_text",+ text: headerText,+ emoji: true,},},+ {+ type: "section",+ text: { type: "mrkdwn", text: slackifyMarkdown(alert.message.body) },+ },+ ...(alert.permalink+ ? [+ {+ type: "actions",+ elements: [+ {+ type: "button",+ text: {+ type: "plain_text",+ text: "View in Langfuse",+ emoji: true,+ },+ url: alert.permalink,+ style: "primary",+ },+ ],+ },+ ]+ : []),+ {+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `⏱ ${alert.timestamp.toISOString()}`,+ },+ ],+ },];+ return { blocks, attachments: [{ color }] };}/**@@ -143,18 +229,22 @@ export class SlackMessageBuilder {/*** Main entry point - builds appropriate message for event type*/- static buildMessage(payload: WebhookInput["payload"]): any[] {+ static buildMessage(payload: WebhookInputPayload): SlackMessage {try {switch (payload.type) {case "prompt-version":- return this.buildPromptVersionMessage(payload);- default:- logger.warn(`Unsupported Slack message type: ${payload.type}`);- return this.buildFallbackMessage(payload);+ return { blocks: this.buildPromptVersionMessage(payload) };+ case "monitor-alert":+ return this.buildMonitorMessage(payload);+ default: {+ const unknownType = (payload as { type: string }).type;+ logger.warn(`Unsupported Slack message type: ${unknownType}`);+ return { blocks: this.buildFallbackMessage(payload) };+ }}} catch (error) {logger.error("Error building Slack message", { error, payload });- return this.buildFallbackMessage(payload);+ return { blocks: this.buildFallbackMessage(payload) };}}}diff --git a/worker/src/queues/monitorQueue.ts b/worker/src/queues/monitorQueue.tsnew file mode 100644index 0000000000..e3e90acb94--- /dev/null+++ b/worker/src/queues/monitorQueue.ts@@ -0,0 +1,39 @@+import { Processor } from "bullmq";+import { v4 } from "uuid";+import {+ instrumentAsync,+ QueueJobs,+ QueueName,+ WebhookQueue,+} from "@langfuse/shared/src/server";+import { MonitorProcessor } from "@langfuse/shared/monitors/server";+import { prisma } from "@langfuse/shared/src/db";+import { SpanKind } from "@opentelemetry/api";++export const monitorQueueProcessor: Processor = async (job) => {+ if (job.name !== QueueJobs.MonitorJob) return;+ return await instrumentAsync(+ {+ name: "process monitor",+ startNewTrace: true,+ spanKind: SpanKind.CONSUMER,+ },+ async () => {+ const webhookQueue = WebhookQueue.getInstance();+ if (!webhookQueue) {+ throw new Error(+ "monitorQueueProcessor: WebhookQueue is unavailable; cannot publish monitor alerts",+ );+ }+ const processor = new MonitorProcessor(prisma, async (input) => {+ await webhookQueue.add(QueueName.WebhookQueue, {+ timestamp: new Date(),+ id: v4(),+ payload: input,+ name: QueueJobs.WebhookJob,+ });+ });+ await processor.process(job.data.payload, new Date());+ },+ );+};diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.tsindex 43bf32ea32..14db950e27 100644--- a/worker/src/queues/webhooks.ts+++ b/worker/src/queues/webhooks.ts@@ -29,11 +29,16 @@ import {getConsecutiveAutomationFailures,SlackService,logger,+ redis,} from "@langfuse/shared/src/server";+import { MonitorWebhookQueueEventSchema } from "@langfuse/shared/monitors/server";import { Processor, Job } from "bullmq";import { backOff } from "exponential-backoff";import { env } from "../env";-import { SlackMessageBuilder } from "../features/slack/slackMessageBuilder";+import {+ SlackMessageBuilder,+ escapeSlackMrkdwn,+} from "../features/slack/slackMessageBuilder";// GitHub repository_dispatch client_payload: max 10 top-level properties and <64KB.// https://docs.github.com/en/rest/repos/repos#create-a-repository-dispatch-event@@ -45,6 +50,67 @@ const GITHUB_REPOSITORY_DISPATCH_TRUNCATED_FIELDS = ["prompt.config",];+/** automationFailureThreshold is the consecutive-failure count after which a monitor-alert trigger is auto-disabled. Mirrors prompt-version's getConsecutiveAutomationFailures threshold (>= 5 failures since the last success). */+const automationFailureThreshold = 5;+const automationFailureTtlSeconds = 24 * 60 * 60;+const automationFailureKey = (projectId: string, automationId: string) =>+ `automation-failures:${projectId}:${automationId}`;++/** incrementAutomationFailure bumps the consecutive-failure counter for a monitor-alert Automation and refreshes the 24h TTL; returns the new count. Inline because monitor-alert is the only consumer today. */+async function incrementAutomationFailure(args: {+ projectId: string;+ automationId: string;+}): Promise<number> {+ if (!redis) return 0;+ const key = automationFailureKey(args.projectId, args.automationId);+ const results = await redis+ .multi()+ .incr(key)+ .expire(key, automationFailureTtlSeconds)+ .exec();+ return Number(results?.[0]?.[1] ?? 0);+}++/** resetAutomationFailures clears the streak after a successful delivery. */+async function resetAutomationFailures(args: {+ projectId: string;+ automationId: string;+}): Promise<void> {+ if (!redis) return;+ await redis.del(automationFailureKey(args.projectId, args.automationId));+}++/** buildWebhookOutboundPayload validates and returns the HTTP body for a WebhookInput, discriminating on payload.type. monitor-alert: the processor already built the unified envelope — pass through. prompt-version: wrap at dispatch time with id = executionId and timestamp = now. */+function buildWebhookOutboundPayload(input: WebhookInput) {+ if (input.payload.type === "monitor-alert") {+ const parsed = MonitorWebhookQueueEventSchema.safeParse(input.payload);+ if (!parsed.success) {+ throw new InternalServerError(+ `Invalid monitor-alert payload: ${parsed.error.message}`,+ );+ }+ return parsed.data;+ }+ const promptPayload = input.payload;+ const parsed = PromptWebhookOutboundSchema.safeParse({+ id: input.executionId,+ timestamp: new Date(),+ type: promptPayload.type,+ apiVersion: "v1",+ action: promptPayload.action,+ prompt: promptPayload.prompt,+ user: promptPayload.user+ ? { name: promptPayload.user.name, email: promptPayload.user.email }+ : undefined,+ });+ if (!parsed.success) {+ throw new InternalServerError(+ `Invalid webhook payload: ${parsed.error.message}`,+ );+ }+ return parsed.data;+}+// Handles both webhook and slack actionsexport const webhookProcessor: Processor = async (job: Job<TQueueJobTypes[QueueName.WebhookQueue]>,@@ -127,6 +193,7 @@ async function executeHttpAction({executionStart,actionConfig,additionalSensitiveHeaders,+ payloadType,}: {url: string;payload: string;@@ -138,7 +205,10 @@ async function executeHttpAction({executionStart: Date;actionConfig: ActionDomainWithSecrets;additionalSensitiveHeaders?: string[];+ payloadType: WebhookInput["payload"]["type"];}): Promise<{ httpStatus: number; responseBody: string }> {+ // monitor-alert does not write AutomationExecution rows; auto-disable rides a Redis counter instead.+ const isMonitorAlert = payloadType === "monitor-alert";let httpStatus: number | undefined;let responseBody: string | undefined;@@ -235,19 +305,33 @@ async function executeHttpAction({);// Update execution status on success- await prisma.automationExecution.update({- where: {- projectId,- triggerId: automation.trigger.id,- actionId: automation.action.id,- id: executionId,- },- data: {- status: ActionExecutionStatus.COMPLETED,- startedAt: executionStart,- finishedAt: new Date(),- },- });+ if (isMonitorAlert) {+ try {+ await resetAutomationFailures({+ projectId,+ automationId: automation.id,+ });+ } catch (resetError) {+ logger.warn(+ `Failed to reset automation failure counter after successful delivery for automation ${automation.id} in project ${projectId}`,+ resetError,+ );+ }+ } else {+ await prisma.automationExecution.update({+ where: {+ projectId,+ triggerId: automation.trigger.id,+ actionId: automation.action.id,+ id: executionId,+ },+ data: {+ status: ActionExecutionStatus.COMPLETED,+ startedAt: executionStart,+ finishedAt: new Date(),+ },+ });+ }return { httpStatus: httpStatus!, responseBody: responseBody! };} catch (error) {@@ -268,6 +352,36 @@ async function executeHttpAction({throw error;}+ if (isMonitorAlert) {+ // monitor-alert: Redis counter compensates for the missing+ // AutomationExecution streak. Disable on the 5th consecutive failure.+ const count = await incrementAutomationFailure({+ projectId,+ automationId: automation.id,+ });+ if (count >= automationFailureThreshold) {+ await prisma.trigger.update({+ where: { id: automation.trigger.id, projectId },+ data: { status: JobConfigState.INACTIVE },+ });+ try {+ await resetAutomationFailures({+ projectId,+ automationId: automation.id,+ });+ } catch (resetError) {+ logger.warn(+ `Failed to reset automation failure counter after auto-disable for automation ${automation.id} in project ${projectId}`,+ resetError,+ );+ }+ logger.warn(+ `Automation ${automation.trigger.id} disabled after ${count} consecutive failures in project ${projectId} (monitor-alert)`,+ );+ }+ return { httpStatus: httpStatus || 0, responseBody: responseBody || "" };+ }+// Update execution status and check if we should disable triggerawait prisma.$transaction(async (tx) => {// Update execution status@@ -373,38 +487,25 @@ async function executeWebhookAction({}const webhookConfig = actionConfig.config;- const webhookUser = input.payload.user- ? {- name: input.payload.user.name,- email: input.payload.user.email,- }- : undefined;- // Validate and prepare webhook payload- const validatedPayload = PromptWebhookOutboundSchema.safeParse({- id: input.executionId,- timestamp: new Date(),- type: input.payload.type,- apiVersion: "v1",- action: input.payload.action,- prompt: input.payload.prompt,- user: webhookUser,- });-- if (!validatedPayload.success) {- throw new InternalServerError(- `Invalid webhook payload: ${validatedPayload.error.message}`,- );+ const validated = buildWebhookOutboundPayload(input);+ let webhookPayload: string;+ if (input.payload.type === "prompt-version") {+ // Prompt-version contract: prompt key always last.+ const { prompt, user, ...otherFields } = validated as Extract<+ typeof validated,+ { type: "prompt-version" }+ >;+ webhookPayload = JSON.stringify({+ ...otherFields,+ ...(user ? { user } : {}),+ prompt,+ });+ } else {+ // monitor-alert: post the envelope verbatim.+ webhookPayload = JSON.stringify(validated);}- // Prepare webhook payload with prompt always last- const { prompt, user, ...otherFields } = validatedPayload.data;- const webhookPayload = JSON.stringify({- ...otherFields,- ...(user ? { user } : {}),- prompt,- });-// Prepare headers with signature if secret existsconst requestHeaders: Record<string, string> = {};const additionalSensitiveHeaders: string[] = [];@@ -448,6 +549,7 @@ async function executeWebhookAction({executionStart,actionConfig,additionalSensitiveHeaders,+ payloadType: input.payload.type,});}@@ -484,63 +586,76 @@ async function executeGitHubDispatchAction({}const githubConfig = actionConfig.config;- const webhookUser = input.payload.user- ? {- name: input.payload.user.name,- email: input.payload.user.email,- }- : undefined;-- // Validate and prepare Langfuse payload- const validatedPayload = PromptWebhookOutboundSchema.safeParse({- id: input.executionId,- timestamp: new Date(),- type: input.payload.type,- apiVersion: "v1",- action: input.payload.action,- prompt: input.payload.prompt,- user: webhookUser,- });-- if (!validatedPayload.success) {- throw new InternalServerError(- `Invalid webhook payload: ${validatedPayload.error.message}`,- );- }-- // Use configured event_type (required field)const eventType = githubConfig.eventType;-- // Transform to GitHub dispatch format- const { prompt, user, ...otherFields } = validatedPayload.data;- const fullGithubPayload = JSON.stringify({- event_type: eventType,- client_payload: {- ...otherFields,- ...(user ? { user } : {}),- prompt,- },- });- const githubPayload =- Buffer.byteLength(fullGithubPayload, "utf8") <- GITHUB_REPOSITORY_DISPATCH_MAX_PAYLOAD_BYTES- ? fullGithubPayload- : JSON.stringify({- event_type: eventType,- client_payload: {- ...otherFields,- ...(user ? { user } : {}),- truncation: {- payloadTruncated: true,- truncatedFields: GITHUB_REPOSITORY_DISPATCH_TRUNCATED_FIELDS,+ const validated = buildWebhookOutboundPayload(input);++ let githubPayload: string;+ if (input.payload.type === "prompt-version") {+ const { prompt, user, ...otherFields } = validated as Extract<+ typeof validated,+ { type: "prompt-version" }+ >;+ const fullGithubPayload = JSON.stringify({+ event_type: eventType,+ client_payload: {+ ...otherFields,+ ...(user ? { user } : {}),+ prompt,+ },+ });+ githubPayload =+ Buffer.byteLength(fullGithubPayload, "utf8") <+ GITHUB_REPOSITORY_DISPATCH_MAX_PAYLOAD_BYTES+ ? fullGithubPayload+ : JSON.stringify({+ event_type: eventType,+ client_payload: {+ ...otherFields,+ ...(user ? { user } : {}),+ truncation: {+ payloadTruncated: true,+ truncatedFields: GITHUB_REPOSITORY_DISPATCH_TRUNCATED_FIELDS,+ },+ prompt: {+ ...prompt,+ prompt: GITHUB_REPOSITORY_DISPATCH_TRUNCATION_MARKER,+ config: {},+ },},- prompt: {- ...prompt,- prompt: GITHUB_REPOSITORY_DISPATCH_TRUNCATION_MARKER,- config: {},+ });+ } else {+ // monitor-alert: post the envelope as client_payload.+ const monitorEnvelope = validated as Extract<+ typeof validated,+ { type: "monitor-alert" }+ >;+ const fullGithubPayload = JSON.stringify({+ event_type: eventType,+ client_payload: monitorEnvelope,+ });+ githubPayload =+ Buffer.byteLength(fullGithubPayload, "utf8") <+ GITHUB_REPOSITORY_DISPATCH_MAX_PAYLOAD_BYTES+ ? fullGithubPayload+ : JSON.stringify({+ event_type: eventType,+ client_payload: {+ ...monitorEnvelope,+ payload: {+ ...monitorEnvelope.payload,+ filters: [],+ message: {+ ...monitorEnvelope.payload.message,+ body: GITHUB_REPOSITORY_DISPATCH_TRUNCATION_MARKER,+ },+ },+ truncation: {+ payloadTruncated: true,+ truncatedFields: ["payload.filters", "payload.message.body"],+ },},- },- });+ });+ }// Prepare headers with GitHub tokenconst requestHeaders: Record<string, string> = {};@@ -575,6 +690,7 @@ async function executeGitHubDispatchAction({executionId,executionStart,actionConfig,+ payloadType: input.payload.type,});}@@ -593,26 +709,41 @@ async function executeSlackAction({const { projectId, executionId } = input;const executionStart = new Date();- try {- const actionConfig = await getActionById({- projectId,- actionId: automation.action.id,- });+ const actionConfig = await getActionById({+ projectId,+ actionId: automation.action.id,+ });- if (!actionConfig) {- throw new InternalServerError("Action config not found");- }+ if (!actionConfig) {+ throw new InternalServerError("Action config not found");+ }- if (!isSlackActionConfig(actionConfig.config)) {- throw new InternalServerError(- "Action config is not a valid Slack configuration",- );- }+ if (!isSlackActionConfig(actionConfig.config)) {+ throw new InternalServerError(+ "Action config is not a valid Slack configuration",+ );+ }- const slackConfig = actionConfig.config;+ const slackConfig = actionConfig.config;++ try {+ // monitor-alert envelopes survive a BullMQ JSON round-trip as plain strings;+ // parse to recover the Dates buildMonitorMessage formats, matching the+ // webhook/github dispatchers' buildWebhookOutboundPayload discipline.+ let payload = input.payload;+ if (payload.type === "monitor-alert") {+ const parsed = MonitorWebhookQueueEventSchema.safeParse(payload);+ if (!parsed.success) {+ throw new InternalServerError(+ `Invalid monitor-alert payload: ${parsed.error.message}`,+ );+ }+ payload = parsed.data;+ }// Build message blocks using predefined formats or custom templatelet blocks: any[] = [];+ let attachments: { color: string }[] | undefined;// TODO: Custom templates not supported via the UI yetif (slackConfig.messageTemplate) {@@ -631,7 +762,9 @@ async function executeSlackAction({// Use predefined message format if no custom template or template failedif (blocks.length === 0) {- blocks = SlackMessageBuilder.buildMessage(input.payload);+ const message = SlackMessageBuilder.buildMessage(payload);+ blocks = message.blocks;+ attachments = message.attachments;logger.debug(`Using predefined message format for action ${automation.action.id}`,);@@ -646,30 +779,76 @@ async function executeSlackAction({client,channelId: slackConfig.channelId,blocks,- text: "Langfuse Notification",+ attachments,+ text:+ payload.type === "monitor-alert"+ ? escapeSlackMrkdwn(payload.payload.message.title)+ : "Langfuse Notification",});// Update execution status to completed- await prisma.automationExecution.update({- where: {- projectId,- triggerId: automation.trigger.id,- actionId: automation.action.id,- id: executionId,- },- data: {- status: ActionExecutionStatus.COMPLETED,- startedAt: executionStart,- finishedAt: new Date(),- output: {- channel: sendResult.channel,- messageTs: sendResult.messageTs,+ if (input.payload.type === "monitor-alert") {+ try {+ await resetAutomationFailures({+ projectId,+ automationId: automation.id,+ });+ } catch (resetError) {+ logger.warn(+ `Failed to reset automation failure counter after successful delivery for automation ${automation.id} in project ${projectId}`,+ resetError,+ );+ }+ } else {+ await prisma.automationExecution.update({+ where: {+ projectId,+ triggerId: automation.trigger.id,+ actionId: automation.action.id,+ id: executionId,},- },- });+ data: {+ status: ActionExecutionStatus.COMPLETED,+ startedAt: executionStart,+ finishedAt: new Date(),+ output: {+ channel: sendResult.channel,+ messageTs: sendResult.messageTs,+ },+ },+ });+ }} catch (error) {logger.error("Error executing Slack action", error);+ if (input.payload.type === "monitor-alert") {+ const count = await incrementAutomationFailure({+ projectId,+ automationId: automation.id,+ });+ if (count >= automationFailureThreshold) {+ await prisma.trigger.update({+ where: { id: automation.trigger.id, projectId },+ data: { status: JobConfigState.INACTIVE },+ });+ try {+ await resetAutomationFailures({+ projectId,+ automationId: automation.id,+ });+ } catch (resetError) {+ logger.warn(+ `Failed to reset automation failure counter after auto-disable for automation ${automation.id} in project ${projectId}`,+ resetError,+ );+ }+ logger.warn(+ `Automation ${automation.trigger.id} disabled after ${count} consecutive failures in project ${projectId} (monitor-alert/slack)`,+ );+ }+ return;+ }+// Get action config for updating in case of failureconst failureActionConfig = await getActionByIdWithSecrets({projectId,diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.tsindex 4893873a09..d42326e32c 100644--- a/worker/src/utils/shutdown.ts+++ b/worker/src/utils/shutdown.ts@@ -18,6 +18,7 @@ import {batchTraceDeletionCleaner,deletedMaskCleaner,queueMetricsRunner,+ monitorRunners,} from "../app";export const onShutdown: NodeJS.SignalsListener = async (signal) => {@@ -56,6 +57,11 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {// Stop queue metrics runnerqueueMetricsRunner?.stop();+ // Stop monitor runners+ for (const runner of monitorRunners) {+ runner.stop();+ }+// Shutdown workers (https://docs.bullmq.io/guide/going-to-production#gracefully-shut-down-workers)await WorkerManager.closeWorkers();