Skip to content

πŸ™Œ OpenHands: AI-Driven Development

126 KB
Raw Blame
import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
  type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import {
  CalendarDays,
  ChevronDown,
  Code2,
  FileText,
  Globe2,
  Info,
  X,
  Zap,
} from "lucide-react";
import AutomationService, {
  type CustomWebhookCreateResponse,
} from "#/api/automation-service/automation-service.api";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import {
  clearAutomationFormSession,
  getAutomationFormSession,
  initializeAutomationFormSession,
  isPendingAutomationSetupId,
  patchAutomationFormSession,
  setAutomationFormSessionRepositories,
  subscribeAutomationFormSession,
} from "#/api/automation-form-session";
import type {
  AutomationSetupDraft,
  AutomationSetupField,
  AutomationSetupFormPatch,
  AutomationSetupFormValues,
} from "#/api/automation-setup-types";
import {
  DEFAULT_AUTOMATION_PLUGIN_REF,
  resolveAutomationSetupPlugins,
  serializeAutomationSetupPluginList,
  type AutomationSetupPluginEntry,
} from "#/api/automation-setup-plugins";
import {
  automationDetailPath,
  automationListPath,
} from "#/manifests/automation-interface";
import { packTarGzip } from "#/utils/tar-gzip";
import { AvailableLanguages } from "#/i18n";
import { I18nKey } from "#/i18n/declaration";
import SparkleIcon from "#/icons/sparkle.svg?react";
import { BrandButton } from "#/components/features/settings/brand-button";
import { BackNavButton } from "#/components/shared/buttons/back-nav-button";
import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";
import { OptionalTag } from "#/components/features/settings/optional-tag";
import { AutomationSetupPromptStack } from "#/components/features/automations/setup/automation-setup-prompt-stack";
import { ContextMenuListItem } from "#/components/features/context-menu/context-menu-list-item";
import { formatTriggerSourceLabel } from "#/components/features/home/featured-automations/automation-run-health";
import { useClickOutsideElement } from "#/hooks/use-click-outside-element";
import { useSettings } from "#/hooks/query/use-settings";
import { usePromptTextareaResize } from "#/hooks/use-prompt-textarea-resize";
import { useSendMessage } from "#/hooks/use-send-message";
import {
  formControlBorderClassName,
  formControlFieldClassName,
  formControlFocusWithinClassName,
  formControlHeightClassName,
  formControlMultilineFieldClassName,
  formControlRadiusClassName,
  formControlSurfaceClassName,
  formControlTransitionClassName,
} from "#/utils/form-control-classes";
import { Divider } from "#/ui/divider";
import { cn } from "#/utils/utils";
import { useDeploymentCapabilities } from "#/hooks/query/use-manifest-capabilities";
import { AUTOMATION_DETAIL_QUERY_KEY } from "#/hooks/query/use-automation-detail";
import { AUTOMATIONS_QUERY_KEY } from "#/hooks/query/use-automations";
import {
  invalidateConversationQueries,
  patchConversationInCache,
} from "#/hooks/mutation/conversation-mutation-utils";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
import { getApiErrorMessage } from "#/utils/api-error-message";
import { useNavigation } from "#/context/navigation-context";
import type {
  AutomationDraftApiResponse,
  SetupRequestBody,
} from "#/manifests/types";
import type { Automation, AutomationRun } from "#/types/automation";
import { formatRelativeTime } from "#/utils/format-relative-time";
import { ActivityLogItem } from "../detail/activity-log-item";
import { requestAutomationSetupAgent } from "./automation-setup-agent-request";
import {
  draftEndpoint,
  draftRunPageErrors,
  draftValidationEndpoint,
  extractDraftDispatchErrors,
  formFromServerDraft,
  getDraftExecutionStatusText,
  getResponseStatus,
  isDraftEndpointUnavailable,
  presetKindForEndpoint,
} from "./automation-setup-draft-service";
import {
  buildAutomationDraftTags,
  buildAutomationSetupModeTags,
  getAutomationDraftIdFromTags,
  getAutomationEditIdFromTags,
  hasAutomationSetupModeTag,
  removeAutomationDraftTags,
} from "#/utils/automation-draft-tags";
import { setupDraftFromAutomation } from "#/utils/automation-edit-draft";
import { withPresetSources } from "#/utils/automation-preset-sources";
import {
  automationCloneProviders,
  automationRepositoriesChanged,
  buildAutomationRepoSources,
} from "#/utils/automation-repo-sources";

const DEFAULT_TIMEZONE = "America/New_York";
const DEFAULT_TIME = "09:00";
const DEFAULT_CUSTOM_SCHEDULE = "0 9 * * *";
const DEFAULT_EVENT_SOURCE = "github";
// Capability feature: preset repositories can be changed with PATCH.
const REPO_UPDATE_FEATURE = "repoUpdate";
/** Used when the deployment has not advertised its event sources yet. */
const FALLBACK_EVENT_SOURCES = ["github", "gitlab", "slack", "linear", "jira"];
const DEFAULT_EVENT_KEY = "issue_comment.created";
const DEFAULT_CUSTOM_ENTRYPOINT = "python3 main.py";
const MAIN_PY_FILENAME = "main.py";
const DEFAULT_CUSTOM_SETUP_SCRIPT_PATH = "setup.sh";
const DEFAULT_CUSTOM_SETUP_SCRIPT = `#!/usr/bin/env bash
:
`;
const addOptionButtonClassName = cn(
  "inline-flex w-fit shrink-0 cursor-pointer items-center rounded-lg border border-[var(--oh-border)] bg-tertiary px-3 py-1.5 text-sm text-content hover:bg-interactive-hover",
  formControlTransitionClassName,
);
const DEFAULT_TIMEOUT_SECONDS = "600";
const PREFLIGHT_TARBALL_PATH =
  "oh-internal://uploads/00000000-0000-0000-0000-000000000000";
export const AGENT_FIELD_STREAM_CHARACTER_DELAY_MS = 12;
export const AGENT_FIELD_STREAM_SETTLE_DELAY_MS = 160;

const FREQUENCIES = [
  "once",
  "hourly",
  "daily",
  "weekdays",
  "weekly",
  "custom",
] as const;
const TIMEZONE_OPTIONS = [
  "America/New_York",
  "America/Chicago",
  "America/Denver",
  "America/Los_Angeles",
  "America/Sao_Paulo",
  "Europe/London",
  "Europe/Paris",
  "Europe/Berlin",
  "Asia/Tokyo",
  "Asia/Shanghai",
  "Asia/Kolkata",
  "Australia/Sydney",
  "UTC",
] as const;
const AUTOMATION_SETUP_FIELD_RENDER_ORDER: AutomationSetupField[] = [
  "kind",
  "name",
  "prompt",
  "pluginSource",
  "pluginRef",
  "pluginList",
  "repository",
  "customCode",
  "entrypoint",
  "setupScriptPath",
  "setupScript",
  "triggerKind",
  "frequency",
  "time",
  "weekday",
  "scheduleDateTime",
  "timezone",
  "customSchedule",
  "eventSource",
  "eventKey",
  "eventFilter",
  "model",
  "agentProfileId",
  "showTimeout",
  "timeoutSeconds",
];

type CustomWebhookSignatureScheme =
  | "hmac_sha256_hex"
  | "standard_webhooks"
  | "slack_v0";

interface CustomWebhookFormState {
  enabled: boolean;
  name: string;
  eventKeyExpr: string;
  signatureHeader: string;
  signatureScheme: CustomWebhookSignatureScheme;
  webhookSecret: string;
}

const DEFAULT_CUSTOM_WEBHOOK_EVENT_KEY_EXPR = "type";
const DEFAULT_CUSTOM_WEBHOOK_SIGNATURE_HEADER = "X-Signature-256";
const DEFAULT_CUSTOM_WEBHOOK_SIGNATURE_SCHEME: CustomWebhookSignatureScheme =
  "hmac_sha256_hex";

const NON_CHARACTER_STREAM_FIELDS = new Set<AutomationSetupField>([
  "kind",
  "triggerKind",
  "frequency",
  "weekday",
  "model",
  "agentProfileId",
  "showTimeout",
  "time",
  "pluginList",
]);
const streamingFieldHighlightClassName =
  "rounded-xl ring-2 ring-[#D5C76B]/80 ring-offset-2 ring-offset-base shadow-[0_0_24px_rgba(213,199,107,0.24)]";

export function parseAutomationSetupRepositories(value: string): string[] {
  const seen = new Set<string>();
  return value
    .split(/[\n,]+/)
    .map((entry) => entry.trim())
    .filter((entry) => {
      if (!entry || seen.has(entry)) return false;
      seen.add(entry);
      return true;
    });
}

type Frequency = (typeof FREQUENCIES)[number];
type StatusMessage = { kind: "success" | "error"; text: string } | null;

interface AutomationSetupPanelProps {
  draft: AutomationSetupDraft;
  conversationId?: string | null;
  conversationTags?: Record<string, string> | null;
  toolbarPortal?: HTMLElement | null;
  showInlineHeader?: boolean;
  reserveComposerSpace?: boolean;
}

function titleCase(value: string): string {
  return value
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 4)
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join(" ");
}

function deriveName(prompt: string): string {
  const withoutLead = prompt
    .replace(/^create\s+(an?\s+)?automation\s+(that|to)?\s*/i, "")
    .replace(/[.!?].*$/, "")
    .trim();
  const name = titleCase(withoutLead || prompt);
  return name || "New Automation";
}

function defaultScheduleDateTimeLocal(): string {
  const date = new Date();
  date.setSeconds(0, 0);
  date.setMinutes(0);
  date.setHours(date.getHours() + 1);
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hour = String(date.getHours()).padStart(2, "0");
  const minute = String(date.getMinutes()).padStart(2, "0");
  return `${date.getFullYear()}-${month}-${day}T${hour}:${minute}`;
}

function onceCron(scheduleDateTime: string): string {
  const match = scheduleDateTime.match(
    /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/,
  );
  if (!match) return DEFAULT_CUSTOM_SCHEDULE;
  const minute = Number(match[5]);
  const hour = Number(match[4]);
  const day = Number(match[3]);
  const month = Number(match[2]);
  return `${minute} ${hour} ${day} ${month} *`;
}

function eventKeyPayload(value: string): string | string[] {
  const keys = value
    .split(",")
    .map((key) => key.trim())
    .filter(Boolean);
  if (keys.length <= 1) return keys[0] ?? DEFAULT_EVENT_KEY;
  return keys;
}

function cronWeekday(weekday: string): number {
  const value = Number(weekday);
  if (!Number.isInteger(value) || value < 0 || value > 6) return 1;
  return value;
}

function toCron(
  time: string,
  frequency: Frequency,
  customSchedule: string,
  scheduleDateTime: string,
  weekday: string,
): string {
  if (frequency === "custom") return customSchedule || DEFAULT_CUSTOM_SCHEDULE;
  if (frequency === "once") return onceCron(scheduleDateTime);
  if (frequency === "hourly") return "0 * * * *";

  const [hour = "9", minute = "0"] = time.split(":");
  const cronTime = `${Number(minute)} ${Number(hour)}`;
  if (frequency === "weekdays") return `${cronTime} * * 1-5`;
  if (frequency === "weekly") return `${cronTime} * * ${cronWeekday(weekday)}`;
  return `${cronTime} * * *`;
}

function buildStarterPython(prompt: string): string {
  return `import json\nimport os\nimport urllib.request\n\n\ndef fire_callback(status="COMPLETED", error=None):\n    url = os.environ.get("AUTOMATION_CALLBACK_URL", "")\n    if not url:\n        return\n    body = {"status": status, "run_id": os.environ.get("AUTOMATION_RUN_ID", "")}\n    if error:\n        body["error"] = error\n    request = urllib.request.Request(\n        url,\n        data=json.dumps(body).encode(),\n        headers={\n            "Content-Type": "application/json",\n            "Authorization": f"Bearer {os.environ.get('AUTOMATION_CALLBACK_API_KEY', '')}",\n        },\n    )\n    urllib.request.urlopen(request, timeout=10)\n\n\ndef main():\n    prompt = ${JSON.stringify(prompt)}\n    print(f"Automation prompt: {prompt}")\n\n\nif __name__ == "__main__":\n    try:\n        main()\n        fire_callback("COMPLETED")\n    except Exception as exc:\n        fire_callback("FAILED", str(exc))\n        raise\n`;
}

function existingTarballDisplayName(path: string): string {
  const trimmed = path.trim();
  if (!trimmed) return "";
  const name = trimmed.split("/").filter(Boolean).pop() ?? trimmed;
  try {
    return decodeURIComponent(name);
  } catch {
    return name;
  }
}

function sortFieldsByRenderOrder(
  fields: AutomationSetupField[],
): AutomationSetupField[] {
  return [...fields].sort(
    (first, second) =>
      AUTOMATION_SETUP_FIELD_RENDER_ORDER.indexOf(first) -
      AUTOMATION_SETUP_FIELD_RENDER_ORDER.indexOf(second),
  );
}

function shouldCharacterStreamField(
  field: AutomationSetupField,
  value: AutomationSetupFormValues[AutomationSetupField],
): value is string {
  return typeof value === "string" && !NON_CHARACTER_STREAM_FIELDS.has(field);
}

function streamingHighlightClassName(isStreaming: boolean) {
  return isStreaming ? streamingFieldHighlightClassName : undefined;
}

function buildDefaultEventTestPayload(
  eventSource: string = DEFAULT_EVENT_SOURCE,
  eventKey: string = DEFAULT_EVENT_KEY,
): string {
  return `${JSON.stringify(
    {
      source: eventSource || DEFAULT_EVENT_SOURCE,
      event: eventKey || DEFAULT_EVENT_KEY,
      action: "test",
    },
    null,
    2,
  )}\n`;
}

function parseEventTestPayload(value: string): Record<string, unknown> | null {
  const trimmed = value.trim();
  if (!trimmed) return null;
  try {
    const parsed = JSON.parse(trimmed) as unknown;
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
      return null;
    }
    return parsed as Record<string, unknown>;
  } catch {
    return null;
  }
}

function buildInitialForm(
  draft: AutomationSetupDraft,
): AutomationSetupFormValues {
  const form = draft.form ?? {};
  const prompt = form.prompt ?? draft.prompt;
  const kind = form.kind ?? draft.kind;
  const pluginEntries = resolveAutomationSetupPlugins(form, draft.plugins);
  return {
    kind,
    name: form.name ?? deriveName(prompt),
    prompt,
    repository: form.repository ?? "",
    pluginSource: pluginEntries[0]?.source ?? "",
    pluginRef: pluginEntries[0]?.ref ?? "",
    pluginList:
      pluginEntries.length > 0
        ? serializeAutomationSetupPluginList(pluginEntries)
        : "",
    customCode: form.customCode ?? buildStarterPython(prompt),
    entrypoint: form.entrypoint ?? DEFAULT_CUSTOM_ENTRYPOINT,
    setupScriptPath: form.setupScriptPath ?? DEFAULT_CUSTOM_SETUP_SCRIPT_PATH,
    setupScript: form.setupScript ?? DEFAULT_CUSTOM_SETUP_SCRIPT,
    triggerKind: form.triggerKind ?? "cron",
    frequency: form.frequency ?? "daily",
    time: form.time ?? DEFAULT_TIME,
    weekday: form.weekday ?? "1",
    scheduleDateTime: form.scheduleDateTime ?? "",
    timezone: form.timezone ?? DEFAULT_TIMEZONE,
    customSchedule: form.customSchedule ?? DEFAULT_CUSTOM_SCHEDULE,
    eventSource: form.eventSource ?? DEFAULT_EVENT_SOURCE,
    eventKey: form.eventKey ?? DEFAULT_EVENT_KEY,
    eventFilter: form.eventFilter ?? "",
    model: form.model ?? "",
    agentProfileId: form.agentProfileId ?? "",
    showTimeout: form.showTimeout ?? false,
    timeoutSeconds: form.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS,
  };
}

function DraftStatusBar({
  draft,
  runs,
  isSubmitting,
  canTest,
  saveFailed,
  onTest,
  onViewRuns,
}: {
  draft: AutomationDraftApiResponse;
  runs: AutomationRun[];
  isSubmitting: boolean;
  canTest: boolean;
  /** The latest save failed, so `draft` no longer describes the form. */
  saveFailed: boolean;
  onTest: () => void;
  onViewRuns: () => void;
}) {
  const { t, i18n } = useTranslation("openhands");
  const validationMessage = draft.validationErrors?.[0]?.message ?? null;
  const statusText = getDraftExecutionStatusText(draft, runs, t);

  // @spec FF-001 β€” Theme-aware validation and load errors
  // A 5% tint keeps the error text at 4.5:1 on every theme's surface.
  const validityClassName = cn(
    "max-w-full min-w-0 whitespace-normal rounded-full px-2.5 py-0.5 text-left text-xs leading-4",
    validationMessage
      ? "w-fit bg-feedback-error/5 text-feedback-error"
      : "bg-[var(--oh-success)]/10 text-[var(--oh-success)]",
  );

  return (
    <section
      data-testid="automation-setup-draft-details"
      className="flex flex-col gap-2 rounded-xl border border-[var(--oh-border)] bg-[var(--oh-surface)] px-3 py-2"
    >
      <div className="flex items-center justify-between gap-2">
        <div className="flex min-w-0 items-center gap-2">
          <h3 className="truncate text-sm text-content">
            {t(I18nKey.AUTOMATION_SETUP$DRAFT_STATUS_TITLE)}
          </h3>
          <span className="truncate text-xs text-muted">
            {formatRelativeTime(
              draft.updatedAt,
              i18n?.language ?? AvailableLanguages[0].value,
              t,
            )}
          </span>
        </div>
        <div className="flex shrink-0 items-center gap-1.5">
          {validationMessage || saveFailed ? null : (
            <span
              data-testid="automation-setup-draft-validity"
              className={validityClassName}
            >
              {statusText}
            </span>
          )}
          <BrandButton
            type="button"
            variant="secondary"
            testId="automation-setup-view-test-runs"
            className="!h-7 !min-h-7 !px-2.5 !text-xs"
            onClick={onViewRuns}
          >
            {t(I18nKey.AUTOMATION_SETUP$VIEW_TEST_RUNS)}
          </BrandButton>
          <BrandButton
            type="button"
            variant="primary"
            testId="automation-setup-draft-test"
            className="!h-7 !min-h-7 shrink-0 !px-2.5 !text-xs"
            isDisabled={isSubmitting || !canTest}
            aria-busy={isSubmitting}
            onClick={onTest}
          >
            {t(I18nKey.AUTOMATION_SETUP$TEST)}
          </BrandButton>
        </div>
      </div>
      {validationMessage ? (
        <p
          data-testid="automation-setup-draft-validity"
          className={validityClassName}
        >
          {statusText}
        </p>
      ) : null}
    </section>
  );
}

function DraftRunTestButton({
  isSubmitting,
  canTest,
  onTest,
}: {
  isSubmitting: boolean;
  canTest: boolean;
  onTest: () => void;
}) {
  const { t } = useTranslation("openhands");
  return (
    <BrandButton
      type="button"
      variant="primary"
      testId="automation-setup-test"
      isDisabled={isSubmitting || !canTest}
      aria-busy={isSubmitting}
      onClick={onTest}
    >
      {t(I18nKey.AUTOMATION_SETUP$TEST)}
    </BrandButton>
  );
}

function DraftRunsPage({
  runs,
  errors,
  isSubmitting,
  canTest,
  onBack,
  onTest,
}: {
  runs: AutomationRun[];
  errors: string[];
  isSubmitting: boolean;
  canTest: boolean;
  onBack: () => void;
  onTest: () => void;
}) {
  const { t } = useTranslation("openhands");

  return (
    <section
      data-testid="automation-setup-draft-runs-page"
      className="flex flex-col gap-4"
    >
      <BackNavButton testId="automation-setup-draft-runs-back" onClick={onBack}>
        {t(I18nKey.BUTTON$BACK)}
      </BackNavButton>
      <div className="flex items-center justify-between gap-3">
        <h3 className="text-xl font-medium text-content">
          {t(I18nKey.AUTOMATION_SETUP$TEST_RUNS)}
        </h3>
        {runs.length > 0 ? (
          <DraftRunTestButton
            canTest={canTest}
            isSubmitting={isSubmitting}
            onTest={onTest}
          />
        ) : null}
      </div>
      {errors.map((message) => (
        <p
          key={message}
          role="alert"
          data-testid="automation-setup-draft-runs-error"
          className="rounded-xl border border-feedback-error/40 bg-feedback-error/10 px-4 py-3 text-sm text-feedback-error"
        >
          {message}
        </p>
      ))}
      {runs.length > 0 ? (
        <div className="overflow-hidden rounded-xl border border-[var(--oh-border)]">
          {runs.map((run, index) => (
            <div
              key={run.id}
              data-testid="automation-setup-draft-run"
              className={cn(index > 0 && "border-t border-[var(--oh-border)]")}
            >
              <ActivityLogItem run={run} />
            </div>
          ))}
        </div>
      ) : (
        <div
          data-testid="automation-setup-draft-runs-empty"
          className="flex flex-col items-center gap-3 rounded-xl border border-[var(--oh-border)] bg-[var(--oh-surface)] px-5 py-10 text-center"
        >
          <p className="text-sm text-content">
            {t(I18nKey.AUTOMATIONS$DETAIL$NO_RUNS)}
          </p>
          <p className="text-sm text-muted">
            {t(I18nKey.AUTOMATION_SETUP$TEST_RUNS_EMPTY_DESCRIPTION)}
          </p>
          <DraftRunTestButton
            canTest={canTest}
            isSubmitting={isSubmitting}
            onTest={onTest}
          />
        </div>
      )}
    </section>
  );
}

function frequencyLabelKey(frequency: Frequency): I18nKey {
  switch (frequency) {
    case "once":
      return I18nKey.AUTOMATION_SETUP$FREQUENCY_ONCE;
    case "hourly":
      return I18nKey.AUTOMATION_SETUP$FREQUENCY_HOURLY;
    case "daily":
      return I18nKey.AUTOMATIONS$FREQUENCY_DAILY;
    case "weekdays":
      return I18nKey.AUTOMATION_SETUP$FREQUENCY_WEEKDAYS;
    case "weekly":
      return I18nKey.AUTOMATION_SETUP$FREQUENCY_WEEKLY;
    case "custom":
      return I18nKey.AUTOMATION_SETUP$TYPE_CUSTOM;
  }
}

export function AutomationSetupPanel({
  draft,
  conversationId,
  conversationTags,
  toolbarPortal,
  showInlineHeader = true,
  reserveComposerSpace = false,
}: AutomationSetupPanelProps) {
  const { t } = useTranslation("openhands");
  const { navigate } = useNavigation();
  const deploymentCapabilities = useDeploymentCapabilities();
  // Connected self-hosted providers name their hosts here; a repository on
  // one of them is sent with its provider so the run can authenticate, as
  // long as the service can clone from that provider at all.
  const providerHosts = useSettings().data?.provider_tokens_set;
  const cloneProviders = automationCloneProviders(
    deploymentCapabilities.data?.repoProviders,
  );
  const eventSourceOptions = deploymentCapabilities.data?.eventSources ?? [];
  const eventTypeOptions = deploymentCapabilities.data?.eventTypes ?? [];
  const initialDraft = conversationId
    ? (getAutomationFormSession(conversationId) ?? draft)
    : draft;
  const [form, setForm] = useState(() => buildInitialForm(initialDraft));
  const [eventTestPayload, setEventTestPayload] = useState(() =>
    buildDefaultEventTestPayload(DEFAULT_EVENT_SOURCE, DEFAULT_EVENT_KEY),
  );
  const [isEventTestPayloadDirty, setIsEventTestPayloadDirty] = useState(false);
  const [customWebhook, setCustomWebhook] = useState<CustomWebhookFormState>({
    enabled: false,
    name: "",
    eventKeyExpr: DEFAULT_CUSTOM_WEBHOOK_EVENT_KEY_EXPR,
    signatureHeader: DEFAULT_CUSTOM_WEBHOOK_SIGNATURE_HEADER,
    signatureScheme: DEFAULT_CUSTOM_WEBHOOK_SIGNATURE_SCHEME,
    webhookSecret: "",
  });
  const [customWebhookRegistration, setCustomWebhookRegistration] =
    useState<CustomWebhookCreateResponse | null>(null);

  const [fieldMetadata, setFieldMetadata] = useState(
    () => initialDraft.fieldMetadata ?? {},
  );
  const [statusMessage, setStatusMessage] = useState<StatusMessage>(null);
  const toastedStatusRef = useRef<StatusMessage>(null);
  useEffect(() => {
    if (!statusMessage || statusMessage === toastedStatusRef.current) return;
    toastedStatusRef.current = statusMessage;
    if (statusMessage.kind === "success") {
      toast.success(statusMessage.text);
      return;
    }
    displayErrorToast(statusMessage.text);
  }, [statusMessage]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [streamingField, setStreamingField] =
    useState<AutomationSetupField | null>(null);
  // Server-backed draft from OpenHands/automation PR #439. Null until the
  // first save creates the draft row; the local store stays the reactive layer
  // the agent streams into, and the server row is the persisted source of truth.
  const [serverDraft, setServerDraft] =
    useState<AutomationDraftApiResponse | null>(null);
  const [draftRuns, setDraftRuns] = useState<AutomationRun[]>([]);
  const [isViewingDraftRuns, setIsViewingDraftRuns] = useState(false);
  const [isHydratingServerDraft, setIsHydratingServerDraft] = useState(false);
  const [saveState, setSaveState] = useState<
    "idle" | "saving" | "saved" | "error"
  >("idle");
  // Request body from the last successful save. Compared with the form so
  // Test stays inactive while there are unsaved edits, even if the service
  // returns a normalized draft that does not byte-match the request.
  const [savedDraftRequestKey, setSavedDraftRequestKey] = useState<
    string | null
  >(null);
  const [isTaggedDraftMissing, setIsTaggedDraftMissing] = useState(false);
  const queryClient = useQueryClient();
  const latestConversationTagsRef = useRef(conversationTags);
  const conversationTagUpdateQueueRef = useRef<Promise<void>>(
    Promise.resolve(),
  );
  const propTaggedServerDraftId =
    getAutomationDraftIdFromTags(conversationTags) ??
    draft.serverDraftId ??
    null;
  const [currentTaggedServerDraftId, setCurrentTaggedServerDraftId] = useState(
    propTaggedServerDraftId,
  );
  const taggedServerDraftId = currentTaggedServerDraftId;
  const serverDraftId =
    serverDraft?.id ?? (isTaggedDraftMissing ? null : taggedServerDraftId);
  const editingAutomationId =
    draft.editingAutomationId?.trim() ||
    getAutomationEditIdFromTags(conversationTags) ||
    "";
  const isEditingExisting = editingAutomationId.length > 0;
  const [existingCustomTarballPath, setExistingCustomTarballPath] = useState(
    draft.existingCustomTarballPath ?? "",
  );
  const [existingRepositories, setExistingRepositories] = useState(
    draft.existingRepositories ?? [],
  );
  const [canUpdateRepositories, setCanUpdateRepositories] = useState(
    draft.canUpdateRepositories ?? false,
  );
  // A new automation sends its repositories on create. An existing one can
  // change them only when the service can rebuild it with them.
  const repositoriesEditable =
    !isEditingExisting ||
    (canUpdateRepositories &&
      (deploymentCapabilities.data?.features ?? []).includes(
        REPO_UPDATE_FEATURE,
      ));
  const streamQueueRef = useRef<
    {
      field: AutomationSetupField;
      value: AutomationSetupFormValues[AutomationSetupField];
      metadata?: NonNullable<
        AutomationSetupDraft["fieldMetadata"]
      >[AutomationSetupField];
    }[]
  >([]);
  const isStreamProcessingRef = useRef(false);
  const streamGenerationRef = useRef(0);
  const streamTimeoutsRef = useRef<number[]>([]);
  const processQueuedStreamsRef = useRef<() => void>(() => {});

  useEffect(() => {
    latestConversationTagsRef.current = conversationTags;
  }, [conversationTags]);

  useEffect(() => {
    setCurrentTaggedServerDraftId(propTaggedServerDraftId);
  }, [propTaggedServerDraftId]);

  useEffect(() => {
    setExistingCustomTarballPath(draft.existingCustomTarballPath ?? "");
  }, [draft.existingCustomTarballPath]);

  useEffect(() => {
    setExistingRepositories(draft.existingRepositories ?? []);
    setCanUpdateRepositories(draft.canUpdateRepositories ?? false);
  }, [draft.existingRepositories, draft.canUpdateRepositories]);

  const updateConversationTags = useCallback(
    async (
      buildNextTags: (
        tags: Record<string, string> | null | undefined,
      ) => Record<string, string>,
    ) => {
      if (!conversationId) return null;

      const update = conversationTagUpdateQueueRef.current
        .catch(() => undefined)
        .then(async () => {
          const nextTags = buildNextTags(latestConversationTagsRef.current);
          const updatedConversation =
            await AgentServerConversationService.updateConversationTags(
              conversationId,
              nextTags,
            );
          const savedTags = updatedConversation.tags ?? nextTags;
          latestConversationTagsRef.current = savedTags;
          patchConversationInCache(queryClient, conversationId, {
            tags: savedTags,
          });
          invalidateConversationQueries(queryClient, conversationId);
          return updatedConversation;
        });

      conversationTagUpdateQueueRef.current = update.then(
        () => undefined,
        () => undefined,
      );
      return update;
    },
    [conversationId, queryClient],
  );

  useEffect(() => {
    if (
      !conversationId ||
      isPendingAutomationSetupId(conversationId) ||
      conversationTags === undefined ||
      hasAutomationSetupModeTag(conversationTags)
    ) {
      return;
    }
    updateConversationTags((tags) => buildAutomationSetupModeTags(tags)).catch(
      (error: unknown) => {
        displayErrorToast(getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)));
      },
    );
  }, [conversationId, conversationTags, updateConversationTags]);

  const saveDraftInFormSession = useCallback(
    (
      saved: AutomationDraftApiResponse,
      nextForm: AutomationSetupFormValues,
    ) => {
      if (!conversationId) return;
      initializeAutomationFormSession(conversationId, {
        ...draft,
        prompt: nextForm.prompt ?? draft.prompt,
        kind: nextForm.kind ?? draft.kind,
        form: nextForm,
        fieldMetadata,
        serverDraftId: saved.id,
        ...(saved.materializedAutomationId
          ? { materializedAutomationId: saved.materializedAutomationId }
          : {}),
      });
    },
    [conversationId, draft, fieldMetadata],
  );

  const updateConversationDraftTags = useCallback(
    async (draftId: string | null) => {
      if (!conversationId || isPendingAutomationSetupId(conversationId)) return;
      await updateConversationTags((tags) =>
        draftId
          ? buildAutomationDraftTags(tags, draftId)
          : removeAutomationDraftTags(tags),
      );
      setCurrentTaggedServerDraftId(draftId);
    },
    [conversationId, updateConversationTags],
  );

  useEffect(() => {
    if (!isEditingExisting || draft.form || !conversationId) return undefined;
    let cancelled = false;
    AutomationService.getAutomation(editingAutomationId)
      .then((automation) => {
        if (cancelled) return;
        const next = setupDraftFromAutomation(automation);
        const nextForm = buildInitialForm(next);
        initializeAutomationFormSession(conversationId, next);
        setExistingCustomTarballPath(next.existingCustomTarballPath ?? "");
        setExistingRepositories(next.existingRepositories ?? []);
        setCanUpdateRepositories(next.canUpdateRepositories ?? false);
        setForm(nextForm);
      })
      .catch((error: unknown) => {
        if (!cancelled) {
          displayErrorToast(
            getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)),
          );
        }
      });
    return () => {
      cancelled = true;
    };
  }, [conversationId, draft.form, editingAutomationId, isEditingExisting]);

  useEffect(() => {
    if (!taggedServerDraftId || serverDraft?.id === taggedServerDraftId) {
      return undefined;
    }

    let cancelled = false;
    setIsHydratingServerDraft(true);
    setSavedDraftRequestKey(null);
    setIsTaggedDraftMissing(false);

    AutomationService.getServerDraft(taggedServerDraftId)
      .then((saved) => {
        if (cancelled) return;
        const nextForm = formFromServerDraft(saved, buildInitialForm(draft));
        setServerDraft(saved);
        setDraftRuns([]);
        setForm(nextForm);
        saveDraftInFormSession(saved, nextForm);
      })
      .catch((error: unknown) => {
        if (cancelled) return;
        if (getResponseStatus(error) === 404) {
          setServerDraft(null);
          setIsTaggedDraftMissing(true);
          return;
        }
        displayErrorToast(getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)));
      })
      .finally(() => {
        if (!cancelled) setIsHydratingServerDraft(false);
      });

    return () => {
      cancelled = true;
    };
  }, [
    conversationId,
    draft,
    saveDraftInFormSession,
    serverDraft?.id,
    taggedServerDraftId,
  ]);

  const {
    kind,
    name,
    prompt,
    repository,
    pluginSource,
    pluginRef,
    pluginList,
    customCode,
    entrypoint,
    setupScriptPath,
    setupScript,
    triggerKind,
    frequency,
    time,
    weekday,
    scheduleDateTime,
    timezone,
    customSchedule,
    eventSource,
    eventKey,
    eventFilter,
    model,
    agentProfileId,
    showTimeout,
    timeoutSeconds,
  } = form;
  const hasExistingCustomBundle = Boolean(
    isEditingExisting && kind === "custom" && existingCustomTarballPath.trim(),
  );

  useEffect(() => {
    if (isEventTestPayloadDirty) return;
    setEventTestPayload(buildDefaultEventTestPayload(eventSource, eventKey));
  }, [eventSource, eventKey, isEventTestPayloadDirty]);

  const clearQueuedStreams = useCallback(() => {
    streamGenerationRef.current += 1;
    for (const timeoutId of streamTimeoutsRef.current) {
      window.clearTimeout(timeoutId);
    }
    streamTimeoutsRef.current = [];
    streamQueueRef.current = [];
    isStreamProcessingRef.current = false;
    setStreamingField(null);
  }, []);

  const scheduleStreamStep = useCallback(
    (callback: () => void, delay: number, generation: number) => {
      const timeoutId = window.setTimeout(() => {
        streamTimeoutsRef.current = streamTimeoutsRef.current.filter(
          (queuedTimeoutId) => queuedTimeoutId !== timeoutId,
        );
        if (generation !== streamGenerationRef.current) return;
        callback();
      }, delay);
      streamTimeoutsRef.current.push(timeoutId);
    },
    [],
  );

  const finishCurrentStream = useCallback(
    (
      field: AutomationSetupField,
      metadata:
        | NonNullable<
            AutomationSetupDraft["fieldMetadata"]
          >[AutomationSetupField]
        | undefined,
      generation: number,
    ) => {
      if (metadata) {
        setFieldMetadata((previous) => ({ ...previous, [field]: metadata }));
      }
      isStreamProcessingRef.current = false;
      scheduleStreamStep(
        () => processQueuedStreamsRef.current(),
        AGENT_FIELD_STREAM_SETTLE_DELAY_MS,
        generation,
      );
    },
    [scheduleStreamStep],
  );

  const processQueuedStreams = useCallback(() => {
    if (isStreamProcessingRef.current) return;
    const nextStream = streamQueueRef.current.shift();
    if (!nextStream) {
      setStreamingField(null);
      return;
    }

    const generation = streamGenerationRef.current;
    isStreamProcessingRef.current = true;
    setStreamingField(nextStream.field);

    if (!shouldCharacterStreamField(nextStream.field, nextStream.value)) {
      setForm((previous) => ({
        ...previous,
        [nextStream.field]: nextStream.value,
      }));
      finishCurrentStream(nextStream.field, nextStream.metadata, generation);
      return;
    }

    const streamValue = nextStream.value;
    setForm((previous) => ({ ...previous, [nextStream.field]: "" }));
    let nextCharacterIndex = 0;
    const streamNextCharacter = () => {
      nextCharacterIndex += 1;
      setForm((previous) => ({
        ...previous,
        [nextStream.field]: streamValue.slice(0, nextCharacterIndex),
      }));
      if (nextCharacterIndex < streamValue.length) {
        scheduleStreamStep(
          streamNextCharacter,
          AGENT_FIELD_STREAM_CHARACTER_DELAY_MS,
          generation,
        );
        return;
      }
      finishCurrentStream(nextStream.field, nextStream.metadata, generation);
    };

    scheduleStreamStep(
      streamNextCharacter,
      AGENT_FIELD_STREAM_CHARACTER_DELAY_MS,
      generation,
    );
  }, [finishCurrentStream, scheduleStreamStep]);

  processQueuedStreamsRef.current = processQueuedStreams;

  useEffect(
    () => () => {
      clearQueuedStreams();
    },
    [clearQueuedStreams],
  );

  useEffect(() => {
    if (!conversationId) return undefined;
    initializeAutomationFormSession(conversationId, {
      ...draft,
      form,
      fieldMetadata,
    });
    return () => clearAutomationFormSession(conversationId);
  }, [conversationId]);

  useEffect(() => {
    if (!conversationId) return undefined;
    return subscribeAutomationFormSession(
      conversationId,
      (nextDraft, result) => {
        if (!nextDraft) return;
        const nextForm = buildInitialForm(nextDraft);
        const nextMetadata = nextDraft.fieldMetadata ?? {};
        setExistingCustomTarballPath(nextDraft.existingCustomTarballPath ?? "");
        const agentFields = sortFieldsByRenderOrder(
          (result?.applied ?? []).filter(
            (field) => nextMetadata[field]?.updatedBy === "agent",
          ),
        );

        if (agentFields.length === 0) {
          clearQueuedStreams();
          setForm(nextForm);
          setFieldMetadata(nextMetadata);
          return;
        }

        const protectedFields = new Set<AutomationSetupField>([
          ...agentFields,
          ...streamQueueRef.current.map((queuedStream) => queuedStream.field),
          ...(streamingField ? [streamingField] : []),
        ]);
        setForm((previous) => {
          const syncedForm = { ...nextForm };
          for (const field of protectedFields) {
            (syncedForm as Record<string, unknown>)[field] = previous[field];
          }
          return syncedForm;
        });
        setFieldMetadata((previous) => {
          const syncedMetadata = { ...nextMetadata };
          for (const field of agentFields) {
            if (previous[field]) {
              syncedMetadata[field] = previous[field];
            } else {
              delete syncedMetadata[field];
            }
          }
          return syncedMetadata;
        });
        streamQueueRef.current.push(
          ...agentFields.map((field) => ({
            field,
            value: nextForm[field],
            metadata: nextMetadata[field],
          })),
        );
        processQueuedStreamsRef.current();
      },
    );
  }, [clearQueuedStreams, conversationId, streamingField]);

  const updateField = <FieldName extends AutomationSetupField>(
    field: FieldName,
    value: AutomationSetupFormValues[FieldName],
  ) => {
    clearQueuedStreams();
    setStatusMessage(null);
    setSaveState("idle");
    setForm((previous) => ({ ...previous, [field]: value }));
    if (!conversationId) return;
    patchAutomationFormSession(
      conversationId,
      { [field]: value } as AutomationSetupFormPatch,
      { source: "user" },
    );
  };

  const pluginEntries = useMemo(
    () =>
      resolveAutomationSetupPlugins(
        { pluginList, pluginSource, pluginRef },
        draft.plugins,
      ),
    [draft.plugins, pluginList, pluginRef, pluginSource],
  );
  const configuredPlugins = pluginEntries.flatMap((entry) => {
    const source = entry.source.trim();
    if (!source) return [];
    const ref = entry.ref.trim();
    return [{ source, ...(ref ? { ref } : {}) }];
  });
  const pluginEndpointSource = configuredPlugins[0]?.source ?? "";

  const writePlugins = (entries: AutomationSetupPluginEntry[]) => {
    const nextList =
      entries.length > 0 ? serializeAutomationSetupPluginList(entries) : "";
    const nextSource = entries[0]?.source ?? "";
    const nextRef = entries[0]?.ref ?? "";
    clearQueuedStreams();
    setStatusMessage(null);
    setSaveState("idle");
    setForm((previous) => ({
      ...previous,
      pluginList: nextList,
      pluginSource: nextSource,
      pluginRef: nextRef,
    }));
    if (!conversationId) return;
    patchAutomationFormSession(
      conversationId,
      {
        pluginList: nextList,
        pluginSource: nextSource,
        pluginRef: nextRef,
      },
      { source: "user" },
    );
  };

  const agentUpdatedSuffix = (field: AutomationSetupField) =>
    fieldMetadata[field]?.updatedBy === "agent"
      ? t(I18nKey.AUTOMATION_SETUP$FILLED_BY_OPENHANDS)
      : undefined;

  const updateCustomWebhook = <FieldName extends keyof CustomWebhookFormState>(
    field: FieldName,
    value: CustomWebhookFormState[FieldName],
  ) => {
    setStatusMessage(null);
    setSaveState("idle");
    setCustomWebhookRegistration(null);
    setCustomWebhook((previous) => ({ ...previous, [field]: value }));
  };

  const normalizedName = () => name.trim() || deriveName(prompt);
  const buildTrigger = () =>
    triggerKind === "event"
      ? {
          type: "event",
          source: eventSource.trim() || DEFAULT_EVENT_SOURCE,
          on: eventKeyPayload(eventKey),
          ...(eventFilter.trim() ? { filter: eventFilter.trim() } : {}),
        }
      : {
          type: "cron",
          schedule: toCron(
            time,
            frequency,
            customSchedule.trim(),
            scheduleDateTime,
            weekday,
          ),
          timezone: timezone.trim() || DEFAULT_TIMEZONE,
        };
  const buildPresetBody = (): SetupRequestBody => {
    const trimmedPrompt = prompt.trim();
    const body: SetupRequestBody = {
      name: normalizedName(),
      ...(trimmedPrompt ? { prompt: trimmedPrompt } : {}),
      trigger: buildTrigger(),
      enabled: false,
    } as SetupRequestBody;
    const repositories = parseAutomationSetupRepositories(repository);
    if (repositories.length > 0) {
      body.repos = buildAutomationRepoSources(
        repositories,
        [],
        providerHosts,
        cloneProviders,
      );
    }
    if (showTimeout && timeoutSeconds.trim())
      body.timeout = Number(timeoutSeconds);
    if (configuredPlugins.length > 0) {
      body.plugins = configuredPlugins;
    }
    if (model.trim()) body.model = model.trim();
    return body;
  };
  const buildCustomBody = (tarballPath: string): SetupRequestBody =>
    ({
      name: normalizedName(),
      trigger: buildTrigger(),
      tarball_path: tarballPath,
      entrypoint: entrypoint.trim(),
      setup_script_path: setupScriptPath.trim(),
      ...(showTimeout && timeoutSeconds.trim()
        ? { timeout: Number(timeoutSeconds) }
        : {}),
    }) as SetupRequestBody;
  /**
   * The request body sent to a server-backed draft. Custom drafts reference a
   * tarball path, but a draft is saved before the upload happens, so the
   * preflight stand-in path stands in until dispatch. Preset drafts carry the
   * same body the final create call would, minus the upload-only fields.
   */
  const draftRequestBody = (
    tarballPath: string = PREFLIGHT_TARBALL_PATH,
  ): SetupRequestBody =>
    kind === "custom" ? buildCustomBody(tarballPath) : buildPresetBody();
  const draftValidationByField = useMemo(() => {
    const byField = new Map<string, string>();
    for (const error of serverDraft?.validationErrors ?? []) {
      if (error.field && !byField.has(error.field)) {
        byField.set(error.field, error.message);
      }
    }
    return byField;
  }, [serverDraft?.validationErrors]);
  const fieldError = (field: string): string | undefined =>
    draftValidationByField.get(field);
  const normalizeDraftForDirtyCheck = (body: SetupRequestBody) => {
    if (kind !== "custom" || typeof body !== "object" || body === null) {
      return body;
    }
    return { ...body, tarball_path: PREFLIGHT_TARBALL_PATH };
  };
  const draftRequestKey = (
    endpoint: string,
    draftName: string,
    body: SetupRequestBody,
  ) =>
    JSON.stringify({
      endpoint,
      name: draftName,
      draft: normalizeDraftForDirtyCheck(body),
      customSource:
        kind === "custom"
          ? {
              customCode,
              setupScript,
            }
          : undefined,
    });
  const currentDraftRequestKey = useMemo(
    () =>
      draftRequestKey(
        draftEndpoint(kind, pluginEndpointSource),
        normalizedName(),
        draftRequestBody(),
      ),
    [
      kind,
      name,
      prompt,
      repository,
      pluginSource,
      pluginRef,
      pluginList,
      customCode,
      entrypoint,
      setupScriptPath,
      setupScript,
      triggerKind,
      frequency,
      time,
      weekday,
      scheduleDateTime,
      timezone,
      customSchedule,
      eventSource,
      eventKey,
      eventFilter,
      model,
      agentProfileId,
      showTimeout,
      timeoutSeconds,
    ],
  );
  const isDraftDirty = savedDraftRequestKey
    ? savedDraftRequestKey !== currentDraftRequestKey
    : !serverDraft ||
      draftRequestKey(
        serverDraft.endpoint,
        serverDraft.name ?? "",
        serverDraft.draft,
      ) !== currentDraftRequestKey;
  const wasHydratingServerDraftRef = useRef(false);
  useEffect(() => {
    if (isHydratingServerDraft) {
      wasHydratingServerDraftRef.current = true;
      return;
    }
    if (!wasHydratingServerDraftRef.current || !serverDraft) return;
    wasHydratingServerDraftRef.current = false;
    setSavedDraftRequestKey(currentDraftRequestKey);
  }, [currentDraftRequestKey, isHydratingServerDraft, serverDraft]);

  const ensureCustomWebhookSource = async (): Promise<boolean> => {
    if (triggerKind !== "event" || !customWebhook.enabled) return true;
    const source = eventSource.trim();
    if (!source) {
      setSaveState("error");
      setStatusMessage({
        kind: "error",
        text: t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SOURCE_REQUIRED),
      });
      return false;
    }
    if (customWebhookRegistration?.source === source) return true;

    try {
      const webhook = await AutomationService.createCustomWebhook({
        name:
          customWebhook.name.trim() ||
          t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_DEFAULT_NAME, { source }),
        source,
        event_key_expr:
          customWebhook.eventKeyExpr.trim() ||
          DEFAULT_CUSTOM_WEBHOOK_EVENT_KEY_EXPR,
        signature_header:
          customWebhook.signatureHeader.trim() ||
          DEFAULT_CUSTOM_WEBHOOK_SIGNATURE_HEADER,
        signature_scheme: customWebhook.signatureScheme,
        ...(customWebhook.webhookSecret.trim()
          ? { webhook_secret: customWebhook.webhookSecret.trim() }
          : {}),
      });
      setCustomWebhookRegistration(webhook);
      return true;
    } catch (error) {
      if (getResponseStatus(error) === 409) {
        setStatusMessage({
          kind: "success",
          text: t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_ALREADY_EXISTS, {
            source,
          }),
        });
        return true;
      }
      setSaveState("error");
      displayErrorToast(getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)));
      return false;
    }
  };

  const uploadCustomArchive = async (): Promise<string> => {
    const archive = await packTarGzip([
      { name: MAIN_PY_FILENAME, content: customCode, mode: 0o644 },
      {
        name: setupScriptPath.trim(),
        content: setupScript,
        mode: 0o755,
      },
    ]);
    return AutomationService.uploadAutomationTarball(normalizedName(), archive);
  };
  const persistServerDraft = async (
    tarballPath?: string,
  ): Promise<AutomationDraftApiResponse> => {
    const body = draftRequestBody(tarballPath);
    const request = {
      endpoint: draftEndpoint(kind, pluginEndpointSource),
      draft: body,
      name: normalizedName(),
    };
    const saved = serverDraftId
      ? await AutomationService.updateServerDraft(serverDraftId, request)
      : await AutomationService.createServerDraft(request);
    setServerDraft(saved);
    saveDraftInFormSession(saved, form);
    setSavedDraftRequestKey(
      draftRequestKey(request.endpoint, request.name ?? "", request.draft),
    );
    setIsTaggedDraftMissing(false);
    if (isPendingAutomationSetupId(conversationId) && !serverDraftId) {
      navigate(`/automations/setup?draftId=${encodeURIComponent(saved.id)}`, {
        replace: true,
      });
    }
    await updateConversationDraftTags(saved.id);
    return saved;
  };
  const runPreflightValidation = async () => {
    const result = await AutomationService.validateDraft({
      endpoint: draftValidationEndpoint(kind, pluginEndpointSource),
      draft:
        kind === "custom"
          ? buildCustomBody(PREFLIGHT_TARBALL_PATH)
          : buildPresetBody(),
    });
    setStatusMessage({
      kind: result.valid ? "success" : "error",
      text: result.valid
        ? t(I18nKey.AUTOMATION_SETUP$READY_TO_TEST)
        : result.errors[0]?.message || t(I18nKey.SETUP$SUBMIT_FAILED),
    });
  };
  const validateRequiredFields = (): boolean => {
    if (!prompt.trim() && kind !== "custom") {
      setStatusMessage({
        kind: "error",
        text: t(I18nKey.AUTOMATION_SETUP$PROMPT_REQUIRED),
      });
      return false;
    }
    if (
      kind !== "custom" &&
      pluginEntries.some((entry) => entry.ref.trim() && !entry.source.trim())
    ) {
      setStatusMessage({
        kind: "error",
        text: t(I18nKey.AUTOMATION_SETUP$PLUGIN_REQUIRED),
      });
      return false;
    }
    if (kind === "custom" && !hasExistingCustomBundle && !customCode.trim()) {
      setStatusMessage({
        kind: "error",
        text: t(I18nKey.AUTOMATION_SETUP$CODE_REQUIRED),
      });
      return false;
    }
    if (kind === "custom" && !entrypoint.trim()) {
      setStatusMessage({
        kind: "error",
        text: t(I18nKey.AUTOMATION_SETUP$ENTRYPOINT_REQUIRED),
      });
      return false;
    }
    if (
      kind === "custom" &&
      !hasExistingCustomBundle &&
      !setupScriptPath.trim()
    ) {
      setStatusMessage({
        kind: "error",
        text: t(I18nKey.AUTOMATION_SETUP$SETUP_SCRIPT_PATH_REQUIRED),
      });
      return false;
    }
    if (kind === "custom" && !hasExistingCustomBundle && !setupScript.trim()) {
      setStatusMessage({
        kind: "error",
        text: t(I18nKey.AUTOMATION_SETUP$SETUP_SCRIPT_REQUIRED),
      });
      return false;
    }
    return true;
  };
  const handleSaveDraft = async () => {
    setIsSubmitting(true);
    setSaveState("saving");
    try {
      if (!(await ensureCustomWebhookSource())) return;
      if (!draftsSupported) {
        setSaveState("saved");
        setStatusMessage(null);
        toast.success(t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED));
        return;
      }
      const tarballPath =
        kind === "custom" ? await uploadCustomArchive() : undefined;
      await persistServerDraft(tarballPath);
      setSaveState("saved");
      setStatusMessage(null);
      toast.success(t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED));
    } catch (error) {
      if (isDraftEndpointUnavailable(error)) {
        setSaveState("saved");
        setStatusMessage(null);
        toast.success(t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED));
        return;
      }
      setSaveState("error");
      displayErrorToast(
        getApiErrorMessage(error, t(I18nKey.AUTOMATION_SETUP$SAVE_FAILED)),
      );
    } finally {
      setIsSubmitting(false);
    }
  };
  const handleTest = async () => {
    if (!validateRequiredFields()) return;
    const eventPayload =
      triggerKind === "event" ? parseEventTestPayload(eventTestPayload) : null;
    if (triggerKind === "event" && eventPayload === null) {
      setStatusMessage({
        kind: "error",
        text: t(I18nKey.AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_INVALID),
      });
      return;
    }
    setIsSubmitting(true);
    setSaveState("saving");
    try {
      if (!(await ensureCustomWebhookSource())) return;
      if (!draftsSupported) {
        setSaveState("saved");
        await runPreflightValidation();
        return;
      }

      // Persist the current form state as a draft first, then dispatch it.
      // The service materializes the validated draft body into a disabled
      // automation and starts a manual run; the draft row stays as source
      // of truth for further edits.
      const tarballPath =
        kind === "custom" ? await uploadCustomArchive() : undefined;
      const saved = await persistServerDraft(tarballPath);
      setSaveState("saved");

      if (!saved.dispatchable) {
        // The draft bar already shows the validation error. A second copy
        // at the bottom of the form just repeats it.
        setStatusMessage(
          saved.validationErrors?.[0]?.message
            ? null
            : {
                kind: "error",
                text: t(I18nKey.SETUP$SUBMIT_FAILED),
              },
        );
        return;
      }

      const run = eventPayload
        ? await AutomationService.dispatchServerDraft(saved.id, {
            eventPayload,
          })
        : await AutomationService.dispatchServerDraft(saved.id);
      const materializedAutomationId =
        typeof (run as unknown as Record<string, unknown>).automation_id ===
        "string"
          ? String((run as unknown as Record<string, unknown>).automation_id)
          : saved.materializedAutomationId;
      setServerDraft({
        ...saved,
        materializedAutomationId,
        lastTestRunId: run.id,
      });
      setDraftRuns((previous) => [
        run,
        ...previous.filter((existing) => existing.id !== run.id),
      ]);
      setStatusMessage({
        kind: "success",
        text: t(I18nKey.AUTOMATION_SETUP$TEST_DISPATCHED),
      });
    } catch (error) {
      if (isDraftEndpointUnavailable(error)) {
        setSaveState("saved");
        await runPreflightValidation();
        return;
      }
      setSaveState("error");
      const dispatchError = extractDraftDispatchErrors(error);
      if (dispatchError) {
        setStatusMessage({
          kind: "error",
          text: dispatchError,
        });
      } else {
        displayErrorToast(
          getApiErrorMessage(error, t(I18nKey.AUTOMATIONS$RUN_NOW_ERROR)),
        );
      }
    } finally {
      setIsSubmitting(false);
    }
  };
  const handleCreate = async () => {
    if (!validateRequiredFields()) return;
    setIsSubmitting(true);
    setSaveState(serverDraftId ? "saving" : saveState);
    try {
      if (!(await ensureCustomWebhookSource())) return;
      let created: Record<string, unknown>;
      if (kind === "custom") {
        const tarballPath = await uploadCustomArchive();
        created = await AutomationService.createAutomationDraft(
          buildCustomBody(tarballPath),
          kind,
        );
      } else {
        created = await AutomationService.createAutomationDraft(
          buildPresetBody(),
          presetKindForEndpoint(kind, pluginEndpointSource),
        );
      }
      setSaveState("saved");
      toast.success(t(I18nKey.AUTOMATION_SETUP$CREATED));
      // The draft has been finalized into a real automation; drop the
      // persisted draft row so it does not linger as an incomplete setup.
      if (serverDraftId) {
        try {
          await AutomationService.deleteServerDraft(serverDraftId);
        } catch {
          // Cleanup is best-effort; the automation was created either way.
        }
        try {
          await updateConversationDraftTags(null);
        } catch {
          // Tag cleanup is best-effort once the automation exists.
        }
      }
      if (typeof created.id === "string")
        navigate(automationDetailPath(created.id));
    } catch (error) {
      displayErrorToast(
        getApiErrorMessage(error, t(I18nKey.SETUP$SUBMIT_FAILED)),
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    const automationId = serverDraft?.materializedAutomationId;
    if (!automationId) {
      setDraftRuns([]);
      return undefined;
    }

    let cancelled = false;
    AutomationService.listAutomationRuns(automationId, { limit: 10, offset: 0 })
      .then((response) => {
        if (!cancelled && response.runs.length > 0) setDraftRuns(response.runs);
      })
      .catch(() => {
        if (!cancelled) setDraftRuns((previous) => previous);
      });

    return () => {
      cancelled = true;
    };
  }, [serverDraft?.materializedAutomationId]);

  const saveStateLabel = () => {
    if (saveState === "saving") return t(I18nKey.AUTOMATION_SETUP$SAVING);
    if (saveState === "error") return t(I18nKey.AUTOMATION_SETUP$SAVE_FAILED);
    if (isEditingExisting) {
      return saveState === "saved"
        ? t(I18nKey.AUTOMATION_SETUP$SAVED_JUST_NOW)
        : null;
    }
    if (serverDraft && !isDraftDirty) {
      return t(I18nKey.AUTOMATION_SETUP$SAVED_JUST_NOW);
    }
    if (isDraftDirty) return t(I18nKey.AUTOMATION_SETUP$UNSAVED_CHANGES);
    return null;
  };

  /**
   * Only fields accepted by the backend PATCH contract are sent when editing an
   * existing automation. Plugins and uploaded code are create-time
   * configuration, and repositories are sent only when they changed and the
   * service can rebuild this automation with them.
   */
  const buildExistingAutomationBody = () => {
    const body: Record<string, unknown> = {
      name: normalizedName(),
      trigger: buildTrigger(),
      model: model.trim() || null,
      timeout:
        showTimeout && timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
    };
    if (kind === "custom")
      body.agent_profile_id = agentProfileId.trim() || null;
    else body.prompt = prompt.trim();
    const repositories = parseAutomationSetupRepositories(repository);
    if (
      repositoriesEditable &&
      automationRepositoriesChanged(repositories, existingRepositories)
    ) {
      body.repos = buildAutomationRepoSources(
        repositories,
        existingRepositories,
        providerHosts,
        cloneProviders,
      );
    }
    return body as Partial<Automation>;
  };

  const handleSaveExisting = async () => {
    if (!validateRequiredFields()) return;
    setIsSubmitting(true);
    setSaveState("saving");
    try {
      if (!(await ensureCustomWebhookSource())) return;
      const updated = await AutomationService.updateAutomation(
        editingAutomationId,
        buildExistingAutomationBody(),
      );
      const saved = withPresetSources(updated);
      const savedRepositories = saved.repositories ?? [];
      // The session re-supplies this draft on every edit, so it must hold the
      // saved list too, or the next change is compared with the old one.
      if (conversationId) {
        setAutomationFormSessionRepositories(conversationId, savedRepositories);
      }
      setExistingRepositories(savedRepositories);
      // The automation's page opens Edit from its cached copy, so replace that
      // copy with the saved automation before anything can reopen it.
      const detailKey = [...AUTOMATION_DETAIL_QUERY_KEY, editingAutomationId];
      queryClient.setQueriesData({ queryKey: detailKey }, saved);
      queryClient.invalidateQueries({ queryKey: detailKey });
      queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });
      setSaveState("saved");
      toast.success(t(I18nKey.AUTOMATIONS$EDIT_SUCCESS));
    } catch (error) {
      setSaveState("error");
      displayErrorToast(
        getApiErrorMessage(error, t(I18nKey.AUTOMATIONS$EDIT_ERROR)),
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleTestExisting = async () => {
    setIsSubmitting(true);
    try {
      const run =
        await AutomationService.dispatchAutomation(editingAutomationId);
      setDraftRuns((previous) => [
        run,
        ...previous.filter((existing) => existing.id !== run.id),
      ]);
      setStatusMessage({
        kind: "success",
        text: t(I18nKey.AUTOMATION_SETUP$TEST_DISPATCHED),
      });
    } catch (error) {
      displayErrorToast(
        getApiErrorMessage(error, t(I18nKey.AUTOMATIONS$RUN_NOW_ERROR)),
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  const closeEditor = () => {
    navigate(automationListPath());
  };

  const compactToolbarButtonClassName = "!h-7 !min-h-7 !px-2.5 !text-xs";
  const visiblePluginEntries = kind === "custom" ? [] : pluginEntries;
  const addPlugin = () =>
    writePlugins([
      ...pluginEntries,
      { source: "", ref: DEFAULT_AUTOMATION_PLUGIN_REF },
    ]);
  const saveStateText = saveStateLabel();
  const draftsSupported = AutomationService.supportsAutomationDrafts(
    deploymentCapabilities.data,
  );
  // Server drafts have to be saved before a test can run. Until then the
  // toolbar button stays visible and inactive.
  const canTestDraft =
    !draftsSupported || (serverDraft !== null && !isDraftDirty);

  const renderToolbarActions = () => (
    <div className="flex shrink-0 items-center gap-1.5">
      {saveStateText ? (
        <span
          data-testid="automation-setup-save-state"
          className="shrink-0 text-xs text-[var(--oh-muted)]"
        >
          {saveStateText}
        </span>
      ) : null}
      {isEditingExisting ? (
        <>
          <BrandButton
            type="button"
            variant="secondary"
            testId="automation-setup-test"
            className={compactToolbarButtonClassName}
            isDisabled={isSubmitting}
            aria-busy={isSubmitting}
            onClick={handleTestExisting}
          >
            {t(I18nKey.AUTOMATION_SETUP$TEST)}
          </BrandButton>
          <BrandButton
            type="button"
            variant="primary"
            testId="automation-setup-save"
            className={compactToolbarButtonClassName}
            isDisabled={isSubmitting}
            aria-busy={isSubmitting}
            onClick={handleSaveExisting}
          >
            {t(I18nKey.BUTTON$SAVE)}
          </BrandButton>
          <BrandButton
            type="button"
            variant="secondary"
            testId="automation-setup-close"
            className={compactToolbarButtonClassName}
            onClick={closeEditor}
          >
            {t(I18nKey.BUTTON$CLOSE)}
          </BrandButton>
        </>
      ) : (
        <>
          <BrandButton
            type="button"
            variant="secondary"
            testId="automation-setup-save-draft"
            className={compactToolbarButtonClassName}
            isDisabled={isSubmitting}
            onClick={handleSaveDraft}
          >
            {t(I18nKey.AUTOMATION_SETUP$SAVE_DRAFT)}
          </BrandButton>
          <BrandButton
            type="button"
            variant="secondary"
            testId="automation-setup-test"
            className={compactToolbarButtonClassName}
            isDisabled={isSubmitting || !canTestDraft}
            aria-busy={isSubmitting}
            onClick={() => {
              setIsViewingDraftRuns(true);
              void handleTest();
            }}
          >
            {t(I18nKey.AUTOMATION_SETUP$TEST)}
          </BrandButton>
          <BrandButton
            type="button"
            variant="primary"
            testId="automation-setup-create"
            className={compactToolbarButtonClassName}
            isDisabled={isSubmitting}
            aria-busy={isSubmitting}
            onClick={handleCreate}
          >
            {t(I18nKey.AUTOMATIONS$CREATE_AUTOMATION_BUTTON)}
          </BrandButton>
        </>
      )}
    </div>
  );

  return (
    <>
      {toolbarPortal
        ? createPortal(renderToolbarActions(), toolbarPortal)
        : null}
      <div
        data-testid="automation-setup-panel"
        className="flex h-full min-h-0 flex-col bg-canvas-base"
      >
        {showInlineHeader ? (
          <header className="flex h-10 min-h-10 shrink-0 items-center justify-between gap-2 border-b border-[var(--oh-border)] bg-canvas-base px-3">
            <div className="flex min-w-0 items-center gap-2">
              <h2 className="min-w-0 truncate text-sm font-medium text-content">
                {name.trim() || t(I18nKey.AUTOMATION_SETUP$TITLE)}
              </h2>
            </div>
            {renderToolbarActions()}
          </header>
        ) : null}

        <div
          className={cn(
            "custom-scrollbar-always min-h-0 flex-1 overflow-y-auto px-5 pt-5 [scrollbar-gutter:stable]",
            reserveComposerSpace ? "pb-52" : "pb-5",
          )}
        >
          <div className="mx-auto flex w-full min-w-0 max-w-[800px] flex-col gap-6">
            {serverDraft && !isViewingDraftRuns ? (
              <DraftStatusBar
                draft={serverDraft}
                runs={draftRuns}
                isSubmitting={isSubmitting}
                canTest={isEditingExisting || canTestDraft}
                saveFailed={saveState === "error"}
                onTest={() => {
                  setIsViewingDraftRuns(true);
                  void (isEditingExisting
                    ? handleTestExisting()
                    : handleTest());
                }}
                onViewRuns={() => setIsViewingDraftRuns(true)}
              />
            ) : null}
            {isViewingDraftRuns ? (
              <DraftRunsPage
                runs={draftRuns}
                errors={draftRunPageErrors(
                  serverDraft,
                  statusMessage,
                  draftRuns,
                )}
                isSubmitting={isSubmitting}
                canTest={isEditingExisting || canTestDraft}
                onBack={() => setIsViewingDraftRuns(false)}
                onTest={isEditingExisting ? handleTestExisting : handleTest}
              />
            ) : null}
            <div
              data-testid="automation-setup-form"
              className={cn(
                "flex flex-col gap-6",
                isViewingDraftRuns && "hidden",
              )}
            >
              <Field
                label={t(I18nKey.AUTOMATIONS$NAME)}
                suffix={agentUpdatedSuffix("name")}
                isStreaming={streamingField === "name"}
                errorText={fieldError("name")}
              >
                <input
                  data-testid="automation-setup-name"
                  value={name}
                  placeholder={t(I18nKey.AUTOMATION_SETUP$NAME_PLACEHOLDER)}
                  onChange={(event) => updateField("name", event.target.value)}
                  className={formControlFieldClassName}
                />
              </Field>

              {isHydratingServerDraft ? (
                <p
                  data-testid="automation-setup-draft-loading"
                  className="rounded-2xl border border-[var(--oh-border)] bg-[var(--oh-surface)] px-5 py-4 text-sm text-muted"
                >
                  {t(I18nKey.AUTOMATION_SETUP$LOADING_DRAFT)}
                </p>
              ) : null}

              {isTaggedDraftMissing ? (
                <p
                  data-testid="automation-setup-draft-missing"
                  className="rounded-2xl border border-[var(--oh-warning)]/40 bg-[var(--oh-warning)]/10 px-5 py-4 text-sm text-[var(--oh-warning)]"
                >
                  {t(I18nKey.AUTOMATION_SETUP$DRAFT_MISSING)}
                </p>
              ) : null}

              <div className="flex flex-col gap-2.5">
                <div className="flex w-full items-center gap-2">
                  <span className="flex items-center gap-2 text-sm">
                    {kind === "custom"
                      ? t(I18nKey.AUTOMATION_SETUP$CUSTOM_PYTHON)
                      : t(I18nKey.AUTOMATIONS$PROMPT)}
                    {agentUpdatedSuffix(
                      kind === "custom" ? "customCode" : "prompt",
                    ) ? (
                      <span className="font-normal text-[var(--oh-muted)]">
                        {agentUpdatedSuffix(
                          kind === "custom" ? "customCode" : "prompt",
                        )}
                      </span>
                    ) : null}
                  </span>
                  <button
                    type="button"
                    data-testid={
                      kind === "custom"
                        ? "automation-setup-kind-prompt"
                        : "automation-setup-kind-custom"
                    }
                    onClick={() =>
                      updateField(
                        "kind",
                        kind === "custom" ? "prompt" : "custom",
                      )
                    }
                    className={cn(
                      addOptionButtonClassName,
                      "ml-auto gap-1.5",
                      streamingHighlightClassName(streamingField === "kind"),
                    )}
                  >
                    {kind === "custom" ? (
                      <FileText className="size-4" aria-hidden />
                    ) : (
                      <Code2 className="size-4" aria-hidden />
                    )}
                    {kind === "custom"
                      ? t(I18nKey.AUTOMATIONS$PROMPT)
                      : t(I18nKey.AUTOMATION_SETUP$TYPE_CUSTOM)}
                  </button>
                </div>
                <SetupKindCrossfade
                  view={kind === "custom" ? "custom" : "prompt"}
                >
                  {kind !== "custom" ? (
                    <AutomationSetupPromptStack
                      prompt={prompt}
                      repository={repository}
                      updatedSuffix={agentUpdatedSuffix("prompt")}
                      repositorySuffix={agentUpdatedSuffix("repository")}
                      isStreaming={streamingField === "prompt"}
                      errorText={fieldError("prompt")}
                      showTitle={false}
                      onPromptChange={(value) => updateField("prompt", value)}
                      onRepositoryChange={(value) =>
                        updateField("repository", value)
                      }
                      repositoryReadOnly={!repositoriesEditable}
                      model={model}
                      onModelChange={(value) => updateField("model", value)}
                    />
                  ) : hasExistingCustomBundle ? (
                    <ExistingCustomBundleSummary
                      tarballPath={existingCustomTarballPath}
                    />
                  ) : (
                    <CustomCodeFields
                      code={customCode}
                      entrypoint={entrypoint}
                      setupScriptPath={setupScriptPath}
                      setupScript={setupScript}
                      updatedSuffixes={{
                        customCode: agentUpdatedSuffix("customCode"),
                        entrypoint: agentUpdatedSuffix("entrypoint"),
                        setupScriptPath: agentUpdatedSuffix("setupScriptPath"),
                        setupScript: agentUpdatedSuffix("setupScript"),
                      }}
                      streamingField={streamingField}
                      onCodeChange={(value) => updateField("customCode", value)}
                      onEntrypointChange={(value) =>
                        updateField("entrypoint", value)
                      }
                      onSetupScriptPathChange={(value) =>
                        updateField("setupScriptPath", value)
                      }
                      onSetupScriptChange={(value) =>
                        updateField("setupScript", value)
                      }
                    />
                  )}
                </SetupKindCrossfade>
              </div>

              <section className="flex flex-col gap-2.5">
                <div
                  role="radiogroup"
                  aria-label={t(I18nKey.AUTOMATIONS$DETAIL$TRIGGER)}
                  className={cn(
                    "grid grid-cols-2 gap-2",
                    streamingHighlightClassName(
                      streamingField === "triggerKind",
                    ),
                  )}
                >
                  <TriggerCard
                    icon={<CalendarDays className="size-4" aria-hidden />}
                    title={t(I18nKey.AUTOMATION_SETUP$SCHEDULE)}
                    description={t(
                      I18nKey.AUTOMATION_SETUP$SCHEDULE_DESCRIPTION,
                    )}
                    selected={triggerKind === "cron"}
                    onClick={() => updateField("triggerKind", "cron")}
                  />
                  <TriggerCard
                    icon={<Zap className="size-4" aria-hidden />}
                    title={t(I18nKey.AUTOMATIONS$DETAIL$TRIGGER_EVENT)}
                    description={t(I18nKey.AUTOMATION_SETUP$EVENT_DESCRIPTION)}
                    selected={triggerKind === "event"}
                    onClick={() => updateField("triggerKind", "event")}
                  />
                </div>
              </section>

              {triggerKind === "cron" ? (
                <ScheduleFields
                  frequency={frequency}
                  time={time}
                  weekday={weekday}
                  scheduleDateTime={scheduleDateTime}
                  timezone={timezone}
                  customSchedule={customSchedule}
                  updatedSuffixes={{
                    frequency: agentUpdatedSuffix("frequency"),
                    time: agentUpdatedSuffix("time"),
                    timezone: agentUpdatedSuffix("timezone"),
                    customSchedule: agentUpdatedSuffix("customSchedule"),
                  }}
                  streamingField={streamingField}
                  setFrequency={(value) => {
                    if (value === "custom" && frequency !== "custom") {
                      // Start Custom from the preset the user configured.
                      updateField(
                        "customSchedule",
                        toCron(
                          time,
                          frequency,
                          customSchedule,
                          scheduleDateTime || defaultScheduleDateTimeLocal(),
                          weekday,
                        ),
                      );
                    }
                    updateField("frequency", value);
                    if (value === "once" && !scheduleDateTime.trim()) {
                      updateField(
                        "scheduleDateTime",
                        defaultScheduleDateTimeLocal(),
                      );
                    }
                  }}
                  setTime={(value) => updateField("time", value)}
                  setWeekday={(value) => updateField("weekday", value)}
                  setScheduleDateTime={(value) =>
                    updateField("scheduleDateTime", value)
                  }
                  setTimezone={(value) => updateField("timezone", value)}
                  setCustomSchedule={(value) =>
                    updateField("customSchedule", value)
                  }
                />
              ) : (
                <EventFields
                  eventSource={eventSource}
                  eventKey={eventKey}
                  eventFilter={eventFilter}
                  eventTestPayload={eventTestPayload}
                  eventSourceOptions={eventSourceOptions}
                  eventTypeOptions={eventTypeOptions}
                  customWebhook={customWebhook}
                  customWebhookRegistration={customWebhookRegistration}
                  usesExistingAutomationTestPayload={isEditingExisting}
                  updatedSuffixes={{
                    eventSource: agentUpdatedSuffix("eventSource"),
                    eventKey: agentUpdatedSuffix("eventKey"),
                    eventFilter: agentUpdatedSuffix("eventFilter"),
                  }}
                  streamingField={streamingField}
                  setEventSource={(value) => updateField("eventSource", value)}
                  setEventKey={(value) => updateField("eventKey", value)}
                  setEventFilter={(value) => updateField("eventFilter", value)}
                  setEventTestPayload={(value) => {
                    setIsEventTestPayloadDirty(true);
                    setEventTestPayload(value);
                  }}
                  setCustomWebhookField={updateCustomWebhook}
                />
              )}

              <section className="flex flex-col gap-2.5">
                <span className="text-sm">
                  {t(I18nKey.AUTOMATION_SETUP$ADDITIONAL_OPTIONS)}
                </span>
                {visiblePluginEntries.length > 0 ? (
                  <div
                    data-testid="automation-setup-plugin-module"
                    className="flex flex-col gap-3 rounded-xl border border-[var(--oh-border)] bg-base-secondary p-4"
                  >
                    {visiblePluginEntries.map((entry, index) => (
                      <div
                        key={`plugin-${index}`}
                        className={cn(
                          "flex min-w-0 gap-2",
                          index === 0 ? "items-end" : "items-center",
                        )}
                      >
                        <div className="grid min-w-0 flex-1 gap-3 md:grid-cols-[2fr_1fr]">
                          <Field
                            label={t(I18nKey.AUTOMATION_SETUP$PLUGIN_SOURCE)}
                            showLabel={index === 0}
                            suffix={
                              index === 0
                                ? agentUpdatedSuffix("pluginSource")
                                : undefined
                            }
                            isStreaming={
                              index === 0 && streamingField === "pluginSource"
                            }
                          >
                            <input
                              data-testid={
                                index === 0
                                  ? "automation-setup-plugin-source"
                                  : `automation-setup-plugin-source-${index}`
                              }
                              value={entry.source}
                              aria-label={
                                index === 0
                                  ? undefined
                                  : t(I18nKey.AUTOMATION_SETUP$PLUGIN_SOURCE)
                              }
                              placeholder={t(
                                I18nKey.AUTOMATION_SETUP$PLUGIN_SOURCE_PLACEHOLDER,
                              )}
                              onChange={(event) =>
                                writePlugins(
                                  pluginEntries.map((plugin, entryIndex) =>
                                    entryIndex === index
                                      ? {
                                          ...plugin,
                                          source: event.target.value,
                                        }
                                      : plugin,
                                  ),
                                )
                              }
                              className={formControlFieldClassName}
                            />
                          </Field>
                          <Field
                            label={t(I18nKey.AUTOMATION_SETUP$PLUGIN_REF)}
                            showLabel={index === 0}
                            suffix={
                              index === 0
                                ? agentUpdatedSuffix("pluginRef")
                                : undefined
                            }
                            isStreaming={
                              index === 0 && streamingField === "pluginRef"
                            }
                          >
                            <input
                              data-testid={
                                index === 0
                                  ? "automation-setup-plugin-ref"
                                  : `automation-setup-plugin-ref-${index}`
                              }
                              value={entry.ref}
                              aria-label={
                                index === 0
                                  ? undefined
                                  : t(I18nKey.AUTOMATION_SETUP$PLUGIN_REF)
                              }
                              placeholder={t(
                                I18nKey.AUTOMATION_SETUP$PLUGIN_REF_PLACEHOLDER,
                              )}
                              onChange={(event) =>
                                writePlugins(
                                  pluginEntries.map((plugin, entryIndex) =>
                                    entryIndex === index
                                      ? { ...plugin, ref: event.target.value }
                                      : plugin,
                                  ),
                                )
                              }
                              className={formControlFieldClassName}
                            />
                          </Field>
                        </div>
                        <div
                          className={cn(
                            "flex shrink-0 items-center",
                            index === 0 && formControlHeightClassName,
                          )}
                        >
                          <button
                            type="button"
                            data-testid={
                              index === 0
                                ? "automation-setup-plugin-remove"
                                : `automation-setup-plugin-remove-${index}`
                            }
                            aria-label={`${t(I18nKey.COMMON$REMOVE)} ${t(I18nKey.AUTOMATION_SETUP$TYPE_PLUGIN)}`}
                            className="inline-flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--oh-muted)] hover:bg-white/10 hover:text-white"
                            onMouseDown={(event) => event.preventDefault()}
                            onClick={() => {
                              const nextEntries = pluginEntries.filter(
                                (_, entryIndex) => entryIndex !== index,
                              );
                              writePlugins(nextEntries);
                              if (
                                nextEntries.length === 0 &&
                                kind === "plugin"
                              ) {
                                updateField("kind", "prompt");
                              }
                            }}
                          >
                            <X className="size-4" aria-hidden />
                          </button>
                        </div>
                      </div>
                    ))}
                    <button
                      type="button"
                      data-testid="automation-setup-add-plugin"
                      onClick={addPlugin}
                      className={cn(
                        addOptionButtonClassName,
                        streamingHighlightClassName(
                          streamingField === "pluginSource",
                        ),
                      )}
                    >
                      {`${t(I18nKey.BUTTON$ADD)} ${t(I18nKey.AUTOMATION_SETUP$TYPE_PLUGIN)}`}
                    </button>
                  </div>
                ) : null}
                {showTimeout ? (
                  <label className="flex w-full min-w-0 flex-col gap-2.5 rounded-xl border border-[var(--oh-border)] bg-base-secondary p-4">
                    <div className="flex w-full items-center gap-2">
                      <span className="text-sm font-normal text-content">
                        {t(I18nKey.AUTOMATION_SETUP$TIMEOUT_SECONDS)}
                      </span>
                      <OptionalTag />
                      {agentUpdatedSuffix("timeoutSeconds") ? (
                        <span className="text-xs text-[var(--oh-muted)]">
                          {agentUpdatedSuffix("timeoutSeconds")}
                        </span>
                      ) : null}
                      <button
                        type="button"
                        data-testid="automation-setup-timeout-remove"
                        aria-label={`${t(I18nKey.COMMON$REMOVE)} ${t(I18nKey.AUTOMATION_SETUP$TIMEOUT_SECONDS)}`}
                        className="ml-auto inline-flex size-6 items-center justify-center rounded-md text-[var(--oh-muted)] hover:bg-white/10 hover:text-white"
                        onMouseDown={(event) => event.preventDefault()}
                        onClick={() => {
                          updateField("showTimeout", false);
                          updateField("timeoutSeconds", "");
                        }}
                      >
                        <X className="size-4" aria-hidden />
                      </button>
                    </div>
                    <input
                      data-testid="automation-setup-timeout"
                      type="number"
                      min="1"
                      name="timeout"
                      value={timeoutSeconds}
                      onChange={(event) =>
                        updateField("timeoutSeconds", event.target.value)
                      }
                      className={cn(
                        formControlFieldClassName,
                        streamingHighlightClassName(
                          streamingField === "timeoutSeconds",
                        ),
                      )}
                    />
                  </label>
                ) : null}
                {kind !== "custom" || !showTimeout ? (
                  <div className="flex flex-wrap items-center gap-2">
                    {kind !== "custom" && visiblePluginEntries.length === 0 ? (
                      <button
                        type="button"
                        data-testid="automation-setup-add-plugin"
                        onClick={addPlugin}
                        className={cn(
                          addOptionButtonClassName,
                          streamingHighlightClassName(
                            streamingField === "pluginSource",
                          ),
                        )}
                      >
                        {`${t(I18nKey.BUTTON$ADD)} ${t(I18nKey.AUTOMATION_SETUP$TYPE_PLUGIN)}`}
                      </button>
                    ) : null}
                    {!showTimeout ? (
                      <button
                        type="button"
                        data-testid="automation-setup-add-timeout"
                        onClick={() => updateField("showTimeout", true)}
                        className={cn(
                          addOptionButtonClassName,
                          streamingHighlightClassName(
                            streamingField === "showTimeout",
                          ),
                        )}
                      >
                        {t(I18nKey.AUTOMATION_SETUP$ADD_TIMEOUT)}
                      </button>
                    ) : null}
                  </div>
                ) : null}
              </section>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

const SETUP_KIND_CROSSFADE_SECONDS = 0.15;

function SetupKindCrossfade({
  view,
  children,
}: {
  view: "prompt" | "custom";
  children: ReactNode;
}) {
  const reduceMotion = useReducedMotion();
  if (reduceMotion || import.meta.env.MODE === "test") {
    return children;
  }

  return (
    <div className="relative">
      <AnimatePresence initial={false}>
        <motion.div
          key={view}
          data-testid="automation-setup-kind-crossfade"
          data-kind={view}
          className="w-full"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{
            opacity: 0,
            position: "absolute",
            top: 0,
            left: 0,
            right: 0,
            pointerEvents: "none",
          }}
          transition={{
            duration: SETUP_KIND_CROSSFADE_SECONDS,
            ease: "easeInOut",
          }}
        >
          {children}
        </motion.div>
      </AnimatePresence>
    </div>
  );
}

function ExistingCustomBundleSummary({ tarballPath }: { tarballPath: string }) {
  const { t } = useTranslation("openhands");
  const bundleName = existingTarballDisplayName(tarballPath) || tarballPath;
  const helpText = t(I18nKey.AUTOMATION_SETUP$EXISTING_BUNDLE_HELP);

  return (
    <div
      data-testid="automation-setup-existing-bundle"
      className="rounded-[15px] border border-[var(--oh-border)] bg-[var(--oh-surface)] p-4"
    >
      <div className="mb-2 flex items-center gap-2 text-sm text-content">
        <span>{t(I18nKey.AUTOMATION_SETUP$EXISTING_BUNDLE)}</span>
        <StyledTooltip content={helpText} placement="top">
          <button
            type="button"
            aria-label={helpText}
            data-testid="automation-setup-existing-bundle-info"
            className="inline-flex size-5 shrink-0 items-center justify-center rounded-full text-[var(--oh-muted)]"
            onMouseDown={(event) => event.preventDefault()}
          >
            <Info className="size-4" aria-hidden />
          </button>
        </StyledTooltip>
      </div>
      <div
        data-testid="automation-setup-existing-bundle-name"
        title={tarballPath}
        className="truncate rounded-lg border border-[var(--oh-border)] bg-[var(--oh-surface-raised)] px-3 py-2 font-mono text-sm text-content"
      >
        {bundleName}
      </div>
    </div>
  );
}

const CUSTOM_CODE_LINE_HEIGHT_PX = 20;
const CUSTOM_CODE_PAD_PX = 16;
const CUSTOM_CODE_VISIBLE_LINES = 12;
/** Top inset plus whole lines, so the scrollbar sits on the card edge and the clip falls between lines. */
const CUSTOM_CODE_MIN_HEIGHT =
  CUSTOM_CODE_PAD_PX + CUSTOM_CODE_VISIBLE_LINES * CUSTOM_CODE_LINE_HEIGHT_PX;
const CUSTOM_CODE_MAX_HEIGHT =
  CUSTOM_CODE_PAD_PX + 28 * CUSTOM_CODE_LINE_HEIGHT_PX;

function CustomCodeFields({
  code,
  entrypoint,
  setupScriptPath,
  setupScript,
  updatedSuffixes,
  streamingField,
  onCodeChange,
  onEntrypointChange,
  onSetupScriptPathChange,
  onSetupScriptChange,
}: {
  code: string;
  entrypoint: string;
  setupScriptPath: string;
  setupScript: string;
  updatedSuffixes: Partial<
    Record<
      "customCode" | "entrypoint" | "setupScriptPath" | "setupScript",
      string | undefined
    >
  >;
  streamingField: AutomationSetupField | null;
  onCodeChange: (value: string) => void;
  onEntrypointChange: (value: string) => void;
  onSetupScriptPathChange: (value: string) => void;
  onSetupScriptChange: (value: string) => void;
}) {
  const { t } = useTranslation("openhands");
  const reduceMotion = useReducedMotion();
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const frameRef = useRef<HTMLDivElement>(null);
  const [detailsOpen, setDetailsOpen] = useState(
    () =>
      entrypoint !== DEFAULT_CUSTOM_ENTRYPOINT ||
      setupScriptPath !== DEFAULT_CUSTOM_SETUP_SCRIPT_PATH ||
      setupScript !== DEFAULT_CUSTOM_SETUP_SCRIPT,
  );
  const { gripRef, isGripDragging, handleGripMouseDown, handleGripTouchStart } =
    usePromptTextareaResize(frameRef, {
      minHeight: CUSTOM_CODE_MIN_HEIGHT,
      maxHeight: CUSTOM_CODE_MAX_HEIGHT,
      contentKey: code,
    });

  useLayoutEffect(() => {
    const textarea = textareaRef.current;
    if (!textarea) return;
    textarea.style.height = "0px";
    textarea.style.height = `${textarea.scrollHeight}px`;
  }, [code]);

  return (
    <div className="relative w-full">
      <div
        data-streaming-active={
          streamingField === "customCode" ? "true" : undefined
        }
        className={cn(
          "relative z-10 -mb-[15px] overflow-hidden rounded-[15px] border border-[var(--oh-border)] bg-[var(--oh-surface)]",
          streamingHighlightClassName(streamingField === "customCode"),
        )}
      >
        <div
          ref={frameRef}
          data-testid="automation-setup-custom-code-scroll"
          className="custom-scrollbar-always min-h-[256px] overflow-x-hidden"
        >
          <div className="px-4 pt-4 pb-4">
            <textarea
              ref={textareaRef}
              data-testid="automation-setup-custom-code"
              aria-label={t(I18nKey.AUTOMATION_SETUP$CUSTOM_PYTHON)}
              rows={CUSTOM_CODE_VISIBLE_LINES}
              value={code}
              onChange={(event) => onCodeChange(event.target.value)}
              spellCheck={false}
              className="block w-full resize-none overflow-hidden border-0 bg-transparent p-0 font-mono text-sm leading-5 text-content outline-none"
            />
          </div>
        </div>
        <div
          data-testid="automation-setup-custom-code-grip"
          className="group absolute bottom-0 left-0 z-20 h-3 w-full"
        >
          <div
            className="absolute inset-0 z-[1] cursor-ns-resize select-none"
            onMouseDown={handleGripMouseDown}
            onTouchStart={handleGripTouchStart}
            aria-hidden
          />
          <div
            ref={gripRef}
            className={cn(
              "pointer-events-none absolute bottom-0 left-0 z-[2] h-px w-full bg-white transition-opacity duration-200",
              isGripDragging
                ? "opacity-100"
                : "opacity-0 group-hover:opacity-100",
            )}
          />
        </div>
      </div>
      <div
        data-testid="automation-setup-custom-details-drawer"
        className="rounded-b-[15px] border-x border-b border-[var(--oh-border)] bg-[var(--oh-surface-raised)] px-4 pb-2 pt-[calc(15px+0.5rem)]"
      >
        <button
          type="button"
          data-testid="automation-setup-custom-details-toggle"
          aria-expanded={detailsOpen}
          aria-controls="automation-setup-custom-details"
          onClick={() => setDetailsOpen((open) => !open)}
          className="flex w-full items-center gap-2 text-left text-sm"
        >
          <ChevronDown
            className={cn(
              "size-4 shrink-0 text-[var(--oh-muted)] transition-transform duration-200 motion-reduce:transition-none",
              detailsOpen && "rotate-180",
            )}
            aria-hidden
          />
          {t(I18nKey.AUTOMATION_SETUP$SHOW_ENTRYPOINT_AND_SETUP)}
        </button>
        <CustomDetailsReveal open={detailsOpen} instant={reduceMotion}>
          <div className="flex flex-col gap-4 pt-3">
            <div className="grid gap-3 md:grid-cols-[2fr_1fr]">
              <Field
                label={t(I18nKey.AUTOMATION_SETUP$ENTRYPOINT)}
                suffix={updatedSuffixes.entrypoint}
                isStreaming={streamingField === "entrypoint"}
              >
                <input
                  data-testid="automation-setup-entrypoint"
                  value={entrypoint}
                  onChange={(event) => onEntrypointChange(event.target.value)}
                  className={formControlFieldClassName}
                />
              </Field>
              <Field
                label={t(I18nKey.AUTOMATION_SETUP$SETUP_SCRIPT_PATH)}
                suffix={updatedSuffixes.setupScriptPath}
                isStreaming={streamingField === "setupScriptPath"}
              >
                <input
                  data-testid="automation-setup-setup-script-path"
                  value={setupScriptPath}
                  onChange={(event) =>
                    onSetupScriptPathChange(event.target.value)
                  }
                  className={formControlFieldClassName}
                />
              </Field>
            </div>
            <Field
              label={t(I18nKey.AUTOMATION_SETUP$SETUP_SCRIPT)}
              suffix={updatedSuffixes.setupScript}
              isStreaming={streamingField === "setupScript"}
            >
              <textarea
                data-testid="automation-setup-setup-script"
                rows={4}
                value={setupScript}
                onChange={(event) => onSetupScriptChange(event.target.value)}
                spellCheck={false}
                className={cn(
                  formControlMultilineFieldClassName,
                  "font-mono text-xs",
                )}
              />
            </Field>
          </div>
        </CustomDetailsReveal>
      </div>
    </div>
  );
}

const CUSTOM_DETAILS_REVEAL_SECONDS = 0.22;

function CustomDetailsReveal({
  open,
  instant,
  children,
}: {
  open: boolean;
  instant: boolean | null;
  children: ReactNode;
}) {
  if (instant || import.meta.env.MODE === "test") {
    if (!open) return null;
    return <div id="automation-setup-custom-details">{children}</div>;
  }

  return (
    <AnimatePresence initial={false}>
      {open ? (
        <motion.div
          id="automation-setup-custom-details"
          initial={{ height: 0, opacity: 0 }}
          animate={{ height: "auto", opacity: 1 }}
          exit={{ height: 0, opacity: 0 }}
          transition={{
            duration: CUSTOM_DETAILS_REVEAL_SECONDS,
            ease: "easeInOut",
          }}
          className="overflow-hidden"
        >
          {children}
        </motion.div>
      ) : null}
    </AnimatePresence>
  );
}

function frequencyTabClassName(selected: boolean) {
  return cn(
    "inline-flex h-full shrink-0 items-center rounded-md px-1.5 text-sm",
    formControlTransitionClassName,
    selected
      ? cn(
          formControlBorderClassName,
          formControlSurfaceClassName,
          "border-[var(--oh-interactive-hover)] text-content",
        )
      : "border border-transparent text-[var(--oh-muted)] hover:text-content",
  );
}

const WEEKDAY_KEYS: I18nKey[] = [
  I18nKey.AUTOMATIONS$WEEKDAY_SUN,
  I18nKey.AUTOMATIONS$WEEKDAY_MON,
  I18nKey.AUTOMATIONS$WEEKDAY_TUE,
  I18nKey.AUTOMATIONS$WEEKDAY_WED,
  I18nKey.AUTOMATIONS$WEEKDAY_THU,
  I18nKey.AUTOMATIONS$WEEKDAY_FRI,
  I18nKey.AUTOMATIONS$WEEKDAY_SAT,
];

function ScheduleFields({
  frequency,
  time,
  weekday,
  scheduleDateTime,
  timezone,
  customSchedule,
  updatedSuffixes,
  streamingField,
  setFrequency,
  setTime,
  setWeekday,
  setScheduleDateTime,
  setTimezone,
  setCustomSchedule,
}: {
  frequency: Frequency;
  time: string;
  weekday: string;
  scheduleDateTime: string;
  timezone: string;
  customSchedule: string;
  updatedSuffixes: Partial<
    Record<
      "frequency" | "time" | "scheduleDateTime" | "timezone" | "customSchedule",
      string | undefined
    >
  >;
  streamingField: AutomationSetupField | null;
  setFrequency: (value: Frequency) => void;
  setTime: (value: string) => void;
  setWeekday: (value: string) => void;
  setScheduleDateTime: (value: string) => void;
  setTimezone: (value: string) => void;
  setCustomSchedule: (value: string) => void;
}) {
  const { t } = useTranslation("openhands");
  const atUpdatedSuffix =
    updatedSuffixes.time ??
    updatedSuffixes.scheduleDateTime ??
    updatedSuffixes.timezone;
  const showTime =
    frequency === "daily" || frequency === "weekdays" || frequency === "weekly";
  const timezoneChoices = TIMEZONE_OPTIONS.includes(
    timezone as (typeof TIMEZONE_OPTIONS)[number],
  )
    ? TIMEZONE_OPTIONS
    : [timezone, ...TIMEZONE_OPTIONS];

  return (
    <section className="flex flex-col gap-2.5">
      <div className="flex min-w-0 items-center gap-2">
        <span className="flex shrink-0 items-center gap-2 text-sm">
          <span>{t(I18nKey.AUTOMATION_SETUP$FREQUENCY)}</span>
          {updatedSuffixes.frequency && (
            <span className="text-xs font-normal text-[var(--oh-muted)]">
              {updatedSuffixes.frequency}
            </span>
          )}
        </span>
        <div
          role="radiogroup"
          aria-label={t(I18nKey.AUTOMATION_SETUP$FREQUENCY)}
          className={cn(
            formControlHeightClassName,
            formControlRadiusClassName,
            "inline-flex max-w-full min-w-0 items-center gap-0.5 overflow-x-auto bg-[var(--oh-surface-raised)] p-0.5",
            streamingHighlightClassName(streamingField === "frequency"),
          )}
        >
          {FREQUENCIES.map((item) => (
            <button
              key={item}
              type="button"
              role="radio"
              data-testid={`automation-setup-frequency-${item}`}
              aria-checked={frequency === item}
              onClick={() => setFrequency(item)}
              className={frequencyTabClassName(frequency === item)}
            >
              {t(frequencyLabelKey(item))}
            </button>
          ))}
        </div>
      </div>
      <div
        data-testid="automation-setup-at-row"
        className="flex w-full min-w-0 items-center gap-4 overflow-x-auto"
      >
        {frequency === "custom" ? (
          <label className="flex shrink-0 items-center gap-2.5">
            <span className="shrink-0 text-sm text-content">
              {t(I18nKey.AUTOMATION_SETUP$TYPE_CUSTOM)}
            </span>
            <input
              data-testid="automation-setup-custom-schedule"
              value={customSchedule}
              onChange={(event) => setCustomSchedule(event.target.value)}
              className={cn(formControlFieldClassName, "w-[14rem]")}
            />
          </label>
        ) : null}
        {frequency === "once" ? (
          <div className="flex shrink-0 items-center gap-2.5">
            <span className="shrink-0 text-sm text-content">
              {t(I18nKey.AUTOMATION_SETUP$AT)}
            </span>
            <input
              aria-label={t(I18nKey.AUTOMATION_SETUP$AT)}
              data-testid="automation-setup-datetime"
              type="datetime-local"
              value={scheduleDateTime || defaultScheduleDateTimeLocal()}
              onChange={(event) => setScheduleDateTime(event.target.value)}
              className={cn(formControlFieldClassName, "w-[15rem]")}
            />
          </div>
        ) : null}
        {showTime ? (
          <div className="flex shrink-0 items-center gap-2.5">
            <span className="shrink-0 text-sm text-content">
              {t(I18nKey.AUTOMATION_SETUP$AT)}
            </span>
            <input
              aria-label={t(I18nKey.AUTOMATION_SETUP$AT)}
              data-testid="automation-setup-time"
              type="time"
              value={time}
              onChange={(event) => setTime(event.target.value)}
              className={cn(formControlFieldClassName, "w-[9.5rem]")}
            />
          </div>
        ) : null}
        {frequency === "weekly" ? (
          <div className="flex shrink-0 items-center gap-2.5">
            <span className="shrink-0 text-sm text-content">
              {t(I18nKey.AUTOMATION_SETUP$ON)}
            </span>
            <div
              className={cn(
                "relative w-fit shrink-0",
                streamingHighlightClassName(streamingField === "weekday"),
              )}
            >
              <select
                aria-label={t(I18nKey.AUTOMATIONS$WEEKDAY)}
                data-testid="automation-setup-weekday"
                value={weekday}
                onChange={(event) => setWeekday(event.target.value)}
                className={cn(
                  formControlFieldClassName,
                  "w-auto appearance-none pr-8",
                )}
              >
                {WEEKDAY_KEYS.map((key, index) => (
                  <option key={key} value={String(index)}>
                    {t(key)}
                  </option>
                ))}
              </select>
              <ChevronDown
                className="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-[var(--oh-muted)]"
                aria-hidden
              />
            </div>
          </div>
        ) : null}
        <div
          data-streaming-active={
            streamingField === "timezone" ? "true" : undefined
          }
          className={cn(
            "relative w-[16rem] shrink-0",
            streamingHighlightClassName(streamingField === "timezone"),
          )}
        >
          <Globe2
            className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-[var(--oh-muted)]"
            aria-hidden
          />
          <select
            aria-label={t(I18nKey.AUTOMATIONS$TIMEZONE)}
            data-testid="automation-setup-timezone"
            value={timezone}
            onChange={(event) => setTimezone(event.target.value)}
            className={cn(
              formControlFieldClassName,
              "appearance-none pl-9 pr-8",
            )}
          >
            {timezoneChoices.map((option) => (
              <option key={option} value={option}>
                {option}
              </option>
            ))}
          </select>
          <ChevronDown
            className="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-[var(--oh-muted)]"
            aria-hidden
          />
        </div>
        {atUpdatedSuffix && (
          <span className="shrink-0 text-xs font-normal text-[var(--oh-muted)]">
            {atUpdatedSuffix}
          </span>
        )}
      </div>
    </section>
  );
}

function knownEventSources(options: string[]) {
  return options.length > 0 ? options : FALLBACK_EVENT_SOURCES;
}

function eventSourceInputValue(value: string, knownSources: string[]) {
  const match = knownSources.find(
    (source) => source.toLowerCase() === value.trim().toLowerCase(),
  );
  return match ? formatTriggerSourceLabel(match) : value;
}

function commitEventSourceInput(typed: string, knownSources: string[]) {
  const normalized = typed.trim().toLowerCase();
  const match = knownSources.find((source) => {
    return (
      source.toLowerCase() === normalized ||
      formatTriggerSourceLabel(source).toLowerCase() === normalized
    );
  });
  return match ?? typed;
}

function EventSourceControl({
  value,
  options,
  onChange,
  onSelectCustom,
}: {
  value: string;
  options: string[];
  onChange: (value: string) => void;
  onSelectCustom: () => void;
}) {
  const { t } = useTranslation("openhands");
  const knownSources = knownEventSources(options);
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);
  const menuRef = useClickOutsideElement<HTMLDivElement>(
    () => setIsMenuOpen(false),
    triggerRef,
  );

  return (
    <div className="relative">
      <input
        ref={inputRef}
        data-testid="automation-setup-event-source"
        value={eventSourceInputValue(value, knownSources)}
        placeholder={t(
          I18nKey.AUTOMATION_SETUP$EVENT_SOURCE_CUSTOM_PLACEHOLDER,
        )}
        onChange={(event) =>
          onChange(commitEventSourceInput(event.target.value, knownSources))
        }
        className={cn(formControlFieldClassName, "pr-9")}
      />
      <button
        ref={triggerRef}
        type="button"
        data-testid="automation-setup-event-source-toggle"
        aria-label={t(I18nKey.AUTOMATION_SETUP$EVENT_SOURCE)}
        aria-haspopup="menu"
        aria-expanded={isMenuOpen}
        className="absolute top-1/2 right-2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-[var(--oh-muted)] hover:bg-white/10 hover:text-white"
        onMouseDown={(event) => event.preventDefault()}
        onClick={() => setIsMenuOpen((open) => !open)}
      >
        <ChevronDown className="size-4 shrink-0" aria-hidden />
      </button>
      {isMenuOpen ? (
        <div
          ref={menuRef}
          role="menu"
          data-testid="automation-setup-event-source-menu"
          className="absolute top-full left-0 z-[60] mt-1 flex max-h-72 w-full flex-col overflow-hidden rounded-md border border-border-subtle bg-tertiary py-1 shadow-lg"
        >
          <div className="min-h-0 flex-1 overflow-y-auto px-1">
            {knownSources.map((source) => (
              <ContextMenuListItem
                key={source}
                testId={`automation-setup-event-source-option-${source}`}
                onClick={(event) => {
                  event.preventDefault();
                  event.stopPropagation();
                  onChange(source);
                  setIsMenuOpen(false);
                }}
                className="flex w-full items-center"
              >
                <span className="truncate">
                  {formatTriggerSourceLabel(source)}
                </span>
              </ContextMenuListItem>
            ))}
          </div>
          <Divider inset="menu" />
          <div className="shrink-0 px-1">
            <ContextMenuListItem
              testId="automation-setup-event-source-custom"
              onClick={(event) => {
                event.preventDefault();
                event.stopPropagation();
                onSelectCustom();
                setIsMenuOpen(false);
                queueMicrotask(() => inputRef.current?.focus());
              }}
              className="flex w-full items-center"
            >
              <span className="truncate">
                {t(I18nKey.AUTOMATION_SETUP$TYPE_CUSTOM)}
              </span>
            </ContextMenuListItem>
          </div>
        </div>
      ) : null}
    </div>
  );
}

function EventFields({
  eventSource,
  eventKey,
  eventFilter,
  eventTestPayload,
  eventSourceOptions,
  eventTypeOptions,
  customWebhook,
  customWebhookRegistration,
  usesExistingAutomationTestPayload,
  updatedSuffixes,
  streamingField,
  setEventSource,
  setEventKey,
  setEventFilter,
  setEventTestPayload,
  setCustomWebhookField,
}: {
  eventSource: string;
  eventKey: string;
  eventFilter: string;
  eventTestPayload: string;
  eventSourceOptions: string[];
  eventTypeOptions: string[];
  customWebhook: CustomWebhookFormState;
  customWebhookRegistration: CustomWebhookCreateResponse | null;
  usesExistingAutomationTestPayload: boolean;
  updatedSuffixes: Partial<
    Record<"eventSource" | "eventKey" | "eventFilter", string | undefined>
  >;
  streamingField: AutomationSetupField | null;
  setEventSource: (value: string) => void;
  setEventKey: (value: string) => void;
  setEventFilter: (value: string) => void;
  setEventTestPayload: (value: string) => void;
  setCustomWebhookField: <FieldName extends keyof CustomWebhookFormState>(
    field: FieldName,
    value: CustomWebhookFormState[FieldName],
  ) => void;
}) {
  const { t } = useTranslation("openhands");
  const { send } = useSendMessage();
  const [isEventFilterOpen, setIsEventFilterOpen] = useState(
    () => eventFilter.trim().length > 0,
  );
  const [isTestPayloadOpen, setIsTestPayloadOpen] = useState(false);
  const showEventFilter =
    isEventFilterOpen ||
    eventFilter.trim().length > 0 ||
    streamingField === "eventFilter";
  const knownSources = knownEventSources(eventSourceOptions);
  const sourceIsKnown = (source: string) =>
    knownSources.some(
      (option) => option.toLowerCase() === source.trim().toLowerCase(),
    );
  const handleEventSourceChange = (value: string) => {
    const leavingKnownSource =
      sourceIsKnown(eventSource) && !sourceIsKnown(value);
    setEventSource(value);
    if (leavingKnownSource) setCustomWebhookField("enabled", true);
    if (sourceIsKnown(value)) setCustomWebhookField("enabled", false);
  };
  const selectCustomEventSource = () => {
    setEventSource("");
    setCustomWebhookField("enabled", true);
  };
  return (
    <div className="@container min-w-0">
      <section className="grid gap-3 @min-[640px]:grid-cols-2">
        <div className="flex min-w-0 flex-col gap-1.5">
          <Field
            label={t(I18nKey.AUTOMATION_SETUP$EVENT_SOURCE)}
            suffix={updatedSuffixes.eventSource}
            isStreaming={streamingField === "eventSource"}
          >
            <EventSourceControl
              value={eventSource}
              options={eventSourceOptions}
              onChange={handleEventSourceChange}
              onSelectCustom={selectCustomEventSource}
            />
          </Field>
          <p
            role="note"
            data-testid="automation-setup-event-public-url-notice"
            className="flex items-start gap-1.5 text-xs leading-4 text-[var(--oh-muted)]"
          >
            <Info className="mt-0.5 size-3.5 shrink-0" aria-hidden />
            {t(I18nKey.AUTOMATION_SETUP$EVENT_PUBLIC_URL_NOTICE)}
          </p>
        </div>
        <div className="flex min-w-0 flex-wrap items-end gap-2 self-start">
          <div
            className={cn(
              "flex min-w-48 flex-1 flex-col gap-2",
              streamingHighlightClassName(streamingField === "eventKey"),
            )}
          >
            <label
              htmlFor="automation-setup-event-key"
              className="flex shrink-0 items-center gap-2 text-sm"
            >
              {t(I18nKey.AUTOMATION_SETUP$EVENT_KEY)}
              {updatedSuffixes.eventKey ? (
                <span className="font-normal text-[var(--oh-muted)]">
                  {updatedSuffixes.eventKey}
                </span>
              ) : null}
            </label>
            <div
              className={cn(
                "flex w-full min-w-0 overflow-hidden",
                formControlHeightClassName,
                formControlRadiusClassName,
                formControlBorderClassName,
                formControlSurfaceClassName,
                formControlTransitionClassName,
                formControlFocusWithinClassName,
                streamingHighlightClassName(streamingField === "eventFilter"),
              )}
            >
              <input
                id="automation-setup-event-key"
                data-testid="automation-setup-event-key"
                value={eventKey}
                list="automation-setup-event-key-options"
                onChange={(event) => setEventKey(event.target.value)}
                className="min-w-0 flex-1 border-0 bg-transparent px-3 text-sm text-contrast outline-none"
              />
              <datalist id="automation-setup-event-key-options">
                {eventTypeOptions.map((eventType) => (
                  <option key={eventType} value={eventType} />
                ))}
              </datalist>
              {showEventFilter ? null : (
                <button
                  type="button"
                  data-testid="automation-setup-add-event-filter"
                  onClick={() => setIsEventFilterOpen(true)}
                  className="inline-flex shrink-0 items-center border-l border-[var(--oh-border)] bg-tertiary px-3 text-sm text-content hover:bg-interactive-hover"
                >
                  {t(I18nKey.AUTOMATION_SETUP$ADD_FILTER)}
                </button>
              )}
            </div>
          </div>
          <button
            type="button"
            data-testid="automation-setup-ask-agent"
            className={cn(addOptionButtonClassName, "h-9 gap-1.5")}
            onClick={() => {
              requestAutomationSetupAgent();
              void send({
                action: "message",
                args: {
                  content: t(I18nKey.AUTOMATION_SETUP$ASK_AGENT_EVENT_PROMPT),
                },
              });
            }}
          >
            <SparkleIcon className="size-3.5 shrink-0" aria-hidden />
            {t(I18nKey.AUTOMATION_SETUP$ASK_AGENT)}
          </button>
        </div>
        {showEventFilter ? (
          <div className="@min-[640px]:col-span-2">
            <div className="relative">
              <button
                type="button"
                data-testid="automation-setup-event-filter-remove"
                aria-label={`${t(I18nKey.COMMON$REMOVE)} ${t(I18nKey.AUTOMATION_SETUP$EVENT_FILTER)}`}
                className="absolute right-0 top-0 inline-flex size-6 items-center justify-center rounded-md text-[var(--oh-muted)] hover:bg-white/10 hover:text-white"
                onClick={() => {
                  setIsEventFilterOpen(false);
                  setEventFilter("");
                }}
              >
                <X className="size-4" aria-hidden />
              </button>
              <Field
                label={t(I18nKey.AUTOMATION_SETUP$EVENT_FILTER)}
                suffix={
                  updatedSuffixes.eventFilter ?? t(I18nKey.COMMON$OPTIONAL)
                }
                isStreaming={streamingField === "eventFilter"}
              >
                <input
                  data-testid="automation-setup-event-filter"
                  value={eventFilter}
                  onChange={(event) => setEventFilter(event.target.value)}
                  className={formControlFieldClassName}
                />
              </Field>
            </div>
          </div>
        ) : null}
        {eventSource.trim() !== "" &&
        !(
          eventSourceOptions.length > 0
            ? eventSourceOptions
            : FALLBACK_EVENT_SOURCES
        ).includes(eventSource.trim()) ? (
          <div className="@min-[640px]:col-span-2">
            <section className="rounded-xl border border-[var(--oh-border)] p-3">
              <div className="flex items-start gap-3 text-sm">
                <input
                  id="automation-setup-custom-webhook-enabled"
                  type="checkbox"
                  data-testid="automation-setup-custom-webhook-enabled"
                  checked={customWebhook.enabled}
                  onChange={(event) =>
                    setCustomWebhookField("enabled", event.target.checked)
                  }
                  className="mt-1"
                />
                <label
                  htmlFor="automation-setup-custom-webhook-enabled"
                  className="flex flex-col gap-1"
                >
                  <span>
                    {t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_TITLE)}
                  </span>
                  <span className="text-xs font-normal leading-5 text-[var(--oh-muted)]">
                    {t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_DESCRIPTION)}
                  </span>
                </label>
              </div>
              {customWebhook.enabled && (
                <div className="mt-3 grid gap-3 md:grid-cols-2">
                  <Field
                    label={t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_NAME)}
                  >
                    <input
                      data-testid="automation-setup-custom-webhook-name"
                      value={customWebhook.name}
                      onChange={(event) =>
                        setCustomWebhookField("name", event.target.value)
                      }
                      className={formControlFieldClassName}
                      placeholder={t(
                        I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_NAME_PLACEHOLDER,
                      )}
                    />
                  </Field>
                  <Field
                    label={t(
                      I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_EVENT_KEY_EXPR,
                    )}
                  >
                    <input
                      data-testid="automation-setup-custom-webhook-event-key-expr"
                      value={customWebhook.eventKeyExpr}
                      onChange={(event) =>
                        setCustomWebhookField(
                          "eventKeyExpr",
                          event.target.value,
                        )
                      }
                      className={formControlFieldClassName}
                    />
                  </Field>
                  <Field
                    label={t(
                      I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_HEADER,
                    )}
                  >
                    <input
                      data-testid="automation-setup-custom-webhook-signature-header"
                      value={customWebhook.signatureHeader}
                      onChange={(event) =>
                        setCustomWebhookField(
                          "signatureHeader",
                          event.target.value,
                        )
                      }
                      className={formControlFieldClassName}
                    />
                  </Field>
                  <Field
                    label={t(
                      I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME,
                    )}
                  >
                    <select
                      data-testid="automation-setup-custom-webhook-signature-scheme"
                      value={customWebhook.signatureScheme}
                      onChange={(event) =>
                        setCustomWebhookField(
                          "signatureScheme",
                          event.target.value as CustomWebhookSignatureScheme,
                        )
                      }
                      className={formControlFieldClassName}
                    >
                      <option value="hmac_sha256_hex">
                        {t(
                          I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME_HMAC,
                        )}
                      </option>
                      <option value="standard_webhooks">
                        {t(
                          I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME_STANDARD,
                        )}
                      </option>
                      <option value="slack_v0">
                        {t(
                          I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME_SLACK,
                        )}
                      </option>
                    </select>
                  </Field>
                  <div className="md:col-span-2">
                    <Field
                      label={t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SECRET)}
                      suffix={t(I18nKey.COMMON$OPTIONAL)}
                    >
                      <input
                        data-testid="automation-setup-custom-webhook-secret"
                        type="password"
                        value={customWebhook.webhookSecret}
                        onChange={(event) =>
                          setCustomWebhookField(
                            "webhookSecret",
                            event.target.value,
                          )
                        }
                        className={formControlFieldClassName}
                        placeholder={t(
                          I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SECRET_PLACEHOLDER,
                        )}
                      />
                    </Field>
                    <p className="mt-2 text-xs leading-5 text-[var(--oh-muted)]">
                      {t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SECRET_HELP)}
                    </p>
                  </div>
                  {customWebhookRegistration && (
                    <div
                      data-testid="automation-setup-custom-webhook-result"
                      className="md:col-span-2 rounded-lg border border-[var(--oh-success)]/40 bg-[var(--oh-success)]/10 p-3 text-xs leading-5 text-white"
                    >
                      <p className="font-medium">
                        {t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_CREATED)}
                      </p>
                      <p className="break-all">
                        {t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_URL, {
                          url: customWebhookRegistration.webhook_url,
                        })}
                      </p>
                      {customWebhookRegistration.webhook_secret && (
                        <p className="break-all">
                          {t(
                            I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_GENERATED_SECRET,
                            {
                              secret: customWebhookRegistration.webhook_secret,
                            },
                          )}
                        </p>
                      )}
                    </div>
                  )}
                </div>
              )}
            </section>
          </div>
        ) : null}
        <div className="@min-[640px]:col-span-2">
          {usesExistingAutomationTestPayload ? (
            <p
              role="note"
              data-testid="automation-setup-existing-test-payload-note"
              className="flex items-start gap-1.5 rounded-lg border border-[var(--oh-border)] bg-[var(--oh-surface)] p-3 text-xs leading-5 text-[var(--oh-muted)]"
            >
              <Info className="mt-0.5 size-3.5 shrink-0" aria-hidden />
              {t(I18nKey.AUTOMATION_SETUP$EXISTING_TEST_PAYLOAD_NOTICE)}
            </p>
          ) : (
            <>
              <button
                type="button"
                data-testid="automation-setup-event-test-payload-toggle"
                aria-expanded={isTestPayloadOpen}
                aria-controls="automation-setup-event-test-payload-panel"
                onClick={() => setIsTestPayloadOpen((open) => !open)}
                className="flex w-full items-center gap-2 text-left text-sm"
              >
                <ChevronDown
                  className={cn(
                    "size-4 shrink-0 text-[var(--oh-muted)] transition-transform duration-200 motion-reduce:transition-none",
                    isTestPayloadOpen && "rotate-180",
                  )}
                  aria-hidden
                />
                {t(I18nKey.AUTOMATION_SETUP$TEST_EVENT_PAYLOAD)}
              </button>
              {isTestPayloadOpen ? (
                <div
                  id="automation-setup-event-test-payload-panel"
                  className="flex flex-col gap-2 pt-2"
                >
                  <textarea
                    data-testid="automation-setup-event-test-payload"
                    value={eventTestPayload}
                    onChange={(event) =>
                      setEventTestPayload(event.target.value)
                    }
                    className={cn(
                      formControlMultilineFieldClassName,
                      "min-h-44 font-mono",
                    )}
                    placeholder={t(
                      I18nKey.AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_PLACEHOLDER,
                    )}
                  />
                  <p className="text-xs leading-5 text-[var(--oh-muted)]">
                    {t(I18nKey.AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_DESCRIPTION)}
                  </p>
                </div>
              ) : null}
            </>
          )}
        </div>
      </section>
    </div>
  );
}

function Field({
  label,
  showLabel = true,
  labelClassName,
  suffix,
  horizontal = false,
  isStreaming = false,
  errorText,
  children,
}: {
  label: string;
  showLabel?: boolean;
  labelClassName?: string;
  suffix?: string;
  horizontal?: boolean;
  isStreaming?: boolean;
  errorText?: string;
  children: ReactNode;
}) {
  return (
    <label
      data-streaming-active={isStreaming ? "true" : undefined}
      className={cn(
        "flex gap-2",
        horizontal ? "items-center" : "flex-col",
        streamingHighlightClassName(isStreaming),
      )}
    >
      {showLabel ? (
        <span
          className={cn(
            "flex shrink-0 items-center gap-2 text-sm",
            labelClassName,
          )}
        >
          <span>{label}</span>
          {suffix && (
            <span className="font-normal text-[var(--oh-muted)]">{suffix}</span>
          )}
        </span>
      ) : null}
      <div className="min-w-0 flex-1">{children}</div>
      {errorText ? (
        <span
          role="alert"
          className="text-xs leading-5 text-[var(--oh-warning)]"
        >
          {errorText}
        </span>
      ) : null}
    </label>
  );
}

function TriggerCard({
  icon,
  title,
  description,
  selected,
  onClick,
}: {
  icon: ReactNode;
  title: string;
  description: string;
  selected: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      role="radio"
      aria-checked={selected}
      onClick={onClick}
      className={cn(
        "rounded-lg border px-3 py-2.5 text-left",
        formControlTransitionClassName,
        selected
          ? "border-[var(--oh-interactive-hover)] bg-surface-raised text-content"
          : "border-[var(--oh-border)] bg-transparent text-content hover:border-[var(--oh-interactive-hover)] hover:bg-surface-raised",
      )}
    >
      <span className="flex items-start gap-2">
        <span className="mt-0.5 text-muted">{icon}</span>
        <span className="min-w-0">
          <span className="block text-sm font-medium">{title}</span>
          <span className="mt-1 block text-xs text-[var(--oh-text-tertiary)]">
            {description}
          </span>
        </span>
      </span>
    </button>
  );
}