🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(monitors): preserve monitor form state when adding an automation (LFE-10982) (#15883)
Nikita Kabardin163ea1358eca
diff --git a/web/src/features/automations/components/automationForm.tsx b/web/src/features/automations/components/automationForm.tsxindex 35321a363b..fa572bb9a0 100644--- a/web/src/features/automations/components/automationForm.tsx+++ b/web/src/features/automations/components/automationForm.tsx@@ -645,6 +645,13 @@ export const AutomationForm = ({const isProjectNotification =watchedEventSource === TriggerEventSource.ProjectNotification;+ // A monitor-sourced trigger has nothing to configure, so with the source+ // locked (e.g. created from the monitor form) the card is pure noise.+ const hideTriggerCard =+ isProjectNotification ||+ (Boolean(lockedEventSource) &&+ watchedEventSource === TriggerEventSource.Monitor);+/** handleEventSourceChange resets eventAction + filter to defaults appropriate for the picked source. */const handleEventSourceChange = (value: TriggerEventSource) => {form.setValue("eventSource", value);@@ -704,8 +711,7 @@ export const AutomationForm = ({</div>)}- {/* Project-notification triggers are match-all, so there is nothing to configure. */}- {!isProjectNotification && (+ {!hideTriggerCard && (<Card><CardHeader><CardTitle>Trigger</CardTitle>diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.access.clienttest.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.access.clienttest.tsxindex a6efff8c41..101f5cd50f 100644--- a/web/src/features/monitors/components/MonitorAutomationsPanel.access.clienttest.tsx+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.access.clienttest.tsx@@ -14,13 +14,12 @@ vi.mock("@/src/utils/api", () => ({useQuery: () => ({ data: [automationRow], isSuccess: true }),},},+ useUtils: () => ({+ automations: { getAutomations: { fetch: vi.fn(async () => []) } },+ }),},}));-vi.mock("next/router", () => ({- useRouter: () => ({ asPath: "/", push: vi.fn() }),-}));-import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";describe("MonitorAutomationsPanel access gating", () => {diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsxnew file mode 100644index 0000000000..6d710caa28--- /dev/null+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsx@@ -0,0 +1,158 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";++const existingRow = {+ id: "auto-1",+ name: "Ping webhook",+ trigger: { id: "trig-1" },+ action: { type: "WEBHOOK" },+};+const createdRow = {+ id: "auto-2",+ name: "Deploy hook",+ trigger: { id: "trig-2" },+ action: { type: "WEBHOOK" },+};++/** automations stands in for the server list; a save flips it the way invalidation would. */+let automations: (typeof existingRow)[] = [];++/** gateFetch defers the post-create list read so a test can interleave user input. */+let gateFetch: Promise<unknown> | undefined;++vi.mock("@/src/utils/api", () => ({+ api: {+ automations: {+ getAutomations: {+ useQuery: () => ({ data: automations, isPending: false }),+ },+ },+ useUtils: () => ({+ automations: {+ getAutomations: {+ fetch: vi.fn(async () => {+ await gateFetch;+ return automations;+ }),+ },+ },+ }),+ },+}));++type SuccessHandler = (+ automationId?: string,+ webhookSecret?: string,+ actionType?: "WEBHOOK" | "GITHUB_DISPATCH",+) => void;++/** stubSave stands in for the real form, whose contract with the panel is "prefill in, onSuccess out". */+let stubSave: (onSuccess: SuccessHandler) => void;++vi.mock("@/src/features/automations/components/automationForm", () => ({+ AutomationForm: ({ onSuccess }: { onSuccess: SuccessHandler }) => (+ <button onClick={() => stubSave(onSuccess)}>stub save</button>+ ),+}));++import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";++/** openCreateDialog opens the "+ Automation" menu and picks one of its items. */+const openCreateDialog = async (item: RegExp) => {+ fireEvent.keyDown(screen.getByRole("button", { name: /^automation$/i }), {+ key: "Enter",+ });+ fireEvent.click(await screen.findByRole("menuitem", { name: item }));+};++describe("MonitorAutomationsPanel automation creation", () => {+ beforeEach(() => {+ gateFetch = undefined;+ });++ it("creates in place and selects the new trigger, never linking away from the monitor form", async () => {+ automations = [existingRow];+ stubSave = (onSuccess) => {+ automations = [existingRow, createdRow];+ onSuccess("auto-2");+ };+ const onTriggerIdsChange = vi.fn();+ render(+ <MonitorAutomationsPanel+ projectId="p1"+ triggerIds={["trig-1"]}+ onTriggerIdsChange={onTriggerIdsChange}+ />,+ );++ await openCreateDialog(/new automation/i);+ // Navigating to the automations page unmounted the monitor form (LFE-10982).+ expect(document.querySelector('a[href*="/automations"]')).toBeNull();++ fireEvent.click(await screen.findByRole("button", { name: /stub save/i }));++ await waitFor(() =>+ expect(onTriggerIdsChange).toHaveBeenCalledWith(["trig-1", "trig-2"]),+ );+ });++ it("keeps the open dialog through the empty-state-to-list switch, so the once-only webhook secret still shows", async () => {+ automations = [];+ stubSave = (onSuccess) => onSuccess("auto-2", "whsec_stub", "WEBHOOK");+ const onTriggerIdsChange = vi.fn();+ // A fresh element per render: React bails out of re-rendering an identical one.+ const panel = () => (+ <MonitorAutomationsPanel+ projectId="p1"+ triggerIds={[]}+ onTriggerIdsChange={onTriggerIdsChange}+ />+ );+ const { rerender } = render(panel());++ await openCreateDialog(/^webhook$/i);+ // The create invalidates the list, so the first automation lands while the+ // dialog is still open; that must not remount the dialog's owner.+ automations = [createdRow];+ rerender(panel());++ fireEvent.click(await screen.findByRole("button", { name: /stub save/i }));+ expect(await screen.findByText("whsec_stub")).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: /saved the secret/i }));+ await waitFor(() =>+ expect(onTriggerIdsChange).toHaveBeenCalledWith(["trig-2"]),+ );+ });++ it("keeps a selection made while the post-create list read is still in flight", async () => {+ automations = [existingRow];+ stubSave = (onSuccess) => {+ automations = [existingRow, createdRow];+ onSuccess("auto-2");+ };+ let releaseFetch = () => {};+ gateFetch = new Promise<void>((resolve) => {+ releaseFetch = resolve;+ });+ const onTriggerIdsChange = vi.fn();+ const panel = (triggerIds: string[]) => (+ <MonitorAutomationsPanel+ projectId="p1"+ triggerIds={triggerIds}+ onTriggerIdsChange={onTriggerIdsChange}+ />+ );+ const { rerender } = render(panel([]));++ await openCreateDialog(/new automation/i);+ fireEvent.click(await screen.findByRole("button", { name: /stub save/i }));++ // The user ticks another automation before the read resolves.+ rerender(panel(["trig-1"]));+ releaseFetch();++ await waitFor(() =>+ expect(onTriggerIdsChange).toHaveBeenCalledWith(["trig-1", "trig-2"]),+ );+ });+});diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsxindex 74a88a3dc4..2383f68018 100644--- a/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsx+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.prune.clienttest.tsx@@ -16,13 +16,12 @@ vi.mock("@/src/utils/api", () => ({useQuery: () => useQueryMock(),},},+ useUtils: () => ({+ automations: { getAutomations: { fetch: vi.fn(async () => []) } },+ }),},}));-vi.mock("next/router", () => ({- useRouter: () => ({ asPath: "/", push: vi.fn() }),-}));-import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";describe("MonitorAutomationsPanel stale-id pruning", () => {diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.toggle.clienttest.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.toggle.clienttest.tsxindex b3f1c63545..e77816113f 100644--- a/web/src/features/monitors/components/MonitorAutomationsPanel.toggle.clienttest.tsx+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.toggle.clienttest.tsx@@ -16,13 +16,12 @@ vi.mock("@/src/utils/api", () => ({useQuery: () => useQueryMock(),},},+ useUtils: () => ({+ automations: { getAutomations: { fetch: vi.fn(async () => []) } },+ }),},}));-vi.mock("next/router", () => ({- useRouter: () => ({ asPath: "/", push: vi.fn() }),-}));-import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";describe("MonitorAutomationsPanel toggle immutability", () => {diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.tsxindex 595f626fcc..ddea8910b6 100644--- a/web/src/features/monitors/components/MonitorAutomationsPanel.tsx+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.tsx@@ -1,7 +1,5 @@-/* eslint-disable @repo/no-style-props, @repo/no-abstracted-overlay-trigger */-import { type ReactNode, useMemo, useCallback } from "react";-import Link from "next/link";-import { useRouter } from "next/router";+/* eslint-disable @repo/no-style-props */+import { useMemo, useCallback, useRef, useState } from "react";import {Check,Github,@@ -13,13 +11,23 @@ import {import { api } from "@/src/utils/api";import { Button } from "@/src/components/ui/button";import { Card, CardContent } from "@/src/components/ui/card";+import {+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/src/components/ui/dialog";import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,DropdownMenuTrigger,} from "@/src/components/ui/dropdown-menu";-import { automationCreateHref } from "@/src/features/automations/components/automationForm";+import { AutomationForm } from "@/src/features/automations/components/automationForm";+import { WebhookSecretRender } from "@/src/features/automations/components/WebhookSecretRender";import { cn } from "@/src/utils/tailwind";import {ActionTypeSchema,@@ -47,6 +55,7 @@ export const MonitorAutomationsPanel = ({onTriggerIdsChange: (next: string[]) => void;hasAccess?: boolean;}) => {+ const utils = api.useUtils();const { data, isPending } = api.automations.getAutomations.useQuery({projectId,@@ -58,54 +67,68 @@ export const MonitorAutomationsPanel = ({},);- if (isPending || !data || data?.length == 0)- return (- <SetupMonitorAutomationsCard- projectId={projectId}- isDisabled={!hasAccess}- />- );+ // The user can keep toggling rows while the refetch below is in flight, so the+ // write must not be based on a render-time snapshot of the selection.+ const latestTriggerIds = useRef(triggerIds);+ latestTriggerIds.current = triggerIds;++ /** selectCreatedAutomation ticks a just-created automation, resolving its trigger id (the panel's key) from the refreshed list. */+ const selectCreatedAutomation = useCallback(+ async (automationId: string) => {+ const automations = await utils.automations.getAutomations.fetch({+ projectId,+ eventSource: TriggerEventSource.Monitor,+ });+ const triggerId = automations?.find((a) => a.id === automationId)?.trigger+ .id;+ const selected = latestTriggerIds.current;+ if (!triggerId || selected.includes(triggerId)) return;+ onTriggerIdsChange([...selected, triggerId]);+ },+ [utils, projectId, onTriggerIdsChange],+ );++ const automations = data ?? [];+ const isEmpty = isPending || automations.length === 0;return (- <MonitorAutomationsListCard- projectId={projectId}- isDisabled={!hasAccess}- automations={data}- selectedTriggerIds={triggerIds}- onSelectedTriggerIdsChange={onTriggerIdsChange}- />+ <div className="space-y-3">+ <Card>+ <CardContent className="space-y-3 pt-4">+ {isEmpty ? (+ <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>+ ) : (+ <MonitorAutomationsSelectableList+ isDisabled={!hasAccess}+ automations={automations}+ selectedTriggerIds={triggerIds}+ onSelectedTriggerIdsChange={onTriggerIdsChange}+ />+ )}+ {/* One CTA for both states: it owns the create dialog, so it must stay+ mounted when the first automation turns the empty state into a list. */}+ <AddAutomationDropdown+ projectId={projectId}+ fullWidth+ isDisabled={!hasAccess}+ onAutomationCreated={selectCreatedAutomation}+ />+ </CardContent>+ </Card>+ </div>);};-/** SetupMonitorAutomationsCard is the empty state prompting creation of the first automation. */-const SetupMonitorAutomationsCard = ({- isDisabled,- projectId,-}: {- isDisabled: boolean;- projectId: string;-}) => (- <MonitorAutomationsCard>- <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- isDisabled={isDisabled}- />- </MonitorAutomationsCard>-);--/** MonitorAutomationsListCard renders the selectable automations and reports the selected trigger IDs. */-const MonitorAutomationsListCard = ({- projectId,+/** MonitorAutomationsSelectableList renders the selectable automations and reports the selected trigger IDs. */+const MonitorAutomationsSelectableList = ({isDisabled,automations,selectedTriggerIds,onSelectedTriggerIdsChange,}: {- projectId: string;isDisabled: boolean;automations: AutomationDomain[];selectedTriggerIds: string[];@@ -136,31 +159,15 @@ const MonitorAutomationsListCard = ({);return (- <MonitorAutomationsCard>- <MonitorAutomationsList- automations={automations}- isDisabled={isDisabled}- selectedTriggerIds={activeSelectedTriggerIds}- onClick={toggleSelectedTriggerId}- />- <AddAutomationDropdown- projectId={projectId}- fullWidth- isDisabled={isDisabled}- />- </MonitorAutomationsCard>+ <MonitorAutomationsList+ automations={automations}+ isDisabled={isDisabled}+ selectedTriggerIds={activeSelectedTriggerIds}+ onClick={toggleSelectedTriggerId}+ />);};-/** MonitorAutomationsCard is the shared card shell for the panel's contents. */-const MonitorAutomationsCard = ({ children }: { children: ReactNode }) => (- <div className="space-y-3">- <Card>- <CardContent className="space-y-3 pt-4">{children}</CardContent>- </Card>- </div>-);-/** MonitorAutomationsList renders one selectable row per automation. */const MonitorAutomationsList = ({automations,@@ -239,49 +246,138 @@ const RowCheckbox = ({ checked }: { checked: boolean }) => (</span>);-/** AddAutomationDropdown renders the "+ Automation" CTA for the empty state and the list footer. */+/** NewAutomationDraft is the pending create-automation dialog; an absent actionType lets the form pick its own default. */+type NewAutomationDraft = { actionType?: ActionTypes };++/** CreatedWebhookSecret is the signing secret of a just-created webhook automation, shown once before the dialog closes. */+type CreatedWebhookSecret = { automationId: string; webhookSecret: string };++/**+ * AddAutomationDropdown renders the "+ Automation" CTA for the empty state and+ * the list footer. Creation happens in a dialog on this page: navigating to the+ * automations page unmounted the monitor form and lost the draft (LFE-10982).+ */const AddAutomationDropdown = ({projectId,fullWidth,isDisabled,+ onAutomationCreated,}: {projectId: string;fullWidth?: boolean;isDisabled?: boolean;+ onAutomationCreated: (automationId: string) => void;}) => {- const router = useRouter();+ const [draft, setDraft] = useState<NewAutomationDraft | null>(null);+ const [createdSecret, setCreatedSecret] =+ useState<CreatedWebhookSecret | null>(null);++ /** closeDialog dismisses both dialog phases, selecting the automation when one was created. */+ const closeDialog = (createdAutomationId?: string) => {+ setDraft(null);+ setCreatedSecret(null);+ if (createdAutomationId) onAutomationCreated(createdAutomationId);+ };+return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="outline"- size="lg"- disabled={isDisabled}- 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)}+ <>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="outline"+ size="lg"+ disabled={isDisabled}+ className={fullWidth ? "w-full" : undefined}>+ <Plus className="mr-2 h-4 w-4" />+ Automation+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuItem onSelect={() => setDraft({})}><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)}>+ </DropdownMenuItem>+ {ActionTypeSchema.options.map((t) => (+ <DropdownMenuItem+ key={t}+ onSelect={() => setDraft({ actionType: t })}+ ><ActionIcon type={t} className="mr-2 h-3.5 w-3.5" />{actionLabel[t]}- </Link>- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ <Dialog+ open={draft !== null}+ onOpenChange={(open) => {+ if (!open) closeDialog(createdSecret?.automationId);+ }}+ >+ <DialogContent+ size="lg"+ // The dialog portals out of the monitor <form>, but React events still+ // bubble through the REACT tree: without this, saving the automation+ // would submit the monitor too. Mirrors DialogContent's own onClick.+ onSubmit={(e) => e.stopPropagation()}+ >+ {createdSecret ? (+ <>+ <DialogHeader>+ <DialogTitle>Webhook secret created</DialogTitle>+ <DialogDescription>+ Copy the webhook secret below — it will only be shown once.+ </DialogDescription>+ </DialogHeader>+ <DialogBody>+ <WebhookSecretRender+ webhookSecret={createdSecret.webhookSecret}+ />+ </DialogBody>+ <DialogFooter>+ <Button onClick={() => closeDialog(createdSecret.automationId)}>+ {"I've saved the secret"}+ </Button>+ </DialogFooter>+ </>+ ) : (+ <>+ <DialogHeader>+ <DialogTitle>New automation</DialogTitle>+ <DialogDescription>+ This automation stays available to every monitor in the+ project.+ </DialogDescription>+ </DialogHeader>+ <DialogBody>+ <AutomationForm+ projectId={projectId}+ isEditing+ lockedEventSource={TriggerEventSource.Monitor}+ prefill={{+ eventSource: TriggerEventSource.Monitor,+ actionType: draft?.actionType,+ }}+ onSuccess={(automationId, webhookSecret, actionType) => {+ if (+ automationId &&+ webhookSecret &&+ actionType === "WEBHOOK"+ ) {+ setCreatedSecret({ automationId, webhookSecret });+ return;+ }+ closeDialog(automationId);+ }}+ onCancel={() => closeDialog()}+ />+ </DialogBody>+ </>+ )}+ </DialogContent>+ </Dialog>+ </>);};