Skip to content

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

feat(monitors): add new monitor automation dialog (#19448)

Mark Salpeterdee236f7b97c
diff --git a/web/.storybook/main.ts b/web/.storybook/main.ts
index 61d51d04b2..7565aa5e5b 100644
--- a/web/.storybook/main.ts
+++ b/web/.storybook/main.ts
@@ -38,6 +38,10 @@ const STORY_TITLE_GROUPS: StoryTitleGroup[] = [
directory: "src/features/in-app-agent/components",
titlePrefix: "Features/In-App Agent",
},
+ {
+ directory: "src/features/monitors/automations",
+ titlePrefix: "Features/Monitors",
+ },
{
directory: "src/features/traces/components",
titlePrefix: "Features/Traces",
diff --git a/web/src/__tests__/server/unit/automations/githubDispatchHelpers.servertest.ts b/web/src/__tests__/server/unit/automations/githubDispatchHelpers.servertest.ts
new file mode 100644
index 0000000000..106bac3fe8
--- /dev/null
+++ b/web/src/__tests__/server/unit/automations/githubDispatchHelpers.servertest.ts
@@ -0,0 +1,19 @@
+import { processGitHubDispatchActionConfig } from "@/src/features/automations/server/githubDispatchHelpers";
+
+describe("processGitHubDispatchActionConfig", () => {
+ it("rejects a non-dispatch URL with the dispatch endpoint message before resolving its host", async () => {
+ await expect(
+ processGitHubDispatchActionConfig({
+ projectId: "project-1",
+ actionConfig: {
+ type: "GITHUB_DISPATCH",
+ url: "https://unresolvable-host.invalid/not-github",
+ eventType: "langfuse-alert",
+ githubToken: "ghp_token",
+ },
+ }),
+ ).rejects.toThrow(
+ "URL must be a valid GitHub repository dispatch endpoint",
+ );
+ });
+});
diff --git a/web/src/features/automations/components/AutomationForm.tsx b/web/src/features/automations/components/AutomationForm.tsx
index cab66845b7..d4bad69f7d 100644
--- a/web/src/features/automations/components/AutomationForm.tsx
+++ b/web/src/features/automations/components/AutomationForm.tsx
@@ -160,35 +160,6 @@ export const parseCreateAutomationPrefill = (
}
};
-/** 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 validation
const baseFormSchema = z.object({
name: z.string().min(1, "Name is required").max(100),
diff --git a/web/src/features/automations/index.ts b/web/src/features/automations/index.ts
index eeb68526c7..40bc058324 100644
--- a/web/src/features/automations/index.ts
+++ b/web/src/features/automations/index.ts
@@ -4,10 +4,7 @@
//
// automationsRouter and the automations page stay off this door.
export { AutomationButton } from "@/src/features/automations/components/AutomationButton";
-export {
- AutomationForm,
- automationCreateHref,
-} from "@/src/features/automations/components/AutomationForm";
+export { AutomationForm } from "@/src/features/automations/components/AutomationForm";
export { actionTypeLabel } from "@/src/features/automations/actionTypeLabels";
export { useAvailableActionTypes } from "@/src/features/automations/useAvailableActionTypes";
export { WebhookSecretRender } from "@/src/features/automations/components/WebhookSecretRender";
diff --git a/web/src/features/automations/server/githubDispatchHelpers.ts b/web/src/features/automations/server/githubDispatchHelpers.ts
index 7d9916f089..606b06e892 100644
--- a/web/src/features/automations/server/githubDispatchHelpers.ts
+++ b/web/src/features/automations/server/githubDispatchHelpers.ts
@@ -60,15 +60,6 @@ export async function processGitHubDispatchActionConfig({
});
}
- try {
- await validateWebhookURL(urlToUse);
- } catch (error) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: `Invalid webhook URL: ${error instanceof Error ? error.message : "Unknown error"}`,
- });
- }
-
// Validate GitHub API URL format
const urlPattern =
/^https:\/\/api\.github\.com\/repos\/[^\/]+\/[^\/]+\/dispatches$/;
@@ -83,6 +74,15 @@ export async function processGitHubDispatchActionConfig({
});
}
+ try {
+ await validateWebhookURL(urlToUse);
+ } catch (error) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Invalid webhook URL: ${error instanceof Error ? error.message : "Unknown error"}`,
+ });
+ }
+
const isUrlChanged =
existingActionConfig !== undefined &&
!areDestinationUrlsEquivalent(urlToUse, existingActionConfig.url);
diff --git a/web/src/features/monitors/automations/ConnectedNewMonitorAutomationDialog.clienttest.tsx b/web/src/features/monitors/automations/ConnectedNewMonitorAutomationDialog.clienttest.tsx
new file mode 100644
index 0000000000..c95e9d51fe
--- /dev/null
+++ b/web/src/features/monitors/automations/ConnectedNewMonitorAutomationDialog.clienttest.tsx
@@ -0,0 +1,144 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { defaultMonitorAutomationFormValues } from "./helpers/monitorAutomationFormSchema";
+import { ConnectedNewMonitorAutomationDialog } from "./ConnectedNewMonitorAutomationDialog";
+
+/** submittedValues is what the stubbed dialog submits. */
+let submittedValues = defaultMonitorAutomationFormValues("WEBHOOK", "Hook");
+
+const mutateAsync = vi.fn();
+
+vi.mock("@/src/utils/api", () => ({
+ reportTrpcErrorWithoutToast: vi.fn(),
+ api: {
+ useUtils: () => ({ automations: { invalidate: vi.fn() } }),
+ automations: {
+ createAutomation: {
+ useMutation: () => ({ mutateAsync, isPending: false }),
+ },
+ },
+ slack: {
+ getIntegrationStatus: {
+ useQuery: () => ({ isPending: true, data: undefined }),
+ },
+ },
+ },
+}));
+vi.mock("@/src/features/automations", () => ({
+ useAvailableActionTypes: (types: string[]) => types,
+}));
+vi.mock("@/src/features/pagerduty", () => ({
+ usePagerDutyTestEvent: () => ({}),
+}));
+vi.mock("@/src/features/rbac", () => ({ useHasProjectAccess: () => true }));
+vi.mock("@/src/features/slack", () => ({
+ useChannelSelectorData: () => ({ canListChannels: true }),
+ useSlackConnect: () => ({ connect: vi.fn(), canConnect: true }),
+ useSlackTestMessage: () => ({ sendTestMessage: vi.fn() }),
+}));
+/** submitResult is what the dialog's onSubmit resolved to. */
+let submitResult: unknown;
+
+vi.mock("./components/NewMonitorAutomationDialog", () => ({
+ NewMonitorAutomationDialog: ({
+ onSubmit,
+ }: {
+ onSubmit: (values: typeof submittedValues) => Promise<unknown>;
+ }) => (
+ <button
+ onClick={async () => {
+ submitResult = await onSubmit(submittedValues);
+ }}
+ >
+ create
+ </button>
+ ),
+}));
+
+describe("ConnectedNewMonitorAutomationDialog", () => {
+ it("passes on a webhook's signing secret for its once-only display", async () => {
+ submittedValues = {
+ ...defaultMonitorAutomationFormValues("WEBHOOK", "Hook"),
+ webhook: { url: "example.com", headers: [] },
+ };
+ mutateAsync.mockResolvedValue({
+ automation: { id: "auto-1" },
+ webhookSecret: "lf-whsec_1",
+ });
+ const onCreated = vi.fn();
+ render(
+ <ConnectedNewMonitorAutomationDialog
+ projectId="p1"
+ onCreated={onCreated}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "create" }));
+
+ await waitFor(() =>
+ expect(onCreated).toHaveBeenCalledWith({
+ automationId: "auto-1",
+ name: "Hook",
+ webhookSecret: "lf-whsec_1",
+ }),
+ );
+ });
+
+ it("never shows a GitHub dispatch token as a webhook secret", async () => {
+ submittedValues = {
+ ...defaultMonitorAutomationFormValues("GITHUB_DISPATCH", "Deploy"),
+ githubDispatch: {
+ url: "api.github.com/repos/o/r/dispatches",
+ eventType: "langfuse-alert",
+ githubToken: "ghp_token",
+ },
+ };
+ mutateAsync.mockResolvedValue({
+ automation: { id: "auto-2" },
+ webhookSecret: "ghp_token",
+ });
+ const onCreated = vi.fn();
+ render(
+ <ConnectedNewMonitorAutomationDialog
+ projectId="p1"
+ onCreated={onCreated}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "create" }));
+
+ await waitFor(() =>
+ expect(onCreated).toHaveBeenCalledWith({
+ automationId: "auto-2",
+ name: "Deploy",
+ webhookSecret: undefined,
+ }),
+ );
+ });
+
+ it("hands a server rejection back to the form instead of reporting a creation", async () => {
+ submittedValues = {
+ ...defaultMonitorAutomationFormValues("WEBHOOK", "Hook"),
+ webhook: { url: "kjhkjhkj.com", headers: [] },
+ };
+ mutateAsync.mockRejectedValue(
+ new Error("Invalid webhook URL: DNS lookup failed for kjhkjhkj.com"),
+ );
+ const onCreated = vi.fn();
+ render(
+ <ConnectedNewMonitorAutomationDialog
+ projectId="p1"
+ onCreated={onCreated}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "create" }));
+
+ await waitFor(() =>
+ expect(submitResult).toEqual({
+ error: "Invalid webhook URL: DNS lookup failed for kjhkjhkj.com",
+ }),
+ );
+ expect(onCreated).not.toHaveBeenCalled();
+ });
+});
diff --git a/web/src/features/monitors/automations/ConnectedNewMonitorAutomationDialog.tsx b/web/src/features/monitors/automations/ConnectedNewMonitorAutomationDialog.tsx
new file mode 100644
index 0000000000..0f11966253
--- /dev/null
+++ b/web/src/features/monitors/automations/ConnectedNewMonitorAutomationDialog.tsx
@@ -0,0 +1,162 @@
+import { type ActionTypes } from "@langfuse/shared";
+import { useAvailableActionTypes } from "@/src/features/automations";
+import { usePagerDutyTestEvent } from "@/src/features/pagerduty";
+import { useHasProjectAccess } from "@/src/features/rbac";
+import {
+ useChannelSelectorData,
+ useSlackConnect,
+ useSlackTestMessage,
+} from "@/src/features/slack";
+import { api, reportTrpcErrorWithoutToast } from "@/src/utils/api";
+import { type SlackFieldsState } from "./components/SlackActionFields";
+import { buildCreateMonitorAutomationInput } from "./helpers/buildCreateMonitorAutomationInput";
+import { type MonitorAutomationFormValues } from "./helpers/monitorAutomationFormSchema";
+import {
+ NewMonitorAutomationDialog,
+ type MonitorAutomationSubmitResult,
+} from "./components/NewMonitorAutomationDialog";
+
+const monitorActionTypes: readonly ActionTypes[] = [
+ "SLACK",
+ "WEBHOOK",
+ "GITHUB_DISPATCH",
+ "PAGERDUTY",
+];
+
+/** ConnectedNewMonitorAutomationDialog creates the monitor automation and feeds the dialog the project's Slack state. */
+export function ConnectedNewMonitorAutomationDialog({
+ projectId,
+ lockedActionType,
+ onCreated,
+}: {
+ projectId: string;
+ lockedActionType?: ActionTypes;
+ onCreated: (automation: CreatedMonitorAutomation) => void;
+}) {
+ const availableActionTypes = useAvailableActionTypes(monitorActionTypes);
+ const slack = useSlackFieldsState(projectId);
+ const pagerDuty = usePagerDutyTestEvent(projectId);
+ const createAutomation = useCreateMonitorAutomation();
+ const submit = useSubmit(createAutomation, projectId, onCreated);
+
+ return (
+ <NewMonitorAutomationDialog
+ actionTypes={offeredActionTypes(lockedActionType, availableActionTypes)}
+ slack={slack}
+ pagerDuty={pagerDuty}
+ isSubmitting={createAutomation.isPending}
+ onSubmit={submit}
+ />
+ );
+}
+
+/** useSlackFieldsState resolves the project's Slack connection, channels, and connect/test actions. */
+function useSlackFieldsState(projectId: string): SlackFieldsState {
+ const canManageIntegration = useHasProjectAccess({
+ projectId,
+ scope: "integrations:CRUD",
+ });
+ const integration = api.slack.getIntegrationStatus.useQuery({ projectId });
+ const isConnected = integration.data?.isConnected === true;
+ const { canListChannels, ...channelSelector } = useChannelSelectorData(
+ projectId,
+ isConnected,
+ );
+ const { connect, connectError, isConnecting, canConnect } = useSlackConnect({
+ projectId,
+ shouldToast: false,
+ onSuccess: () => integration.refetch(),
+ });
+ const { sendTestMessage, isPending: isTesting } = useSlackTestMessage({
+ projectId,
+ shouldToast: false,
+ });
+
+ if (integration.isPending) return { status: "loading" };
+ if (!isConnected) {
+ return {
+ status: "disconnected",
+ canManageIntegration,
+ canConnect: canConnect && canManageIntegration,
+ connectError,
+ isConnecting,
+ onConnect: connect,
+ };
+ }
+ return {
+ status: "connected",
+ channelSelector: { ...channelSelector, disabled: !canListChannels },
+ isTesting,
+ onTestChannel: sendTestMessage,
+ };
+}
+
+/** useCreateMonitorAutomation creates an automation and refreshes every automation list. */
+function useCreateMonitorAutomation() {
+ const utils = api.useUtils();
+ return api.automations.createAutomation.useMutation({
+ onSuccess: () => utils.automations.invalidate(),
+ // The dialog shows rejections under the field they concern.
+ onError: (error) => reportTrpcErrorWithoutToast(error, "automations"),
+ });
+}
+
+/** useSubmit creates the automation and reports it, or resolves to the server's rejection for the form to show. */
+function useSubmit(
+ createAutomation: ReturnType<typeof useCreateMonitorAutomation>,
+ projectId: string,
+ onCreated: (automation: CreatedMonitorAutomation) => void,
+) {
+ return async (
+ values: MonitorAutomationFormValues,
+ ): Promise<MonitorAutomationSubmitResult> => {
+ try {
+ const result = await createAutomation.mutateAsync(
+ buildCreateMonitorAutomationInput(projectId, values),
+ );
+ onCreated({
+ automationId: result.automation.id,
+ name: values.name.trim(),
+ // GitHub dispatch also returns its token in `webhookSecret`.
+ webhookSecret: webhookSigningSecret(
+ values.actionType,
+ result.webhookSecret,
+ ),
+ });
+ return {};
+ } catch (error) {
+ return { error: rejectionMessage(error) };
+ }
+ };
+}
+
+/** offeredActionTypes limits the dialog to the locked action, if there is one. */
+function offeredActionTypes(
+ lockedActionType: ActionTypes | undefined,
+ availableActionTypes: ActionTypes[],
+): ActionTypes[] {
+ if (lockedActionType) return [lockedActionType];
+ return availableActionTypes;
+}
+
+/** rejectionMessage is the reason the server gave for refusing the automation. */
+function rejectionMessage(error: unknown): string {
+ if (error instanceof Error && error.message) return error.message;
+ return "The automation could not be created. Try again.";
+}
+
+/** webhookSigningSecret keeps the returned secret only for webhooks, the one action whose secret is shown once. */
+function webhookSigningSecret(
+ actionType: ActionTypes,
+ secret: string | undefined,
+): string | undefined {
+ if (actionType !== "WEBHOOK") return undefined;
+ return secret;
+}
+
+/** CreatedMonitorAutomation is a just-created automation; `webhookSecret` is set only for webhooks. */
+export type CreatedMonitorAutomation = {
+ automationId: string;
+ name: string;
+ webhookSecret?: string;
+};
diff --git a/web/src/features/monitors/automations/NewMonitorAutomationDialogController.tsx b/web/src/features/monitors/automations/NewMonitorAutomationDialogController.tsx
new file mode 100644
index 0000000000..315c10eb45
--- /dev/null
+++ b/web/src/features/monitors/automations/NewMonitorAutomationDialogController.tsx
@@ -0,0 +1,127 @@
+import { type ReactNode } from "react";
+
+import { type ActionTypes } from "@langfuse/shared";
+import { DialogController } from "@/src/components/design-system/DialogController/DialogController";
+import { showSuccessToast } from "@/src/features/notifications";
+import { WebhookSecretDialog } from "./components/WebhookSecretDialog";
+import {
+ ConnectedNewMonitorAutomationDialog,
+ type CreatedMonitorAutomation,
+} from "./ConnectedNewMonitorAutomationDialog";
+
+/** secretDialogDelayMs lets the create dialog finish its exit animation before the secret dialog enters. */
+const secretDialogDelayMs = 200;
+
+/** NewMonitorAutomationDialogController owns the create-automation dialog and the webhook secret dialog that follows it. */
+export function NewMonitorAutomationDialogController({
+ projectId,
+ onCreated,
+ children,
+}: {
+ projectId: string;
+ onCreated?: (automationId: string) => void;
+ children: (control: {
+ openDialog: (draft?: NewMonitorAutomationDraft) => void;
+ }) => ReactNode;
+}) {
+ return (
+ <WebhookSecretDialogController>
+ {({ openSecretDialog }) => (
+ <ConnectedNewMonitorAutomationDialogController
+ projectId={projectId}
+ onCreated={onCreated}
+ openSecretDialog={openSecretDialog}
+ >
+ {children}
+ </ConnectedNewMonitorAutomationDialogController>
+ )}
+ </WebhookSecretDialogController>
+ );
+}
+
+/** WebhookSecretDialogController shows a webhook's once-only secret after the create dialog has closed. */
+function WebhookSecretDialogController({
+ children,
+}: {
+ children: (control: {
+ openSecretDialog: (secret: CreatedWebhookSecret) => void;
+ }) => ReactNode;
+}) {
+ return (
+ <DialogController<CreatedWebhookSecret>
+ renderDialog={({ state }) => (
+ <WebhookSecretDialog
+ automationName={state.automationName}
+ webhookSecret={state.webhookSecret}
+ />
+ )}
+ >
+ {({ openDialog }) =>
+ children({
+ openSecretDialog: (secret) =>
+ setTimeout(() => openDialog(secret), secretDialogDelayMs),
+ })
+ }
+ </DialogController>
+ );
+}
+
+/** ConnectedNewMonitorAutomationDialogController opens the create dialog and announces each automation it creates. */
+function ConnectedNewMonitorAutomationDialogController({
+ projectId,
+ onCreated,
+ openSecretDialog,
+ children,
+}: {
+ projectId: string;
+ onCreated?: (automationId: string) => void;
+ openSecretDialog: (secret: CreatedWebhookSecret) => void;
+ children: (control: {
+ openDialog: (draft?: NewMonitorAutomationDraft) => void;
+ }) => ReactNode;
+}) {
+ return (
+ <DialogController<NewMonitorAutomationDraft>
+ renderDialog={({ state, closeDialog }) => (
+ <ConnectedNewMonitorAutomationDialog
+ projectId={projectId}
+ lockedActionType={state.actionType}
+ onCreated={(automation) => {
+ closeDialog();
+ onCreated?.(automation.automationId);
+ announceCreated(automation, openSecretDialog);
+ }}
+ />
+ )}
+ >
+ {({ openDialog }) =>
+ children({ openDialog: (draft = {}) => openDialog(draft) })
+ }
+ </DialogController>
+ );
+}
+
+/** announceCreated shows a webhook's once-only secret, or a success toast for every other action. */
+function announceCreated(
+ automation: CreatedMonitorAutomation,
+ showSecret: (secret: CreatedWebhookSecret) => void,
+) {
+ if (automation.webhookSecret) {
+ showSecret({
+ automationName: automation.name,
+ webhookSecret: automation.webhookSecret,
+ });
+ return;
+ }
+ showSuccessToast({
+ operation: "automation.create",
+ title: "Automation Created",
+ description: `Successfully created automation "${automation.name}".`,
+ });
+}
+
+/** NewMonitorAutomationDraft opens the dialog with the picker, or locked to one action. */
+export type NewMonitorAutomationDraft = { actionType?: ActionTypes };
+
+/** CreatedWebhookSecret is the signing secret shown once after a webhook automation is created. */
+type CreatedWebhookSecret = { automationName: string; webhookSecret: string };
diff --git a/web/src/features/monitors/automations/components/DividedDialogBody.tsx b/web/src/features/monitors/automations/components/DividedDialogBody.tsx
new file mode 100644
index 0000000000..4ba296d181
--- /dev/null
+++ b/web/src/features/monitors/automations/components/DividedDialogBody.tsx
@@ -0,0 +1,10 @@
+import { type ReactNode } from "react";
+
+/** DividedDialogBody is a scrolling dialog body set off from the header and footer by borders. */
+export function DividedDialogBody({ children }: { children: ReactNode }) {
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto border-y p-4">
+ {children}
+ </div>
+ );
+}
diff --git a/web/src/features/monitors/automations/components/FieldGroup.tsx b/web/src/features/monitors/automations/components/FieldGroup.tsx
new file mode 100644
index 0000000000..8239d4ecda
--- /dev/null
+++ b/web/src/features/monitors/automations/components/FieldGroup.tsx
@@ -0,0 +1,17 @@
+import { type ReactNode } from "react";
+
+/** FieldGroup lays out a labelled group of controls like a form field when no single control owns the label. */
+export function FieldGroup({
+ label,
+ children,
+}: {
+ label: string;
+ children: ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-2">
+ <p className="text-sm leading-none font-bold">{label}</p>
+ {children}
+ </div>
+ );
+}
diff --git a/web/src/features/monitors/automations/components/FieldHelp.tsx b/web/src/features/monitors/automations/components/FieldHelp.tsx
new file mode 100644
index 0000000000..2aeb4c4c3a
--- /dev/null
+++ b/web/src/features/monitors/automations/components/FieldHelp.tsx
@@ -0,0 +1,16 @@
+import { type ReactNode } from "react";
+
+/** FieldHelp is help text with inline code or links, rendered below a field whose input lists `id` in aria-describedby. */
+export function FieldHelp({
+ id,
+ children,
+}: {
+ id: string;
+ children: ReactNode;
+}) {
+ return (
+ <p id={id} className="text-muted-foreground text-sm">
+ {children}
+ </p>
+ );
+}
diff --git a/web/src/features/monitors/automations/components/FieldWithHelp.tsx b/web/src/features/monitors/automations/components/FieldWithHelp.tsx
new file mode 100644
index 0000000000..b326e199fd
--- /dev/null
+++ b/web/src/features/monitors/automations/components/FieldWithHelp.tsx
@@ -0,0 +1,6 @@
+import { type ReactNode } from "react";
+
+/** FieldWithHelp keeps a form field and the FieldHelp below it as close together as the field's own help text. */
+export function FieldWithHelp({ children }: { children: ReactNode }) {
+ return <div className="flex flex-col gap-2">{children}</div>;
+}
diff --git a/web/src/features/monitors/automations/components/GitHubDispatchActionFields.tsx b/web/src/features/monitors/automations/components/GitHubDispatchActionFields.tsx
new file mode 100644
index 0000000000..2458a8165f
--- /dev/null
+++ b/web/src/features/monitors/automations/components/GitHubDispatchActionFields.tsx
@@ -0,0 +1,126 @@
+import { useId } from "react";
+import { type UseFormReturn } from "react-hook-form";
+
+import { Form } from "@/src/components/design-system/Form/Form";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { PasswordInput } from "@/src/components/design-system/PasswordInput/PasswordInput";
+import { type MonitorAutomationFormValues } from "../helpers/monitorAutomationFormSchema";
+import { InlineCode } from "./InlineCode";
+import { describedBy } from "../helpers/describedBy";
+import { stripUrlScheme } from "../helpers/stripUrlScheme";
+import { FieldHelp } from "./FieldHelp";
+import { FieldWithHelp } from "./FieldWithHelp";
+import { HelpLink } from "./HelpLink";
+import { PrefixedInput } from "./PrefixedInput";
+
+const dispatchDocsUrl =
+ "https://docs.github.com/en/rest/repos/repos#create-a-repository-dispatch-event";
+const createTokenUrl =
+ "https://github.com/settings/tokens/new?scopes=repo&description=Langfuse%20Automation";
+
+/** GitHubDispatchActionFields collects the repository dispatch endpoint, event type, and token. */
+export function GitHubDispatchActionFields({
+ form,
+}: {
+ form: UseFormReturn<MonitorAutomationFormValues>;
+}) {
+ const urlHelpId = useId();
+ const eventTypeHelpId = useId();
+ const tokenHelpId = useId();
+
+ return (
+ <>
+ <FieldWithHelp>
+ <Form.Field
+ control={form.control}
+ name="githubDispatch.url"
+ label="Repository dispatch URL"
+ >
+ {(field) => (
+ <PrefixedInput
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onChange={(event) =>
+ field.onChange(stripUrlScheme(event.target.value))
+ }
+ onBlur={field.onBlur}
+ ref={field.ref}
+ prefix="https://"
+ inputMode="url"
+ placeholder="api.github.com/repos/owner/repo/dispatches"
+ aria-describedby={describedBy(
+ field.inputDescribedById,
+ urlHelpId,
+ )}
+ aria-invalid={!!field.error}
+ error={!!field.error}
+ />
+ )}
+ </Form.Field>
+ <FieldHelp id={urlHelpId}>
+ GitHub API endpoint for repository dispatch.{" "}
+ <HelpLink href={dispatchDocsUrl} text="Learn more" />
+ </FieldHelp>
+ </FieldWithHelp>
+ <FieldWithHelp>
+ <Form.Field
+ control={form.control}
+ name="githubDispatch.eventType"
+ label="Event type"
+ >
+ {(field) => (
+ <Input
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onChange={field.onChange}
+ onBlur={field.onBlur}
+ ref={field.ref}
+ placeholder="e.g. langfuse-alert"
+ aria-describedby={describedBy(
+ field.inputDescribedById,
+ eventTypeHelpId,
+ )}
+ aria-invalid={!!field.error}
+ error={!!field.error}
+ />
+ )}
+ </Form.Field>
+ <FieldHelp id={eventTypeHelpId}>
+ Add this to the <InlineCode>on.repository_dispatch.types</InlineCode>{" "}
+ filter in your workflow.
+ </FieldHelp>
+ </FieldWithHelp>
+ <FieldWithHelp>
+ <Form.Field
+ control={form.control}
+ name="githubDispatch.githubToken"
+ label="GitHub personal access token"
+ >
+ {(field) => (
+ <PasswordInput
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onChange={field.onChange}
+ onBlur={field.onBlur}
+ ref={field.ref}
+ placeholder="ghp_..."
+ aria-describedby={describedBy(
+ field.inputDescribedById,
+ tokenHelpId,
+ )}
+ aria-invalid={!!field.error}
+ error={!!field.error}
+ />
+ )}
+ </Form.Field>
+ <FieldHelp id={tokenHelpId}>
+ GitHub PAT with <InlineCode>repo</InlineCode> scope for repository
+ dispatch. <HelpLink href={createTokenUrl} text="Create token" />
+ </FieldHelp>
+ </FieldWithHelp>
+ </>
+ );
+}
diff --git a/web/src/features/monitors/automations/components/HelpLink.tsx b/web/src/features/monitors/automations/components/HelpLink.tsx
new file mode 100644
index 0000000000..aa3b22340f
--- /dev/null
+++ b/web/src/features/monitors/automations/components/HelpLink.tsx
@@ -0,0 +1,21 @@
+import { SquareArrowOutUpRight } from "@langfuse/icons";
+
+/** HelpLink renders an underlined external link that sits inside field help text and opens in a new tab. */
+export function HelpLink({ href, text }: { href: string; text: string }) {
+ return (
+ <a
+ className="text-link hover:text-link-hover underline underline-offset-2"
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {text}
+ <SquareArrowOutUpRight
+ aria-hidden
+ size="sm"
+ color="muted"
+ __rawClassName="ml-0.75 inline-block align-[-1px]"
+ />
+ </a>
+ );
+}
diff --git a/web/src/features/monitors/automations/components/InlineCode.tsx b/web/src/features/monitors/automations/components/InlineCode.tsx
new file mode 100644
index 0000000000..e6920b848f
--- /dev/null
+++ b/web/src/features/monitors/automations/components/InlineCode.tsx
@@ -0,0 +1,23 @@
+import { type ReactNode } from "react";
+
+import { cn } from "@/src/utils/tailwind";
+
+/** InlineCode renders a code fragment inside help text. */
+export function InlineCode({
+ children,
+ isShaded = false,
+}: {
+ children: ReactNode;
+ isShaded?: boolean;
+}) {
+ return (
+ <code
+ className={cn(
+ "font-mono text-xs",
+ isShaded && "bg-muted rounded-md px-1 py-px",
+ )}
+ >
+ {children}
+ </code>
+ );
+}
diff --git a/web/src/features/monitors/automations/components/NewMonitorAutomationDialog.stories.tsx b/web/src/features/monitors/automations/components/NewMonitorAutomationDialog.stories.tsx
new file mode 100644
index 0000000000..4a8d6e124d
--- /dev/null
+++ b/web/src/features/monitors/automations/components/NewMonitorAutomationDialog.stories.tsx
@@ -0,0 +1,299 @@
+import { type ComponentProps } from "react";
+import { expect, fn, userEvent, waitFor, within } from "storybook/test";
+
+import preview from "@/.storybook/preview";
+import { DialogController } from "@/src/components/design-system/DialogController/DialogController";
+import { defaultMonitorAutomationFormValues } from "../helpers/monitorAutomationFormSchema";
+import { NewMonitorAutomationDialog } from "./NewMonitorAutomationDialog";
+import { WebhookSecretDialog } from "./WebhookSecretDialog";
+
+const channels = ["alerts", "ml-ops", "on-call", "llm-quality"].map((name) => ({
+ id: `C-${name}`,
+ name,
+}));
+
+const onSurroundingFormSubmit = fn();
+
+const baseArgs: ComponentProps<typeof NewMonitorAutomationDialog> = {
+ actionTypes: ["SLACK", "WEBHOOK", "GITHUB_DISPATCH", "PAGERDUTY"],
+ slack: {
+ status: "connected",
+ channelSelector: {
+ channelsData: { channels, hasPrivateChannelAccess: true },
+ isLoading: false,
+ hasError: false,
+ isRefreshing: false,
+ onRefresh: fn(),
+ },
+ isTesting: false,
+ onTestChannel: fn(async () => ({
+ status: "sent" as const,
+ channel: { id: "C-alerts", name: "alerts" },
+ })),
+ },
+ pagerDuty: {
+ canSend: true,
+ isTestAlertOpen: false,
+ isSending: false,
+ sendError: undefined,
+ onSend: fn(async () => {}),
+ onResetSend: fn(),
+ isResolving: false,
+ onResolve: fn(),
+ },
+ isSubmitting: false,
+ onSubmit: fn(async () => ({})),
+};
+
+const meta = preview.meta({
+ component: NewMonitorAutomationDialog,
+ parameters: { layout: "fullscreen" },
+ args: baseArgs,
+ render: (args) => <OpenDialog {...args} />,
+});
+
+export const Picker = meta.story({});
+
+export const LockedSlack = meta.story({ args: { actionTypes: ["SLACK"] } });
+
+export const LockedWebhook = meta.story({
+ args: { actionTypes: ["WEBHOOK"] },
+});
+
+export const LockedGitHubDispatch = meta.story({
+ args: { actionTypes: ["GITHUB_DISPATCH"] },
+});
+
+export const LockedPagerDuty = meta.story({
+ args: { actionTypes: ["PAGERDUTY"] },
+});
+
+export const SlackNotConnected = meta.story({
+ args: {
+ slack: {
+ status: "disconnected",
+ canManageIntegration: true,
+ canConnect: true,
+ isConnecting: false,
+ onConnect: fn(),
+ },
+ },
+});
+
+export const SlackCannotConnect = meta.story({
+ args: {
+ slack: {
+ status: "disconnected",
+ canManageIntegration: false,
+ canConnect: false,
+ isConnecting: false,
+ onConnect: fn(),
+ },
+ },
+});
+
+export const SlackChannelsFailedToLoad = meta.story({
+ args: {
+ slack: {
+ status: "connected",
+ channelSelector: {
+ channelsData: null,
+ isLoading: false,
+ hasError: true,
+ isRefreshing: false,
+ onRefresh: fn(),
+ onReauthenticate: fn(),
+ },
+ isTesting: false,
+ onTestChannel: fn(async () => ({
+ status: "sent" as const,
+ channel: { id: "C-alerts", name: "alerts" },
+ })),
+ },
+ },
+});
+
+export const SlackChannelSelected = meta.story({
+ args: {
+ defaultValues: {
+ ...defaultMonitorAutomationFormValues("SLACK", "Staging alerts"),
+ slack: { channelId: "C-alerts", channelName: "alerts" },
+ },
+ },
+});
+
+export const ErrorsShown = meta.story({
+ name: "(Test) Errors shown",
+ args: {
+ onSubmit: fn(async () => ({})),
+ actionTypes: ["WEBHOOK"],
+ defaultValues: {
+ ...defaultMonitorAutomationFormValues("WEBHOOK", "Staging alerts"),
+ webhook: {
+ url: "not a url",
+ headers: [
+ { name: "content-type", value: "text/plain", isSecret: false },
+ ],
+ },
+ },
+ },
+ play: async ({ args, canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+ await body.findByDisplayValue("not a url");
+ await userEvent.click(
+ body.getByRole("button", { name: "Create automation" }),
+ );
+ await waitFor(() =>
+ expect(body.getByText("Enter a valid HTTPS URL.")).toBeVisible(),
+ );
+ await expect(args.onSubmit).not.toHaveBeenCalled();
+ },
+});
+
+export const TestInvalidDispatchUrlShowsError = meta.story({
+ name: "(Test) Invalid dispatch URL shows the form error",
+ args: {
+ onSubmit: fn(async () => ({})),
+ actionTypes: ["GITHUB_DISPATCH"],
+ defaultValues: {
+ ...defaultMonitorAutomationFormValues("GITHUB_DISPATCH", "Deploy"),
+ githubDispatch: {
+ url: "not a url",
+ eventType: "langfuse-alert",
+ githubToken: "ghp_token",
+ },
+ },
+ },
+ play: async ({ args, canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+ await body.findByDisplayValue("not a url");
+ await userEvent.click(
+ body.getByRole("button", { name: "Create automation" }),
+ );
+ await waitFor(() =>
+ expect(
+ body.getByText("Enter a valid repository dispatch URL."),
+ ).toBeVisible(),
+ );
+ await expect(args.onSubmit).not.toHaveBeenCalled();
+ },
+});
+
+export const TestServerErrorShownInline = meta.story({
+ name: "(Test) Server error shown inline",
+ args: {
+ actionTypes: ["GITHUB_DISPATCH"],
+ defaultValues: {
+ ...defaultMonitorAutomationFormValues("GITHUB_DISPATCH", "Deploy"),
+ githubDispatch: {
+ url: "kjhkjhkj.com",
+ eventType: "langfuse-alert",
+ githubToken: "ghp_token",
+ },
+ },
+ onSubmit: fn(async () => ({
+ error: "Invalid webhook URL: DNS lookup failed for kjhkjhkj.com",
+ })),
+ },
+ play: async ({ canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+ await body.findByDisplayValue("kjhkjhkj.com");
+ await userEvent.click(
+ body.getByRole("button", { name: "Create automation" }),
+ );
+ await waitFor(() =>
+ expect(
+ body.getByText(
+ "Invalid webhook URL: DNS lookup failed for kjhkjhkj.com",
+ ),
+ ).toBeVisible(),
+ );
+ await expect(
+ body.getByLabelText("Repository dispatch URL"),
+ ).toHaveAttribute("aria-invalid", "true");
+ },
+});
+
+export const TestWebhookSubmitsHttpsUrl = meta.story({
+ name: "(Test) Webhook submits the https URL",
+ args: {
+ onSubmit: fn(async () => ({})),
+ actionTypes: ["WEBHOOK"],
+ },
+ play: async ({ args, canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+ const create = body.getByRole("button", { name: "Create automation" });
+ await userEvent.type(body.getByLabelText("Name"), "Staging alerts");
+ await expect(create).toBeDisabled();
+
+ await userEvent.type(
+ body.getByLabelText("Webhook URL"),
+ "https://example.com/hook",
+ );
+ await userEvent.click(create);
+
+ await expect(args.onSubmit).toHaveBeenCalledWith(
+ expect.objectContaining({
+ webhook: { url: "example.com/hook", headers: [] },
+ }),
+ );
+ },
+});
+
+export const TestDoesNotSubmitSurroundingForm = meta.story({
+ name: "(Test) Does not submit the surrounding form",
+ args: {
+ onSubmit: fn(async () => ({})),
+ actionTypes: ["WEBHOOK"],
+ defaultValues: {
+ ...defaultMonitorAutomationFormValues("WEBHOOK", "Staging alerts"),
+ webhook: { url: "example.com/hook", headers: [] },
+ },
+ },
+ render: (args) => (
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ onSurroundingFormSubmit();
+ }}
+ >
+ <OpenDialog {...args} />
+ </form>
+ ),
+ play: async ({ args, canvasElement }) => {
+ const body = within(canvasElement.ownerDocument.body);
+ await userEvent.click(
+ body.getByRole("button", { name: "Create automation" }),
+ );
+ await waitFor(() => expect(args.onSubmit).toHaveBeenCalled());
+ await expect(onSurroundingFormSubmit).not.toHaveBeenCalled();
+ },
+});
+
+export const WebhookSecret = meta.story({
+ render: () => (
+ <DialogController
+ initialState={() => ({})}
+ renderDialog={() => (
+ <WebhookSecretDialog
+ automationName="Staging alerts"
+ webhookSecret="lf-whsec_3f9a1c0d8e7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b"
+ />
+ )}
+ >
+ {() => null}
+ </DialogController>
+ ),
+});
+
+/** OpenDialog renders the dialog already open, as its controller would. */
+function OpenDialog(props: ComponentProps<typeof NewMonitorAutomationDialog>) {
+ return (
+ <DialogController
+ initialState={() => ({})}
+ renderDialog={() => <NewMonitorAutomationDialog {...props} />}
+ >
+ {() => null}
+ </DialogController>
+ );
+}
diff --git a/web/src/features/monitors/automations/components/NewMonitorAutomationDialog.tsx b/web/src/features/monitors/automations/components/NewMonitorAutomationDialog.tsx
new file mode 100644
index 0000000000..1285b2c03e
--- /dev/null
+++ b/web/src/features/monitors/automations/components/NewMonitorAutomationDialog.tsx
@@ -0,0 +1,216 @@
+import { useId } from "react";
+import { useForm, useWatch, type UseFormReturn } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+
+import { type ActionTypes } from "@langfuse/shared";
+import { type PagerDutyTestEventState } from "@/src/features/pagerduty";
+import { Dialog } from "@/src/components/design-system/Dialog/Dialog";
+import { Form } from "@/src/components/design-system/Form/Form";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";
+import { DividedDialogBody } from "./DividedDialogBody";
+import { GitHubDispatchActionFields } from "./GitHubDispatchActionFields";
+import { PagerDutyActionFields } from "./PagerDutyActionFields";
+import { SlackActionFields, type SlackFieldsState } from "./SlackActionFields";
+import { WebhookActionFields } from "./WebhookActionFields";
+import { isMonitorAutomationFormComplete } from "../helpers/isMonitorAutomationFormComplete";
+import { serverErrorField } from "../helpers/serverErrorField";
+import {
+ defaultMonitorAutomationFormValues,
+ monitorAutomationFormSchema,
+ type MonitorAutomationFormValues,
+} from "../helpers/monitorAutomationFormSchema";
+
+const defaultActionType: ActionTypes = "SLACK";
+
+/** monitorActionLabel names each action in the picker and the locked dialog title. */
+const monitorActionLabel: Record<ActionTypes, string> = {
+ SLACK: "Slack",
+ WEBHOOK: "Webhook",
+ GITHUB_DISPATCH: "GitHub dispatch",
+ PAGERDUTY: "PagerDuty",
+};
+
+/** NewMonitorAutomationDialog collects a name and one action's fields for a new monitor automation. */
+export function NewMonitorAutomationDialog({
+ actionTypes,
+ slack,
+ pagerDuty,
+ defaultValues,
+ isSubmitting,
+ onSubmit,
+}: {
+ actionTypes: ActionTypes[];
+ slack: SlackFieldsState;
+ pagerDuty: PagerDutyTestEventState;
+ defaultValues?: MonitorAutomationFormValues;
+ isSubmitting: boolean;
+ onSubmit: (
+ values: MonitorAutomationFormValues,
+ ) => Promise<MonitorAutomationSubmitResult>;
+}) {
+ const formId = useId();
+ const form = useForm<MonitorAutomationFormValues>({
+ resolver: zodResolver(monitorAutomationFormSchema),
+ defaultValues:
+ defaultValues ??
+ defaultMonitorAutomationFormValues(actionTypes[0] ?? defaultActionType),
+ });
+ const values = useWatch({ control: form.control });
+ const isComplete = isMonitorAutomationFormComplete(
+ values as MonitorAutomationFormValues,
+ );
+ const rootError = form.formState.errors.root?.server?.message;
+ const submit = async (submitted: MonitorAutomationFormValues) => {
+ const { error } = await onSubmit(submitted);
+ if (!error) return;
+ form.setError(serverErrorField(submitted.actionType, error), {
+ message: error,
+ });
+ };
+
+ return (
+ <Dialog
+ title={dialogTitle(actionTypes)}
+ actions={[
+ {
+ label: "Create automation",
+ type: "submit",
+ form: formId,
+ disabled: !isComplete || isSubmitting,
+ loading: isSubmitting,
+ },
+ ]}
+ >
+ <DividedDialogBody>
+ <Form
+ id={formId}
+ actions={[]}
+ onSubmit={(event) => {
+ // The dialog portals out of any surrounding form, but React still bubbles submit through it.
+ event.stopPropagation();
+ return form.handleSubmit(submit)(event);
+ }}
+ >
+ <NameField form={form} />
+ {actionTypes.length > 1 && (
+ <ActionTypeField form={form} actionTypes={actionTypes} />
+ )}
+ <ActionFields
+ form={form}
+ actionType={form.watch("actionType")}
+ slack={slack}
+ pagerDuty={pagerDuty}
+ />
+ {rootError && <FormError message={rootError} />}
+ </Form>
+ </DividedDialogBody>
+ </Dialog>
+ );
+}
+
+/** FormError shows a rejection that concerns no single field. */
+function FormError({ message }: { message: string }) {
+ return (
+ <p role="alert" className="text-destructive text-sm">
+ {message}
+ </p>
+ );
+}
+
+/** NameField is the automation name, shown on every alert it connects to. */
+function NameField({ form }: { form: MonitorAutomationForm }) {
+ return (
+ <Form.Field
+ control={form.control}
+ name="name"
+ label="Name"
+ description="Can be connected to any alert in the project."
+ >
+ {(field) => (
+ <Input
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onChange={field.onChange}
+ onBlur={field.onBlur}
+ ref={field.ref}
+ placeholder="e.g. Staging alerts"
+ aria-describedby={field.inputDescribedById}
+ aria-invalid={!!field.error}
+ error={!!field.error}
+ />
+ )}
+ </Form.Field>
+ );
+}
+
+/** ActionTypeField picks the action and clears the previous action's fields on change. */
+function ActionTypeField({
+ form,
+ actionTypes,
+}: {
+ form: MonitorAutomationForm;
+ actionTypes: ActionTypes[];
+}) {
+ return (
+ <Form.Field control={form.control} name="actionType" label="Action">
+ {(field) => (
+ <SelectInput<ActionTypes>
+ id={field.id}
+ value={field.value}
+ onValueChange={(actionType) =>
+ form.reset(
+ defaultMonitorAutomationFormValues(
+ actionType,
+ form.getValues("name"),
+ ),
+ )
+ }
+ options={actionTypes.map((actionType) => ({
+ value: actionType,
+ label: monitorActionLabel[actionType],
+ }))}
+ placeholder="Select an action"
+ aria-describedby={field.inputDescribedById}
+ />
+ )}
+ </Form.Field>
+ );
+}
+
+/** ActionFields renders the fields of the selected action. */
+function ActionFields({
+ form,
+ actionType,
+ slack,
+ pagerDuty,
+}: {
+ form: MonitorAutomationForm;
+ actionType: ActionTypes;
+ slack: SlackFieldsState;
+ pagerDuty: PagerDutyTestEventState;
+}) {
+ switch (actionType) {
+ case "SLACK":
+ return <SlackActionFields form={form} slack={slack} />;
+ case "WEBHOOK":
+ return <WebhookActionFields form={form} />;
+ case "GITHUB_DISPATCH":
+ return <GitHubDispatchActionFields form={form} />;
+ case "PAGERDUTY":
+ return <PagerDutyActionFields form={form} testEvent={pagerDuty} />;
+ }
+}
+
+/** dialogTitle names the only offered action, or the alert automation in general. */
+function dialogTitle(actionTypes: ActionTypes[]): string {
+ if (actionTypes.length !== 1) return "New alert automation";
+ return `New ${monitorActionLabel[actionTypes[0]]} automation`;
+}
+
+/** MonitorAutomationForm is the form state shared with the action field groups. */
+type MonitorAutomationForm = UseFormReturn<MonitorAutomationFormValues>;
+
+/** MonitorAutomationSubmitResult is the server's answer to a create; `error` is its rejection message. */
+export type MonitorAutomationSubmitResult = { error?: string };
diff --git a/web/src/features/monitors/automations/components/PagerDutyActionFields.tsx b/web/src/features/monitors/automations/components/PagerDutyActionFields.tsx
new file mode 100644
index 0000000000..909350a376
--- /dev/null
+++ b/web/src/features/monitors/automations/components/PagerDutyActionFields.tsx
@@ -0,0 +1,94 @@
+import { useId } from "react";
+import { type UseFormReturn } from "react-hook-form";
+
+import { type PagerDutyRegion } from "@langfuse/shared/pagerduty";
+import {
+ PagerDutyTestEventButtonsView,
+ type PagerDutyTestEventState,
+} from "@/src/features/pagerduty";
+import { Form } from "@/src/components/design-system/Form/Form";
+import { PasswordInput } from "@/src/components/design-system/PasswordInput/PasswordInput";
+import { SelectInput } from "@/src/components/design-system/SelectInput/SelectInput";
+import { type MonitorAutomationFormValues } from "../helpers/monitorAutomationFormSchema";
+import { describedBy } from "../helpers/describedBy";
+import { FieldHelp } from "./FieldHelp";
+import { FieldWithHelp } from "./FieldWithHelp";
+import { HelpLink } from "./HelpLink";
+
+const integrationDocsUrl =
+ "https://support.pagerduty.com/main/docs/services-and-integrations#create-a-generic-events-api-integration";
+
+const regionOptions: { value: PagerDutyRegion; label: string }[] = [
+ { value: "US", label: "US (events.pagerduty.com)" },
+ { value: "EU", label: "EU (events.eu.pagerduty.com)" },
+];
+
+/** PagerDutyActionFields collects the integration key and region, and can send them a test event. */
+export function PagerDutyActionFields({
+ form,
+ testEvent,
+}: {
+ form: UseFormReturn<MonitorAutomationFormValues>;
+ testEvent: PagerDutyTestEventState;
+}) {
+ const routingKeyHelpId = useId();
+ const routingKey = form.watch("pagerDuty.routingKey");
+ const region = form.watch("pagerDuty.region");
+
+ return (
+ <>
+ <FieldWithHelp>
+ <Form.Field
+ control={form.control}
+ name="pagerDuty.routingKey"
+ label="Integration Key"
+ >
+ {(field) => (
+ <PasswordInput
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onChange={field.onChange}
+ onBlur={field.onBlur}
+ ref={field.ref}
+ placeholder="e.g. R0212P1QXGEIQE2NMTQ7L7WXD00DWHIN"
+ aria-describedby={describedBy(
+ field.inputDescribedById,
+ routingKeyHelpId,
+ )}
+ aria-invalid={!!field.error}
+ error={!!field.error}
+ />
+ )}
+ </Form.Field>
+ <FieldHelp id={routingKeyHelpId}>
+ Integration key for a PagerDuty Service or Event Orchestration.{" "}
+ <HelpLink href={integrationDocsUrl} text="Learn more" />
+ </FieldHelp>
+ </FieldWithHelp>
+ <Form.Field
+ control={form.control}
+ name="pagerDuty.region"
+ label="Region"
+ description="The service region of your PagerDuty account."
+ >
+ {(field) => (
+ <SelectInput<PagerDutyRegion>
+ id={field.id}
+ value={field.value}
+ onValueChange={field.onChange}
+ options={regionOptions}
+ placeholder="Select a region"
+ aria-describedby={field.inputDescribedById}
+ />
+ )}
+ </Form.Field>
+ <div className="flex">
+ <PagerDutyTestEventButtonsView
+ target={{ region, routingKey: routingKey.trim() || undefined }}
+ testEvent={testEvent}
+ />
+ </div>
+ </>
+ );
+}
diff --git a/web/src/features/monitors/automations/components/PrefixedInput.stories.tsx b/web/src/features/monitors/automations/components/PrefixedInput.stories.tsx
new file mode 100644
index 0000000000..5d1b8d9694
--- /dev/null
+++ b/web/src/features/monitors/automations/components/PrefixedInput.stories.tsx
@@ -0,0 +1,39 @@
+import { expect, userEvent, within } from "storybook/test";
+
+import preview from "@/.storybook/preview";
+import { PrefixedInput } from "./PrefixedInput";
+
+const meta = preview.meta({
+ component: PrefixedInput,
+ args: {
+ "aria-label": "Webhook URL",
+ addon: "POST",
+ prefix: "https://",
+ placeholder: "example.com/webhook",
+ },
+});
+
+export const Default = meta.story({});
+
+export const WithoutAddon = meta.story({
+ args: {
+ "aria-label": "Repository dispatch URL",
+ addon: undefined,
+ placeholder: "api.github.com/repos/owner/repo/dispatches",
+ },
+});
+
+export const Invalid = meta.story({
+ args: { value: "not a url", error: true, "aria-invalid": true },
+});
+
+export const TestFocusesOnAddonClick = meta.story({
+ name: "(Test) Focuses on addon click",
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await userEvent.click(canvas.getByText("POST"));
+ await expect(
+ canvas.getByRole("textbox", { name: "Webhook URL" }),
+ ).toHaveFocus();
+ },
+});
diff --git a/web/src/features/monitors/automations/components/PrefixedInput.tsx b/web/src/features/monitors/automations/components/PrefixedInput.tsx
new file mode 100644
index 0000000000..866f780efe
--- /dev/null
+++ b/web/src/features/monitors/automations/components/PrefixedInput.tsx
@@ -0,0 +1,90 @@
+import {
+ useRef,
+ type InputHTMLAttributes,
+ type MouseEvent,
+ type Ref,
+ type RefObject,
+} from "react";
+
+import { cn } from "@/src/utils/tailwind";
+
+/** PrefixedInput renders a text input after an optional shaded addon and a muted prefix inside one shared border. */
+export function PrefixedInput({
+ addon,
+ prefix,
+ error,
+ ref,
+ ...props
+}: Pick<
+ InputHTMLAttributes<HTMLInputElement>,
+ | "aria-describedby"
+ | "aria-invalid"
+ | "id"
+ | "inputMode"
+ | "name"
+ | "onBlur"
+ | "onChange"
+ | "placeholder"
+ | "value"
+> & {
+ addon?: string;
+ prefix: string;
+ error?: boolean;
+ ref?: Ref<HTMLInputElement>;
+}) {
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ return (
+ <div
+ className={cn(
+ "bg-background ring-offset-background focus-within:ring-ring flex h-8 w-full min-w-0 cursor-text items-center overflow-hidden rounded-md border text-sm focus-within:ring-2 focus-within:ring-offset-2",
+ borderClassName(error),
+ )}
+ onMouseDown={(event) => focusInput(event, inputRef)}
+ >
+ {addon && (
+ <span className="bg-muted text-muted-foreground border-input flex h-full shrink-0 items-center border-r px-2.5 font-mono text-xs">
+ {addon}
+ </span>
+ )}
+ <span className="text-foreground-secondary shrink-0 pr-0.5 pl-3">
+ {prefix}
+ </span>
+ <input
+ {...props}
+ className="placeholder:text-muted-foreground h-full min-w-0 flex-1 border-0 bg-transparent py-0 pr-3 pl-0 text-sm shadow-none outline-hidden focus:ring-0"
+ data-1p-ignore
+ ref={(input) => attachInput(input, inputRef, ref)}
+ />
+ </div>
+ );
+}
+
+/** borderClassName colors the shared border and focus ring for the error state. */
+function borderClassName(error: boolean | undefined): string {
+ if (error) {
+ return "border-destructive focus-within:ring-destructive/40 focus-within:ring-offset-0";
+ }
+ return "border-input";
+}
+
+/** focusInput moves focus to the input when the addon or prefix is pressed. */
+function focusInput(
+ event: MouseEvent<HTMLDivElement>,
+ inputRef: RefObject<HTMLInputElement | null>,
+) {
+ if (event.target === inputRef.current) return;
+ event.preventDefault();
+ inputRef.current?.focus();
+}
+
+/** attachInput stores the input locally and forwards it to the caller's ref. */
+function attachInput(
+ input: HTMLInputElement | null,
+ inputRef: RefObject<HTMLInputElement | null>,
+ ref: Ref<HTMLInputElement> | undefined,
+) {
+ inputRef.current = input;
+ if (typeof ref === "function") ref(input);
+ else if (ref) ref.current = input;
+}
diff --git a/web/src/features/monitors/automations/components/SlackActionFields.tsx b/web/src/features/monitors/automations/components/SlackActionFields.tsx
new file mode 100644
index 0000000000..ba5314ae3f
--- /dev/null
+++ b/web/src/features/monitors/automations/components/SlackActionFields.tsx
@@ -0,0 +1,217 @@
+import { useId, useState } from "react";
+import { type UseFormReturn } from "react-hook-form";
+import { SiSlack } from "@langfuse/icons/si";
+
+import { Button } from "@/src/components/design-system/Button/Button";
+import { Form } from "@/src/components/design-system/Form/Form";
+import {
+ ChannelSelectorView,
+ type ChannelSelectorViewProps,
+ type SlackChannel,
+ type SlackTestMessageResult,
+} from "@/src/features/slack";
+import { type MonitorAutomationFormValues } from "../helpers/monitorAutomationFormSchema";
+import { FieldGroup } from "./FieldGroup";
+import { InlineCode } from "./InlineCode";
+import { FieldHelp } from "./FieldHelp";
+import { FieldWithHelp } from "./FieldWithHelp";
+
+/** SlackActionFields picks the channel of a connected workspace, or offers to connect one. */
+export function SlackActionFields({
+ form,
+ slack,
+}: {
+ form: UseFormReturn<MonitorAutomationFormValues>;
+ slack: SlackFieldsState;
+}) {
+ if (slack.status === "disconnected") {
+ return <SlackConnectField slack={slack} />;
+ }
+ return <SlackChannelFields form={form} slack={slack} />;
+}
+
+/** SlackConnectField starts the Slack workspace connection. */
+function SlackConnectField({
+ slack,
+}: {
+ slack: Extract<SlackFieldsState, { status: "disconnected" }>;
+}) {
+ return (
+ <FieldGroup label="Slack channel">
+ <p className="text-muted-foreground text-sm">
+ Connect your Slack workspace to enable real-time notifications for your
+ automations.
+ {!slack.canManageIntegration &&
+ " Ask a project admin to connect Slack."}
+ </p>
+ <div className="flex">
+ <Button
+ type="button"
+ variant="primary"
+ icon={SiSlack}
+ text={connectLabel(slack.isConnecting)}
+ disabled={!slack.canConnect || slack.isConnecting}
+ onClick={slack.onConnect}
+ />
+ </div>
+ {slack.connectError && (
+ <p role="alert" className="text-destructive text-sm">
+ {slack.connectError}
+ </p>
+ )}
+ </FieldGroup>
+ );
+}
+
+/** SlackChannelFields selects the channel and tests it once one is chosen; testing also resolves a typed #name. */
+function SlackChannelFields({
+ form,
+ slack,
+}: {
+ form: UseFormReturn<MonitorAutomationFormValues>;
+ slack: Exclude<SlackFieldsState, { status: "disconnected" }>;
+}) {
+ const channelId = form.watch("slack.channelId");
+ const channelName = form.watch("slack.channelName");
+ const selectedChannel = selectedSlackChannel(channelId, channelName);
+ const channelHelpId = useId();
+ const [testResult, setTestResult] = useState<SlackTestMessageResult>();
+ const selectChannel = (channel: SlackChannel) => {
+ form.setValue("slack.channelId", channel.id);
+ form.setValue("slack.channelName", channel.name);
+ };
+
+ return (
+ <>
+ <FieldWithHelp>
+ <Form.Field
+ control={form.control}
+ name="slack.channelId"
+ label="Slack channel"
+ >
+ {() => (
+ <ChannelSelectorView
+ {...channelSelectorData(slack)}
+ selectedChannelId={channelId}
+ selectedChannel={selectedChannel}
+ onChannelSelect={(channel) => {
+ setTestResult(undefined);
+ selectChannel(channel);
+ }}
+ placeholder="Select a channel"
+ />
+ )}
+ </Form.Field>
+ <FieldHelp id={channelHelpId}>
+ Select the Slack channel where notifications will be sent. Private
+ channels appear only for the person who connected Slack, and only if
+ both they and the app are members. Invite the app with{" "}
+ <InlineCode isShaded>/invite @Langfuse</InlineCode>.
+ </FieldHelp>
+ </FieldWithHelp>
+ {selectedChannel && slack.status === "connected" && (
+ <div className="flex items-center gap-3">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Test channel"
+ loading={slack.isTesting}
+ onClick={async () => {
+ const result = await slack.onTestChannel(selectedChannel);
+ setTestResult(result);
+ if (result.status === "sent") {
+ selectChannel({
+ ...selectedChannel,
+ id: result.channel.id,
+ name: result.channel.name ?? selectedChannel.name,
+ });
+ }
+ }}
+ />
+ <TestChannelStatus result={testResult} />
+ </div>
+ )}
+ </>
+ );
+}
+
+/** TestChannelStatus explains the test, then reports how the last one went. */
+function TestChannelStatus({
+ result,
+}: {
+ result: SlackTestMessageResult | undefined;
+}) {
+ if (result?.status === "failed") {
+ return (
+ <p role="alert" className="text-destructive text-sm">
+ {result.message}
+ </p>
+ );
+ }
+ if (result?.status === "sent") {
+ return (
+ <p role="status" className="text-muted-foreground text-sm">
+ Test message sent. Check the channel in Slack.
+ </p>
+ );
+ }
+ return (
+ <p className="text-muted-foreground text-sm">
+ Test this channel to verify the bot can send messages.
+ </p>
+ );
+}
+
+/** connectLabel reflects a pending Slack OAuth popup. */
+function connectLabel(isConnecting: boolean): string {
+ if (isConnecting) return "Connecting...";
+ return "Connect Slack";
+}
+
+/** selectedSlackChannel is the channel the form holds, if one is chosen. */
+function selectedSlackChannel(
+ channelId: string,
+ channelName: string,
+): SlackChannel | null {
+ if (!channelId) return null;
+ return { id: channelId, name: channelName };
+}
+
+/** channelSelectorData is the channel list state, empty and loading until the integration status is known. */
+function channelSelectorData(
+ slack: Exclude<SlackFieldsState, { status: "disconnected" }>,
+): SlackChannelSelectorData {
+ if (slack.status === "connected") return slack.channelSelector;
+ return {
+ channelsData: null,
+ isLoading: true,
+ hasError: false,
+ isRefreshing: false,
+ onRefresh: () => {},
+ disabled: true,
+ };
+}
+
+/** SlackFieldsState is what the Slack fields need to know about the project's Slack integration. */
+export type SlackFieldsState =
+ | { status: "loading" }
+ | {
+ status: "disconnected";
+ canManageIntegration: boolean;
+ canConnect: boolean;
+ connectError?: string;
+ isConnecting: boolean;
+ onConnect: () => void;
+ }
+ | {
+ status: "connected";
+ channelSelector: SlackChannelSelectorData;
+ isTesting: boolean;
+ onTestChannel: (channel: SlackChannel) => Promise<SlackTestMessageResult>;
+ };
+
+/** SlackChannelSelectorData is the channel list state ChannelSelectorView renders, without the selection. */
+type SlackChannelSelectorData = Omit<
+ ChannelSelectorViewProps,
+ "selectedChannelId" | "selectedChannel" | "onChannelSelect" | "placeholder"
+>;
diff --git a/web/src/features/monitors/automations/components/WebhookActionFields.tsx b/web/src/features/monitors/automations/components/WebhookActionFields.tsx
new file mode 100644
index 0000000000..9ee2de4864
--- /dev/null
+++ b/web/src/features/monitors/automations/components/WebhookActionFields.tsx
@@ -0,0 +1,195 @@
+import { useFieldArray, type UseFormReturn } from "react-hook-form";
+import { Lock, LockOpen, Plus, X } from "@langfuse/icons";
+
+import {
+ WebhookContentTypeHeader,
+ WebhookDefaultHeaders,
+ WebhookSignatureHeader,
+ WebhookUserAgentHeader,
+} from "@langfuse/shared";
+import { Button } from "@/src/components/design-system/Button/Button";
+import { Form } from "@/src/components/design-system/Form/Form";
+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { type MonitorAutomationFormValues } from "../helpers/monitorAutomationFormSchema";
+import { stripUrlScheme } from "../helpers/stripUrlScheme";
+import { FieldGroup } from "./FieldGroup";
+import { PrefixedInput } from "./PrefixedInput";
+
+const defaultHeaders = [
+ {
+ name: WebhookContentTypeHeader,
+ value: WebhookDefaultHeaders[WebhookContentTypeHeader],
+ },
+ {
+ name: WebhookUserAgentHeader,
+ value: WebhookDefaultHeaders[WebhookUserAgentHeader],
+ },
+ { name: WebhookSignatureHeader, value: "t=<timestamp>,v1=<signature>" },
+];
+
+/** WebhookActionFields collects the https endpoint and the custom request headers. */
+export function WebhookActionFields({
+ form,
+}: {
+ form: UseFormReturn<MonitorAutomationFormValues>;
+}) {
+ return (
+ <>
+ <WebhookUrlField form={form} />
+ <WebhookHeadersField form={form} />
+ </>
+ );
+}
+
+/** WebhookUrlField takes the host and path; the https scheme is fixed in the prefix. */
+function WebhookUrlField({
+ form,
+}: {
+ form: UseFormReturn<MonitorAutomationFormValues>;
+}) {
+ return (
+ <Form.Field
+ control={form.control}
+ name="webhook.url"
+ label="Webhook URL"
+ description="Called whenever the severity changes."
+ >
+ {(field) => (
+ <PrefixedInput
+ id={field.id}
+ name={field.name}
+ value={field.value}
+ onChange={(event) =>
+ field.onChange(stripUrlScheme(event.target.value))
+ }
+ onBlur={field.onBlur}
+ ref={field.ref}
+ addon="POST"
+ prefix="https://"
+ inputMode="url"
+ placeholder="example.com/webhook"
+ aria-describedby={field.inputDescribedById}
+ aria-invalid={!!field.error}
+ error={!!field.error}
+ />
+ )}
+ </Form.Field>
+ );
+}
+
+/** WebhookHeadersField shows the headers Langfuse adds and edits the custom ones. */
+function WebhookHeadersField({
+ form,
+}: {
+ form: UseFormReturn<MonitorAutomationFormValues>;
+}) {
+ const headers = useFieldArray({
+ control: form.control,
+ name: "webhook.headers",
+ });
+
+ return (
+ <FieldGroup label="Headers">
+ <p className="text-muted-foreground text-sm">
+ Default headers (automatically added by Langfuse):
+ </p>
+ {defaultHeaders.map((header) => (
+ <div key={header.name} className="grid grid-cols-2 gap-2">
+ <Input aria-label="Header name" value={header.name} disabled />
+ <Input aria-label="Header value" value={header.value} disabled />
+ </div>
+ ))}
+ <p className="text-muted-foreground pt-2 text-sm">
+ Optional custom headers to include in the webhook request:
+ </p>
+ {headers.fields.map((header, index) => (
+ <CustomHeaderRow
+ key={header.id}
+ form={form}
+ index={index}
+ onRemove={() => headers.remove(index)}
+ />
+ ))}
+ <div className="pt-1">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Add custom header"
+ icon={Plus}
+ onClick={() =>
+ headers.append({ name: "", value: "", isSecret: false })
+ }
+ />
+ </div>
+ </FieldGroup>
+ );
+}
+
+/** CustomHeaderRow edits one custom header; a locked header is stored as a secret. */
+function CustomHeaderRow({
+ form,
+ index,
+ onRemove,
+}: {
+ form: UseFormReturn<MonitorAutomationFormValues>;
+ index: number;
+ onRemove: () => void;
+}) {
+ const isSecret = form.watch(`webhook.headers.${index}.isSecret`);
+ const nameError = form.formState.errors.webhook?.headers?.[index]?.name;
+ const valueError = form.formState.errors.webhook?.headers?.[index]?.value;
+ const errorMessage = nameError?.message ?? valueError?.message;
+
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] items-center gap-2">
+ <Input
+ aria-label="Header name"
+ placeholder="Header name"
+ error={!!nameError}
+ {...form.register(`webhook.headers.${index}.name`)}
+ />
+ <Input
+ aria-label="Header value"
+ placeholder="Value"
+ type={headerValueInputType(isSecret)}
+ error={!!valueError}
+ {...form.register(`webhook.headers.${index}.value`)}
+ />
+ <div className="flex items-center gap-1">
+ <IconButton
+ icon={lockIcon(isSecret)}
+ label={lockLabel(isSecret)}
+ aria-pressed={isSecret}
+ onClick={() =>
+ form.setValue(`webhook.headers.${index}.isSecret`, !isSecret)
+ }
+ />
+ <IconButton icon={X} label="Remove header" onClick={onRemove} />
+ </div>
+ </div>
+ {errorMessage && (
+ <p className="text-destructive text-sm">{errorMessage}</p>
+ )}
+ </div>
+ );
+}
+
+/** headerValueInputType masks secret header values. */
+function headerValueInputType(isSecret: boolean): "password" | "text" {
+ if (isSecret) return "password";
+ return "text";
+}
+
+/** lockIcon shows a closed lock for secret headers. */
+function lockIcon(isSecret: boolean) {
+ if (isSecret) return Lock;
+ return LockOpen;
+}
+
+/** lockLabel names what the lock toggle will do. */
+function lockLabel(isSecret: boolean): string {
+ if (isSecret) return "Make header public";
+ return "Make header secret";
+}
diff --git a/web/src/features/monitors/automations/components/WebhookSecretDialog.tsx b/web/src/features/monitors/automations/components/WebhookSecretDialog.tsx
new file mode 100644
index 0000000000..e7e89727e7
--- /dev/null
+++ b/web/src/features/monitors/automations/components/WebhookSecretDialog.tsx
@@ -0,0 +1,99 @@
+import { useId, useState } from "react";
+import { Check, Copy } from "@langfuse/icons";
+
+import { Dialog } from "@/src/components/design-system/Dialog/Dialog";
+import { Form } from "@/src/components/design-system/Form/Form";
+import { IconButton } from "@/src/components/design-system/IconButton/IconButton";
+import { Input } from "@/src/components/design-system/Input/Input";
+import { copyTextToClipboard } from "@/src/utils/clipboard";
+import { DividedDialogBody } from "./DividedDialogBody";
+import { InlineCode } from "./InlineCode";
+import { describedBy } from "../helpers/describedBy";
+import { FieldHelp } from "./FieldHelp";
+import { FieldWithHelp } from "./FieldWithHelp";
+
+/** WebhookSecretDialog shows a just-created webhook automation's signing secret, which is never shown again. */
+export function WebhookSecretDialog({
+ automationName,
+ webhookSecret,
+}: {
+ automationName: string;
+ webhookSecret: string;
+}) {
+ const secretHelpId = useId();
+ const [copyStatus, setCopyStatus] = useState<CopyStatus>("idle");
+
+ return (
+ <Dialog
+ title={`Automation "${automationName}" was created`}
+ closeLabel="Done"
+ >
+ <DividedDialogBody>
+ <FieldWithHelp>
+ <Form.Field label="Webhook secret">
+ {(field) => (
+ <div className="flex flex-col gap-1">
+ <div className="ph-no-capture grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2">
+ <Input
+ id={field.id}
+ value={webhookSecret}
+ aria-describedby={describedBy(
+ field.inputDescribedById,
+ secretHelpId,
+ )}
+ readOnly
+ />
+ <IconButton
+ icon={copyIcon(copyStatus)}
+ label={copyLabel(copyStatus)}
+ variant="outline"
+ onClick={async () =>
+ setCopyStatus(await copySecret(webhookSecret))
+ }
+ />
+ </div>
+ {copyStatus === "failed" && (
+ <p role="alert" className="text-destructive text-sm">
+ Copy failed. Select the secret and copy it manually.
+ </p>
+ )}
+ </div>
+ )}
+ </Form.Field>
+ <FieldHelp id={secretHelpId}>
+ Use this secret to verify webhook signatures. It is included in the{" "}
+ <InlineCode isShaded>x-langfuse-signature</InlineCode> header.{" "}
+ <strong className="text-foreground font-bold">
+ This will not be shown again.
+ </strong>
+ </FieldHelp>
+ </FieldWithHelp>
+ </DividedDialogBody>
+ </Dialog>
+ );
+}
+
+/** copySecret copies the secret and reports whether the clipboard accepted it. */
+async function copySecret(webhookSecret: string): Promise<CopyStatus> {
+ try {
+ await copyTextToClipboard(webhookSecret);
+ return "copied";
+ } catch {
+ return "failed";
+ }
+}
+
+/** copyIcon confirms a successful copy with a check mark. */
+function copyIcon(copyStatus: CopyStatus) {
+ if (copyStatus === "copied") return Check;
+ return Copy;
+}
+
+/** copyLabel names the copy button's state for assistive technology. */
+function copyLabel(copyStatus: CopyStatus): string {
+ if (copyStatus === "copied") return "Secret copied";
+ return "Copy secret";
+}
+
+/** CopyStatus is the outcome of the last copy attempt. */
+type CopyStatus = "idle" | "copied" | "failed";
diff --git a/web/src/features/monitors/automations/helpers/buildCreateMonitorAutomationInput.clienttest.ts b/web/src/features/monitors/automations/helpers/buildCreateMonitorAutomationInput.clienttest.ts
new file mode 100644
index 0000000000..b3b613a7e9
--- /dev/null
+++ b/web/src/features/monitors/automations/helpers/buildCreateMonitorAutomationInput.clienttest.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it } from "vitest";
+
+import { buildCreateMonitorAutomationInput } from "./buildCreateMonitorAutomationInput";
+import {
+ defaultMonitorAutomationFormValues,
+ monitorAutomationFormSchema,
+} from "./monitorAutomationFormSchema";
+
+describe("buildCreateMonitorAutomationInput", () => {
+ it("creates an active monitor automation posting to the https URL with named headers", () => {
+ const values = {
+ ...defaultMonitorAutomationFormValues("WEBHOOK", " Staging alerts "),
+ webhook: {
+ url: "example.com/hook",
+ headers: [
+ { name: " x-team ", value: " ml ", isSecret: false },
+ { name: "authorization", value: "Bearer t", isSecret: true },
+ { name: "", value: "", isSecret: false },
+ ],
+ },
+ };
+
+ expect(buildCreateMonitorAutomationInput("p1", values)).toEqual({
+ projectId: "p1",
+ name: "Staging alerts",
+ eventSource: "monitor",
+ eventAction: [],
+ filter: null,
+ status: "ACTIVE",
+ actionType: "WEBHOOK",
+ actionConfig: {
+ type: "WEBHOOK",
+ url: "https://example.com/hook",
+ requestHeaders: {
+ "x-team": { secret: false, value: "ml" },
+ authorization: { secret: true, value: "Bearer t" },
+ },
+ apiVersion: { monitor: "v1" },
+ },
+ });
+ });
+
+ it("dispatches to the https URL for the host and path typed after the prefix", () => {
+ const values = {
+ ...defaultMonitorAutomationFormValues("GITHUB_DISPATCH", "Deploy"),
+ githubDispatch: {
+ url: " api.github.com/repos/o/r/dispatches ",
+ eventType: "langfuse-alert",
+ githubToken: "ghp_token",
+ },
+ };
+
+ expect(
+ buildCreateMonitorAutomationInput("p1", values).actionConfig,
+ ).toEqual({
+ type: "GITHUB_DISPATCH",
+ url: "https://api.github.com/repos/o/r/dispatches",
+ eventType: "langfuse-alert",
+ githubToken: "ghp_token",
+ });
+ });
+});
+
+describe("monitorAutomationFormSchema", () => {
+ it("rejects a webhook host that does not form a valid URL", () => {
+ const values = {
+ ...defaultMonitorAutomationFormValues("WEBHOOK", "Hook"),
+ webhook: { url: "not a host", headers: [] },
+ };
+
+ const result = monitorAutomationFormSchema.safeParse(values);
+
+ expect(result.error?.issues).toEqual([
+ expect.objectContaining({
+ path: ["webhook", "url"],
+ message: "Enter a valid HTTPS URL.",
+ }),
+ ]);
+ });
+
+ it.each(["my_service.internal/hook", "[2001:db8::1]/hook"])(
+ "accepts the webhook host %s, which the server also accepts",
+ (url) => {
+ const values = {
+ ...defaultMonitorAutomationFormValues("WEBHOOK", "Hook"),
+ webhook: { url, headers: [] },
+ };
+
+ expect(monitorAutomationFormSchema.safeParse(values).success).toBe(true);
+ },
+ );
+
+ it("rejects a custom header that overrides a Langfuse header", () => {
+ const values = {
+ ...defaultMonitorAutomationFormValues("WEBHOOK", "Hook"),
+ webhook: {
+ url: "example.com",
+ headers: [
+ { name: "Content-Type", value: "text/plain", isSecret: false },
+ ],
+ },
+ };
+
+ const result = monitorAutomationFormSchema.safeParse(values);
+
+ expect(result.error?.issues).toEqual([
+ expect.objectContaining({ path: ["webhook", "headers", 0, "name"] }),
+ ]);
+ });
+
+ it("ignores the fields of actions other than the selected one", () => {
+ const values = {
+ ...defaultMonitorAutomationFormValues("SLACK", "Slack"),
+ webhook: { url: "not a host", headers: [] },
+ };
+
+ expect(monitorAutomationFormSchema.safeParse(values).success).toBe(true);
+ });
+});
diff --git a/web/src/features/monitors/automations/helpers/buildCreateMonitorAutomationInput.ts b/web/src/features/monitors/automations/helpers/buildCreateMonitorAutomationInput.ts
new file mode 100644
index 0000000000..172f435ce2
--- /dev/null
+++ b/web/src/features/monitors/automations/helpers/buildCreateMonitorAutomationInput.ts
@@ -0,0 +1,70 @@
+import { TriggerEventSource, type ActionCreate } from "@langfuse/shared";
+
+import { type RouterInputs } from "@/src/utils/api";
+import {
+ httpsUrl,
+ type MonitorAutomationFormValues,
+} from "./monitorAutomationFormSchema";
+
+/** buildCreateMonitorAutomationInput maps the form to an active monitor-triggered automation. */
+export function buildCreateMonitorAutomationInput(
+ projectId: string,
+ values: MonitorAutomationFormValues,
+): RouterInputs["automations"]["createAutomation"] {
+ return {
+ projectId,
+ name: values.name.trim(),
+ eventSource: TriggerEventSource.Monitor,
+ eventAction: [],
+ filter: null,
+ status: "ACTIVE",
+ actionType: values.actionType,
+ actionConfig: buildActionConfig(values),
+ };
+}
+
+/** buildActionConfig builds the config of the selected action. */
+function buildActionConfig(values: MonitorAutomationFormValues): ActionCreate {
+ switch (values.actionType) {
+ case "SLACK":
+ return {
+ type: "SLACK",
+ channelId: values.slack.channelId,
+ channelName: values.slack.channelName,
+ };
+ case "WEBHOOK":
+ return {
+ type: "WEBHOOK",
+ url: httpsUrl(values.webhook.url),
+ requestHeaders: requestHeaders(values.webhook.headers),
+ apiVersion: { monitor: "v1" },
+ };
+ case "GITHUB_DISPATCH":
+ return {
+ type: "GITHUB_DISPATCH",
+ url: httpsUrl(values.githubDispatch.url),
+ eventType: values.githubDispatch.eventType.trim(),
+ githubToken: values.githubDispatch.githubToken.trim(),
+ };
+ case "PAGERDUTY":
+ return {
+ type: "PAGERDUTY",
+ region: values.pagerDuty.region,
+ routingKey: values.pagerDuty.routingKey.trim(),
+ };
+ }
+}
+
+/** requestHeaders keys the named custom headers by trimmed name. */
+function requestHeaders(
+ headers: MonitorAutomationFormValues["webhook"]["headers"],
+): Record<string, { secret: boolean; value: string }> {
+ return Object.fromEntries(
+ headers
+ .filter((header) => header.name.trim())
+ .map((header) => [
+ header.name.trim(),
+ { secret: header.isSecret, value: header.value.trim() },
+ ]),
+ );
+}
diff --git a/web/src/features/monitors/automations/helpers/describedBy.ts b/web/src/features/monitors/automations/helpers/describedBy.ts
new file mode 100644
index 0000000000..ec8c7399db
--- /dev/null
+++ b/web/src/features/monitors/automations/helpers/describedBy.ts
@@ -0,0 +1,8 @@
+/** describedBy joins the ids an input's aria-describedby should list, skipping missing ones. */
+export function describedBy(
+ ...ids: (string | undefined)[]
+): string | undefined {
+ const present = ids.filter((id) => id !== undefined);
+ if (present.length === 0) return undefined;
+ return present.join(" ");
+}
diff --git a/web/src/features/monitors/automations/helpers/isMonitorAutomationFormComplete.ts b/web/src/features/monitors/automations/helpers/isMonitorAutomationFormComplete.ts
new file mode 100644
index 0000000000..bc8c65e12b
--- /dev/null
+++ b/web/src/features/monitors/automations/helpers/isMonitorAutomationFormComplete.ts
@@ -0,0 +1,31 @@
+import { type MonitorAutomationFormValues } from "./monitorAutomationFormSchema";
+
+/** isMonitorAutomationFormComplete reports whether the name and the selected action's required fields are filled. */
+export function isMonitorAutomationFormComplete(
+ values: MonitorAutomationFormValues,
+): boolean {
+ return isFilled(values.name) && requiredActionFields(values).every(isFilled);
+}
+
+/** requiredActionFields lists the values the selected action cannot be created without. */
+function requiredActionFields(values: MonitorAutomationFormValues): string[] {
+ switch (values.actionType) {
+ case "SLACK":
+ return [values.slack.channelId];
+ case "WEBHOOK":
+ return [values.webhook.url];
+ case "GITHUB_DISPATCH":
+ return [
+ values.githubDispatch.url,
+ values.githubDispatch.eventType,
+ values.githubDispatch.githubToken,
+ ];
+ case "PAGERDUTY":
+ return [values.pagerDuty.routingKey];
+ }
+}
+
+/** isFilled rejects blank strings. */
+function isFilled(value: string): boolean {
+ return value.trim().length > 0;
+}
diff --git a/web/src/features/monitors/automations/helpers/monitorAutomationFormSchema.ts b/web/src/features/monitors/automations/helpers/monitorAutomationFormSchema.ts
new file mode 100644
index 0000000000..ab4e8c91dd
--- /dev/null
+++ b/web/src/features/monitors/automations/helpers/monitorAutomationFormSchema.ts
@@ -0,0 +1,192 @@
+import { z } from "zod";
+
+import {
+ ActionTypeSchema,
+ PagerDutyActionCreateSchema,
+ WebhookProtectedHeaders,
+} from "@langfuse/shared";
+
+const maxNameLength = 100;
+const maxEventTypeLength = 100;
+const pagerDutyRoutingKeySchema =
+ PagerDutyActionCreateSchema.shape.routingKey.unwrap();
+
+/** monitorAutomationFormSchema validates the format of the active action's fields; completeness is gated by the submit button. */
+export const monitorAutomationFormSchema = z
+ .object({
+ name: z
+ .string()
+ .max(maxNameLength, `Name must be ${maxNameLength} characters or less.`),
+ actionType: ActionTypeSchema,
+ slack: z.object({ channelId: z.string(), channelName: z.string() }),
+ webhook: z.object({
+ url: z.string(),
+ headers: z.array(
+ z.object({
+ name: z.string(),
+ value: z.string(),
+ isSecret: z.boolean(),
+ }),
+ ),
+ }),
+ githubDispatch: z.object({
+ url: z.string(),
+ eventType: z.string(),
+ githubToken: z.string(),
+ }),
+ pagerDuty: z.object({
+ routingKey: z.string(),
+ region: PagerDutyActionCreateSchema.shape.region,
+ }),
+ })
+ .superRefine((values, ctx) => {
+ for (const issue of activeActionIssues(values)) ctx.addIssue(issue);
+ });
+
+/** defaultMonitorAutomationFormValues is an empty form for the given action. */
+export function defaultMonitorAutomationFormValues(
+ actionType: MonitorAutomationFormValues["actionType"],
+ name = "",
+): MonitorAutomationFormValues {
+ return {
+ name,
+ actionType,
+ slack: { channelId: "", channelName: "" },
+ webhook: { url: "", headers: [] },
+ githubDispatch: { url: "", eventType: "", githubToken: "" },
+ pagerDuty: { routingKey: "", region: "US" },
+ };
+}
+
+/** activeActionIssues lists the format issues of the fields the selected action submits. */
+function activeActionIssues(values: MonitorAutomationFormValues): FormIssue[] {
+ switch (values.actionType) {
+ case "WEBHOOK":
+ return webhookIssues(values.webhook);
+ case "GITHUB_DISPATCH":
+ return githubDispatchIssues(values.githubDispatch);
+ case "PAGERDUTY":
+ return pagerDutyIssues(values.pagerDuty);
+ case "SLACK":
+ return [];
+ }
+}
+
+/** webhookIssues checks the URL and the custom headers. */
+function webhookIssues(
+ webhook: MonitorAutomationFormValues["webhook"],
+): FormIssue[] {
+ const headerIssues = webhookHeaderIssues(webhook.headers);
+ if (isHttpsUrl(httpsUrl(webhook.url))) return headerIssues;
+ return [
+ issue(["webhook", "url"], "Enter a valid HTTPS URL."),
+ ...headerIssues,
+ ];
+}
+
+/** webhookHeaderIssues checks each partly filled header row; fully empty rows are dropped on submit. */
+function webhookHeaderIssues(
+ headers: MonitorAutomationFormValues["webhook"]["headers"],
+): FormIssue[] {
+ const seenNames = new Set<string>();
+ return headers.flatMap((header, index) => {
+ const name = header.name.trim().toLowerCase();
+ const path = (field: "name" | "value") => [
+ "webhook",
+ "headers",
+ index,
+ field,
+ ];
+ if (!name && !header.value.trim()) return [];
+ if (!name) return [issue(path("name"), "Header name is required.")];
+ if (WebhookProtectedHeaders.includes(name)) {
+ return [issue(path("name"), "This header is added by Langfuse.")];
+ }
+ if (seenNames.has(name)) {
+ return [issue(path("name"), "Header names must be unique.")];
+ }
+ seenNames.add(name);
+ if (!header.value.trim()) {
+ return [issue(path("value"), "Header value is required.")];
+ }
+ return [];
+ });
+}
+
+/** githubDispatchIssues checks the dispatch URL and the event type length. */
+function githubDispatchIssues(
+ githubDispatch: MonitorAutomationFormValues["githubDispatch"],
+): FormIssue[] {
+ const issues: FormIssue[] = [];
+ if (!isHttpsUrl(httpsUrl(githubDispatch.url))) {
+ issues.push(
+ issue(
+ ["githubDispatch", "url"],
+ "Enter a valid repository dispatch URL.",
+ ),
+ );
+ }
+ if (githubDispatch.eventType.trim().length > maxEventTypeLength) {
+ issues.push(
+ issue(
+ ["githubDispatch", "eventType"],
+ `Event type must be ${maxEventTypeLength} characters or less.`,
+ ),
+ );
+ }
+ return issues;
+}
+
+/** pagerDutyIssues checks the routing key against PagerDuty's key format. */
+function pagerDutyIssues(
+ pagerDuty: MonitorAutomationFormValues["pagerDuty"],
+): FormIssue[] {
+ const result = pagerDutyRoutingKeySchema.safeParse(pagerDuty.routingKey);
+ if (result.success) return [];
+ return [
+ issue(["pagerDuty", "routingKey"], result.error.issues[0]?.message ?? ""),
+ ];
+}
+
+/** httpsUrl is the submitted URL for the host and path typed after a fixed https:// prefix. */
+export function httpsUrl(hostAndPath: string): string {
+ return `https://${hostAndPath.trim()}`;
+}
+
+/** isHttpsUrl accepts absolute https URLs with a host. */
+function isHttpsUrl(url: string): boolean {
+ return isUrlWithHost(url) && url.toLowerCase().startsWith("https://");
+}
+
+/** isUrlWithHost accepts absolute URLs with a host, including underscores and IPv6 literals. */
+function isUrlWithHost(url: string): boolean {
+ const hostname = parseHostname(url);
+ // Chromium percent-encodes invalid hosts such as "not a url" instead of rejecting them.
+ return Boolean(hostname) && !hostname?.includes("%");
+}
+
+/** parseHostname is the URL's hostname, or undefined when it does not parse. */
+function parseHostname(url: string): string | undefined {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return undefined;
+ }
+}
+
+/** issue builds a custom zod issue for a form field. */
+function issue(path: (string | number)[], message: string): FormIssue {
+ return { code: "custom", path, message };
+}
+
+/** MonitorAutomationFormValues is the state of the new monitor automation form. */
+export type MonitorAutomationFormValues = z.infer<
+ typeof monitorAutomationFormSchema
+>;
+
+/** FormIssue is a field error raised by the schema refinement. */
+type FormIssue = {
+ code: "custom";
+ path: (string | number)[];
+ message: string;
+};
diff --git a/web/src/features/monitors/automations/helpers/serverErrorField.clienttest.ts b/web/src/features/monitors/automations/helpers/serverErrorField.clienttest.ts
new file mode 100644
index 0000000000..865830a848
--- /dev/null
+++ b/web/src/features/monitors/automations/helpers/serverErrorField.clienttest.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+
+import { serverErrorField } from "./serverErrorField";
+
+describe("serverErrorField", () => {
+ it.each([
+ [
+ "GITHUB_DISPATCH",
+ "Invalid webhook URL: DNS lookup failed for kjhkjhkj.com",
+ "githubDispatch.url",
+ ],
+ [
+ "GITHUB_DISPATCH",
+ "GitHub Personal Access Token is required",
+ "githubDispatch.githubToken",
+ ],
+ ["WEBHOOK", "Invalid webhook URL: blocked host", "webhook.url"],
+ [
+ "WEBHOOK",
+ 'Secret header "x" must be re-entered when changing the webhook URL',
+ "root.server",
+ ],
+ [
+ "SLACK",
+ "Send a test message to this channel before saving so it can be resolved.",
+ "slack.channelId",
+ ],
+ ["PAGERDUTY", "Something unexpected", "root.server"],
+ ] as const)(
+ "shows a %s rejection %j under %s",
+ (actionType, message, field) => {
+ expect(serverErrorField(actionType, message)).toBe(field);
+ },
+ );
+});
diff --git a/web/src/features/monitors/automations/helpers/serverErrorField.ts b/web/src/features/monitors/automations/helpers/serverErrorField.ts
new file mode 100644
index 0000000000..4bef68e851
--- /dev/null
+++ b/web/src/features/monitors/automations/helpers/serverErrorField.ts
@@ -0,0 +1,45 @@
+import { type MonitorAutomationFormValues } from "./monitorAutomationFormSchema";
+
+/** serverErrorField picks the field a server rejection is about, falling back to the whole form. */
+export function serverErrorField(
+ actionType: MonitorAutomationFormValues["actionType"],
+ message: string,
+): ServerErrorField {
+ return actionFieldFor(actionType, message) ?? "root.server";
+}
+
+/** actionFieldFor matches the rejection message against the selected action's fields. */
+function actionFieldFor(
+ actionType: MonitorAutomationFormValues["actionType"],
+ message: string,
+): ServerErrorField | undefined {
+ switch (actionType) {
+ case "SLACK":
+ if (/channel/i.test(message)) return "slack.channelId";
+ return undefined;
+ case "WEBHOOK":
+ if (/header/i.test(message)) return undefined;
+ if (/url|host|dns/i.test(message)) return "webhook.url";
+ return undefined;
+ case "GITHUB_DISPATCH":
+ if (/token/i.test(message)) return "githubDispatch.githubToken";
+ if (/event type/i.test(message)) return "githubDispatch.eventType";
+ if (/url|host|dns/i.test(message)) return "githubDispatch.url";
+ return undefined;
+ case "PAGERDUTY":
+ if (/routing key|integration key/i.test(message)) {
+ return "pagerDuty.routingKey";
+ }
+ return undefined;
+ }
+}
+
+/** ServerErrorField is a form field a server rejection can be shown under. */
+type ServerErrorField =
+ | "root.server"
+ | "slack.channelId"
+ | "webhook.url"
+ | "githubDispatch.url"
+ | "githubDispatch.eventType"
+ | "githubDispatch.githubToken"
+ | "pagerDuty.routingKey";
diff --git a/web/src/features/monitors/automations/helpers/stripUrlScheme.ts b/web/src/features/monitors/automations/helpers/stripUrlScheme.ts
new file mode 100644
index 0000000000..0d624ec124
--- /dev/null
+++ b/web/src/features/monitors/automations/helpers/stripUrlScheme.ts
@@ -0,0 +1,6 @@
+const schemePattern = /^\s*https?:\/\//i;
+
+/** stripUrlScheme drops a typed or pasted http(s) scheme, which the field's fixed prefix already shows. */
+export function stripUrlScheme(value: string): string {
+ return value.replace(schemePattern, "");
+}
diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsx
index cb9a1f3248..2ef8f8fdb8 100644
--- a/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsx
+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.create.clienttest.tsx
@@ -53,20 +53,25 @@ vi.mock("@/src/utils/api", () => ({
},
}));
-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>
- ),
-}));
+type CreatedHandler = (automation: {
+ automationId: string;
+ name: string;
+ webhookSecret?: string;
+}) => void;
+
+/** stubSave stands in for the real dialog, whose contract with the panel is "action in, onCreated out". */
+let stubSave: (onCreated: CreatedHandler) => void;
+
+vi.mock(
+ "@/src/features/monitors/automations/ConnectedNewMonitorAutomationDialog",
+ () => ({
+ ConnectedNewMonitorAutomationDialog: ({
+ onCreated,
+ }: {
+ onCreated: CreatedHandler;
+ }) => <button onClick={() => stubSave(onCreated)}>stub save</button>,
+ }),
+);
import { MonitorAutomationsPanel } from "./MonitorAutomationsPanel";
@@ -83,9 +88,9 @@ describe("MonitorAutomationsPanel automation creation", () => {
it("creates in place and selects the new trigger, never linking away from the monitor form", async () => {
automations = [existingRow];
- stubSave = (onSuccess) => {
+ stubSave = (onCreated) => {
automations = [existingRow, createdRow];
- onSuccess("auto-2");
+ onCreated({ automationId: "auto-2", name: "Deploy hook" });
};
const onTriggerIdsChange = vi.fn();
render(
@@ -110,7 +115,12 @@ describe("MonitorAutomationsPanel automation creation", () => {
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");
+ stubSave = (onCreated) =>
+ onCreated({
+ automationId: "auto-2",
+ name: "Deploy hook",
+ webhookSecret: "whsec_stub",
+ });
const onTriggerIdsChange = vi.fn();
// A fresh element per render: React bails out of re-rendering an identical one.
const panel = () => (
@@ -129,9 +139,7 @@ describe("MonitorAutomationsPanel automation creation", () => {
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 }));
+ expect(await screen.findByDisplayValue("whsec_stub")).toBeInTheDocument();
await waitFor(() =>
expect(onTriggerIdsChange).toHaveBeenCalledWith(["trig-2"]),
);
@@ -139,9 +147,9 @@ describe("MonitorAutomationsPanel automation creation", () => {
it("keeps a selection made while the post-create list read is still in flight", async () => {
automations = [existingRow];
- stubSave = (onSuccess) => {
+ stubSave = (onCreated) => {
automations = [existingRow, createdRow];
- onSuccess("auto-2");
+ onCreated({ automationId: "auto-2", name: "Deploy hook" });
};
let releaseFetch = () => {};
gateFetch = new Promise<void>((resolve) => {
diff --git a/web/src/features/monitors/components/MonitorAutomationsPanel.tsx b/web/src/features/monitors/components/MonitorAutomationsPanel.tsx
index 60ec599f2b..752d175018 100644
--- a/web/src/features/monitors/components/MonitorAutomationsPanel.tsx
+++ b/web/src/features/monitors/components/MonitorAutomationsPanel.tsx
@@ -1,5 +1,5 @@
-/* eslint-disable @repo/no-style-props, @typescript-eslint/no-deprecated, @typescript-eslint/no-use-before-define -- Legacy UI usage retained during migration to design-system components. */
-import { useMemo, useCallback, useRef, useState } from "react";
+/* eslint-disable @repo/no-style-props, @typescript-eslint/no-use-before-define -- Legacy UI usage retained during migration to design-system components. */
+import { useMemo, useCallback, useRef } from "react";
import {
Check,
Github,
@@ -12,22 +12,12 @@ import { SiPagerduty } from "@langfuse/icons/si";
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 } from "@/src/components/design-system/DropdownMenu/DropdownMenu";
import {
actionTypeLabel,
- AutomationForm,
useAvailableActionTypes,
- WebhookSecretRender,
} from "@/src/features/automations";
+import { NewMonitorAutomationDialogController } from "@/src/features/monitors/automations/NewMonitorAutomationDialogController";
import { cn } from "@/src/utils/tailwind";
import {
ActionTypeSchema,
@@ -246,12 +236,6 @@ const RowCheckbox = ({ checked }: { checked: boolean }) => (
</span>
);
-/** 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
@@ -269,120 +253,48 @@ const AddAutomationDropdown = ({
onAutomationCreated: (automationId: string) => void;
}) => {
const actionTypes = useAvailableActionTypes(ActionTypeSchema.options);
- 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
- disabled={isDisabled}
- placement="bottom-end"
- items={[
- {
- type: "item",
- id: "new",
- title: "New automation",
- icon: Plus,
- onClick: () => setDraft({}),
- },
- ...actionTypes.map((actionType) => ({
- type: "item" as const,
- id: actionType,
- title: actionTypeLabel[actionType],
- icon: actionIcon[actionType],
- onClick: () => setDraft({ actionType }),
- })),
- ]}
- >
- {({ getTriggerProps }) => (
- <Button
- variant="outline"
- size="lg"
- disabled={isDisabled}
- className={fullWidth ? "w-full" : undefined}
- {...getTriggerProps()}
- >
- <Plus size="base" color="default" __rawClassName="mr-2" />
- Automation
- </Button>
- )}
- </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()}
+ <NewMonitorAutomationDialogController
+ projectId={projectId}
+ onCreated={onAutomationCreated}
+ >
+ {({ openDialog }) => (
+ <DropdownMenu
+ disabled={isDisabled}
+ placement="bottom-end"
+ items={[
+ {
+ type: "item",
+ id: "new",
+ title: "New automation",
+ icon: Plus,
+ onClick: () => openDialog(),
+ },
+ ...actionTypes.map((actionType) => ({
+ type: "item" as const,
+ id: actionType,
+ title: actionTypeLabel[actionType],
+ icon: actionIcon[actionType],
+ onClick: () => openDialog({ actionType }),
+ })),
+ ]}
>
- {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 alert 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>
- </>
+ {({ getTriggerProps }) => (
+ <Button
+ variant="outline"
+ size="lg"
+ disabled={isDisabled}
+ className={fullWidth ? "w-full" : undefined}
+ {...getTriggerProps()}
+ >
+ <Plus size="base" color="default" __rawClassName="mr-2" />
+ Automation
+ </Button>
)}
- </DialogContent>
- </Dialog>
- </>
+ </DropdownMenu>
+ )}
+ </NewMonitorAutomationDialogController>
);
};
diff --git a/web/src/features/monitors/components/MonitorsOnboarding.clienttest.tsx b/web/src/features/monitors/components/MonitorsOnboarding.clienttest.tsx
index fe1be4b296..fb954e7d5a 100644
--- a/web/src/features/monitors/components/MonitorsOnboarding.clienttest.tsx
+++ b/web/src/features/monitors/components/MonitorsOnboarding.clienttest.tsx
@@ -1,10 +1,21 @@
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import { type Session } from "next-auth";
import type * as EnvModule from "@/src/env.mjs";
import { MonitorsOnboarding } from "./MonitorsOnboarding";
+vi.mock(
+ "@/src/features/monitors/automations/ConnectedNewMonitorAutomationDialog",
+ () => ({
+ ConnectedNewMonitorAutomationDialog: ({
+ lockedActionType,
+ }: {
+ lockedActionType?: string;
+ }) => <p>New {lockedActionType} automation dialog</p>,
+ }),
+);
+
const sessionMock = vi.hoisted(() => ({ data: null as Session | null }));
vi.mock("next-auth/react", () => ({
useSession: () => ({ data: sessionMock.data, status: "authenticated" }),
@@ -26,26 +37,15 @@ vi.mock("@/src/env.mjs", async (importOriginal) => {
/** signIn sets the session user's admin flag and the deployment's Cloud region. */
const signIn = ({ admin, region }: { admin: boolean; region?: string }) => {
- sessionMock.data = { expires: "1", user: { admin } } as unknown as Session;
+ sessionMock.data = {
+ expires: "1",
+ user: { admin, organizations: [] },
+ } as unknown as Session;
cloudRegion.value = region;
};
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", () => {
afterEach(() => {
sessionMock.data = null;
@@ -64,20 +64,21 @@ describe("MonitorsOnboarding", () => {
expect(screen.getByText("Decide what to monitor")).toBeInTheDocument();
expect(
- screen.getByRole("link", { name: /Connect Slack/i }),
+ screen.getByRole("button", { name: /Connect Slack/i }),
).toBeInTheDocument();
expect(
- screen.getByRole("link", { name: /Connect Webhooks/i }),
+ screen.getByRole("button", { name: /Connect Webhooks/i }),
).toBeInTheDocument();
expect(
- screen.getByRole("link", { name: /Connect Github Actions/i }),
+ screen.getByRole("button", { name: /Connect Github Actions/i }),
).toBeInTheDocument();
expect(
screen.getByRole("link", { name: /Create Alert/i }),
).toBeInTheDocument();
});
- it("links each channel button to /automations?view=create with the matching prefill actionType", () => {
+ it("opens the new automation dialog locked to each clicked channel, without leaving the page", () => {
+ signIn({ admin: true });
render(<MonitorsOnboarding projectId={PROJECT_ID} hasCUDAccess={true} />);
const cases: Array<{ label: RegExp; expected: string }> = [
@@ -87,16 +88,21 @@ describe("MonitorsOnboarding", () => {
];
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}/alerts`);
+ fireEvent.click(screen.getByRole("button", { name: label }));
+ expect(
+ screen.getByText(`New ${expected} automation dialog`),
+ ).toBeInTheDocument();
}
+ expect(document.querySelector('a[href*="/automations"]')).toBeNull();
+ });
+
+ it("disables the channel buttons for users who cannot create automations", () => {
+ signIn({ admin: false });
+ render(<MonitorsOnboarding projectId={PROJECT_ID} hasCUDAccess={true} />);
+
+ expect(
+ screen.getByRole("button", { name: /Connect Slack/i }),
+ ).toBeDisabled();
});
it("hides the PagerDuty CTA from users who are not admins", () => {
@@ -104,7 +110,7 @@ describe("MonitorsOnboarding", () => {
render(<MonitorsOnboarding projectId={PROJECT_ID} hasCUDAccess={true} />);
expect(
- screen.queryByRole("link", { name: /Connect PagerDuty/i }),
+ screen.queryByRole("button", { name: /Connect PagerDuty/i }),
).not.toBeInTheDocument();
});
@@ -113,7 +119,7 @@ describe("MonitorsOnboarding", () => {
render(<MonitorsOnboarding projectId={PROJECT_ID} hasCUDAccess={true} />);
expect(
- screen.queryByRole("link", { name: /Connect PagerDuty/i }),
+ screen.queryByRole("button", { name: /Connect PagerDuty/i }),
).not.toBeInTheDocument();
});
@@ -121,11 +127,12 @@ describe("MonitorsOnboarding", () => {
signIn({ admin: true, region: "EU" });
render(<MonitorsOnboarding projectId={PROJECT_ID} hasCUDAccess={true} />);
- const link = screen.getByRole("link", { name: /Connect PagerDuty/i });
- expect(link).not.toHaveTextContent("Internal");
- expect(parsePrefill(link.getAttribute("href")!).actionType).toBe(
- "PAGERDUTY",
- );
+ const button = screen.getByRole("button", { name: /Connect PagerDuty/i });
+ expect(button).not.toHaveTextContent("Internal");
+ fireEvent.click(button);
+ expect(
+ screen.getByText("New PAGERDUTY automation dialog"),
+ ).toBeInTheDocument();
});
it("links the Create Alert CTA to the project's new-alert route", () => {
diff --git a/web/src/features/monitors/components/MonitorsOnboarding.tsx b/web/src/features/monitors/components/MonitorsOnboarding.tsx
index 9a0033f214..2a52140386 100644
--- a/web/src/features/monitors/components/MonitorsOnboarding.tsx
+++ b/web/src/features/monitors/components/MonitorsOnboarding.tsx
@@ -1,4 +1,3 @@
-import Link from "next/link";
import { Github, Plus, Slack, Webhook } from "@langfuse/icons";
import { SiPagerduty } from "@langfuse/icons/si";
import { DropdownIndicator } from "@/src/components/design-system/DropdownIndicator/DropdownIndicator";
@@ -6,10 +5,9 @@ import { DropdownIndicator } from "@/src/components/design-system/DropdownIndica
import { ActionButton } from "@/src/components/ActionButton";
import { Button } from "@/src/components/ui/button";
import { SplashScreen } from "@/src/components/ui/SplashScreen";
-import {
- automationCreateHref,
- useAvailableActionTypes,
-} from "@/src/features/automations";
+import { useAvailableActionTypes } from "@/src/features/automations";
+import { NewMonitorAutomationDialogController } from "@/src/features/monitors/automations/NewMonitorAutomationDialogController";
+import { useHasProjectAccess } from "@/src/features/rbac";
import { type ActionTypes } from "@langfuse/shared";
/** OnboardingChannel describes one notification-channel CTA shown in step 1 of the splash. */
@@ -68,31 +66,10 @@ export function MonitorsOnboarding({
title: "Choose where alerts should go",
description: channelsDescription(actionTypes),
content: (
- <div className="flex flex-col gap-2">
- {visibleChannels.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}/alerts`,
- )}
- >
- <span className="flex items-center gap-2">
- {channel.icon}
- {channel.label}
- </span>
- <DropdownIndicator direction="right" />
- </Link>
- </Button>
- ))}
- </div>
+ <ChannelButtons
+ projectId={projectId}
+ channels={visibleChannels}
+ />
),
},
{
@@ -117,6 +94,45 @@ export function MonitorsOnboarding({
);
}
+/** ChannelButtons opens the new automation dialog locked to the chosen channel. */
+function ChannelButtons({
+ projectId,
+ channels,
+}: {
+ projectId: string;
+ channels: OnboardingChannel[];
+}) {
+ const hasAutomationAccess = useHasProjectAccess({
+ projectId,
+ scope: "automations:CUD",
+ });
+
+ return (
+ <NewMonitorAutomationDialogController projectId={projectId}>
+ {({ openDialog }) => (
+ <div className="flex flex-col gap-2">
+ {channels.map((channel) => (
+ <Button
+ key={channel.actionType}
+ variant="outline"
+ size="lg"
+ className="w-full justify-between gap-2 px-6 py-5"
+ disabled={!hasAutomationAccess}
+ onClick={() => openDialog({ actionType: channel.actionType })}
+ >
+ <span className="flex items-center gap-2">
+ {channel.icon}
+ {channel.label}
+ </span>
+ <DropdownIndicator direction="right" />
+ </Button>
+ ))}
+ </div>
+ )}
+ </NewMonitorAutomationDialogController>
+ );
+}
+
/** channelsDescription names the channels the user can connect. */
function channelsDescription(actionTypes: ActionTypes[]): string {
if (actionTypes.includes("PAGERDUTY")) {
diff --git a/web/src/features/pagerduty/components/PagerDutyTestEventButtons.tsx b/web/src/features/pagerduty/components/PagerDutyTestEventButtons.tsx
index 03b997366f..9be137cb46 100644
--- a/web/src/features/pagerduty/components/PagerDutyTestEventButtons.tsx
+++ b/web/src/features/pagerduty/components/PagerDutyTestEventButtons.tsx
@@ -1,15 +1,6 @@
-import { useState } from "react";
-import { CircleCheck, Send } from "@langfuse/icons";
-
import { type PagerDutyRegion } from "@langfuse/shared/pagerduty";
-import { Button } from "@/src/components/design-system/Button/Button";
-import { showSuccessToast } from "@/src/features/notifications";
-import { useHasProjectAccess } from "@/src/features/rbac";
-import { api } from "@/src/utils/api";
-import {
- PagerDutyTestEventDialogController,
- type PagerDutyTestEventTarget,
-} from "./PagerDutyTestEventDialogController";
+import { usePagerDutyTestEvent } from "../hooks/usePagerDutyTestEvent";
+import { PagerDutyTestEventButtonsView } from "./PagerDutyTestEventButtonsView";
/** PagerDutyTestEventButtons triggers a critical test alert, then offers to resolve it. */
export function PagerDutyTestEventButtons({
@@ -25,111 +16,13 @@ export function PagerDutyTestEventButtons({
actionId: string | undefined;
disabled?: boolean;
}) {
- const hasAccess = useHasProjectAccess({
- projectId,
- scope: "automations:CUD",
- });
- const [isTestAlertOpen, setIsTestAlertOpen] = useState(false);
- const isDisabled = disabled || !hasAccess || !(routingKey || actionId);
- const target = { region, routingKey, actionId };
+ const testEvent = usePagerDutyTestEvent(projectId);
return (
- <PagerDutyTestEventDialogController
- projectId={projectId}
- onSent={() => setIsTestAlertOpen(true)}
- >
- {({ openDialog }) => (
- <TestEventButton
- projectId={projectId}
- target={target}
- disabled={isDisabled}
- isTestAlertOpen={isTestAlertOpen}
- onSend={() => openDialog(target)}
- onResolved={() => setIsTestAlertOpen(false)}
- />
- )}
- </PagerDutyTestEventDialogController>
- );
-}
-
-/** TestEventButton shows the send button, or the resolve button while the test alert is open. */
-function TestEventButton({
- projectId,
- target,
- disabled,
- isTestAlertOpen,
- onSend,
- onResolved,
-}: {
- projectId: string;
- target: PagerDutyTestEventTarget;
- disabled: boolean;
- isTestAlertOpen: boolean;
- onSend: () => void;
- onResolved: () => void;
-}) {
- if (isTestAlertOpen) {
- return (
- <ResolveTestEventButton
- projectId={projectId}
- target={target}
- disabled={disabled}
- onResolved={onResolved}
- />
- );
- }
- return (
- <Button
- type="button"
- text="Send test event"
- variant="secondary"
- size="sm"
- icon={Send}
+ <PagerDutyTestEventButtonsView
+ target={{ region, routingKey, actionId }}
+ testEvent={testEvent}
disabled={disabled}
- onClick={onSend}
/>
);
}
-
-/** ResolveTestEventButton resolves the open test alert. */
-function ResolveTestEventButton({
- projectId,
- target,
- disabled,
- onResolved,
-}: {
- projectId: string;
- target: PagerDutyTestEventTarget;
- disabled: boolean;
- onResolved: () => void;
-}) {
- const resolveTestEvent = useResolveTestEvent(onResolved);
-
- return (
- <Button
- type="button"
- text="Resolve test event"
- variant="secondary"
- size="sm"
- icon={CircleCheck}
- disabled={disabled || resolveTestEvent.isPending}
- onClick={() =>
- resolveTestEvent.mutate({ projectId, ...target, step: "resolve" })
- }
- />
- );
-}
-
-/** useResolveTestEvent resolves the test alert and reports it. */
-function useResolveTestEvent(onResolved: () => void) {
- return api.automations.sendPagerDutyTestEvent.useMutation({
- onSuccess: () => {
- onResolved();
- showSuccessToast({
- operation: "automations.sendPagerDutyTestEvent",
- title: "Test event resolved",
- description: "PagerDuty accepted the resolve of the test alert.",
- });
- },
- });
-}
diff --git a/web/src/features/pagerduty/components/PagerDutyTestEventButtonsView.tsx b/web/src/features/pagerduty/components/PagerDutyTestEventButtonsView.tsx
new file mode 100644
index 0000000000..4b75c0c1be
--- /dev/null
+++ b/web/src/features/pagerduty/components/PagerDutyTestEventButtonsView.tsx
@@ -0,0 +1,73 @@
+import { CircleCheck, Send } from "@langfuse/icons";
+
+import { Button } from "@/src/components/design-system/Button/Button";
+import {
+ type PagerDutyTestEventState,
+ type PagerDutyTestEventTarget,
+} from "../hooks/usePagerDutyTestEvent";
+import { PagerDutyTestEventDialogController } from "./PagerDutyTestEventDialogController";
+
+/** PagerDutyTestEventButtonsView sends a critical test alert after a warning, then offers to resolve it. */
+export function PagerDutyTestEventButtonsView({
+ target,
+ testEvent,
+ disabled = false,
+}: {
+ target: PagerDutyTestEventTarget;
+ testEvent: PagerDutyTestEventState;
+ disabled?: boolean;
+}) {
+ const isDisabled =
+ disabled || !testEvent.canSend || !(target.routingKey || target.actionId);
+
+ return (
+ <PagerDutyTestEventDialogController testEvent={testEvent}>
+ {({ openDialog }) => (
+ <TestEventButton
+ target={target}
+ testEvent={testEvent}
+ disabled={isDisabled}
+ onSend={() => openDialog(target)}
+ />
+ )}
+ </PagerDutyTestEventDialogController>
+ );
+}
+
+/** TestEventButton shows the send button, or the resolve button while the test alert is open. */
+function TestEventButton({
+ target,
+ testEvent,
+ disabled,
+ onSend,
+}: {
+ target: PagerDutyTestEventTarget;
+ testEvent: PagerDutyTestEventState;
+ disabled: boolean;
+ onSend: () => void;
+}) {
+ if (testEvent.isTestAlertOpen) {
+ return (
+ <Button
+ type="button"
+ text="Resolve test event"
+ variant="secondary"
+ size="sm"
+ icon={CircleCheck}
+ disabled={disabled || testEvent.isResolving}
+ onClick={() => testEvent.onResolve(target)}
+ />
+ );
+ }
+ return (
+ <Button
+ type="button"
+ text="Send test event"
+ variant="secondary"
+ size="sm"
+ icon={Send}
+ disabled={disabled}
+ onClick={onSend}
+ />
+ );
+}
diff --git a/web/src/features/pagerduty/components/PagerDutyTestEventDialogController.tsx b/web/src/features/pagerduty/components/PagerDutyTestEventDialogController.tsx
index 665d9a68e5..6b92ab1360 100644
--- a/web/src/features/pagerduty/components/PagerDutyTestEventDialogController.tsx
+++ b/web/src/features/pagerduty/components/PagerDutyTestEventDialogController.tsx
@@ -1,55 +1,33 @@
import { type ReactNode } from "react";
-import { type PagerDutyRegion } from "@langfuse/shared/pagerduty";
import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";
-import { showSuccessToast } from "@/src/features/notifications";
-import { api } from "@/src/utils/api";
+import {
+ type PagerDutyTestEventState,
+ type PagerDutyTestEventTarget,
+} from "../hooks/usePagerDutyTestEvent";
/** PagerDutyTestEventDialogController warns that a test alert pages whoever is on call, then triggers it. */
export function PagerDutyTestEventDialogController({
- projectId,
- onSent,
+ testEvent,
children,
}: {
- projectId: string;
- onSent: () => void;
+ testEvent: PagerDutyTestEventState;
children: (control: {
openDialog: (target: PagerDutyTestEventTarget) => void;
}) => ReactNode;
}) {
- const sendTestEvent = api.automations.sendPagerDutyTestEvent.useMutation({
- meta: { silentAllErrors: true },
- });
-
- const handleConfirm = async (target: PagerDutyTestEventTarget) => {
- await sendTestEvent.mutateAsync({ projectId, ...target, step: "trigger" });
- onSent();
- showSuccessToast({
- operation: "automations.sendPagerDutyTestEvent",
- title: "Test event sent",
- description: "PagerDuty accepted the critical test alert.",
- });
- };
-
return (
<ConfirmationDialogController<PagerDutyTestEventTarget>
title="Send PagerDuty test event"
text="This triggers a real critical test alert on the PagerDuty service and pages whoever is on call. Resolve it here once it arrives."
confirmLabel="Send test event"
variant="default"
- loading={sendTestEvent.isPending}
- error={sendTestEvent.error?.message}
- onAfterDismiss={() => sendTestEvent.reset()}
- onConfirm={handleConfirm}
+ loading={testEvent.isSending}
+ error={testEvent.sendError}
+ onAfterDismiss={testEvent.onResetSend}
+ onConfirm={testEvent.onSend}
>
{({ openDialog }) => children({ openDialog })}
</ConfirmationDialogController>
);
}
-
-/** PagerDutyTestEventTarget is the key a test event goes to: the typed key, else the action's stored key. */
-export type PagerDutyTestEventTarget = {
- region: PagerDutyRegion;
- routingKey?: string;
- actionId?: string;
-};
diff --git a/web/src/features/pagerduty/hooks/usePagerDutyTestEvent.ts b/web/src/features/pagerduty/hooks/usePagerDutyTestEvent.ts
new file mode 100644
index 0000000000..5ff1ed0ddf
--- /dev/null
+++ b/web/src/features/pagerduty/hooks/usePagerDutyTestEvent.ts
@@ -0,0 +1,73 @@
+import { useState } from "react";
+
+import { type PagerDutyRegion } from "@langfuse/shared/pagerduty";
+import { showSuccessToast } from "@/src/features/notifications";
+import { useHasProjectAccess } from "@/src/features/rbac";
+import { api } from "@/src/utils/api";
+
+/** usePagerDutyTestEvent triggers a critical test alert for the project and resolves it once it is open. */
+export function usePagerDutyTestEvent(
+ projectId: string,
+): PagerDutyTestEventState {
+ const canSend = useHasProjectAccess({
+ projectId,
+ scope: "automations:CUD",
+ });
+ const [isTestAlertOpen, setIsTestAlertOpen] = useState(false);
+ const sendTestEvent = api.automations.sendPagerDutyTestEvent.useMutation({
+ meta: { silentAllErrors: true },
+ });
+ const resolveTestEvent = api.automations.sendPagerDutyTestEvent.useMutation({
+ onSuccess: () => {
+ setIsTestAlertOpen(false);
+ showSuccessToast({
+ operation: "automations.sendPagerDutyTestEvent",
+ title: "Test event resolved",
+ description: "PagerDuty accepted the resolve of the test alert.",
+ });
+ },
+ });
+
+ return {
+ canSend,
+ isTestAlertOpen,
+ isSending: sendTestEvent.isPending,
+ sendError: sendTestEvent.error?.message,
+ onSend: async (target) => {
+ await sendTestEvent.mutateAsync({
+ projectId,
+ ...target,
+ step: "trigger",
+ });
+ setIsTestAlertOpen(true);
+ showSuccessToast({
+ operation: "automations.sendPagerDutyTestEvent",
+ title: "Test event sent",
+ description: "PagerDuty accepted the critical test alert.",
+ });
+ },
+ onResetSend: () => sendTestEvent.reset(),
+ isResolving: resolveTestEvent.isPending,
+ onResolve: (target) =>
+ resolveTestEvent.mutate({ projectId, ...target, step: "resolve" }),
+ };
+}
+
+/** PagerDutyTestEventTarget is the key a test event goes to: the typed key, else the action's stored key. */
+export type PagerDutyTestEventTarget = {
+ region: PagerDutyRegion;
+ routingKey?: string;
+ actionId?: string;
+};
+
+/** PagerDutyTestEventState is what the test event buttons show and do. */
+export type PagerDutyTestEventState = {
+ canSend: boolean;
+ isTestAlertOpen: boolean;
+ isSending: boolean;
+ sendError: string | undefined;
+ onSend: (target: PagerDutyTestEventTarget) => Promise<void>;
+ onResetSend: () => void;
+ isResolving: boolean;
+ onResolve: (target: PagerDutyTestEventTarget) => void;
+};
diff --git a/web/src/features/pagerduty/index.ts b/web/src/features/pagerduty/index.ts
index b957da4e0a..6dcd4fff48 100644
--- a/web/src/features/pagerduty/index.ts
+++ b/web/src/features/pagerduty/index.ts
@@ -1 +1,6 @@
export { PagerDutyActionForm } from "@/src/features/pagerduty/components/PagerDutyActionForm";
+export { PagerDutyTestEventButtonsView } from "@/src/features/pagerduty/components/PagerDutyTestEventButtonsView";
+export {
+ usePagerDutyTestEvent,
+ type PagerDutyTestEventState,
+} from "@/src/features/pagerduty/hooks/usePagerDutyTestEvent";
diff --git a/web/src/features/projects/ProjectSettingsPage.tsx b/web/src/features/projects/ProjectSettingsPage.tsx
index 54d4debea0..ceb5578fe0 100644
--- a/web/src/features/projects/ProjectSettingsPage.tsx
+++ b/web/src/features/projects/ProjectSettingsPage.tsx
@@ -51,7 +51,7 @@ import { usePostHogIntegration } from "@/src/features/posthog-integration/usePos
import { useMixpanelIntegration } from "@/src/features/mixpanel-integration/useMixpanelIntegration";
import { useBlobStorageIntegration } from "@/src/features/blobstorage-integration/useBlobStorageIntegration";
import { useExternalMediaStorage } from "@/src/features/external-media-storage/useExternalMediaStorage";
-import { useSlackIntegration } from "@/src/features/slack/useSlackIntegration";
+import { useSlackIntegration } from "@/src/features/slack/hooks/useSlackIntegration";
type ProjectSettingsPageEntry = {
title: string;
diff --git a/web/src/features/slack/SlackIntegrationPage.tsx b/web/src/features/slack/SlackIntegrationPage.tsx
index 46eb1dd799..e8e3f63358 100644
--- a/web/src/features/slack/SlackIntegrationPage.tsx
+++ b/web/src/features/slack/SlackIntegrationPage.tsx
@@ -8,7 +8,7 @@ import {
} from "@/src/features/slack/components/ChannelSelector";
import { SlackTestMessageButton } from "@/src/features/slack/components/SlackTestMessageButton";
import { PrivateChannelsInfoTooltip } from "@/src/features/slack/components/PrivateChannelsInfoTooltip";
-import { useSlackIntegration } from "@/src/features/slack/useSlackIntegration";
+import { useSlackIntegration } from "@/src/features/slack/hooks/useSlackIntegration";
import { useRouter } from "next/router";
import { useState, useEffect } from "react";
import { Badge } from "@/src/components/design-system/Badge/Badge";
diff --git a/web/src/features/slack/components/ChannelSelector.tsx b/web/src/features/slack/components/ChannelSelector.tsx
index 39d4f54ef6..ba07770fda 100644
--- a/web/src/features/slack/components/ChannelSelector.tsx
+++ b/web/src/features/slack/components/ChannelSelector.tsx
@@ -1,9 +1,6 @@
-/* eslint-disable @typescript-eslint/no-use-before-define */
-import React, { useState, useMemo, useEffect } from "react";
-import { api, reportNonTrpcError } from "@/src/utils/api";
-import { env } from "@/src/env.mjs";
+import React from "react";
import { type SlackChannel } from "@langfuse/shared/src/server";
-import { useHasProjectAccess } from "@/src/features/rbac";
+import { useChannelSelectorData } from "@/src/features/slack/hooks/useChannelSelectorData";
import {
ChannelSelectorView,
type ChannelSelectorViewProps,
@@ -24,8 +21,6 @@ type ChannelSelectorProps = {
| "onReauthenticate"
>;
-const MAX_SLACK_CHANNEL_PAGES = 20;
-
/**
* ChannelSelector loads the project's Slack channels and renders them in
* ChannelSelectorView.
@@ -34,101 +29,13 @@ export const ChannelSelector: React.FC<ChannelSelectorProps> = ({
projectId,
...viewProps
}) => {
- const [isRefreshing, setIsRefreshing] = useState(false);
- // Read-only roles still see the saved channel via `selectedChannel`, but
- // may not enumerate every channel the bot can see.
- const canListChannels = useHasProjectAccess({
- projectId,
- scope: "automations:CUD",
- });
- const canManageIntegration = useHasProjectAccess({
- projectId,
- scope: "integrations:CRUD",
- });
- const { channelsData, isLoadingChannels, error, refetchChannels } =
- useSlackChannels(projectId, canListChannels);
-
- const handleRefresh = async () => {
- setIsRefreshing(true);
- try {
- await refetchChannels();
- } finally {
- setIsRefreshing(false);
- }
- };
-
- const handleReauthenticate = () => {
- window.open(
- `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/public/slack/install?projectId=${projectId}`,
- "slack-reauth",
- "width=600,height=700",
- );
- };
+ const { canListChannels, ...data } = useChannelSelectorData(projectId);
return (
<ChannelSelectorView
{...viewProps}
+ {...data}
disabled={viewProps.disabled || !canListChannels}
- channelsData={channelsData}
- isLoading={isLoadingChannels}
- hasError={!!error}
- isRefreshing={isRefreshing}
- onRefresh={handleRefresh}
- onReauthenticate={canManageIntegration ? handleReauthenticate : undefined}
/>
);
};
-
-const useSlackChannels = (projectId: string, enabled: boolean) => {
- const {
- data: channelsPages,
- isLoading,
- isFetching,
- isFetchingNextPage,
- hasNextPage,
- fetchNextPage,
- error,
- refetch: refetchChannels,
- } = api.slack.getChannels.useInfiniteQuery(
- { projectId },
- {
- enabled: !!projectId && enabled,
- getNextPageParam: (lastPage, allPages) =>
- allPages.length >= MAX_SLACK_CHANNEL_PAGES
- ? undefined
- : lastPage.nextCursor,
- staleTime: 5 * 60 * 1000,
- },
- );
-
- const channelsData = useMemo(() => {
- const pages = channelsPages?.pages ?? [];
- if (pages.length === 0) return null;
-
- return {
- channels: pages.flatMap((page) => page.channels),
- hasPrivateChannelAccess: pages.every(
- (page) => page.hasPrivateChannelAccess,
- ),
- };
- }, [channelsPages?.pages]);
-
- const isLoadingChannels =
- isLoading || isFetchingNextPage || (isFetching && !channelsData);
-
- // useInfiniteQuery stores page state, but next pages are only loaded when requested.
- useEffect(() => {
- if (error || !hasNextPage || isFetchingNextPage) return;
-
- // Query failures are classified + captured by the QueryCache seam; only
- // report non-tRPC failures of the fetch dispatch itself.
- fetchNextPage().catch((error) => reportNonTrpcError(error, "slack"));
- }, [error, fetchNextPage, hasNextPage, isFetchingNextPage]);
-
- return {
- channelsData,
- isLoadingChannels,
- error,
- refetchChannels,
- };
-};
diff --git a/web/src/features/slack/components/SlackConnectButton.tsx b/web/src/features/slack/components/SlackConnectButton.tsx
index fdf46a2c50..3010f0a955 100644
--- a/web/src/features/slack/components/SlackConnectButton.tsx
+++ b/web/src/features/slack/components/SlackConnectButton.tsx
@@ -1,8 +1,7 @@
-import React, { useState, useEffect, useRef } from "react";
+import React from "react";
import { Button, type ButtonProps } from "@/src/components/ui/button";
import { SiSlack } from "@langfuse/icons/si";
-import { api } from "@/src/utils/api";
-import { showSuccessToast, showErrorToast } from "@/src/features/notifications";
+import { useSlackConnect } from "@/src/features/slack/hooks/useSlackConnect";
/**
* Props for the SlackConnectButton component
@@ -42,155 +41,16 @@ export const SlackConnectButton: React.FC<SlackConnectButtonProps> = ({
onError,
showText = true,
}) => {
- const [isConnecting, setIsConnecting] = useState(false);
- const popupRef = useRef<Window | null>(null);
- const intervalRef = useRef<NodeJS.Timeout | null>(null);
- const messageHandlerRef = useRef<((event: MessageEvent) => void) | null>(
- null,
- );
-
- // Get integration status
- const { data: integrationStatus } = api.slack.getIntegrationStatus.useQuery(
- { projectId },
- { enabled: !!projectId },
- );
-
- // Cleanup effect for component unmount
- useEffect(() => {
- return () => {
- // Clean up popup if it's still open
- if (popupRef.current && !popupRef.current.closed) {
- popupRef.current.close();
- }
-
- // Clean up interval
- if (intervalRef.current) {
- clearInterval(intervalRef.current);
- }
-
- // Clean up event listener
- if (messageHandlerRef.current) {
- window.removeEventListener("message", messageHandlerRef.current);
- }
- };
- }, []);
-
- // Handle connect button click
- const handleConnect = async () => {
- if (!integrationStatus?.installUrl) {
- const errorMessage = "Install URL not available. Please try again.";
- onError?.(new Error(errorMessage));
- showErrorToast("Connection Failed", errorMessage, {
- operation: "slack.connect",
- errorOrigin: "backend",
- errorCategory: "product_state",
- });
- return;
- }
-
- setIsConnecting(true);
-
- try {
- // Open OAuth flow in popup window
- const popup = window.open(
- integrationStatus.installUrl,
- "slack-oauth",
- "width=600,height=700,scrollbars=yes,resizable=yes",
- );
-
- if (!popup) {
- throw new Error("Popup blocked. Please allow popups and try again.");
- }
-
- // Store popup reference
- popupRef.current = popup;
-
- // Listen for messages from popup
- const handleMessage = (event: MessageEvent) => {
- // Verify origin for security
- if (event.origin !== window.location.origin) {
- return;
- }
-
- if (event.data.type === "slack-oauth-success") {
- popup.close();
- setIsConnecting(false);
-
- showSuccessToast({
- operation: "slack.connect",
- title: "Slack Connected",
- description: `Successfully connected to ${event.data.teamName}.`,
- });
-
- onSuccess?.();
-
- // Clean up event listener and interval
- window.removeEventListener("message", handleMessage);
- if (intervalRef.current) {
- clearInterval(intervalRef.current);
- intervalRef.current = null;
- }
- popupRef.current = null;
- messageHandlerRef.current = null;
- } else if (event.data.type === "slack-oauth-error") {
- popup.close();
- setIsConnecting(false);
-
- showErrorToast("Connection Failed", event.data.error, {
- operation: "slack.connect",
- errorOrigin: "backend",
- errorCategory: "internal",
- });
- onError?.(new Error(event.data.error));
-
- // Clean up event listener and interval
- window.removeEventListener("message", handleMessage);
- if (intervalRef.current) {
- clearInterval(intervalRef.current);
- intervalRef.current = null;
- }
- popupRef.current = null;
- messageHandlerRef.current = null;
- }
- };
-
- // Store message handler reference
- messageHandlerRef.current = handleMessage;
-
- // Add message listener
- window.addEventListener("message", handleMessage);
-
- // Also listen for popup being closed manually
- const checkClosed = setInterval(() => {
- if (popup.closed) {
- setIsConnecting(false);
- window.removeEventListener("message", handleMessage);
- clearInterval(checkClosed);
- popupRef.current = null;
- messageHandlerRef.current = null;
- intervalRef.current = null;
- }
- }, 1000);
-
- // Store interval reference
- intervalRef.current = checkClosed;
- } catch (error) {
- setIsConnecting(false);
- const errorMessage =
- error instanceof Error ? error.message : "Failed to connect to Slack";
- onError?.(new Error(errorMessage));
- showErrorToast("Connection Failed", errorMessage, {
- operation: "slack.connect",
- errorOrigin: "frontend",
- errorCategory: "product_state",
- });
- }
- };
+ const { connect, isConnecting, canConnect } = useSlackConnect({
+ projectId,
+ onSuccess,
+ onError,
+ });
return (
<Button
- onClick={handleConnect}
- disabled={disabled || isConnecting || !integrationStatus?.installUrl}
+ onClick={connect}
+ disabled={disabled || isConnecting || !canConnect}
variant={variant}
size={size}
className="flex items-center gap-2"
diff --git a/web/src/features/slack/components/SlackTestMessageButton.tsx b/web/src/features/slack/components/SlackTestMessageButton.tsx
index e5fcf9a443..1e27504842 100644
--- a/web/src/features/slack/components/SlackTestMessageButton.tsx
+++ b/web/src/features/slack/components/SlackTestMessageButton.tsx
@@ -1,10 +1,8 @@
import React from "react";
import { Button, type ButtonProps } from "@/src/components/ui/button";
import { Zap } from "@langfuse/icons";
-import { api } from "@/src/utils/api";
-import { showSuccessToast, showErrorToast } from "@/src/features/notifications";
import { type SlackChannel } from "./ChannelSelector";
-import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
+import { useSlackTestMessage } from "@/src/features/slack/hooks/useSlackTestMessage";
/**
* Props for the SlackTestMessageButton component
@@ -54,44 +52,19 @@ export const SlackTestMessageButton: React.FC<SlackTestMessageButtonProps> = ({
showText = true,
hasAccess = true,
}) => {
- // Test message mutation
- const testMessageMutation = api.slack.sendTestMessage.useMutation({
- onSuccess: (data) => {
- showSuccessToast({
- operation: "slack.test_message_send",
- title: "Test Message Sent",
- description: "Test message sent successfully to the selected channel.",
- });
- onSuccess?.(data.channelInfo);
- },
- onError: (error) => {
- showErrorToast(
- "Failed to Send Test Message",
- error.message,
- classifyTrpcToastError(error, "slack.test_message_send"),
- );
- onError?.(new Error(error.message));
- },
+ const { sendTestMessage, isPending } = useSlackTestMessage({
+ projectId,
+ onSuccess,
+ onError,
});
- // Handle test message
const handleTestMessage = async () => {
if (!selectedChannel) return;
-
- try {
- await testMessageMutation.mutateAsync({
- projectId,
- channelId: selectedChannel.id,
- channelName: selectedChannel.name ?? undefined,
- });
- } catch {
- // Error handling is done in the mutation
- }
+ await sendTestMessage(selectedChannel);
};
// Determine if button should be disabled
- const isDisabled =
- disabled || !hasAccess || testMessageMutation.isPending || !selectedChannel;
+ const isDisabled = disabled || !hasAccess || isPending || !selectedChannel;
return (
<Button
@@ -101,7 +74,7 @@ export const SlackTestMessageButton: React.FC<SlackTestMessageButtonProps> = ({
size={size}
className="flex items-center gap-2"
>
- {testMessageMutation.isPending ? (
+ {isPending ? (
<>
<div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
{showText && <span>Sending...</span>}
diff --git a/web/src/features/slack/hooks/useChannelSelectorData.ts b/web/src/features/slack/hooks/useChannelSelectorData.ts
new file mode 100644
index 0000000000..2042afc6c6
--- /dev/null
+++ b/web/src/features/slack/hooks/useChannelSelectorData.ts
@@ -0,0 +1,49 @@
+import { useState } from "react";
+
+import { env } from "@/src/env.mjs";
+import { useHasProjectAccess } from "@/src/features/rbac";
+import { useSlackChannels } from "@/src/features/slack/hooks/useSlackChannels";
+
+/** useChannelSelectorData loads the channel list and the refresh/reauthenticate actions ChannelSelectorView needs. */
+export function useChannelSelectorData(projectId: string, isEnabled = true) {
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ // Read-only roles still see the saved channel via `selectedChannel`, but
+ // may not enumerate every channel the bot can see.
+ const canListChannels = useHasProjectAccess({
+ projectId,
+ scope: "automations:CUD",
+ });
+ const canManageIntegration = useHasProjectAccess({
+ projectId,
+ scope: "integrations:CRUD",
+ });
+ const { channelsData, isLoadingChannels, error, refetchChannels } =
+ useSlackChannels(projectId, canListChannels && isEnabled);
+
+ const handleRefresh = async () => {
+ setIsRefreshing(true);
+ try {
+ await refetchChannels();
+ } finally {
+ setIsRefreshing(false);
+ }
+ };
+
+ const handleReauthenticate = () => {
+ window.open(
+ `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/public/slack/install?projectId=${projectId}`,
+ "slack-reauth",
+ "width=600,height=700",
+ );
+ };
+
+ return {
+ canListChannels,
+ channelsData,
+ isLoading: isLoadingChannels,
+ hasError: !!error,
+ isRefreshing,
+ onRefresh: handleRefresh,
+ onReauthenticate: canManageIntegration ? handleReauthenticate : undefined,
+ };
+}
diff --git a/web/src/features/slack/hooks/useSlackChannels.ts b/web/src/features/slack/hooks/useSlackChannels.ts
new file mode 100644
index 0000000000..ba7d545a83
--- /dev/null
+++ b/web/src/features/slack/hooks/useSlackChannels.ts
@@ -0,0 +1,60 @@
+import { useEffect, useMemo } from "react";
+
+import { api, reportNonTrpcError } from "@/src/utils/api";
+
+const MAX_SLACK_CHANNEL_PAGES = 20;
+
+/** useSlackChannels loads every channel page the Slack bot can see for a project. */
+export const useSlackChannels = (projectId: string, enabled: boolean) => {
+ const {
+ data: channelsPages,
+ isLoading,
+ isFetching,
+ isFetchingNextPage,
+ hasNextPage,
+ fetchNextPage,
+ error,
+ refetch: refetchChannels,
+ } = api.slack.getChannels.useInfiniteQuery(
+ { projectId },
+ {
+ enabled: !!projectId && enabled,
+ getNextPageParam: (lastPage, allPages) =>
+ allPages.length >= MAX_SLACK_CHANNEL_PAGES
+ ? undefined
+ : lastPage.nextCursor,
+ staleTime: 5 * 60 * 1000,
+ },
+ );
+
+ const channelsData = useMemo(() => {
+ const pages = channelsPages?.pages ?? [];
+ if (pages.length === 0) return null;
+
+ return {
+ channels: pages.flatMap((page) => page.channels),
+ hasPrivateChannelAccess: pages.every(
+ (page) => page.hasPrivateChannelAccess,
+ ),
+ };
+ }, [channelsPages?.pages]);
+
+ const isLoadingChannels =
+ isLoading || isFetchingNextPage || (isFetching && !channelsData);
+
+ // useInfiniteQuery stores page state, but next pages are only loaded when requested.
+ useEffect(() => {
+ if (error || !hasNextPage || isFetchingNextPage) return;
+
+ // Query failures are classified + captured by the QueryCache seam; only
+ // report non-tRPC failures of the fetch dispatch itself.
+ fetchNextPage().catch((error) => reportNonTrpcError(error, "slack"));
+ }, [error, fetchNextPage, hasNextPage, isFetchingNextPage]);
+
+ return {
+ channelsData,
+ isLoadingChannels,
+ error,
+ refetchChannels,
+ };
+};
diff --git a/web/src/features/slack/hooks/useSlackConnect.ts b/web/src/features/slack/hooks/useSlackConnect.ts
new file mode 100644
index 0000000000..682f1a8369
--- /dev/null
+++ b/web/src/features/slack/hooks/useSlackConnect.ts
@@ -0,0 +1,160 @@
+import { useEffect, useRef, useState } from "react";
+
+import { showSuccessToast, showErrorToast } from "@/src/features/notifications";
+import { api } from "@/src/utils/api";
+
+/** useSlackConnect runs the Slack OAuth popup flow for a project and tracks whether it is pending or failed; it reports the outcome in a toast unless `shouldToast` is false. */
+export function useSlackConnect({
+ projectId,
+ onSuccess,
+ onError,
+ shouldToast = true,
+}: {
+ projectId: string;
+ shouldToast?: boolean;
+ onSuccess?: () => void;
+ onError?: (error: Error) => void;
+}) {
+ const [isConnecting, setIsConnecting] = useState(false);
+ const [connectError, setConnectError] = useState<string>();
+ const popupRef = useRef<Window | null>(null);
+ const intervalRef = useRef<NodeJS.Timeout | null>(null);
+ const messageHandlerRef = useRef<((event: MessageEvent) => void) | null>(
+ null,
+ );
+
+ const { data: integrationStatus } = api.slack.getIntegrationStatus.useQuery(
+ { projectId },
+ { enabled: !!projectId },
+ );
+
+ useEffect(() => {
+ return () => {
+ if (popupRef.current && !popupRef.current.closed) {
+ popupRef.current.close();
+ }
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ }
+ if (messageHandlerRef.current) {
+ window.removeEventListener("message", messageHandlerRef.current);
+ }
+ };
+ }, []);
+
+ const connect = async () => {
+ if (!integrationStatus?.installUrl) {
+ const errorMessage = "Install URL not available. Please try again.";
+ setConnectError(errorMessage);
+ onError?.(new Error(errorMessage));
+ if (shouldToast)
+ showErrorToast("Connection Failed", errorMessage, {
+ operation: "slack.connect",
+ errorOrigin: "backend",
+ errorCategory: "product_state",
+ });
+ return;
+ }
+
+ setIsConnecting(true);
+ setConnectError(undefined);
+
+ try {
+ const popup = window.open(
+ integrationStatus.installUrl,
+ "slack-oauth",
+ "width=600,height=700,scrollbars=yes,resizable=yes",
+ );
+
+ if (!popup) {
+ throw new Error("Popup blocked. Please allow popups and try again.");
+ }
+
+ popupRef.current = popup;
+
+ const handleMessage = (event: MessageEvent) => {
+ if (event.origin !== window.location.origin) {
+ return;
+ }
+
+ if (event.data.type === "slack-oauth-success") {
+ popup.close();
+ setIsConnecting(false);
+
+ if (shouldToast)
+ showSuccessToast({
+ operation: "slack.connect",
+ title: "Slack Connected",
+ description: `Successfully connected to ${event.data.teamName}.`,
+ });
+
+ onSuccess?.();
+
+ window.removeEventListener("message", handleMessage);
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ intervalRef.current = null;
+ }
+ popupRef.current = null;
+ messageHandlerRef.current = null;
+ } else if (event.data.type === "slack-oauth-error") {
+ popup.close();
+ setIsConnecting(false);
+
+ if (shouldToast)
+ showErrorToast("Connection Failed", event.data.error, {
+ operation: "slack.connect",
+ errorOrigin: "backend",
+ errorCategory: "internal",
+ });
+ setConnectError(event.data.error);
+ onError?.(new Error(event.data.error));
+
+ window.removeEventListener("message", handleMessage);
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ intervalRef.current = null;
+ }
+ popupRef.current = null;
+ messageHandlerRef.current = null;
+ }
+ };
+
+ messageHandlerRef.current = handleMessage;
+ window.addEventListener("message", handleMessage);
+
+ // The user can close the popup without finishing OAuth.
+ const checkClosed = setInterval(() => {
+ if (popup.closed) {
+ setIsConnecting(false);
+ window.removeEventListener("message", handleMessage);
+ clearInterval(checkClosed);
+ popupRef.current = null;
+ messageHandlerRef.current = null;
+ intervalRef.current = null;
+ }
+ }, 1000);
+
+ intervalRef.current = checkClosed;
+ } catch (error) {
+ setIsConnecting(false);
+ const errorMessage =
+ error instanceof Error ? error.message : "Failed to connect to Slack";
+ setConnectError(errorMessage);
+ onError?.(new Error(errorMessage));
+ if (shouldToast)
+ showErrorToast("Connection Failed", errorMessage, {
+ operation: "slack.connect",
+ errorOrigin: "frontend",
+ errorCategory: "product_state",
+ });
+ }
+ };
+
+ return {
+ connect,
+ connectError,
+ isConnecting,
+ canConnect: Boolean(integrationStatus?.installUrl),
+ };
+}
diff --git a/web/src/features/slack/useSlackIntegration.clienttest.ts b/web/src/features/slack/hooks/useSlackIntegration.clienttest.ts
similarity index 100%
rename from web/src/features/slack/useSlackIntegration.clienttest.ts
rename to web/src/features/slack/hooks/useSlackIntegration.clienttest.ts
diff --git a/web/src/features/slack/useSlackIntegration.ts b/web/src/features/slack/hooks/useSlackIntegration.ts
similarity index 100%
rename from web/src/features/slack/useSlackIntegration.ts
rename to web/src/features/slack/hooks/useSlackIntegration.ts
diff --git a/web/src/features/slack/hooks/useSlackTestMessage.ts b/web/src/features/slack/hooks/useSlackTestMessage.ts
new file mode 100644
index 0000000000..064aeb14c9
--- /dev/null
+++ b/web/src/features/slack/hooks/useSlackTestMessage.ts
@@ -0,0 +1,78 @@
+import { showSuccessToast, showErrorToast } from "@/src/features/notifications";
+import { type SlackChannel } from "@/src/features/slack/components/ChannelSelector";
+import { api } from "@/src/utils/api";
+import { classifyTrpcToastError } from "@/src/utils/trpcErrorClassification";
+
+/** useSlackTestMessage sends a test message to a Slack channel and reports the outcome in a toast unless `shouldToast` is false. */
+export function useSlackTestMessage({
+ projectId,
+ onSuccess,
+ onError,
+ shouldToast = true,
+}: {
+ projectId: string;
+ shouldToast?: boolean;
+ onSuccess?: (channelInfo: {
+ id: string;
+ name?: string;
+ isPrivate?: boolean;
+ }) => void;
+ onError?: (error: Error) => void;
+}) {
+ const testMessageMutation = api.slack.sendTestMessage.useMutation({
+ onSuccess: (data) => {
+ if (shouldToast) {
+ showSuccessToast({
+ operation: "slack.test_message_send",
+ title: "Test Message Sent",
+ description:
+ "Test message sent successfully to the selected channel.",
+ });
+ }
+ onSuccess?.(data.channelInfo);
+ },
+ onError: (error) => {
+ if (shouldToast) {
+ showErrorToast(
+ "Failed to Send Test Message",
+ error.message,
+ classifyTrpcToastError(error, "slack.test_message_send"),
+ );
+ }
+ onError?.(new Error(error.message));
+ },
+ });
+
+ /** sendTestMessage resolves to the channel as Slack reports it, or to the reason sending failed. */
+ const sendTestMessage = async (
+ channel: SlackChannel,
+ ): Promise<SlackTestMessageResult> => {
+ try {
+ const result = await testMessageMutation.mutateAsync({
+ projectId,
+ channelId: channel.id,
+ channelName: channel.name ?? undefined,
+ });
+ return { status: "sent", channel: result.channelInfo };
+ } catch (error) {
+ // The mutation's onError already reported it.
+ return { status: "failed", message: errorMessage(error) };
+ }
+ };
+
+ return { sendTestMessage, isPending: testMessageMutation.isPending };
+}
+
+/** errorMessage is the human-readable reason of a failed request. */
+function errorMessage(error: unknown): string {
+ if (error instanceof Error) return error.message;
+ return "Failed to send the test message.";
+}
+
+/** SlackTestMessageResult is the outcome of one test message. */
+export type SlackTestMessageResult =
+ | {
+ status: "sent";
+ channel: { id: string; name?: string; isPrivate?: boolean };
+ }
+ | { status: "failed"; message: string };
diff --git a/web/src/features/slack/index.ts b/web/src/features/slack/index.ts
index 23bddf1aae..1e5d5fa4b6 100644
--- a/web/src/features/slack/index.ts
+++ b/web/src/features/slack/index.ts
@@ -6,3 +6,11 @@ export {
} from "@/src/features/slack/components/ChannelSelector";
export { SlackConnectionCard } from "@/src/features/slack/components/SlackConnectionCard";
export { SlackTestMessageButton } from "@/src/features/slack/components/SlackTestMessageButton";
+export {
+ ChannelSelectorView,
+ type ChannelSelectorViewProps,
+} from "@/src/features/slack/components/ChannelSelectorView/ChannelSelectorView";
+export { useChannelSelectorData } from "@/src/features/slack/hooks/useChannelSelectorData";
+export { useSlackConnect } from "@/src/features/slack/hooks/useSlackConnect";
+export { useSlackTestMessage } from "@/src/features/slack/hooks/useSlackTestMessage";
+export { type SlackTestMessageResult } from "@/src/features/slack/hooks/useSlackTestMessage";