Skip to content

🙌 OpenHands: AI-Driven Development

feat: finalize automation setup draft flow (#17688)

Rohit Malhotra5a8c3832154b
diff --git a/.agents/skills/verify-openhands/references/feature-map/F21-automations-dashboard.md b/.agents/skills/verify-openhands/references/feature-map/F21-automations-dashboard.md
index c3e207845f..c8248f8a34 100644
--- a/.agents/skills/verify-openhands/references/feature-map/F21-automations-dashboard.md
+++ b/.agents/skills/verify-openhands/references/feature-map/F21-automations-dashboard.md
@@ -23,7 +23,7 @@ Source: `src/routes/automations-list.tsx`, `src/components/features/automations/
- `F21.list-loading`: once the backend is healthy, the header, tiles and controls render at once while three card skeletons stand in for the list until the first page arrives.
- `F21.backend-unavailable`: when the health check fails, the page shows **Automations Unavailable** with a Retry button.
- `F21.list-error`: when the list request fails with nothing cached, the page shows **Failed to load automations** with Retry.
-- `F21.add-menu`: the header **Add Automation** menu offers **Create Automation** and **Import automation**; Create Automation opens the **How to create an automation** dialog (instructions, docs link, Create Automation), which X and Escape close.
+- `F21.add-menu`: the header **Add Automation** menu offers **Create Automation** and **Import automation**; Create Automation opens the guided setup page at `/automations/setup` (F22).
- `F21.empty-state`: with zero automations the page shows **No automations configured**, the "Create an automation" instructions, a docs link, **Create Automation** and the Recommended automations rail; the view toggle is disabled.
- `F21.empty-rail`: a Recommended automations card on the empty dashboard opens its template setup at `/automations/new/<template-id>` (F22 owns the setup flow).
- `F21.overview-tiles`: four tiles summarize the loaded org list: Automations (`N active`), Needs attention (`Latest run failed` or `No latest-run failures`; an enabled automation counts when its latest run is Failed or its task outcome is `failed` or `blocked`, while Partial and Needs review do not count), Total runs and Average duration.
@@ -56,7 +56,7 @@ Source: `src/routes/automations-list.tsx`, `src/components/features/automations/
- Command menu (`Control+k`/`Meta+k` or `command-menu-trigger`): type `Automations` or a keyword such as `cron`, press Enter.
- With Automate pinned, `/` (logo, a bare visit) lands on `/automations`.
- Sub-page navigation: `automations-navbar-desktop` (aside) or `automations-navbar-mobile` (phone strip), links `automations-navigation-list` and `automations-navigation-templates`.
-- Header **Add Automation** (`automations-add-automation`) → **Create Automation** (`automations-add-automation-create`) or **Import automation** (`automations-import-automation`, F22); on the empty dashboard, the Recommended automations rail cards (`recommended-automation-rail-card-<id>`).
+- Header **Add Automation** (`automations-add-automation`) → **Create Automation** (`automations-add-automation-create`, `/automations/setup`, F22) or **Import automation** (`automations-import-automation`, F22); on the empty dashboard, the Recommended automations rail cards (`recommended-automation-rail-card-<id>`).
- Getting-started checklist item **Schedule a task** links to `/automations` (onboarding checklist family).
- Per automation: Play (`automation-run-now-<id>`, name "Run now") and kebab (name "Automation actions") on each card or row; the card itself and the row link open the detail page (F23).
@@ -82,7 +82,7 @@ Preconditions:
- **List loading (`F21.list-loading`).** Run `control-openhands browser goto /settings/secrets`, then `control-openhands browser click 'testid=sidebar-automations-link' --observe '[data-testid="automation-card-skeleton"], [data-testid="automations-add-automation"]' --observe-ms 2000`. One observed state is `Add Automation` plus three empty skeleton entries (about 50 ms), followed by `Add Automation` alone.
- **Health loading and missing manifest (`F21.health-loading`, `F21.manifest-404`).** Blocked. The health-only skeleton (title and three `automation-card-skeleton`, no header buttons) shows only on the first health fetch, which the sidebar checklist always makes before a user can reach the dashboard, and stopping the service makes the fetch fail at once rather than hang. The 404 needs a build without the automation interface manifest.
- **Empty state (`F21.empty-state`).** With no automations run `control-openhands browser goto /automations`, `control-openhands browser text 'testid=automations-empty'`, `control-openhands browser enabled 'testid=automations-view-toggle'` and `control-openhands browser screenshot --feature F21.empty-state --name empty`. The text starts `No automations configured`, contains `Create an automation`, `Learn more in the documentation` and `Create Automation`, and lists the Recommended automations; `enabled` is `false`; the tiles read `Automations 0 / 0 active` and `Needs attention 0 / No latest-run failures`. **Create Automation** (`automations-create-automation`) starts a model-backed chat: see F22.
-- **Add Automation menu (`F21.add-menu`).** Run `control-openhands browser click 'testid=automations-add-automation'` and `control-openhands browser snapshot 'testid=automations-add-automation-menu'`: buttons `Create Automation` and `Import automation`. `control-openhands browser press Escape` (or a click on `role=heading[name="Dashboard"]`) makes `browser count 'testid=automations-add-automation-menu'` `0`. Reopen it, `control-openhands browser click 'testid=automations-add-automation-create'` and `control-openhands browser snapshot 'role=dialog'`: `dialog "How to create an automation"` with Close, the instructions (`Create an automation` as code), `Learn more in the documentation` (`https://docs.openhands.dev/openhands/usage/automations/overview`) and `Create Automation` (`automations-create-automation`, model-backed, F22). `control-openhands browser click 'testid=add-automation-modal-close'` and `browser press Escape` each make `browser count 'testid=add-automation-modal'` `0`.
+- **Add Automation menu (`F21.add-menu`).** Run `control-openhands browser click 'testid=automations-add-automation'` and `control-openhands browser snapshot 'testid=automations-add-automation-menu'`: buttons `Create Automation` and `Import automation`. `control-openhands browser press Escape` (or a click on `role=heading[name="Dashboard"]`) makes `browser count 'testid=automations-add-automation-menu'` `0`. Reopen it and `control-openhands browser click 'testid=automations-add-automation-create' --expect-url '/automations/setup'`: the agent-assisted setup page opens. Go back to `/automations`, reopen the menu, and `control-openhands browser click 'testid=automations-import-automation'`: the import modal is covered by F22.
- **Recommended rail on the empty dashboard (`F21.empty-rail`).** With no automations, `control-openhands browser click 'testid=automations-empty >> testid=recommended-automation-rail-card-custom-automation' --expect-url 'automations/new'` lands on `/automations/new/custom-automation` with the **Before you start** prerequisites dialog (F22). `control-openhands browser back` returns to `/automations`; there `browser attr 'testid=recommended-automations-rail-fade-left' data-visible` is `false` and `...-fade-right` is `true` (scrolling is F03.recommended-automations-rail).
- **Arrange two automations (import, F22).** Run `control-openhands browser click 'testid=automations-add-automation'`, `control-openhands browser click 'testid=automations-import-automation'`, `control-openhands browser upload 'testid=automations-import-file' "$OH_VERIFY_RUN/evidence/_fixtures/qa-f21-alpha.automation.json"`, `control-openhands browser click 'testid=import-automation-confirm'`, `control-openhands browser wait 'testid=import-automation-modal' --state detached`. Repeat with `qa-f21-beta.automation.json`. Both arrive disabled, under **Inactive 2**.
- **Grid cards (`F21.card-grid`).** Run `control-openhands browser reload`, `control-openhands browser snapshot 'role=main'` and `control-openhands browser screenshot --feature F21.card-grid --name grid`. Each card shows its name, prompt, pills (`pull_request.opened` + GitHub logo for Beta, `cron` for Alpha), **No activity yet**, and `Runs 0 / Recent success — / Avg. duration —`; both Play buttons are `[disabled]`.
diff --git a/.agents/skills/verify-openhands/references/feature-map/F22-automation-creation.md b/.agents/skills/verify-openhands/references/feature-map/F22-automation-creation.md
index 48bc040352..9ff3fc55d7 100644
--- a/.agents/skills/verify-openhands/references/feature-map/F22-automation-creation.md
+++ b/.agents/skills/verify-openhands/references/feature-map/F22-automation-creation.md
@@ -7,12 +7,12 @@ either opens a manifest-driven setup dialog at `/automations/new/<id>`
(prerequisites → form → review → **Confirm and create**), or first asks where a
GitHub/Slack responder should run, or first asks the user to install missing
MCP integrations, or seeds a conversation with the entry's launch prompt.
-**Add Automation → Create Automation** explains how to ask the agent and opens a
-chat pre-filled with `Create an automation`. **Add Automation →
-Import automation** reads an exported JSON file, previews it and creates it
-disabled.
+**Add Automation → Create Automation** opens the agent-assisted setup page at
+`/automations/setup`, where the user can draft, save, test and dispatch a
+custom automation with agent help. **Add Automation → Import automation** reads
+an exported JSON file, previews it and creates it disabled.
-Source: `src/routes/automation-templates.tsx`, `src/routes/automation-setup-route.tsx`, `src/components/features/automations/` (`recommended-automations-launcher.tsx`, `recommended-automations-section.tsx`, `responder-deployment-modal.tsx`, `add-automation-modal.tsx`, `create-instructions.tsx`, `import-automation-modal.tsx`, `agent-profile-selector.tsx`), `src/components/features/manifest/`, `src/manifests/`, `src/hooks/use-launch-skill-in-chat.ts`, `src/hooks/use-responder-url-secret.ts`, `src/utils/automation-export.ts`, `src/api/automation-service/automation-service.api.ts`, `node_modules/@openhands/extensions/automations/`.
+Source: `src/routes/automation-templates.tsx`, `src/routes/automation-setup-route.tsx`, `src/routes/automation-setup-new.tsx`, `src/components/features/automations/` (`recommended-automations-launcher.tsx`, `recommended-automations-section.tsx`, `responder-deployment-modal.tsx`, `create-instructions.tsx`, `import-automation-modal.tsx`, `agent-profile-selector.tsx`, `setup/`), `src/components/features/manifest/`, `src/manifests/`, `src/hooks/use-start-automation-setup.ts`, `src/hooks/use-launch-skill-in-chat.ts`, `src/hooks/use-responder-url-secret.ts`, `src/utils/automation-export.ts`, `src/api/automation-service/automation-service.api.ts`, `node_modules/@openhands/extensions/automations/`.
## Sub-features
@@ -37,7 +37,7 @@ Source: `src/routes/automation-templates.tsx`, `src/routes/automation-setup-rout
- `F22.setup-fallback-conversation`: **Set up in a conversation** creates a conversation seeded with the entry's setup message.
- `F22.setup-close`: X or Escape goes back in history; on a cold deep link it replaces the location with `/automations`.
- `F22.setup-unknown-id`: `/automations/new/<id>` for an id no catalog entry claims is a 404.
-- `F22.create-helper-conversation`: **Add Automation → Create Automation** opens **How to create an automation**; its **Create Automation** closes the dialog, opens `/conversations` and pre-fills the composer with `Create an automation`; an agent asked to create an automation creates it.
+- `F22.agent-assisted-setup`: **Add Automation → Create Automation** opens `/automations/setup`, whose setup panel collects name, action, trigger, model/profile and custom code, can ask the agent for help, saves server-backed drafts, opens test runs behind a Back button and dispatches the finished automation.
- `F22.import-picker`: **Add Automation → Import automation** opens a dialog that explains the format (docs link), says the import is disabled, and offers a dropzone and **Choose file**.
- `F22.import-validation`: a file that is not JSON shows the toast `The selected file is not valid JSON.`; a JSON file that breaks the format shows one toast listing every issue; the dialog stays on the picker.
- `F22.import-preview`: a valid file switches the dialog to a preview (Name, Trigger, Prompt, Plugins) with the disabled notice, **Cancel** and **Import automation**.
@@ -88,7 +88,7 @@ Preconditions:
- **Responder launch with Slack installed (`F22.responder-local-launch`).** Arrange Slack as installed with its catalog command, a dummy token and offline npm, so nothing is downloaded or contacted (arrange, not proof): write `qa-slack.json` (outside the workspace) containing `{"agent_settings_diff":{"mcp_config":{"slack":{"command":"npx","args":["-y","@zencoderai/slack-mcp-server"],"env":{"SLACK_BOT_TOKEN":"xoxb-qa-dummy","SLACK_TEAM_ID":"T0000000000","npm_config_offline":"true"}}}}}` and run `control-openhands api PATCH /api/settings --data @qa-slack.json --write`. On `/automations/templates` run `control-openhands browser click 'testid=recommended-automation-card-slack-standup-digest'`, `control-openhands browser wait 'testid=responder-deployment-modal'`, `control-openhands browser click 'testid=responder-deployment-continue-local'` and `control-openhands browser wait-url '/conversations/[0-9a-f-]+' --timeout 60000` (note `<slack-id>`). `control-openhands browser count 'testid=mcp-install-modal'` is `0`. After `sleep 5`, `control-openhands browser eval "document.querySelector('[data-testid=chat-input]').innerText"` is `/standup-digest:setup` and `control-openhands browser count 'testid=user-message'` is `0` (`control-openhands browser screenshot --feature F22.responder-local-launch --name slack-prefilled`). Run `control-openhands browser click 'testid=submit-button'` and `control-openhands browser wait 'testid=user-message >> has-text=/standup-digest:setup' --timeout 15000`. Then run `control-openhands conversation pause <slack-id>` at once. The setup skill is open-ended. On 2026-10-08, deepseek-flash spent 25 tool calls exploring the host, including files outside the run, before asking a setup question. Restore with `control-openhands api DELETE /api/settings/mcp/slack --write`; `control-openhands api GET /api/settings --pick agent_settings.mcp_config` is `{}`. Run this bullet after Responder choice, which needs Slack not installed.
- **Install queue (`F22.template-mcp-install-queue`).** Run `control-openhands browser click 'testid=recommended-automation-card-linear-triage-assistant'`: `dialog "Linear"` (URL `https://mcp.linear.app/mcp`, optional API key). `control-openhands browser click 'testid=mcp-install-cancel'`; `browser count 'role=dialog'` is `0`, the URL stays `/automations/templates`, `control-openhands conversation list` has no new conversation and `api GET /api/settings` still has an empty `mcp_config`. Completing the queue is blocked: **Install** first tests the connection (Linear without a key: `Connection failed: HTTPStatusError: Client error '401 Unauthorized'…`; Tavily `research-brief-writer` with a dummy key: `Connection timed out. Check the URL and try again.`), so it never launches without a working credential.
- **Prompt launch (`F22.template-launch-conversation`).** Use a card whose required integrations all need external setup, so no install dialog queues: on `/automations/templates` run `control-openhands browser click 'testid=recommended-automation-pills-jira-issue-to-bitbucket-pr-overflow'` (`dialog: Bitbucket Needs external setup`), `control-openhands browser press Escape`, then `control-openhands browser click 'testid=recommended-automation-card-jira-issue-to-bitbucket-pr' --expect-url '/conversations/[0-9a-f]' --timeout 60000`. `control-openhands browser eval "document.querySelector('[data-testid=chat-input]').innerText"` is `/ticket-to-code-change:setup`, and `control-openhands conversation events <id> --kinds MessageEvent --from-start` (id from the URL) has `total` `0` even 20 s later: the launch command is pre-filled, not sent (the featured copy promises "a pre-filled conversation"). Do not press send (no model cost). Take `browser screenshot --feature F22.template-launch-conversation --name prefilled`. Cards with an installable missing integration (`research-brief-writer`, Tavily) go through the install queue first and are blocked here (see Preconditions).
-- **Create Automation helper (`F22.create-helper-conversation`).** On `/automations` (`control-openhands browser goto /automations`; Prompt launch ends on a conversation) run `control-openhands browser click 'testid=automations-add-automation'`, `control-openhands browser click 'testid=automations-add-automation-create'`, `control-openhands browser text 'testid=add-automation-modal >> testid=automations-create-instructions-example'` (`Create an automation`), then `control-openhands browser click 'testid=add-automation-modal >> testid=automations-create-automation' --expect-url '/conversations'` and `control-openhands browser eval "document.querySelector('[data-testid=chat-input]').innerText"`: the composer holds `Create an automation`, it has focus (`control-openhands browser eval "document.activeElement.getAttribute('data-testid')"` is `chat-input`), and the dialog is gone (`control-openhands browser count 'testid=add-automation-modal'` is `0`). Take `control-openhands browser screenshot --feature F22.create-helper-conversation --name prefilled`. Nothing is sent until the user presses send. The agent half (`conversation start` reloads `/` and replaces the composer text): `control-openhands conversation start --prompt "Create an automation now, without asking questions: name QA_F22 Agent, cron schedule 0 0 1 1 * in UTC, prompt: Reply with the single word pong. Then reply with only its id." --wait --timeout 400` finishes, and `control-openhands browser goto /automations` then `control-openhands browser count '[data-testid^="automation-card-"] >> has-text=QA_F22 Agent'` is `1`.
+- **Agent-assisted setup (`F22.agent-assisted-setup`).** On `/automations` run `control-openhands browser click 'testid=automations-add-automation'`, then `control-openhands browser click 'testid=automations-add-automation-create' --expect-url '/automations/setup'`: the page shows `automation-setup-panel`, `automation-setup-form`, `automation-setup-docked-composer`, Save draft (`automation-setup-save-draft`) and Test (`automation-setup-test`). Fill a prompt/name/trigger, save the draft, then the draft status (`automation-setup-draft-details`) shows whether it is ready to test. `automation-setup-view-test-runs` opens `automation-setup-draft-runs-page`; `automation-setup-draft-runs-back` returns to the form.
- **Import picker (`F22.import-picker`).** On `/automations` run `control-openhands browser click 'testid=automations-add-automation'`, `control-openhands browser click 'testid=automations-import-automation'`, `control-openhands browser attr 'testid=import-automation-modal' data-view` (`picker`) and `control-openhands browser snapshot 'testid=import-automation-modal'`: heading `Import automation`, the explanation with link `File format documentation` (`https://docs.openhands.dev/openhands/usage/agent-canvas/managing-automations#exported-file-format`), `The imported automation will be disabled until you review and enable it.`, `Drop a .json file here`, `or`, `Choose file`.
- **Bad files (`F22.import-validation`).** In the open picker run `control-openhands browser upload 'testid=automations-import-file' "$OH_VERIFY_RUN/evidence/_fixtures/qa-f22-broken.json"` and `control-openhands browser toasts`: `The selected file is not valid JSON.` Then upload `qa-f22-schema.json` the same way: one toast reads `version: expected 1`, `spec.name: expected a non-empty string`, `spec.trigger.source: required for an event trigger`, `spec.trigger.on: required for an event trigger`, `spec.enabled: expected a boolean` (one per line). `data-view` stays `picker`.
- **Preview and cancel (`F22.import-preview`).** Upload `qa-f22-import.automation.json`: `data-view` is `preview` and `browser snapshot 'testid=import-automation-modal'` shows `Review the automation details before importing.`, Name `QA_F22 Imported`, Trigger `0 0 1 1 * · UTC`, the Prompt, Plugins `github:OpenHands/extensions/plugins/qa-none`, the disabled notice, `Cancel` and `Import automation`. `control-openhands browser click 'testid=import-automation-cancel'` closes it (`count` `0`); reopening shows `data-view` `picker` again.
@@ -96,7 +96,7 @@ Preconditions:
- **Choose file (`F22.import-choose-file`).** On `/automations` (`control-openhands browser goto /automations`; Import ends on QA_F22 View's page) open Add Automation → Import automation and run `control-openhands browser upload-via 'testid=import-automation-choose-file' "$OH_VERIFY_RUN/evidence/_fixtures/qa-f22-import.automation.json"` (answers the real file chooser): `browser attr 'testid=import-automation-modal' data-view` is `preview`. Close with `testid=import-automation-modal-close`, reopen, and `control-openhands browser upload-via 'testid=import-automation-dropzone >> text=Drop a .json file here' "$OH_VERIFY_RUN/evidence/_fixtures/qa-f22-import.automation.json"`: `preview` again. `control-openhands browser press Escape` closes the dialog (`browser count 'testid=import-automation-modal'` `0`).
- **Drop a file (`F22.import-dropzone`).** Open the import dialog again and run `control-openhands browser drop-files 'testid=import-automation-dropzone' "$OH_VERIFY_RUN/evidence/_fixtures/qa-f22-import.automation.json" --stage over`: `browser attr 'testid=import-automation-dropzone' data-active` is `true` (focus border). Close and reopen the dialog, then `control-openhands browser drop-files 'testid=import-automation-dropzone' "$OH_VERIFY_RUN/evidence/_fixtures/qa-f22-import.automation.json"`: `data-view` is `preview` with Name `QA_F22 Imported` (`browser text 'testid=import-automation-modal'`). Close with `testid=import-automation-modal-close`.
- **Phone (`F22.phone`).** Run `control-openhands browser viewport phone`, `control-openhands browser goto /automations/templates`, `control-openhands browser bbox 'testid=recommended-automations-section'` (`pageHorizontalOverflow` `false`) and `browser screenshot --feature F22.phone --name templates`. Click `testid=recommended-automation-card-custom-automation`, then `testid=setup-continue-button`; `browser bbox 'testid=setup-dialog'` is `insideViewport` `true` with no page overflow (`--name setup`). Close it, `control-openhands browser goto /automations`, open Add Automation → Import automation, upload `qa-f22-import.automation.json`; `browser bbox 'testid=import-automation-modal'` is `insideViewport` `true` (`--name import-preview`). Close with `testid=import-automation-modal-close`, then `control-openhands browser viewport desktop`.
-- **Cleanup.** Deleting an automation is F21's flow; here remove the fixtures with `control-openhands api DELETE /api/automation/v1/<id> --write` for each `QA_F22 …` (Custom, Plugin, Tarball, Imported, View, Agent) and `Daily news digest` id from `control-openhands api GET '/api/automation/v1?limit=100'`. Delete `OPENHANDS_URL` in Settings → Secrets (`control-openhands browser click 'testid=secret-item >> has-text=OPENHANDS_URL >> testid=delete-secret-button'`, then `testid=confirmation-modal >> testid=confirm-button`, as in F14.delete) unless the next recipe wants it. The fallback and agent conversations stay in the conversation list (F04 deletes them). With zero automations, `control-openhands browser goto /automations` and `control-openhands browser click 'testid=automations-empty >> testid=automations-create-automation' --expect-url '/conversations'` pre-fill the composer from the empty-state entry point too (`browser eval "document.querySelector('[data-testid=chat-input]').innerText"` is `Create an automation`).
+- **Cleanup.** Deleting an automation is F21's flow; here remove the fixtures with `control-openhands api DELETE /api/automation/v1/<id> --write` for each `QA_F22 …` (Custom, Plugin, Tarball, Imported, View, Agent) and `Daily news digest` id from `control-openhands api GET '/api/automation/v1?limit=100'`. Delete `OPENHANDS_URL` in Settings → Secrets (`control-openhands browser click 'testid=secret-item >> has-text=OPENHANDS_URL >> testid=delete-secret-button'`, then `testid=confirmation-modal >> testid=confirm-button`, as in F14.delete) unless the next recipe wants it. The fallback and setup conversations stay in the conversation list (F04 deletes them). With zero automations, `control-openhands browser goto /automations` and `control-openhands browser click 'testid=automations-empty >> testid=automations-create-automation' --expect-url '/automations/setup'` opens the agent-assisted setup page.
## Gotchas
diff --git a/__tests__/components/automations/add-automation-modal.test.tsx b/__tests__/components/automations/add-automation-modal.test.tsx
deleted file mode 100644
index e9ac97628a..0000000000
--- a/__tests__/components/automations/add-automation-modal.test.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import React from "react";
-import { render, screen } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { describe, expect, it, vi } from "vitest";
-import {
- NavigationProvider,
- type NavigationContextValue,
-} from "#/context/navigation-context";
-import { AddAutomationModal } from "#/components/features/automations/add-automation-modal";
-import { I18nKey } from "#/i18n/declaration";
-
-vi.mock("#/hooks/query/use-settings", () => ({
- useSettings: () => ({ data: { user_consents_to_analytics: true } }),
-}));
-
-vi.mock("react-i18next", () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
- Trans: ({
- i18nKey,
- components,
- children,
- }: {
- i18nKey: string;
- components?: Record<string, React.ReactElement>;
- children?: React.ReactNode;
- }) => {
- if (i18nKey !== I18nKey.AUTOMATIONS$EMPTY_OPTION_CONVERSATION_DESC) {
- return children ?? i18nKey;
- }
-
- return (
- <>
- Start a new conversation and tell OpenHands to{" "}
- {components?.example
- ? React.cloneElement(
- components.example,
- {},
- <>
- {components.cmd
- ? React.cloneElement(
- components.cmd,
- {},
- "Create an automation",
- )
- : null}
- {components.punct
- ? React.cloneElement(components.punct, {}, ".")
- : null}
- </>,
- )
- : null}
- </>
- );
- },
-}));
-
-function renderModal(isOpen = true) {
- const onClose = vi.fn();
- const navigation: NavigationContextValue = {
- currentPath: "/automations",
- conversationId: null,
- isNavigating: false,
- navigate: vi.fn(),
- };
-
- render(
- <NavigationProvider value={navigation}>
- <AddAutomationModal isOpen={isOpen} onClose={onClose} />
- </NavigationProvider>,
- );
-
- return { onClose };
-}
-
-describe("AddAutomationModal", () => {
- it("renders the create instructions content when open", () => {
- renderModal();
-
- expect(screen.getByTestId("add-automation-modal")).toBeInTheDocument();
- expect(
- screen.getByTestId("automations-create-instructions-example"),
- ).toHaveTextContent("Create an automation");
- expect(
- screen.getByTestId("automations-create-automation"),
- ).toHaveTextContent(I18nKey.AUTOMATIONS$CREATE_AUTOMATION_BUTTON);
- expect(
- screen.queryByText(I18nKey.AUTOMATIONS$EMPTY_OPTION_PLUGIN_TITLE),
- ).not.toBeInTheDocument();
- });
-
- it("does not render when closed", () => {
- renderModal(false);
-
- expect(screen.queryByTestId("add-automation-modal")).not.toBeInTheDocument();
- });
-
- it("calls onClose when the close button is clicked", async () => {
- const user = userEvent.setup();
- const { onClose } = renderModal();
-
- await user.click(screen.getByTestId("add-automation-modal-close"));
-
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/__tests__/components/automations/automation-setup-draft-service.test.ts b/__tests__/components/automations/automation-setup-draft-service.test.ts
index 7296135c96..fd000d8e82 100644
--- a/__tests__/components/automations/automation-setup-draft-service.test.ts
+++ b/__tests__/components/automations/automation-setup-draft-service.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest";
import { HttpError } from "@openhands/typescript-client";
-import { extractDraftDispatchErrors } from "#/components/features/automations/setup/automation-setup-draft-service";
+import {
+ extractDraftDispatchErrors,
+ formFromServerDraft,
+ setupDraftFromServerDraft,
+} from "#/components/features/automations/setup/automation-setup-draft-service";
+import type { AutomationSetupFormValues } from "#/api/automation-setup-types";
+import type { AutomationDraftApiResponse } from "#/manifests/types";
const detailEnvelope = {
detail: {
@@ -39,3 +45,86 @@ describe("extractDraftDispatchErrors", () => {
expect(extractDraftDispatchErrors(error)).toBe("Draft is not dispatchable");
});
});
+
+const baseSavedDraft: AutomationDraftApiResponse = {
+ id: "draft-1",
+ endpoint: "/v1/preset/prompt",
+ name: "Saved draft",
+ draft: {},
+ validationErrors: null,
+ dispatchable: true,
+ sourceAutomationId: null,
+ materializedAutomationId: null,
+ lastTestRunId: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+};
+
+const baseForm: AutomationSetupFormValues = {
+ name: "",
+ prompt: "",
+ repository: "",
+ pluginSource: "",
+ pluginRef: "",
+ pluginList: "",
+ customCode: "",
+ entrypoint: "",
+ setupScriptPath: "",
+ setupScript: "",
+ triggerKind: "cron",
+ frequency: "daily",
+ time: "09:00",
+ scheduleDateTime: "",
+ timezone: "UTC",
+ weekday: "1",
+ customSchedule: "",
+ eventSource: "github",
+ eventKey: "",
+ eventFilter: "",
+ model: "",
+ agentProfileId: "",
+ showTimeout: false,
+ timeoutSeconds: "",
+ kind: "prompt",
+};
+
+describe("setupDraftFromServerDraft", () => {
+ it("hydrates all repositories and event keys from saved drafts", () => {
+ const saved = {
+ ...baseSavedDraft,
+ draft: {
+ prompt: "Triage issues",
+ repos: [{ url: "acme/one" }, { url: "acme/two" }],
+ trigger: {
+ type: "event",
+ source: "github",
+ on: ["pull_request", "issues"],
+ },
+ },
+ } satisfies AutomationDraftApiResponse;
+
+ const draft = setupDraftFromServerDraft(saved);
+
+ expect(draft.form?.repository).toBe("acme/one, acme/two");
+ expect(draft.form?.eventKey).toBe("pull_request,issues");
+ });
+
+ it("updates an existing form with all repositories and event keys", () => {
+ const saved = {
+ ...baseSavedDraft,
+ draft: {
+ repos: [{ url: "acme/one" }, { url: "acme/two" }],
+ trigger: {
+ type: "event",
+ source: "github",
+ on: ["push", "release.published"],
+ },
+ },
+ } satisfies AutomationDraftApiResponse;
+
+ const form = formFromServerDraft(saved, baseForm);
+
+ expect(form.repository).toBe("acme/one, acme/two");
+ expect(form.eventKey).toBe("push,release.published");
+ });
+});
diff --git a/__tests__/components/automations/automation-setup-panel.test.tsx b/__tests__/components/automations/automation-setup-panel.test.tsx
index 7346ba7e16..6ef72e3cf4 100644
--- a/__tests__/components/automations/automation-setup-panel.test.tsx
+++ b/__tests__/components/automations/automation-setup-panel.test.tsx
@@ -21,6 +21,7 @@ import {
} from "#/components/features/automations/setup/automation-setup-panel";
import AutomationService from "#/api/automation-service/automation-service.api";
import {
+ PENDING_AUTOMATION_SETUP_ID,
getAutomationFormSession,
initializeAutomationFormSession,
} from "#/api/automation-form-session";
@@ -30,7 +31,9 @@ import { packTarGzip } from "#/utils/tar-gzip";
import { handleAutomationFormUpdateAction } from "#/services/automation-form";
import { AUTOMATION_FORM_UPDATE_ACTION_KIND } from "#/constants/automation-form";
import { AUTOMATION_SETUP_SHOW_AGENT_EVENT } from "#/components/features/automations/setup/automation-setup-agent-request";
+import { setupDraftFromAutomation } from "#/utils/automation-edit-draft";
import { useDeploymentCapabilities } from "#/hooks/query/use-manifest-capabilities";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
import type { AutomationDraftApiResponse } from "#/manifests/types";
const mockNavigate = vi.fn();
@@ -111,6 +114,9 @@ vi.mock("#/api/automation-service/automation-service.api", () => ({
listServerDrafts: vi.fn(),
listAutomationRuns: vi.fn().mockResolvedValue({ runs: [], total: 0 }),
dispatchServerDraft: vi.fn(),
+ dispatchAutomation: vi.fn(),
+ updateAutomation: vi.fn(),
+ getAutomation: vi.fn(),
createCustomWebhook: vi.fn(),
supportsAutomationDrafts: vi.fn(),
},
@@ -183,6 +189,7 @@ vi.mock("#/utils/tar-gzip", () => ({
}));
vi.mock("#/manifests/automation-interface", () => ({
+ automationListPath: () => "/automations",
automationDetailPath: (id: string) => `/automations/${id}`,
getAutomationEndpoint: (name: string) =>
name === "createPlugin"
@@ -442,9 +449,12 @@ describe("AutomationSetupPanel", () => {
}),
}),
);
- expect(screen.getByTestId("automation-setup-status")).toHaveTextContent(
+ expect(mockToastSuccess).toHaveBeenCalledWith(
"AUTOMATION_SETUP$READY_TO_TEST",
);
+ expect(
+ screen.queryByTestId("automation-setup-status"),
+ ).not.toBeInTheDocument();
});
it("pins an automation model without changing the conversation profile", async () => {
@@ -493,9 +503,13 @@ describe("AutomationSetupPanel", () => {
const user = userEvent.setup();
renderPanel();
+ const agentProfile = screen.getByTestId("automation-setup-agent-profile");
+ const model = screen.getByTestId("automation-setup-model");
+ expect(agentProfile).toHaveAttribute("aria-label", "default");
expect(
- screen.getByTestId("automation-setup-agent-profile"),
- ).toHaveAttribute("aria-label", "default");
+ agentProfile.compareDocumentPosition(model) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
await user.click(screen.getByTestId("automation-setup-agent-profile"));
await user.click(
screen.getByTestId("automation-setup-agent-profile-option-reviewer"),
@@ -1051,6 +1065,41 @@ describe("AutomationSetupPanel", () => {
updatedAt: "2026-01-01T00:00:00.000Z",
};
+ const echoSavedDraft = (
+ request: {
+ endpoint?: AutomationDraftApiResponse["endpoint"];
+ name?: string | null;
+ draft?: AutomationDraftApiResponse["draft"];
+ },
+ overrides: Partial<AutomationDraftApiResponse> = {},
+ ): AutomationDraftApiResponse => ({
+ ...dispatchableDraft,
+ endpoint: request.endpoint ?? dispatchableDraft.endpoint,
+ name: request.name ?? null,
+ draft: request.draft ?? dispatchableDraft.draft,
+ ...overrides,
+ });
+
+ const mockSavedDraftEcho = (
+ overrides: Partial<AutomationDraftApiResponse> = {},
+ ) => {
+ vi.mocked(AutomationService.createServerDraft).mockImplementation(
+ async (request) => echoSavedDraft(request, overrides),
+ );
+ vi.mocked(AutomationService.updateServerDraft).mockImplementation(
+ async (_id, request) => echoSavedDraft(request, overrides),
+ );
+ };
+
+ const saveDraftAndWaitForTest = async (
+ user: ReturnType<typeof userEvent.setup>,
+ ) => {
+ await user.click(screen.getByTestId("automation-setup-save-draft"));
+ await waitFor(() =>
+ expect(screen.getByTestId("automation-setup-test")).toBeEnabled(),
+ );
+ };
+
beforeEach(() => {
vi.mocked(AutomationService.supportsAutomationDrafts).mockReturnValue(
true,
@@ -1163,9 +1212,12 @@ describe("AutomationSetupPanel", () => {
}),
),
);
- expect(screen.getByTestId("automation-setup-status")).toHaveTextContent(
+ expect(mockToastSuccess).toHaveBeenCalledWith(
"AUTOMATION_SETUP$DRAFT_SAVED",
);
+ expect(
+ screen.queryByTestId("automation-setup-status"),
+ ).not.toBeInTheDocument();
expect(
screen.getByTestId("automation-setup-draft-details"),
).toBeInTheDocument();
@@ -1184,23 +1236,17 @@ describe("AutomationSetupPanel", () => {
expect(AutomationService.createServerDraft).toHaveBeenCalledTimes(1);
});
- it("keeps a saved custom server draft clean after uploading its bundle", async () => {
- vi.mocked(AutomationService.uploadAutomationTarball).mockResolvedValue(
- "oh-internal://uploads/custom-archive",
- );
- vi.mocked(AutomationService.createServerDraft).mockImplementation(
- async (request) => ({
- ...dispatchableDraft,
- id: "draft-custom",
- endpoint: request.endpoint,
- name: request.name ?? "",
- draft: request.draft as never,
- validationErrors: null,
- }),
- );
+ it("uploads fresh custom bundles and keeps the saved draft clean", async () => {
+ vi.mocked(AutomationService.uploadAutomationTarball)
+ .mockResolvedValueOnce("oh-internal://uploads/custom-draft-1")
+ .mockResolvedValueOnce("oh-internal://uploads/custom-draft-2");
+ mockSavedDraftEcho({ validationErrors: null });
const user = userEvent.setup();
- renderPanel({ prompt: "Run a custom security check", kind: "custom" });
+ renderPanel({
+ prompt: "Run generated Python",
+ kind: "custom",
+ });
await user.click(screen.getByTestId("automation-setup-save-draft"));
@@ -1209,19 +1255,127 @@ describe("AutomationSetupPanel", () => {
expect.objectContaining({
endpoint: "/v1",
draft: expect.objectContaining({
- tarball_path: "oh-internal://uploads/custom-archive",
+ tarball_path: "oh-internal://uploads/custom-draft-1",
+ entrypoint: "python3 main.py",
+ setup_script_path: "setup.sh",
}),
}),
),
);
await waitFor(() =>
- expect(screen.getByTestId("automation-setup-save-state")).toHaveTextContent(
- "AUTOMATION_SETUP$SAVED_JUST_NOW",
+ expect(
+ screen.getByTestId("automation-setup-save-state"),
+ ).toHaveTextContent("AUTOMATION_SETUP$SAVED_JUST_NOW"),
+ );
+ expect(
+ screen.getByTestId("automation-setup-save-state"),
+ ).not.toHaveTextContent("AUTOMATION_SETUP$UNSAVED_CHANGES");
+ expect(AutomationService.uploadAutomationTarball).toHaveBeenCalledTimes(
+ 1,
+ );
+ expect(packTarGzip).toHaveBeenCalledWith([
+ expect.objectContaining({ name: "main.py", mode: 0o644 }),
+ expect.objectContaining({ name: "setup.sh", mode: 0o755 }),
+ ]);
+
+ await user.click(screen.getByTestId("automation-setup-save-draft"));
+
+ await waitFor(() =>
+ expect(AutomationService.updateServerDraft).toHaveBeenCalledWith(
+ "draft-1",
+ expect.objectContaining({
+ draft: expect.objectContaining({
+ tarball_path: "oh-internal://uploads/custom-draft-2",
+ }),
+ }),
),
);
- expect(screen.getByTestId("automation-setup-save-state")).not.toHaveTextContent(
- "AUTOMATION_SETUP$UNSAVED_CHANGES",
+ expect(AutomationService.uploadAutomationTarball).toHaveBeenCalledTimes(
+ 2,
+ );
+ });
+
+ it("opens test runs from the draft status and returns to the form", async () => {
+ mockSavedDraftEcho({ validationErrors: null });
+ vi.mocked(AutomationService.getServerDraft).mockResolvedValue(
+ dispatchableDraft,
+ );
+
+ const user = userEvent.setup();
+ renderPanel();
+
+ expect(screen.getByTestId("automation-setup-test")).toBeDisabled();
+
+ await saveDraftAndWaitForTest(user);
+ expect(
+ screen.getByTestId("automation-setup-draft-details"),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("automation-setup-draft-test")).toBeEnabled();
+
+ await user.click(screen.getByTestId("automation-setup-view-test-runs"));
+
+ expect(
+ screen.getByTestId("automation-setup-draft-runs-page"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByTestId("automation-setup-draft-runs-empty"),
+ ).toHaveTextContent("AUTOMATIONS$DETAIL$NO_RUNS");
+ expect(screen.getByTestId("automation-setup-form")).toHaveClass("hidden");
+
+ await user.click(screen.getByTestId("automation-setup-draft-runs-back"));
+
+ expect(screen.getByTestId("automation-setup-form")).not.toHaveClass(
+ "hidden",
+ );
+ expect(
+ screen.queryByTestId("automation-setup-draft-runs-page"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows draft and test errors on the test runs page", async () => {
+ const blockedDraft = {
+ ...dispatchableDraft,
+ dispatchable: false,
+ validationErrors: [
+ {
+ field: null,
+ code: "webhook",
+ message: "No webhook is configured",
+ },
+ ],
+ };
+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue(
+ blockedDraft,
+ );
+ vi.mocked(AutomationService.updateServerDraft).mockResolvedValue(
+ blockedDraft,
+ );
+
+ const user = userEvent.setup();
+ renderPanel();
+ await user.click(screen.getByTestId("automation-setup-save-draft"));
+ await screen.findByTestId("automation-setup-draft-details");
+ await user.click(screen.getByTestId("automation-setup-view-test-runs"));
+
+ expect(
+ screen.getByTestId("automation-setup-draft-runs-error"),
+ ).toHaveTextContent("No webhook is configured");
+
+ const pageTest = screen
+ .getAllByTestId("automation-setup-test")
+ .find((button) =>
+ screen
+ .getByTestId("automation-setup-draft-runs-empty")
+ .contains(button),
+ );
+ await user.click(pageTest!);
+
+ await waitFor(() =>
+ expect(
+ screen.getAllByTestId("automation-setup-draft-runs-error"),
+ ).toHaveLength(1),
);
+ expect(AutomationService.dispatchServerDraft).not.toHaveBeenCalled();
});
it("tags the conversation with the server draft id after saving", async () => {
@@ -1248,6 +1402,31 @@ describe("AutomationSetupPanel", () => {
);
});
+ it("stores the server draft id in the pending setup session after saving", async () => {
+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue(
+ dispatchableDraft,
+ );
+
+ const user = userEvent.setup();
+ renderPanel(undefined, PENDING_AUTOMATION_SETUP_ID, null);
+
+ await user.click(screen.getByTestId("automation-setup-save-draft"));
+
+ await waitFor(() =>
+ expect(getAutomationFormSession(PENDING_AUTOMATION_SETUP_ID)).toEqual(
+ expect.objectContaining({
+ serverDraftId: "draft-1",
+ form: expect.objectContaining({
+ prompt: "Review every pull request",
+ }),
+ }),
+ ),
+ );
+ expect(
+ AgentServerConversationService.updateConversationTags,
+ ).not.toHaveBeenCalled();
+ });
+
it("hydrates a tagged server draft when the panel opens", async () => {
vi.mocked(AutomationService.getServerDraft).mockResolvedValue({
...dispatchableDraft,
@@ -1381,12 +1560,7 @@ describe("AutomationSetupPanel", () => {
});
it("persists then dispatches the draft on Test", async () => {
- vi.mocked(AutomationService.createServerDraft).mockResolvedValue(
- dispatchableDraft,
- );
- vi.mocked(AutomationService.updateServerDraft).mockResolvedValue(
- dispatchableDraft,
- );
+ mockSavedDraftEcho();
vi.mocked(AutomationService.dispatchServerDraft).mockResolvedValue({
id: "run-1",
status: "PENDING" as never,
@@ -1400,6 +1574,7 @@ describe("AutomationSetupPanel", () => {
const user = userEvent.setup();
renderPanel();
+ await saveDraftAndWaitForTest(user);
await user.click(screen.getByTestId("automation-setup-test"));
await waitFor(() =>
@@ -1408,37 +1583,59 @@ describe("AutomationSetupPanel", () => {
),
);
expect(AutomationService.validateDraft).not.toHaveBeenCalled();
- expect(screen.getByTestId("automation-setup-status")).toHaveTextContent(
+ expect(mockToastSuccess).toHaveBeenCalledWith(
"AUTOMATION_SETUP$TEST_DISPATCHED",
);
+ expect(
+ screen.queryByTestId("automation-setup-status"),
+ ).not.toBeInTheDocument();
expect(mockNavigate).not.toHaveBeenCalledWith(
"/conversations/conv-run-1",
);
});
it("surfaces validation errors when the draft is not dispatchable", async () => {
- vi.mocked(AutomationService.createServerDraft).mockResolvedValue({
- ...dispatchableDraft,
- dispatchable: false,
- validationErrors: [
- {
- field: "trigger.schedule",
- code: "interval_too_short",
- message: "Minimum interval is 5 minutes.",
- },
- ],
- });
+ const blocked = (
+ request: Parameters<typeof echoSavedDraft>[0],
+ ): AutomationDraftApiResponse =>
+ echoSavedDraft(request, {
+ dispatchable: false,
+ validationErrors: [
+ {
+ field: "trigger.schedule",
+ code: "interval_too_short",
+ message: "Minimum interval is 5 minutes.",
+ },
+ ],
+ });
+ vi.mocked(AutomationService.createServerDraft).mockImplementation(
+ async (request) => blocked(request),
+ );
+ vi.mocked(AutomationService.updateServerDraft).mockImplementation(
+ async (_id, request) => blocked(request),
+ );
const user = userEvent.setup();
renderPanel();
+ await saveDraftAndWaitForTest(user);
+ const validity = screen.getByTestId("automation-setup-draft-validity");
+ expect(validity.parentElement).toBe(
+ screen.getByTestId("automation-setup-draft-details"),
+ );
+ expect(validity.previousElementSibling).toContainElement(
+ screen.getByTestId("automation-setup-draft-test"),
+ );
await user.click(screen.getByTestId("automation-setup-test"));
await waitFor(() =>
- expect(screen.getByTestId("automation-setup-status")).toHaveTextContent(
- "Minimum interval is 5 minutes.",
- ),
+ expect(
+ screen.getByTestId("automation-setup-draft-runs-error"),
+ ).toHaveTextContent("Minimum interval is 5 minutes."),
);
+ expect(
+ screen.queryByTestId("automation-setup-status"),
+ ).not.toBeInTheDocument();
expect(AutomationService.dispatchServerDraft).not.toHaveBeenCalled();
});
@@ -1485,9 +1682,7 @@ describe("AutomationSetupPanel", () => {
});
it("sends synthetic JSON payload when testing an event draft", async () => {
- vi.mocked(AutomationService.createServerDraft).mockResolvedValue(
- dispatchableDraft,
- );
+ mockSavedDraftEcho();
vi.mocked(AutomationService.dispatchServerDraft).mockResolvedValue({
id: "run-1",
status: "PENDING" as never,
@@ -1514,6 +1709,7 @@ describe("AutomationSetupPanel", () => {
value: JSON.stringify({ type: "issue.created", action: "opened" }),
},
});
+ await saveDraftAndWaitForTest(user);
await user.click(screen.getByTestId("automation-setup-test"));
await waitFor(() =>
@@ -1551,9 +1747,7 @@ describe("AutomationSetupPanel", () => {
updated_at: "2026-01-01T00:00:00.000Z",
webhook_secret: "generated-secret",
});
- vi.mocked(AutomationService.createServerDraft).mockResolvedValue(
- dispatchableDraft,
- );
+ mockSavedDraftEcho();
vi.mocked(AutomationService.dispatchServerDraft).mockResolvedValue({
id: "run-1",
status: "PENDING" as never,
@@ -1597,12 +1791,19 @@ describe("AutomationSetupPanel", () => {
),
).not.toBeNull();
await user.click(custom);
- fireEvent.change(screen.getByTestId("automation-setup-event-source"), {
+ const sourceInput = screen.getByTestId("automation-setup-event-source");
+ expect(sourceInput).toHaveValue("");
+ expect(sourceInput).toHaveAttribute(
+ "placeholder",
+ "AUTOMATION_SETUP$EVENT_SOURCE_CUSTOM_PLACEHOLDER",
+ );
+ expect(sourceInput).toHaveFocus();
+ fireEvent.change(sourceInput, {
target: { value: "incident-alerts" },
});
expect(
screen.getByTestId("automation-setup-custom-webhook-enabled"),
- ).toBeInTheDocument();
+ ).toBeChecked();
await user.click(
screen.getByTestId("automation-setup-event-source-toggle"),
);
@@ -1612,9 +1813,6 @@ describe("AutomationSetupPanel", () => {
await user.click(
screen.getByTestId("automation-setup-event-source-toggle"),
);
- await user.click(
- screen.getByTestId("automation-setup-custom-webhook-enabled"),
- );
await user.type(
screen.getByTestId("automation-setup-custom-webhook-name"),
"Incident webhook",
@@ -1627,6 +1825,7 @@ describe("AutomationSetupPanel", () => {
screen.getByTestId("automation-setup-custom-webhook-signature-header"),
{ target: { value: "X-Incident-Signature" } },
);
+ await saveDraftAndWaitForTest(user);
await user.click(screen.getByTestId("automation-setup-test"));
await waitFor(() =>
@@ -1662,12 +1861,16 @@ describe("AutomationSetupPanel", () => {
"automation-setup-event-test-payload",
);
fireEvent.change(payloadInput, { target: { value: "not json" } });
+ mockSavedDraftEcho();
+ await saveDraftAndWaitForTest(user);
await user.click(screen.getByTestId("automation-setup-test"));
- expect(screen.getByTestId("automation-setup-status")).toHaveTextContent(
+ expect(displayErrorToast).toHaveBeenCalledWith(
"AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_INVALID",
);
- expect(AutomationService.createServerDraft).not.toHaveBeenCalled();
+ expect(
+ screen.queryByTestId("automation-setup-status"),
+ ).not.toBeInTheDocument();
expect(AutomationService.dispatchServerDraft).not.toHaveBeenCalled();
});
@@ -1707,4 +1910,278 @@ describe("AutomationSetupPanel", () => {
);
});
});
+
+ it("saves and tests an existing automation instead of drafting or creating one", async () => {
+ vi.mocked(AutomationService.updateAutomation).mockResolvedValue({
+ id: "auto-1",
+ } as never);
+ vi.mocked(AutomationService.dispatchAutomation).mockResolvedValue({
+ id: "run-9",
+ } as never);
+
+ const user = userEvent.setup();
+ renderPanel({
+ prompt: "Review every pull request",
+ kind: "prompt",
+ editingAutomationId: "auto-1",
+ form: {
+ kind: "prompt",
+ name: "Daily digest",
+ prompt: "Review every pull request",
+ },
+ });
+
+ expect(
+ screen.queryByTestId("automation-setup-save-draft"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("automation-setup-create"),
+ ).not.toBeInTheDocument();
+ expect(
+ [
+ ...(screen
+ .getByTestId("automation-setup-test")
+ .parentElement?.querySelectorAll("button") ?? []),
+ ].map((button) => button.getAttribute("data-testid")),
+ ).toEqual([
+ "automation-setup-test",
+ "automation-setup-save",
+ "automation-setup-close",
+ ]);
+ expect(screen.getByTestId("automation-setup-save")).toHaveTextContent(
+ "BUTTON$SAVE",
+ );
+ expect(screen.getByTestId("automation-setup-close")).toHaveTextContent(
+ "BUTTON$CLOSE",
+ );
+ expect(screen.getByTestId("automation-setup-name")).toHaveValue(
+ "Daily digest",
+ );
+
+ await user.click(screen.getByTestId("automation-setup-save"));
+ await waitFor(() =>
+ expect(AutomationService.updateAutomation).toHaveBeenCalledWith(
+ "auto-1",
+ expect.objectContaining({
+ name: "Daily digest",
+ prompt: "Review every pull request",
+ }),
+ ),
+ );
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(1);
+ expect(
+ vi.mocked(AutomationService.updateAutomation).mock.calls[0][1],
+ ).not.toEqual(
+ expect.objectContaining({
+ repository: expect.anything(),
+ repos: expect.anything(),
+ plugins: expect.anything(),
+ }),
+ );
+ expect(AutomationService.createServerDraft).not.toHaveBeenCalled();
+ expect(AutomationService.createAutomationDraft).not.toHaveBeenCalled();
+
+ await user.click(screen.getByTestId("automation-setup-test"));
+ await waitFor(() =>
+ expect(AutomationService.dispatchAutomation).toHaveBeenCalledWith(
+ "auto-1",
+ ),
+ );
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(1);
+
+ await user.click(screen.getByTestId("automation-setup-close"));
+ expect(mockNavigate).toHaveBeenCalledWith("/automations");
+ });
+
+ it("preserves multi-event trigger keys when saving an existing automation", async () => {
+ vi.mocked(AutomationService.updateAutomation).mockResolvedValue({
+ id: "auto-1",
+ } as never);
+
+ const user = userEvent.setup();
+ renderPanel(
+ setupDraftFromAutomation({
+ id: "auto-1",
+ name: "Triage",
+ prompt: "Triage it",
+ enabled: true,
+ created_at: "2026-01-01T00:00:00.000Z",
+ updated_at: "2026-01-01T00:00:00.000Z",
+ trigger: {
+ type: "event",
+ source: "github",
+ on: ["pull_request", "issues"],
+ },
+ }),
+ );
+
+ await user.click(screen.getByTestId("automation-setup-save"));
+
+ await waitFor(() =>
+ expect(AutomationService.updateAutomation).toHaveBeenCalledWith(
+ "auto-1",
+ expect.objectContaining({
+ trigger: expect.objectContaining({
+ on: ["pull_request", "issues"],
+ }),
+ }),
+ ),
+ );
+ });
+
+ it("explains existing event automation tests use the backend payload", async () => {
+ vi.mocked(AutomationService.updateAutomation).mockResolvedValue({
+ id: "auto-1",
+ } as never);
+ vi.mocked(AutomationService.dispatchAutomation).mockResolvedValue({
+ id: "run-1",
+ } as never);
+
+ const user = userEvent.setup();
+ renderPanel(
+ setupDraftFromAutomation({
+ id: "auto-1",
+ name: "Triage",
+ prompt: "Triage it",
+ enabled: true,
+ created_at: "2026-01-01T00:00:00.000Z",
+ updated_at: "2026-01-01T00:00:00.000Z",
+ trigger: {
+ type: "event",
+ source: "github",
+ on: "issues",
+ },
+ }),
+ );
+
+ expect(
+ screen.getByTestId("automation-setup-existing-test-payload-note"),
+ ).toHaveTextContent("AUTOMATION_SETUP$EXISTING_TEST_PAYLOAD_NOTICE");
+ expect(
+ screen.queryByTestId("automation-setup-event-test-payload-toggle"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("automation-setup-event-test-payload"),
+ ).not.toBeInTheDocument();
+
+ await user.click(screen.getByTestId("automation-setup-test"));
+
+ await waitFor(() =>
+ expect(AutomationService.dispatchAutomation).toHaveBeenCalledWith(
+ "auto-1",
+ ),
+ );
+ expect(AutomationService.dispatchServerDraft).not.toHaveBeenCalled();
+ });
+
+ it("does not send unsupported repository and plugin fields while editing", async () => {
+ vi.mocked(AutomationService.updateAutomation).mockResolvedValue({
+ id: "auto-1",
+ } as never);
+
+ const user = userEvent.setup();
+ renderPanel(
+ setupDraftFromAutomation({
+ id: "auto-1",
+ name: "Reviewer",
+ prompt: "Review PRs",
+ enabled: true,
+ created_at: "2026-01-01T00:00:00.000Z",
+ updated_at: "2026-01-01T00:00:00.000Z",
+ repository: "OpenHands/OpenHands",
+ plugins: ["github:OpenHands/extensions/plugins/pr-review"],
+ trigger: {
+ type: "cron",
+ schedule: "0 9 * * *",
+ timezone: "UTC",
+ },
+ }),
+ );
+
+ await user.click(screen.getByTestId("automation-setup-repository-remove"));
+ await user.click(screen.getByTestId("automation-setup-plugin-remove"));
+ await user.click(screen.getByTestId("automation-setup-save"));
+
+ await waitFor(() =>
+ expect(AutomationService.updateAutomation).toHaveBeenCalledWith(
+ "auto-1",
+ expect.objectContaining({
+ name: "Reviewer",
+ prompt: "Review PRs",
+ }),
+ ),
+ );
+ expect(
+ vi.mocked(AutomationService.updateAutomation).mock.calls[0][1],
+ ).not.toEqual(
+ expect.objectContaining({
+ repository: expect.anything(),
+ repos: expect.anything(),
+ plugins: expect.anything(),
+ }),
+ );
+ });
+
+ it("shows existing custom bundle metadata without replacing it on save", async () => {
+ vi.mocked(AutomationService.updateAutomation).mockResolvedValue({
+ id: "auto-1",
+ } as never);
+
+ const user = userEvent.setup();
+ renderPanel(
+ setupDraftFromAutomation({
+ id: "auto-1",
+ name: "Nightly scan",
+ prompt: null,
+ enabled: true,
+ created_at: "2026-01-01T00:00:00.000Z",
+ updated_at: "2026-01-01T00:00:00.000Z",
+ entrypoint: "python3 scan.py",
+ setup_script_path: "install.sh",
+ tarball_path: "oh-internal://uploads/REAL-user-code.tar.gz",
+ trigger: {
+ type: "cron",
+ schedule: "0 9 * * *",
+ timezone: "UTC",
+ },
+ }),
+ );
+
+ expect(
+ screen.getByTestId("automation-setup-existing-bundle"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByTestId("automation-setup-existing-bundle-name"),
+ ).toHaveTextContent("REAL-user-code.tar.gz");
+ expect(
+ screen.getByTestId("automation-setup-existing-bundle-info"),
+ ).toHaveAccessibleName("AUTOMATION_SETUP$EXISTING_BUNDLE_HELP");
+ expect(
+ screen.queryByTestId("automation-setup-custom-code"),
+ ).not.toBeInTheDocument();
+
+ await user.click(screen.getByTestId("automation-setup-save"));
+
+ await waitFor(() =>
+ expect(AutomationService.updateAutomation).toHaveBeenCalledWith(
+ "auto-1",
+ expect.objectContaining({
+ name: "Nightly scan",
+ }),
+ ),
+ );
+ expect(
+ vi.mocked(AutomationService.updateAutomation).mock.calls[0][1],
+ ).not.toEqual(expect.objectContaining({ entrypoint: expect.anything() }));
+ expect(AutomationService.uploadAutomationTarball).not.toHaveBeenCalled();
+ expect(packTarGzip).not.toHaveBeenCalled();
+ expect(
+ vi.mocked(AutomationService.updateAutomation).mock.calls[0][1],
+ ).not.toEqual(expect.objectContaining({ tarball_path: expect.anything() }));
+ expect(
+ vi.mocked(AutomationService.updateAutomation).mock.calls[0][1],
+ ).not.toEqual(
+ expect.objectContaining({ setup_script_path: expect.anything() }),
+ );
+ });
});
diff --git a/__tests__/components/automations/create-instructions.test.tsx b/__tests__/components/automations/create-instructions.test.tsx
index 8171f38be5..e9c4bb4a99 100644
--- a/__tests__/components/automations/create-instructions.test.tsx
+++ b/__tests__/components/automations/create-instructions.test.tsx
@@ -1,15 +1,35 @@
import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import {
NavigationProvider,
type NavigationContextValue,
} from "#/context/navigation-context";
import { CreateInstructions } from "#/components/features/automations/create-instructions";
import { I18nKey } from "#/i18n/declaration";
-import { useConversationStore } from "#/stores/conversation-store";
-import * as telemetry from "#/services/telemetry";
+
+const mocks = vi.hoisted(() => ({
+ createConversationMutate: vi.fn(),
+ trackAutomationCreatedButton: vi.fn(),
+}));
+
+vi.mock("#/hooks/mutation/use-create-conversation", () => ({
+ useCreateConversation: () => ({
+ mutate: mocks.createConversationMutate,
+ isPending: false,
+ }),
+}));
+
+vi.mock("#/contexts/active-backend-context", () => ({
+ useActiveBackend: () => ({ backend: { kind: "local" } }),
+}));
+
+vi.mock("#/hooks/use-tracking", () => ({
+ useTracking: () => ({
+ trackAutomationCreatedButton: mocks.trackAutomationCreatedButton,
+ }),
+}));
vi.mock("#/hooks/query/use-settings", () => ({
useSettings: () => ({ data: { user_consents_to_analytics: true } }),
@@ -82,43 +102,24 @@ function renderCreateInstructions() {
}
describe("CreateInstructions", () => {
- let captureMock: ReturnType<typeof vi.spyOn>;
-
beforeEach(() => {
- captureMock = vi
- .spyOn(telemetry, "trackEvent")
- .mockResolvedValue(undefined);
- useConversationStore.setState({ messageToSend: null });
+ mocks.createConversationMutate.mockReset();
+ mocks.trackAutomationCreatedButton.mockReset();
+ mocks.createConversationMutate.mockImplementation((_payload, options) => {
+ options?.onSuccess?.({ conversation_id: "conv-new" });
+ });
});
- afterEach(() => {
- captureMock.mockRestore();
- });
-
- it("captures automation_created_button with the active backend kind when Create Automation is clicked", async () => {
- const user = userEvent.setup();
- renderCreateInstructions();
-
- await user.click(screen.getByTestId("automations-create-automation"));
-
- expect(captureMock).toHaveBeenCalledWith(
- "automation_created_button",
- expect.objectContaining({ backend_kind: "local" }),
- );
- });
-
- it("navigates to conversations with a prefilled prompt when Create Automation is clicked", async () => {
+ it("tracks the click and opens the setup form without creating a conversation", async () => {
const user = userEvent.setup();
- const setMessageToSend = vi.fn();
- useConversationStore.setState({ setMessageToSend });
const { navigate } = renderCreateInstructions();
await user.click(screen.getByTestId("automations-create-automation"));
- expect(navigate).toHaveBeenCalledWith("/conversations");
- expect(setMessageToSend).toHaveBeenCalledWith(
- "Create an automation",
- "home",
- );
+ expect(mocks.trackAutomationCreatedButton).toHaveBeenCalledWith({
+ backendKind: "local",
+ });
+ expect(mocks.createConversationMutate).not.toHaveBeenCalled();
+ expect(navigate).toHaveBeenCalledWith("/automations/setup");
});
});
diff --git a/__tests__/components/automations/detail/run-logs-modal.test.tsx b/__tests__/components/automations/detail/run-logs-modal.test.tsx
index d3e0898d9d..b0f72c1877 100644
--- a/__tests__/components/automations/detail/run-logs-modal.test.tsx
+++ b/__tests__/components/automations/detail/run-logs-modal.test.tsx
@@ -69,6 +69,38 @@ describe("RunLogsModal", () => {
expect(container).toBeEmptyDOMElement();
});
+ it("scrolls long log content inside the dialog", () => {
+ useBashCommandLogsMock.mockReturnValue(
+ makeHookResult({
+ data: [
+ {
+ id: "o1",
+ kind: "BashOutput",
+ timestamp: "2026-01-01T10:00:00Z",
+ command_id: "cmd-1",
+ order: 0,
+ stdout: "line\n".repeat(80),
+ stderr: null,
+ },
+ ],
+ }),
+ );
+ render(
+ <RunLogsModal
+ isOpen
+ conversationId="conv-1"
+ bashCommandId="cmd-1"
+ onClose={() => {}}
+ />,
+ );
+
+ const body = screen.getByTestId("run-logs-body");
+ expect(body).toHaveClass("max-h-[80vh]", "overflow-y-auto");
+ expect(
+ screen.getByTestId("run-logs-output-stdout").parentElement,
+ ).not.toHaveClass("overflow-auto");
+ });
+
it("uses the 'Logs' title (not 'Run logs')", () => {
useBashCommandLogsMock.mockReturnValue(makeHookResult());
render(
diff --git a/__tests__/components/features/home/featured-automations-section.test.tsx b/__tests__/components/features/home/featured-automations-section.test.tsx
index 346c20f623..b817276536 100644
--- a/__tests__/components/features/home/featured-automations-section.test.tsx
+++ b/__tests__/components/features/home/featured-automations-section.test.tsx
@@ -27,6 +27,17 @@ import {
} from "#/types/automation";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
+const homeMocks = vi.hoisted(() => ({
+ createConversationMutate: vi.fn(),
+ navigate: vi.fn(),
+}));
+
+vi.mock("#/hooks/mutation/use-create-conversation", () => ({
+ useCreateConversation: () => ({
+ mutate: homeMocks.createConversationMutate,
+ }),
+}));
+
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: { name?: string; count?: number }) => {
@@ -150,7 +161,7 @@ function renderHomeAutomations(ui: React.ReactElement) {
currentPath: "/",
conversationId: null,
isNavigating: false,
- navigate: vi.fn(),
+ navigate: homeMocks.navigate,
}}
>
{ui}
@@ -572,7 +583,7 @@ describe("home automations on a cloud backend", () => {
__resetActiveStoreForTests();
});
- it("opens the Edit modal in place from a row menu instead of leaving the home surface", async () => {
+ it("opens the setup page from a row menu", async () => {
// Arrange — make a cloud backend active before mounting.
setRegisteredBackends([cloudBackend]);
setActiveSelection({ backendId: cloudBackend.id });
@@ -588,11 +599,11 @@ describe("home automations on a cloud backend", () => {
await user.click(screen.getByTestId("running-automation-menu-auto-1"));
await user.click(screen.getByTestId("running-automation-edit-auto-1"));
- // Assert — the editor opens pre-filled for this row rather than
- // bouncing the user to the detail page.
- const nameInput = (await screen.findByTestId(
- "edit-automation-name",
- )) as HTMLInputElement;
- expect(nameInput.value).toBe("Daily digest");
+ // Assert — Edit opens the setup form for this row rather than the modal.
+ expect(homeMocks.createConversationMutate).not.toHaveBeenCalled();
+ expect(homeMocks.navigate).toHaveBeenCalledWith("/automations/setup?automationId=auto-1");
+ expect(
+ screen.queryByTestId("edit-automation-name"),
+ ).not.toBeInTheDocument();
});
});
diff --git a/__tests__/hooks/use-start-automation-setup.test.ts b/__tests__/hooks/use-start-automation-setup.test.ts
new file mode 100644
index 0000000000..4b521c9edf
--- /dev/null
+++ b/__tests__/hooks/use-start-automation-setup.test.ts
@@ -0,0 +1,176 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useStartAutomationSetup } from "#/hooks/use-start-automation-setup";
+
+const mocks = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ mutate: vi.fn(),
+ isPending: false,
+ getAutomationFormSession: vi.fn(),
+ initializeAutomationFormSession: vi.fn(),
+ clearAutomationFormSession: vi.fn(),
+ markAutomationSetupHandoff: vi.fn(),
+}));
+
+vi.mock("#/hooks/mutation/use-create-conversation", () => ({
+ useCreateConversation: () => ({
+ mutate: mocks.mutate,
+ isPending: mocks.isPending,
+ }),
+}));
+
+vi.mock("#/api/automation-form-session", () => ({
+ PENDING_AUTOMATION_SETUP_ID: "pending-new-automation",
+ getAutomationFormSession: (...args: unknown[]) =>
+ mocks.getAutomationFormSession(...args),
+ initializeAutomationFormSession: (...args: unknown[]) =>
+ mocks.initializeAutomationFormSession(...args),
+ clearAutomationFormSession: (...args: unknown[]) =>
+ mocks.clearAutomationFormSession(...args),
+}));
+
+vi.mock("#/api/automation-setup-handoff-store", () => ({
+ markAutomationSetupHandoff: (...args: unknown[]) =>
+ mocks.markAutomationSetupHandoff(...args),
+}));
+
+vi.mock("#/contexts/active-backend-context", () => ({
+ useActiveBackend: () => ({ backend: { kind: "local" } }),
+}));
+
+vi.mock("#/context/navigation-context", () => ({
+ useNavigation: () => ({ navigate: mocks.navigate }),
+}));
+
+vi.mock("#/hooks/use-tracking", () => ({
+ useTracking: () => ({ trackAutomationCreatedButton: vi.fn() }),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+describe("useStartAutomationSetup", () => {
+ beforeEach(() => {
+ mocks.navigate.mockReset();
+ mocks.mutate.mockReset();
+ mocks.getAutomationFormSession.mockReset();
+ mocks.initializeAutomationFormSession.mockReset();
+ mocks.clearAutomationFormSession.mockReset();
+ mocks.markAutomationSetupHandoff.mockReset();
+ mocks.isPending = false;
+ });
+
+ it("creates the conversation from the prompt and keeps the form draft", () => {
+ const draft = {
+ prompt: "Summarize overnight alerts",
+ kind: "prompt" as const,
+ form: { name: "Incident digest" },
+ };
+ mocks.getAutomationFormSession.mockReturnValue(draft);
+ mocks.mutate.mockImplementation((_payload, options) => {
+ options?.onSuccess?.({ conversation_id: "conv-prompt" });
+ });
+ const { result } = renderHook(() => useStartAutomationSetup());
+
+ result.current.startConversationFromPrompt(" Watch the inbox ");
+
+ expect(mocks.mutate).toHaveBeenCalledWith(
+ {
+ query: "Watch the inbox",
+ automationSetup: true,
+ entryPoint: "automations_add",
+ },
+ expect.any(Object),
+ );
+ expect(mocks.initializeAutomationFormSession).toHaveBeenCalledWith(
+ "conv-prompt",
+ draft,
+ );
+ expect(mocks.clearAutomationFormSession).toHaveBeenCalledWith(
+ "pending-new-automation",
+ );
+ expect(mocks.markAutomationSetupHandoff).toHaveBeenCalledWith(
+ "conv-prompt",
+ );
+ expect(mocks.navigate).toHaveBeenCalledWith("/conversations/conv-prompt");
+ });
+
+ it("sends saved draft tags with the initial prompt", () => {
+ const draft = {
+ prompt: "Draft prompt",
+ kind: "prompt" as const,
+ serverDraftId: "draft-1",
+ materializedAutomationId: "auto-draft-1",
+ form: { name: "Saved draft", prompt: "Draft prompt" },
+ };
+ mocks.getAutomationFormSession.mockReturnValue(draft);
+ mocks.mutate.mockImplementation(async (_payload, options) => {
+ await options?.onSuccess?.({ conversation_id: "conv-draft" });
+ });
+ const { result } = renderHook(() => useStartAutomationSetup());
+
+ result.current.startConversationFromPrompt(" Refine the cadence ");
+
+ expect(mocks.mutate).toHaveBeenCalledWith(
+ {
+ query: "Refine the cadence",
+ automationSetup: true,
+ automationSetupTags: {
+ automationsetup: "draft",
+ automationdraftid: "draft-1",
+ automationmaterializeddraftid: "auto-draft-1",
+ },
+ entryPoint: "automation_draft_resume",
+ },
+ expect.any(Object),
+ );
+ expect(mocks.initializeAutomationFormSession).toHaveBeenCalledWith(
+ "conv-draft",
+ draft,
+ );
+ expect(mocks.navigate).toHaveBeenCalledWith("/conversations/conv-draft");
+ });
+
+ it("sends edited automation tags with the initial prompt", () => {
+ const draft = {
+ prompt: "Existing prompt",
+ kind: "prompt" as const,
+ editingAutomationId: "auto-1",
+ form: { name: "Existing automation", prompt: "Existing prompt" },
+ };
+ mocks.getAutomationFormSession.mockReturnValue(draft);
+ mocks.mutate.mockImplementation(async (_payload, options) => {
+ await options?.onSuccess?.({ conversation_id: "conv-edit" });
+ });
+ const { result } = renderHook(() => useStartAutomationSetup());
+
+ result.current.startConversationFromPrompt(" Adjust this automation ");
+
+ expect(mocks.mutate).toHaveBeenCalledWith(
+ {
+ query: "Adjust this automation",
+ automationSetup: true,
+ automationSetupTags: {
+ automationsetup: "draft",
+ automationeditid: "auto-1",
+ },
+ entryPoint: "automation_edit",
+ },
+ expect.any(Object),
+ );
+ expect(mocks.initializeAutomationFormSession).toHaveBeenCalledWith(
+ "conv-edit",
+ draft,
+ );
+ expect(mocks.navigate).toHaveBeenCalledWith("/conversations/conv-edit");
+ });
+
+ it("does not create a conversation from an empty prompt", () => {
+ const { result } = renderHook(() => useStartAutomationSetup());
+
+ result.current.startConversationFromPrompt(" ");
+
+ expect(mocks.mutate).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/routes/automation-detail.test.tsx b/__tests__/routes/automation-detail.test.tsx
index bb44181e3d..f376e1c9ef 100644
--- a/__tests__/routes/automation-detail.test.tsx
+++ b/__tests__/routes/automation-detail.test.tsx
@@ -61,6 +61,26 @@ vi.mock("#/api/cloud/organization-service.api", async (importOriginal) => ({
getCloudOrganizationMember: vi.fn(),
}));
+const detailMocks = vi.hoisted(() => ({
+ createConversationMutate: vi.fn(),
+ navigate: vi.fn(),
+}));
+
+vi.mock("#/hooks/mutation/use-create-conversation", () => ({
+ useCreateConversation: () => ({
+ mutate: detailMocks.createConversationMutate,
+ }),
+}));
+
+vi.mock("#/context/navigation-context", () => ({
+ useNavigation: () => ({
+ currentPath: "/automations/auto-1",
+ conversationId: null,
+ isNavigating: false,
+ navigate: detailMocks.navigate,
+ }),
+}));
+
const localBackend: Backend = {
id: "local-1",
name: "Local 1",
@@ -137,6 +157,8 @@ beforeEach(() => {
profiles: [],
active_profile: null,
});
+ detailMocks.createConversationMutate.mockReset();
+ detailMocks.navigate.mockReset();
setRegisteredBackends([localBackend, cloudBackend]);
setActiveSelection({ backendId: localBackend.id });
});
@@ -165,7 +187,7 @@ describe("AutomationDetail — Edit in the kebab menu", () => {
).toBeInTheDocument();
});
- it("opens the Edit modal pre-filled from the kebab menu when the active backend is cloud", async () => {
+ it("opens the setup page from the kebab menu when the active backend is cloud", async () => {
// Arrange — switch to the cloud backend BEFORE rendering so the
// detail page mounts under cloud (the backend-change guard would
// otherwise stop the fetch).
@@ -182,13 +204,16 @@ describe("AutomationDetail — Edit in the kebab menu", () => {
screen.getByRole("button", { name: I18nKey.AUTOMATIONS$EDIT }),
);
- // Assert — the Edit modal mounts on cloud, pre-filled for this
- // automation; the permission model (mocked to canManage above) decides,
- // not the backend kind.
- const nameInput = (await screen.findByTestId(
- "edit-automation-name",
- )) as HTMLInputElement;
- expect(nameInput.value).toBe(automation.name);
+ // Assert — Edit opens the setup form without starting or seeding an agent
+ // conversation. The permission model (mocked to canManage above) decides
+ // whether the action exists, not the backend kind.
+ expect(detailMocks.createConversationMutate).not.toHaveBeenCalled();
+ expect(detailMocks.navigate).toHaveBeenCalledWith(
+ "/automations/setup?automationId=auto-1",
+ );
+ expect(
+ screen.queryByTestId("edit-automation-name"),
+ ).not.toBeInTheDocument();
});
});
diff --git a/__tests__/routes/automation-setup-new.test.tsx b/__tests__/routes/automation-setup-new.test.tsx
new file mode 100644
index 0000000000..d683ece5dd
--- /dev/null
+++ b/__tests__/routes/automation-setup-new.test.tsx
@@ -0,0 +1,121 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter } from "react-router";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import AutomationSetupNew from "#/routes/automation-setup-new";
+import AutomationService from "#/api/automation-service/automation-service.api";
+import {
+ PENDING_AUTOMATION_SETUP_ID,
+ clearAutomationFormSession,
+} from "#/api/automation-form-session";
+import type { Automation } from "#/types/automation";
+import type { AutomationDraftApiResponse } from "#/manifests/types";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("#/api/automation-service/automation-service.api", () => ({
+ default: {
+ getAutomation: vi.fn(),
+ getServerDraft: vi.fn(),
+ },
+}));
+
+vi.mock("#/hooks/use-start-automation-setup", () => ({
+ useStartAutomationSetup: () => ({
+ startConversationFromPrompt: vi.fn(),
+ isPending: false,
+ }),
+}));
+
+vi.mock("#/components/features/chat/interactive-chat-box", () => ({
+ InteractiveChatBox: () => <div data-testid="mock-chat-box" />,
+}));
+
+vi.mock(
+ "#/components/features/automations/setup/automation-setup-panel",
+ () => ({
+ AutomationSetupPanel: ({ draft }: { draft: unknown }) => (
+ <pre data-testid="setup-panel-draft">{JSON.stringify(draft)}</pre>
+ ),
+ }),
+);
+
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displayErrorToast: vi.fn(),
+}));
+
+const automation: Automation = {
+ id: "auto-1",
+ name: "Daily digest",
+ prompt: "Review pull requests",
+ enabled: true,
+ created_at: "2026-01-01T00:00:00.000Z",
+ updated_at: "2026-01-01T00:00:00.000Z",
+ repository: "OpenHands/OpenHands",
+ trigger: { type: "cron", schedule: "0 9 * * *", timezone: "UTC" },
+};
+
+const serverDraft: AutomationDraftApiResponse = {
+ id: "draft-1",
+ endpoint: "/v1/preset/prompt",
+ name: "Saved draft",
+ draft: {
+ prompt: "Triage issues",
+ repos: [{ url: "acme/one" }, { url: "acme/two" }],
+ trigger: { type: "event", source: "github", on: ["issues", "push"] },
+ },
+ validationErrors: null,
+ dispatchable: true,
+ sourceAutomationId: null,
+ materializedAutomationId: null,
+ lastTestRunId: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+};
+
+function renderRoute(path: string) {
+ return render(
+ <MemoryRouter initialEntries={[path]}>
+ <AutomationSetupNew />
+ </MemoryRouter>,
+ );
+}
+
+describe("AutomationSetupNew", () => {
+ beforeEach(() => {
+ clearAutomationFormSession(PENDING_AUTOMATION_SETUP_ID);
+ vi.clearAllMocks();
+ });
+
+ it("reloads an existing automation editor from the automationId query", async () => {
+ vi.mocked(AutomationService.getAutomation).mockResolvedValue(automation);
+
+ renderRoute("/automations/setup?automationId=auto-1");
+
+ await waitFor(() =>
+ expect(AutomationService.getAutomation).toHaveBeenCalledWith("auto-1"),
+ );
+ const draft = JSON.parse(
+ screen.getByTestId("setup-panel-draft").textContent ?? "{}",
+ );
+ expect(draft.editingAutomationId).toBe("auto-1");
+ expect(draft.form.name).toBe("Daily digest");
+ });
+
+ it("reloads a saved draft from the draftId query", async () => {
+ vi.mocked(AutomationService.getServerDraft).mockResolvedValue(serverDraft);
+
+ renderRoute("/automations/setup?draftId=draft-1");
+
+ await waitFor(() =>
+ expect(AutomationService.getServerDraft).toHaveBeenCalledWith("draft-1"),
+ );
+ const draft = JSON.parse(
+ screen.getByTestId("setup-panel-draft").textContent ?? "{}",
+ );
+ expect(draft.serverDraftId).toBe("draft-1");
+ expect(draft.form.repository).toBe("acme/one, acme/two");
+ expect(draft.form.eventKey).toBe("issues,push");
+ });
+});
diff --git a/__tests__/routes/automations-list-behavior.test.tsx b/__tests__/routes/automations-list-behavior.test.tsx
index a371665d54..b765c53215 100644
--- a/__tests__/routes/automations-list-behavior.test.tsx
+++ b/__tests__/routes/automations-list-behavior.test.tsx
@@ -141,6 +141,7 @@ vi.mock("#/hooks/use-tracking", () => ({
useTracking: () => ({
trackPrebuiltAutomationEnabled: mocks.trackEnabled,
trackAutomationExported: mocks.trackExported,
+ trackAutomationCreatedButton: vi.fn(),
}),
}));
@@ -341,23 +342,6 @@ vi.mock(
}),
);
-vi.mock("#/components/features/automations/add-automation-modal", () => ({
- AddAutomationModal: ({
- isOpen,
- onClose,
- }: {
- isOpen: boolean;
- onClose: () => void;
- }) =>
- isOpen ? (
- <div data-testid="add-modal">
- <button type="button" onClick={onClose}>
- close-add
- </button>
- </div>
- ) : null,
-}));
-
vi.mock("#/components/features/automations/import-automation-modal", () => ({
ImportAutomationModal: ({
isOpen,
@@ -888,7 +872,7 @@ describe("automations list interactions", () => {
expect(screen.queryByTestId("delete-modal")).not.toBeInTheDocument();
});
- it("opens and closes editing for local automations", async () => {
+ it("opens the setup page when editing an automation", async () => {
const automation = makeAutomation();
mocks.automationsState.data = { automations: [automation], total: 1 };
const user = userEvent.setup();
@@ -897,9 +881,11 @@ describe("automations list interactions", () => {
await user.click(
screen.getByRole("button", { name: `edit-${automation.id}` }),
);
- expect(screen.getByTestId("edit-modal")).toHaveTextContent(automation.name);
- await user.click(screen.getByRole("button", { name: "close-edit" }));
+ expect(mocks.createConversation).not.toHaveBeenCalled();
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ "/automations/setup?automationId=automation-1",
+ );
expect(screen.queryByTestId("edit-modal")).not.toBeInTheDocument();
});
@@ -955,15 +941,14 @@ describe("automations list interactions", () => {
).toBeInTheDocument();
});
- it("opens and closes the add-automation form", async () => {
+ it("starts the setup page from the add-automation action", async () => {
const user = userEvent.setup();
renderList();
- expect(screen.queryByTestId("add-modal")).not.toBeInTheDocument();
await user.click(screen.getByTestId("automations-add-automation"));
- expect(screen.getByTestId("add-modal")).toBeInTheDocument();
- await user.click(screen.getByRole("button", { name: "close-add" }));
+ expect(mocks.createConversation).not.toHaveBeenCalled();
+ expect(mocks.navigate).toHaveBeenCalledWith("/automations/setup");
expect(screen.queryByTestId("add-modal")).not.toBeInTheDocument();
});
diff --git a/__tests__/routes/automations-list.test.tsx b/__tests__/routes/automations-list.test.tsx
index afe6bbbd93..732c4500cb 100644
--- a/__tests__/routes/automations-list.test.tsx
+++ b/__tests__/routes/automations-list.test.tsx
@@ -44,6 +44,7 @@ import { AUTOMATION_STACK_SECTION_BOTTOM_CLASS } from "#/utils/automation-stack-
const mocks = vi.hoisted(() => ({
createConversationMutate: vi.fn(),
+ initializeAutomationFormSession: vi.fn(),
navigate: vi.fn(),
}));
@@ -61,6 +62,12 @@ vi.mock("#/hooks/mutation/use-create-conversation", () => ({
useCreateConversation: () => ({ mutate: mocks.createConversationMutate }),
}));
+vi.mock("#/api/automation-form-session", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("#/api/automation-form-session")>()),
+ initializeAutomationFormSession: (...args: unknown[]) =>
+ mocks.initializeAutomationFormSession(...args),
+}));
+
vi.mock("#/context/navigation-context", () => ({
useNavigation: () => ({
currentPath: "/automations",
@@ -245,6 +252,8 @@ beforeEach(() => {
vi.mocked(AutomationService.deleteAutomation).mockReset();
vi.mocked(AutomationService.deleteAutomation).mockResolvedValue(undefined);
mocks.createConversationMutate.mockReset();
+ mocks.initializeAutomationFormSession.mockReset();
+
mocks.navigate.mockReset();
vi.mocked(
AgentServerConversationService.batchGetAppConversations,
@@ -273,7 +282,6 @@ afterEach(() => {
});
describe("AutomationsList — draft sections", () => {
-
it("does not request saved drafts when capabilities do not advertise drafts", async () => {
vi.mocked(AutomationService.getCapabilities).mockResolvedValue({
ready: true,
@@ -341,6 +349,15 @@ describe("AutomationsList — draft sections", () => {
screen.getByTestId("automation-setup-draft-draft-event"),
).queryByTestId("styled-tooltip-content"),
).not.toBeInTheDocument();
+ const editButton = within(draftCard).getByTestId(
+ "automation-setup-draft-edit-draft-1",
+ );
+ expect(editButton).toBeEnabled();
+ expect(editButton).toHaveAttribute("aria-label", I18nKey.AUTOMATIONS$EDIT);
+ expect(
+ editButton.compareDocumentPosition(activePlay) &
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
expect(
within(draftCard).getByTestId("automation-setup-draft-delete-draft-1"),
).toBeInTheDocument();
@@ -356,7 +373,7 @@ describe("AutomationsList — draft sections", () => {
).not.toBeInTheDocument();
});
- it("does not start a conversation when resuming a saved draft in this PR", async () => {
+ it("opens saved drafts in the deferred setup route without starting a conversation", async () => {
const user = userEvent.setup();
vi.mocked(AutomationService.listServerDrafts).mockResolvedValue(
draftListResponse,
@@ -368,16 +385,30 @@ describe("AutomationsList — draft sections", () => {
"automation-setup-draft-draft-1",
);
await user.click(
- within(draftCard).getByTestId("automation-setup-draft-resume-draft-1"),
+ within(draftCard).getByTestId("automation-setup-draft-edit-draft-1"),
);
+ expect(mocks.initializeAutomationFormSession).toHaveBeenCalledWith(
+ "pending-new-automation",
+ expect.objectContaining({
+ prompt: "Draft prompt",
+ kind: "prompt",
+ serverDraftId: "draft-1",
+ materializedAutomationId: "auto-draft-1",
+ form: expect.objectContaining({
+ kind: "prompt",
+ name: "Saved setup draft",
+ prompt: "Draft prompt",
+ }),
+ }),
+ );
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ "/automations/setup?draftId=draft-1",
+ );
expect(mocks.createConversationMutate).not.toHaveBeenCalled();
expect(
AgentServerConversationService.updateConversationTags,
).not.toHaveBeenCalled();
- expect(mocks.navigate).not.toHaveBeenCalledWith(
- expect.stringContaining("/conversations/"),
- );
});
it("can test and delete saved setup drafts", async () => {
@@ -464,13 +495,29 @@ describe("AutomationsList — Edit from the row kebab", () => {
screen.getByRole("button", { name: I18nKey.AUTOMATIONS$EDIT }),
);
- // Assert — the shared Edit modal mounts wired to this row (name input is
- // pre-filled with that row's name, proving the list page passed the right
- // automation through).
- const nameInput = (await screen.findByTestId(
- "edit-automation-name",
- )) as HTMLInputElement;
- expect(nameInput.value).toBe(automation.name);
+ // Assert — edit opens the collapsed setup form without starting or
+ // seeding an agent conversation.
+ expect(mocks.createConversationMutate).not.toHaveBeenCalled();
+ expect(mocks.initializeAutomationFormSession).toHaveBeenCalledWith(
+ "pending-new-automation",
+ expect.objectContaining({
+ prompt: automation.prompt,
+ kind: "prompt",
+ editingAutomationId: automation.id,
+ form: expect.objectContaining({
+ name: automation.name,
+ prompt: automation.prompt,
+ repository: automation.repository,
+ model: automation.model,
+ }),
+ }),
+ );
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ "/automations/setup?automationId=auto-1",
+ );
+ expect(
+ screen.queryByTestId("edit-automation-name"),
+ ).not.toBeInTheDocument();
});
it("opens the Edit modal pre-filled from the row kebab when the active backend is cloud", async () => {
@@ -492,12 +539,23 @@ describe("AutomationsList — Edit from the row kebab", () => {
screen.getByRole("button", { name: I18nKey.AUTOMATIONS$EDIT }),
);
- // Assert — the same Edit modal mounts on cloud, wired to this row; the
- // permission model decides, not the backend kind.
- const nameInput = (await screen.findByTestId(
- "edit-automation-name",
- )) as HTMLInputElement;
- expect(nameInput.value).toBe(automation.name);
+ // Assert — cloud uses the same collapsed setup form; the permission model
+ // decides whether Edit is offered, not which editor opens.
+ expect(mocks.createConversationMutate).not.toHaveBeenCalled();
+ expect(mocks.initializeAutomationFormSession).toHaveBeenCalledWith(
+ "pending-new-automation",
+ expect.objectContaining({
+ prompt: automation.prompt,
+ kind: "prompt",
+ editingAutomationId: automation.id,
+ }),
+ );
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ "/automations/setup?automationId=auto-1",
+ );
+ expect(
+ screen.queryByTestId("edit-automation-name"),
+ ).not.toBeInTheDocument();
});
});
@@ -775,7 +833,11 @@ describe("AutomationsList — add automation menu", () => {
).toBeInTheDocument();
await user.click(screen.getByTestId("automations-add-automation-create"));
- expect(screen.getByTestId("add-automation-modal")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("add-automation-modal"),
+ ).not.toBeInTheDocument();
+ expect(mocks.createConversationMutate).not.toHaveBeenCalled();
+ expect(mocks.navigate).toHaveBeenCalledWith("/automations/setup");
});
it("opens the import picker from the Add Automation menu", async () => {
diff --git a/__tests__/utils/automation-edit-draft.test.ts b/__tests__/utils/automation-edit-draft.test.ts
new file mode 100644
index 0000000000..9a25885848
--- /dev/null
+++ b/__tests__/utils/automation-edit-draft.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from "vitest";
+import type { Automation } from "#/types/automation";
+import { setupDraftFromAutomation } from "#/utils/automation-edit-draft";
+
+function automation(overrides: Partial<Automation> = {}): Automation {
+ return {
+ id: "auto-1",
+ name: "Daily digest",
+ prompt: "Summarize yesterday's PRs",
+ trigger: {
+ type: "cron",
+ schedule: "0 9 * * *",
+ timezone: "America/New_York",
+ },
+ enabled: true,
+ repository: "acme/repo",
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+describe("setupDraftFromAutomation", () => {
+ it("maps a daily prompt automation onto the setup form and keeps the edit id", () => {
+ const draft = setupDraftFromAutomation(automation());
+
+ expect(draft.editingAutomationId).toBe("auto-1");
+ expect(draft.kind).toBe("prompt");
+ expect(draft.form).toMatchObject({
+ name: "Daily digest",
+ prompt: "Summarize yesterday's PRs",
+ repository: "acme/repo",
+ frequency: "daily",
+ time: "09:00",
+ timezone: "America/New_York",
+ triggerKind: "cron",
+ });
+ });
+
+ it.each([
+ {
+ name: "hourly cron",
+ automation: automation({
+ trigger: { type: "cron", schedule: "0 * * * *" },
+ }),
+ expected: { triggerKind: "cron", frequency: "hourly" },
+ },
+ {
+ name: "custom cron",
+ automation: automation({
+ trigger: { type: "cron", schedule: "*/17 * * * *" },
+ }),
+ expected: {
+ triggerKind: "cron",
+ frequency: "custom",
+ customSchedule: "*/17 * * * *",
+ },
+ },
+ {
+ name: "event trigger",
+ automation: automation({
+ prompt: "On each pull request",
+ trigger: {
+ type: "event",
+ source: "github",
+ on: "pull_request",
+ filter: "action == 'opened'",
+ },
+ }),
+ expected: {
+ triggerKind: "event",
+ eventSource: "github",
+ eventKey: "pull_request",
+ eventFilter: "action == 'opened'",
+ },
+ },
+ ])("maps $name fields", ({ automation: savedAutomation, expected }) => {
+ expect(setupDraftFromAutomation(savedAutomation).form).toMatchObject(
+ expected,
+ );
+ });
+});
diff --git a/src/api/automation-form-session.ts b/src/api/automation-form-session.ts
index d5909136b2..82325a4bc6 100644
--- a/src/api/automation-form-session.ts
+++ b/src/api/automation-form-session.ts
@@ -16,6 +16,14 @@ import type {
const AUTOMATION_FORM_SESSION_CHANGED_EVENT =
"openhands:automation-form-session-changed";
+
+export const PENDING_AUTOMATION_SETUP_ID = "pending-new-automation";
+
+export function isPendingAutomationSetupId(
+ conversationId: string | null | undefined,
+): boolean {
+ return conversationId === PENDING_AUTOMATION_SETUP_ID;
+}
const AUTOMATION_SETUP_KINDS: AutomationSetupKind[] = [
"prompt",
"plugin",
@@ -157,6 +165,10 @@ function normalizeDraft(value: AutomationSetupDraft): AutomationSetupDraft {
};
const normalizedPlugins = pluginSources;
const fieldMetadata = normalizeFieldMetadata(value.fieldMetadata);
+ const editingAutomationId =
+ typeof value.editingAutomationId === "string"
+ ? value.editingAutomationId.trim()
+ : "";
const serverDraftId =
typeof value.serverDraftId === "string" ? value.serverDraftId.trim() : "";
const materializedAutomationId =
@@ -176,6 +188,7 @@ function normalizeDraft(value: AutomationSetupDraft): AutomationSetupDraft {
kind,
...(normalizedPlugins.length > 0 ? { plugins: normalizedPlugins } : {}),
form: normalizedForm,
+ ...(editingAutomationId ? { editingAutomationId } : {}),
...(serverDraftId ? { serverDraftId } : {}),
...(materializedAutomationId ? { materializedAutomationId } : {}),
...(fieldMetadata ? { fieldMetadata } : {}),
diff --git a/src/api/automation-setup-types.ts b/src/api/automation-setup-types.ts
index 65491fd1aa..ba45a6fa97 100644
--- a/src/api/automation-setup-types.ts
+++ b/src/api/automation-setup-types.ts
@@ -56,9 +56,11 @@ export interface AutomationSetupDraft {
prompt: string;
kind: AutomationSetupKind;
plugins?: string[];
- form?: AutomationSetupFormPatch;
+ editingAutomationId?: string;
serverDraftId?: string;
materializedAutomationId?: string | null;
+ existingCustomTarballPath?: string;
+ form?: AutomationSetupFormPatch;
fieldMetadata?: Partial<
Record<AutomationSetupField, AutomationSetupFieldMetadata>
>;
diff --git a/src/components/features/automations/add-automation-modal.tsx b/src/components/features/automations/add-automation-modal.tsx
deleted file mode 100644
index b11d4708a0..0000000000
--- a/src/components/features/automations/add-automation-modal.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
-import { ModalCloseButton } from "#/components/shared/modals/modal-close-button";
-import { I18nKey } from "#/i18n/declaration";
-import { cn } from "#/utils/utils";
-import { modalTitleLgClassName } from "#/utils/modal-classes";
-import { CreateInstructionsContent } from "./create-instructions";
-
-interface AddAutomationModalProps {
- isOpen: boolean;
- onClose: () => void;
-}
-
-export function AddAutomationModal({
- isOpen,
- onClose,
-}: AddAutomationModalProps) {
- const { t } = useTranslation("openhands");
-
- if (!isOpen) return null;
-
- return (
- <ModalBackdrop
- onClose={onClose}
- aria-label={t(I18nKey.AUTOMATIONS$EMPTY_HOW_TO_CREATE_TITLE)}
- >
- <div
- data-testid="add-automation-modal"
- className="relative flex w-full max-w-lg flex-col rounded-xl border border-border bg-base-secondary"
- >
- <ModalCloseButton
- onClose={onClose}
- testId="add-automation-modal-close"
- />
- <header className="flex-shrink-0 px-6 pb-4 pt-6">
- <h2
- id="add-automation-modal-title"
- className={cn("pr-6", modalTitleLgClassName)}
- >
- {t(I18nKey.AUTOMATIONS$EMPTY_HOW_TO_CREATE_TITLE)}
- </h2>
- </header>
- <div className="px-6 pb-6">
- <CreateInstructionsContent onLaunch={onClose} />
- </div>
- </div>
- </ModalBackdrop>
- );
-}
diff --git a/src/components/features/automations/create-instructions.tsx b/src/components/features/automations/create-instructions.tsx
index cdfa46ddcc..d8be3e90b8 100644
--- a/src/components/features/automations/create-instructions.tsx
+++ b/src/components/features/automations/create-instructions.tsx
@@ -5,9 +5,7 @@ import ChevronDownIcon from "#/icons/chevron-down.svg?react";
import MessageSquareShareIcon from "#/icons/message-square-share.svg?react";
import { cn } from "#/utils/utils";
import { BrandButton } from "#/components/features/settings/brand-button";
-import { useLaunchSkillInChat } from "#/hooks/use-launch-skill-in-chat";
-import { useActiveBackend } from "#/contexts/active-backend-context";
-import { useTracking } from "#/hooks/use-tracking";
+import { useStartAutomationSetup } from "#/hooks/use-start-automation-setup";
import { getAutomationsDocsUrl } from "#/manifests/automation-interface";
function InlineExampleWrap({ children }: { children?: ReactNode }) {
@@ -43,22 +41,9 @@ interface CreateInstructionsProps {
collapsible?: boolean;
}
-interface CreateInstructionsContentProps {
- onLaunch?: () => void;
-}
-
-export function CreateInstructionsContent({
- onLaunch,
-}: CreateInstructionsContentProps = {}) {
+export function CreateInstructionsContent() {
const { t } = useTranslation("openhands");
- const launchInChat = useLaunchSkillInChat();
- const active = useActiveBackend();
- const { trackAutomationCreatedButton } = useTracking();
-
- const handleCreateAutomation = () => {
- trackAutomationCreatedButton({ backendKind: active.backend.kind });
- launchInChat(t(I18nKey.AUTOMATIONS$CREATE_AUTOMATION_PROMPT), onLaunch);
- };
+ const { startSetup, isPending } = useStartAutomationSetup();
return (
<div className="flex flex-col gap-5">
@@ -84,7 +69,8 @@ export function CreateInstructionsContent({
type="button"
variant="primary"
testId="automations-create-automation"
- onClick={handleCreateAutomation}
+ isDisabled={isPending}
+ onClick={startSetup}
startContent={
<MessageSquareShareIcon className="size-4" aria-hidden />
}
diff --git a/src/components/features/automations/detail/run-logs-modal.tsx b/src/components/features/automations/detail/run-logs-modal.tsx
index bdb8c71627..272a393f94 100644
--- a/src/components/features/automations/detail/run-logs-modal.tsx
+++ b/src/components/features/automations/detail/run-logs-modal.tsx
@@ -7,7 +7,6 @@ import {
type SandboxIssue,
} from "#/hooks/query/use-bash-command-logs";
import type { BashOutput } from "@openhands/typescript-client";
-import { cn } from "#/utils/utils";
import { modalTitleLgMediumClassName } from "#/utils/modal-classes";
import {
AutomationRunStatus,
@@ -272,131 +271,137 @@ export function RunLogsModal({
}}
role="presentation"
/>
- <div className="relative flex max-h-[80vh] w-full max-w-3xl flex-col overflow-y-auto rounded-xl border border-border bg-surface p-6">
- <button
- type="button"
- onClick={onClose}
- className="absolute right-4 top-4 text-muted hover:text-foreground"
- aria-label={t(I18nKey.AUTOMATIONS$CANCEL)}
- >
- <XMarkIcon className="size-5" />
- </button>
-
- <h2 className={cn("pr-8", modalTitleLgMediumClassName)}>
- {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TITLE)}
- </h2>
-
- <RunInspectionSummary run={run} />
-
- <div
- role="tablist"
- aria-label={t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TITLE)}
- className="mt-4 flex gap-1 border-b border-border"
- >
- <button
- type="button"
- role="tab"
- aria-selected={activeTab === "stdout"}
- aria-controls="run-logs-panel-stdout"
- id="run-logs-tab-stdout"
- tabIndex={activeTab === "stdout" ? 0 : -1}
- onClick={() => setActiveTab("stdout")}
- className={`${tabBaseClass} ${
- activeTab === "stdout" ? tabActiveClass : tabInactiveClass
- }`}
- >
- {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TAB_OUTPUT)}
- </button>
+ <div
+ data-testid="run-logs-body"
+ className="relative flex max-h-[80vh] w-full max-w-3xl flex-col overflow-y-auto overscroll-contain rounded-xl border border-border bg-surface"
+ >
+ <div className="sticky top-0 z-10 flex shrink-0 items-center justify-between gap-4 bg-surface px-6 pb-4 pt-6">
+ <h2 className={modalTitleLgMediumClassName}>
+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TITLE)}
+ </h2>
<button
type="button"
- role="tab"
- aria-selected={activeTab === "stderr"}
- aria-controls="run-logs-panel-stderr"
- id="run-logs-tab-stderr"
- tabIndex={activeTab === "stderr" ? 0 : -1}
- onClick={() => setActiveTab("stderr")}
- className={`${tabBaseClass} ${
- activeTab === "stderr" ? tabActiveClass : tabInactiveClass
- }`}
+ onClick={onClose}
+ className="text-muted hover:text-foreground"
+ aria-label={t(I18nKey.AUTOMATIONS$CANCEL)}
>
- {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TAB_ERROR)}
+ <XMarkIcon className="size-5" />
</button>
</div>
- <div
- role="tabpanel"
- id={`run-logs-panel-${activeTab}`}
- aria-labelledby={`run-logs-tab-${activeTab}`}
- className="mt-3 min-h-[12rem] flex-1 overflow-auto rounded-lg border border-border bg-black/40 p-4 font-mono text-xs"
- >
- {noBashCommand && (
- <p className="text-muted italic">
- {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_NO_COMMAND)}
- </p>
- )}
-
- {!noBashCommand && conversationMissing && (
- <p className="text-muted italic">
- {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_CONVERSATION_MISSING)}
- </p>
- )}
+ <div className="px-6 pb-6">
+ <RunInspectionSummary run={run} />
- {!noBashCommand && !conversationMissing && sandboxIssue && (
- <p
- data-testid={`run-logs-sandbox-issue-${sandboxIssue}`}
- className="text-muted italic"
+ <div
+ role="tablist"
+ aria-label={t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TITLE)}
+ className="mt-4 flex gap-1 border-b border-border"
+ >
+ <button
+ type="button"
+ role="tab"
+ aria-selected={activeTab === "stdout"}
+ aria-controls="run-logs-panel-stdout"
+ id="run-logs-tab-stdout"
+ tabIndex={activeTab === "stdout" ? 0 : -1}
+ onClick={() => setActiveTab("stdout")}
+ className={`${tabBaseClass} ${
+ activeTab === "stdout" ? tabActiveClass : tabInactiveClass
+ }`}
>
- {t(SANDBOX_ISSUE_I18N[sandboxIssue])}
- </p>
- )}
+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TAB_OUTPUT)}
+ </button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={activeTab === "stderr"}
+ aria-controls="run-logs-panel-stderr"
+ id="run-logs-tab-stderr"
+ tabIndex={activeTab === "stderr" ? 0 : -1}
+ onClick={() => setActiveTab("stderr")}
+ className={`${tabBaseClass} ${
+ activeTab === "stderr" ? tabActiveClass : tabInactiveClass
+ }`}
+ >
+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TAB_ERROR)}
+ </button>
+ </div>
- {!noBashCommand &&
- !conversationMissing &&
- !sandboxIssue &&
- loading && (
+ <div
+ role="tabpanel"
+ id={`run-logs-panel-${activeTab}`}
+ aria-labelledby={`run-logs-tab-${activeTab}`}
+ className="mt-3 min-h-[12rem] rounded-lg border border-border bg-black/40 p-4 font-mono text-xs"
+ >
+ {noBashCommand && (
<p className="text-muted italic">
- {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_LOADING)}
+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_NO_COMMAND)}
</p>
)}
- {!noBashCommand &&
- !conversationMissing &&
- !sandboxIssue &&
- !loading &&
- error &&
- !outputs && (
- <p className="text-danger">
- {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_ERROR)}: {String(error)}
+ {!noBashCommand && conversationMissing && (
+ <p className="text-muted italic">
+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_CONVERSATION_MISSING)}
</p>
)}
- {!loading && !sandboxIssue && outputs && (
- <pre
- data-testid={`run-logs-output-${activeTab}`}
- className={`whitespace-pre-wrap break-words ${
- activeTab === "stderr" ? "text-danger" : "text-content"
- }`}
- >
- {activeBody.length > 0 ? (
- activeBody
- ) : (
- <span className="text-muted italic">
- {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_EMPTY)}
- </span>
+ {!noBashCommand && !conversationMissing && sandboxIssue && (
+ <p
+ data-testid={`run-logs-sandbox-issue-${sandboxIssue}`}
+ className="text-muted italic"
+ >
+ {t(SANDBOX_ISSUE_I18N[sandboxIssue])}
+ </p>
+ )}
+
+ {!noBashCommand &&
+ !conversationMissing &&
+ !sandboxIssue &&
+ loading && (
+ <p className="text-muted italic">
+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_LOADING)}
+ </p>
)}
- </pre>
- )}
- </div>
- {run?.status === AutomationRunStatus.FAILED && (
- <div className="mt-4 flex justify-end">
- <DebugAutomationButton
- run={run}
- automation={automation}
- stderr={stderr}
- />
+ {!noBashCommand &&
+ !conversationMissing &&
+ !sandboxIssue &&
+ !loading &&
+ error &&
+ !outputs && (
+ <p className="text-danger">
+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_ERROR)}: {String(error)}
+ </p>
+ )}
+
+ {!loading && !sandboxIssue && outputs && (
+ <pre
+ data-testid={`run-logs-output-${activeTab}`}
+ className={`whitespace-pre-wrap break-words ${
+ activeTab === "stderr" ? "text-danger" : "text-content"
+ }`}
+ >
+ {activeBody.length > 0 ? (
+ activeBody
+ ) : (
+ <span className="text-muted italic">
+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_EMPTY)}
+ </span>
+ )}
+ </pre>
+ )}
</div>
- )}
+
+ {run?.status === AutomationRunStatus.FAILED && (
+ <div className="mt-4 flex justify-end">
+ <DebugAutomationButton
+ run={run}
+ automation={automation}
+ stderr={stderr}
+ />
+ </div>
+ )}
+ </div>
</div>
</div>
);
diff --git a/src/components/features/automations/setup/automation-setup-draft-service.ts b/src/components/features/automations/setup/automation-setup-draft-service.ts
index b7ccda2b95..3c5d3e4ba4 100644
--- a/src/components/features/automations/setup/automation-setup-draft-service.ts
+++ b/src/components/features/automations/setup/automation-setup-draft-service.ts
@@ -1,5 +1,7 @@
import { isSdkHttpError } from "#/api/agent-server-compatibility";
import type {
+ AutomationSetupDraft,
+ AutomationSetupFormPatch,
AutomationSetupFormValues,
AutomationSetupKind,
} from "#/api/automation-setup-types";
@@ -28,12 +30,40 @@ function getStringField(
return typeof field === "string" ? field : undefined;
}
-function getFirstObject(
+function getObjectArray(
value: Record<string, unknown>,
key: string,
-): Record<string, unknown> | null {
+): Record<string, unknown>[] {
const field = value[key];
- return Array.isArray(field) ? asRecord(field[0]) : null;
+ return Array.isArray(field)
+ ? field.flatMap((item) => {
+ const record = asRecord(item);
+ return record ? [record] : [];
+ })
+ : [];
+}
+
+function getRepositoryField(
+ value: Record<string, unknown>,
+): string | undefined {
+ const repositories = getObjectArray(value, "repos")
+ .map((repo) => getStringField(repo, "url")?.trim())
+ .filter((repo): repo is string => !!repo);
+ if (repositories.length > 0) return repositories.join(", ");
+ return typeof value.repository === "string" ? value.repository : undefined;
+}
+
+function getEventKeyField(
+ trigger: Record<string, unknown>,
+): string | undefined {
+ const eventKey = trigger.on;
+ if (typeof eventKey === "string") return eventKey;
+ if (!Array.isArray(eventKey)) return undefined;
+ const eventKeys = eventKey
+ .filter((item): item is string => typeof item === "string")
+ .map((item) => item.trim())
+ .filter(Boolean);
+ return eventKeys.length > 0 ? eventKeys.join(",") : undefined;
}
function getPluginEntries(
@@ -53,6 +83,81 @@ function getPluginEntries(
});
}
+function kindForDraftEndpoint(
+ endpoint: AutomationDraftEndpoint,
+): AutomationSetupKind {
+ if (endpoint === "/v1") return "custom";
+ if (endpoint === "/v1/preset/plugin") return "plugin";
+ return "prompt";
+}
+
+export function setupDraftFromServerDraft(
+ saved: AutomationDraftApiResponse,
+): AutomationSetupDraft {
+ const body = saved.draft as Record<string, unknown>;
+ const trigger = asRecord(body.trigger);
+ const pluginEntries = getPluginEntries(body);
+ const kind = kindForDraftEndpoint(saved.endpoint);
+ const form: AutomationSetupFormPatch = { kind };
+
+ const savedName = saved.name ?? getStringField(body, "name");
+ if (savedName !== undefined) form.name = savedName;
+ const savedPrompt = getStringField(body, "prompt");
+ if (savedPrompt !== undefined) form.prompt = savedPrompt;
+ const savedRepository = getRepositoryField(body);
+ if (savedRepository !== undefined) form.repository = savedRepository;
+ if (pluginEntries.length > 0) {
+ form.pluginSource = pluginEntries[0]?.source ?? "";
+ form.pluginRef = pluginEntries[0]?.ref ?? "";
+ form.pluginList = serializeAutomationSetupPluginList(pluginEntries);
+ }
+ const savedEntrypoint = getStringField(body, "entrypoint");
+ if (savedEntrypoint !== undefined) form.entrypoint = savedEntrypoint;
+ const savedSetupScriptPath = getStringField(body, "setup_script_path");
+ if (savedSetupScriptPath !== undefined) {
+ form.setupScriptPath = savedSetupScriptPath;
+ }
+ if (trigger) {
+ form.triggerKind =
+ getStringField(trigger, "type") === "event" ? "event" : "cron";
+ const schedule = getStringField(trigger, "schedule");
+ if (schedule) {
+ form.frequency = "custom";
+ form.customSchedule = schedule;
+ }
+ const savedTimezone = getStringField(trigger, "timezone");
+ if (savedTimezone !== undefined) form.timezone = savedTimezone;
+ const savedEventSource = getStringField(trigger, "source");
+ if (savedEventSource !== undefined) form.eventSource = savedEventSource;
+ const savedEventKey = getEventKeyField(trigger);
+ if (savedEventKey !== undefined) form.eventKey = savedEventKey;
+ const savedEventFilter = getStringField(trigger, "filter");
+ if (savedEventFilter !== undefined) form.eventFilter = savedEventFilter;
+ }
+ const savedModel = getStringField(body, "model");
+ if (savedModel !== undefined) form.model = savedModel;
+ const savedAgentProfileId = getStringField(body, "agent_profile_id");
+ if (savedAgentProfileId !== undefined) {
+ form.agentProfileId = savedAgentProfileId;
+ }
+ if (typeof body.timeout === "number") {
+ form.showTimeout = true;
+ form.timeoutSeconds = String(body.timeout);
+ }
+
+ const prompt = form.prompt ?? "";
+ return {
+ prompt,
+ kind,
+ ...(pluginEntries.length > 0
+ ? { plugins: pluginEntries.map((entry) => entry.source).filter(Boolean) }
+ : {}),
+ form,
+ serverDraftId: saved.id,
+ materializedAutomationId: saved.materializedAutomationId,
+ };
+}
+
export function formFromServerDraft(
saved: AutomationDraftApiResponse,
base: AutomationSetupFormValues,
@@ -69,22 +174,14 @@ export function formFromServerDraft(
ref: base.pluginRef,
},
].filter((entry) => entry.source || entry.ref);
- const repo = getFirstObject(body, "repos");
- const endpointKind: AutomationSetupKind =
- saved.endpoint === "/v1"
- ? "custom"
- : saved.endpoint === "/v1/preset/plugin"
- ? "plugin"
- : "prompt";
+ const endpointKind = kindForDraftEndpoint(saved.endpoint);
return {
...base,
kind: endpointKind,
name: saved.name ?? getStringField(body, "name") ?? base.name,
prompt: getStringField(body, "prompt") ?? base.prompt,
- repository:
- getStringField(repo ?? {}, "url") ??
- (typeof body.repository === "string" ? body.repository : base.repository),
+ repository: getRepositoryField(body) ?? base.repository,
pluginSource: savedPlugins[0]?.source ?? "",
pluginRef: savedPlugins[0]?.ref ?? "",
pluginList:
@@ -103,11 +200,9 @@ export function formFromServerDraft(
getStringField(trigger ?? {}, "schedule") ?? base.customSchedule,
timezone: getStringField(trigger ?? {}, "timezone") ?? base.timezone,
eventSource: getStringField(trigger ?? {}, "source") ?? base.eventSource,
- eventKey:
- getStringField(trigger ?? {}, "on") ??
- (Array.isArray(trigger?.on) && typeof trigger.on[0] === "string"
- ? trigger.on[0]
- : base.eventKey),
+ eventKey: trigger
+ ? (getEventKeyField(trigger) ?? base.eventKey)
+ : base.eventKey,
eventFilter: getStringField(trigger ?? {}, "filter") ?? base.eventFilter,
model: getStringField(body, "model") ?? base.model,
agentProfileId:
diff --git a/src/components/features/automations/setup/automation-setup-panel.tsx b/src/components/features/automations/setup/automation-setup-panel.tsx
index cb3179ec74..948d0ef058 100644
--- a/src/components/features/automations/setup/automation-setup-panel.tsx
+++ b/src/components/features/automations/setup/automation-setup-panel.tsx
@@ -28,7 +28,9 @@ import AutomationService, {
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import {
clearAutomationFormSession,
+ getAutomationFormSession,
initializeAutomationFormSession,
+ isPendingAutomationSetupId,
patchAutomationFormSession,
subscribeAutomationFormSession,
} from "#/api/automation-form-session";
@@ -44,12 +46,17 @@ import {
serializeAutomationSetupPluginList,
type AutomationSetupPluginEntry,
} from "#/api/automation-setup-plugins";
-import { automationDetailPath } from "#/manifests/automation-interface";
+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";
@@ -80,12 +87,13 @@ import type {
AutomationDraftApiResponse,
SetupRequestBody,
} from "#/manifests/types";
-import type { AutomationRun } from "#/types/automation";
+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,
@@ -98,9 +106,11 @@ import {
buildAutomationDraftTags,
buildAutomationSetupModeTags,
getAutomationDraftIdFromTags,
+ getAutomationEditIdFromTags,
hasAutomationSetupModeTag,
removeAutomationDraftTags,
} from "#/utils/automation-draft-tags";
+import { setupDraftFromAutomation } from "#/utils/automation-edit-draft";
const DEFAULT_TIMEZONE = "America/New_York";
const DEFAULT_TIME = "09:00";
@@ -275,6 +285,15 @@ function onceCron(scheduleDateTime: string): string {
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;
@@ -303,6 +322,17 @@ 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[] {
@@ -392,94 +422,193 @@ function buildInitialForm(
};
}
-function DraftRunDetailsCard({
+function DraftStatusBar({
draft,
runs,
+ isSubmitting,
+ canTest,
+ onTest,
+ onViewRuns,
}: {
draft: AutomationDraftApiResponse;
runs: AutomationRun[];
+ isSubmitting: boolean;
+ canTest: boolean;
+ onTest: () => void;
+ onViewRuns: () => void;
}) {
const { t, i18n } = useTranslation("openhands");
const validationMessage = draft.validationErrors?.[0]?.message ?? null;
const statusText = getDraftExecutionStatusText(draft, runs, t);
+ 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-red-500/10 text-red-300"
+ : "bg-[var(--oh-success)]/10 text-[var(--oh-success)]",
+ );
+
return (
<section
data-testid="automation-setup-draft-details"
- className="rounded-2xl border border-[var(--oh-border)] bg-[var(--oh-surface)]"
+ className="flex flex-col gap-2 rounded-xl border border-[var(--oh-border)] bg-[var(--oh-surface)] px-3 py-2"
>
- <div className="border-b border-[var(--oh-border)] px-5 py-4">
- <div className="flex flex-wrap items-start justify-between gap-3">
- <div>
- <h3 className="text-sm font-semibold text-content">
- {t(I18nKey.AUTOMATION_SETUP$DRAFT_STATUS_TITLE)}
- </h3>
- <p className="mt-1 text-sm text-muted">
- {t(I18nKey.AUTOMATION_SETUP$DRAFT_STATUS_DESCRIPTION)}
- </p>
- </div>
- <span
- data-testid="automation-setup-draft-validity"
- className={cn(
- "rounded-full px-3 py-1 text-xs",
- validationMessage
- ? "bg-[var(--oh-warning)]/10 text-[var(--oh-warning)]"
- : "bg-[var(--oh-success)]/10 text-[var(--oh-success)]",
+ <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,
)}
- >
- {statusText}
</span>
</div>
- <dl className="mt-4 grid gap-3 text-sm md:grid-cols-2">
- <div>
- <dt className="text-xs text-muted">
- {t(I18nKey.AUTOMATION_SETUP$LAST_SAVED)}
- </dt>
- <dd className="mt-1 text-content">
- {formatRelativeTime(
- draft.updatedAt,
- i18n?.language ?? AvailableLanguages[0].value,
- t,
- )}
- </dd>
- </div>
- {draft.materializedAutomationId ? (
- <div>
- <dt className="text-xs text-muted">
- {t(I18nKey.AUTOMATION_SETUP$TEST_AUTOMATION)}
- </dt>
- <dd className="mt-1 truncate font-mono text-xs text-content">
- {draft.materializedAutomationId}
- </dd>
- </div>
- ) : null}
- </dl>
+ <div className="flex shrink-0 items-center gap-1.5">
+ {validationMessage ? 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>
+ );
+}
- <div className="px-5 py-3">
- <h4 className="text-sm font-medium text-content">
+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)}
- </h4>
+ </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-red-500/40 bg-red-500/10 px-4 py-3 text-sm text-red-300"
+ >
+ {message}
+ </p>
+ ))}
{runs.length > 0 ? (
- <div>
+ <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(
- "border-t border-[var(--oh-border)]",
- index === 0 && "bg-[var(--oh-focus)]/10",
- )}
+ className={cn(index > 0 && "border-t border-[var(--oh-border)]")}
>
<ActivityLogItem run={run} />
</div>
))}
</div>
) : (
- <p className="border-t border-[var(--oh-border)] px-5 py-6 text-sm text-muted">
- {t(I18nKey.AUTOMATIONS$DETAIL$NO_RUNS)}
- </p>
+ <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>
);
@@ -515,7 +644,10 @@ export function AutomationSetupPanel({
const deploymentCapabilities = useDeploymentCapabilities();
const eventSourceOptions = deploymentCapabilities.data?.eventSources ?? [];
const eventTypeOptions = deploymentCapabilities.data?.eventTypes ?? [];
- const [form, setForm] = useState(() => buildInitialForm(draft));
+ const initialDraft = conversationId
+ ? (getAutomationFormSession(conversationId) ?? draft)
+ : draft;
+ const [form, setForm] = useState(() => buildInitialForm(initialDraft));
const [eventTestPayload, setEventTestPayload] = useState(() =>
buildDefaultEventTestPayload(DEFAULT_EVENT_SOURCE, DEFAULT_EVENT_KEY),
);
@@ -532,9 +664,19 @@ export function AutomationSetupPanel({
useState<CustomWebhookCreateResponse | null>(null);
const [fieldMetadata, setFieldMetadata] = useState(
- () => draft.fieldMetadata ?? {},
+ () => 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);
@@ -544,10 +686,14 @@ export function AutomationSetupPanel({
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);
@@ -558,13 +704,23 @@ export function AutomationSetupPanel({
Promise.resolve(),
);
const propTaggedServerDraftId =
- getAutomationDraftIdFromTags(conversationTags);
+ 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 streamQueueRef = useRef<
{
field: AutomationSetupField;
@@ -587,6 +743,10 @@ export function AutomationSetupPanel({
setCurrentTaggedServerDraftId(propTaggedServerDraftId);
}, [propTaggedServerDraftId]);
+ useEffect(() => {
+ setExistingCustomTarballPath(draft.existingCustomTarballPath ?? "");
+ }, [draft.existingCustomTarballPath]);
+
const updateConversationTags = useCallback(
async (
buildNextTags: (
@@ -625,6 +785,7 @@ export function AutomationSetupPanel({
useEffect(() => {
if (
!conversationId ||
+ isPendingAutomationSetupId(conversationId) ||
conversationTags === undefined ||
hasAutomationSetupModeTag(conversationTags)
) {
@@ -660,7 +821,7 @@ export function AutomationSetupPanel({
const updateConversationDraftTags = useCallback(
async (draftId: string | null) => {
- if (!conversationId) return;
+ if (!conversationId || isPendingAutomationSetupId(conversationId)) return;
await updateConversationTags((tags) =>
draftId
? buildAutomationDraftTags(tags, draftId)
@@ -671,6 +832,28 @@ export function AutomationSetupPanel({
[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 ?? "");
+ setForm(nextForm);
+ })
+ .catch((error: unknown) => {
+ if (!cancelled) {
+ displayErrorToast(error instanceof Error ? error.message : null);
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [conversationId, draft.form, editingAutomationId, isEditingExisting]);
+
useEffect(() => {
if (!taggedServerDraftId || serverDraft?.id === taggedServerDraftId) {
return undefined;
@@ -741,6 +924,9 @@ export function AutomationSetupPanel({
showTimeout,
timeoutSeconds,
} = form;
+ const hasExistingCustomBundle = Boolean(
+ isEditingExisting && kind === "custom" && existingCustomTarballPath.trim(),
+ );
useEffect(() => {
if (isEventTestPayloadDirty) return;
@@ -870,6 +1056,7 @@ export function AutomationSetupPanel({
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",
@@ -997,7 +1184,7 @@ export function AutomationSetupPanel({
? {
type: "event",
source: eventSource.trim() || DEFAULT_EVENT_SOURCE,
- on: eventKey.trim() || DEFAULT_EVENT_KEY,
+ on: eventKeyPayload(eventKey),
...(eventFilter.trim() ? { filter: eventFilter.trim() } : {}),
}
: {
@@ -1218,6 +1405,11 @@ export function AutomationSetupPanel({
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;
};
@@ -1254,7 +1446,7 @@ export function AutomationSetupPanel({
});
return false;
}
- if (kind === "custom" && !customCode.trim()) {
+ if (kind === "custom" && !hasExistingCustomBundle && !customCode.trim()) {
setStatusMessage({
kind: "error",
text: t(I18nKey.AUTOMATION_SETUP$CODE_REQUIRED),
@@ -1268,14 +1460,18 @@ export function AutomationSetupPanel({
});
return false;
}
- if (kind === "custom" && !setupScriptPath.trim()) {
+ if (
+ kind === "custom" &&
+ !hasExistingCustomBundle &&
+ !setupScriptPath.trim()
+ ) {
setStatusMessage({
kind: "error",
text: t(I18nKey.AUTOMATION_SETUP$SETUP_SCRIPT_PATH_REQUIRED),
});
return false;
}
- if (kind === "custom" && !setupScript.trim()) {
+ if (kind === "custom" && !hasExistingCustomBundle && !setupScript.trim()) {
setStatusMessage({
kind: "error",
text: t(I18nKey.AUTOMATION_SETUP$SETUP_SCRIPT_REQUIRED),
@@ -1291,29 +1487,21 @@ export function AutomationSetupPanel({
if (!(await ensureCustomWebhookSource())) return;
if (!draftsSupported) {
setSaveState("saved");
- setStatusMessage({
- kind: "success",
- text: t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED),
- });
+ setStatusMessage(null);
+ toast.success(t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED));
return;
}
const tarballPath =
kind === "custom" ? await uploadCustomArchive() : undefined;
- const saved = await persistServerDraft(tarballPath);
+ await persistServerDraft(tarballPath);
setSaveState("saved");
- setStatusMessage({
- kind: "success",
- text:
- saved.validationErrors?.[0]?.message ??
- t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED),
- });
+ setStatusMessage(null);
+ toast.success(t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED));
} catch (error) {
if (isDraftEndpointUnavailable(error)) {
setSaveState("saved");
- setStatusMessage({
- kind: "success",
- text: t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED),
- });
+ setStatusMessage(null);
+ toast.success(t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED));
return;
}
setSaveState("error");
@@ -1353,12 +1541,16 @@ export function AutomationSetupPanel({
setSaveState("saved");
if (!saved.dispatchable) {
- setStatusMessage({
- kind: "error",
- text:
- saved.validationErrors?.[0]?.message ??
- t(I18nKey.SETUP$SUBMIT_FAILED),
- });
+ // 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;
}
@@ -1473,6 +1665,11 @@ export function AutomationSetupPanel({
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);
}
@@ -1480,6 +1677,68 @@ export function AutomationSetupPanel({
return null;
};
+ /**
+ * Only fields accepted by the backend PATCH contract are sent when editing an
+ * existing automation. Repositories, plugins and uploaded code are create-time
+ * configuration today, so the edit form must not include them in PATCH.
+ */
+ const buildExistingAutomationBody = () => {
+ const body: Record<string, unknown> = {
+ name: normalizedName(),
+ trigger: buildTrigger(),
+ model: model.trim() || null,
+ agent_profile_id: agentProfileId.trim() || null,
+ timeout:
+ showTimeout && timeoutSeconds.trim() ? Number(timeoutSeconds) : null,
+ };
+ if (kind !== "custom") body.prompt = prompt.trim();
+ return body as Partial<Automation>;
+ };
+
+ const handleSaveExisting = async () => {
+ if (!validateRequiredFields()) return;
+ setIsSubmitting(true);
+ setSaveState("saving");
+ try {
+ if (!(await ensureCustomWebhookSource())) return;
+ await AutomationService.updateAutomation(
+ editingAutomationId,
+ buildExistingAutomationBody(),
+ );
+ setSaveState("saved");
+ toast.success(t(I18nKey.AUTOMATIONS$EDIT_SUCCESS));
+ } catch (error) {
+ setSaveState("error");
+ displayErrorToast(error instanceof Error ? error.message : null);
+ } 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(error instanceof Error ? error.message : null);
+ } 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 = () =>
@@ -1491,6 +1750,10 @@ export function AutomationSetupPanel({
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">
@@ -1502,38 +1765,79 @@ export function AutomationSetupPanel({
{saveStateText}
</span>
) : null}
- <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}
- aria-busy={isSubmitting}
- onClick={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>
+ {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>
);
@@ -1564,413 +1868,401 @@ export function AutomationSetupPanel({
)}
>
<div className="mx-auto flex w-full min-w-0 max-w-[800px] flex-col gap-6">
- <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}
+ {serverDraft && !isViewingDraftRuns ? (
+ <DraftStatusBar
+ draft={serverDraft}
+ runs={draftRuns}
+ isSubmitting={isSubmitting}
+ canTest={isEditingExisting || canTestDraft}
+ onTest={() => {
+ setIsViewingDraftRuns(true);
+ void (isEditingExisting
+ ? handleTestExisting()
+ : handleTest());
+ }}
+ onViewRuns={() => setIsViewingDraftRuns(true)}
/>
- </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>
+ {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>
- {serverDraft ? (
- <DraftRunDetailsCard draft={serverDraft} runs={draftRuns} />
- ) : null}
+ {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}
- <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"),
- )}
+ {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" ? (
- <FileText className="size-4" aria-hidden />
+ {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)
+ }
+ model={model}
+ onModelChange={(value) => updateField("model", value)}
+ agentProfileId={agentProfileId}
+ onAgentProfileChange={(value) =>
+ updateField("agentProfileId", value)
+ }
+ />
+ ) : hasExistingCustomBundle ? (
+ <ExistingCustomBundleSummary
+ tarballPath={existingCustomTarballPath}
+ />
) : (
- <Code2 className="size-4" aria-hidden />
+ <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)
+ }
+ />
)}
- {kind === "custom"
- ? t(I18nKey.AUTOMATIONS$PROMPT)
- : t(I18nKey.AUTOMATION_SETUP$TYPE_CUSTOM)}
- </button>
+ </SetupKindCrossfade>
</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)
- }
- model={model}
- onModelChange={(value) => updateField("model", value)}
- agentProfileId={agentProfileId}
- onAgentProfileChange={(value) =>
- updateField("agentProfileId", value)
- }
+
+ <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")}
/>
- ) : (
- <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)
- }
+ <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")}
/>
- )}
- </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")}
+ </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) => {
+ 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)
+ }
/>
- <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")}
+ ) : (
+ <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}
/>
- </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) => {
- 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}
- 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={
+ <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
- ? "automation-setup-plugin-source"
- : `automation-setup-plugin-source-${index}`
+ ? agentUpdatedSuffix("pluginSource")
+ : undefined
}
- value={entry.source}
- aria-label={
+ 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
- ? undefined
- : t(I18nKey.AUTOMATION_SETUP$PLUGIN_SOURCE)
+ ? agentUpdatedSuffix("pluginRef")
+ : undefined
}
- placeholder={t(
- I18nKey.AUTOMATION_SETUP$PLUGIN_SOURCE_PLACEHOLDER,
- )}
- onChange={(event) =>
- writePlugins(
- pluginEntries.map((plugin, entryIndex) =>
- entryIndex === index
- ? { ...plugin, source: event.target.value }
- : plugin,
- ),
- )
+ isStreaming={
+ index === 0 && streamingField === "pluginRef"
}
- 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,
+ )}
>
- <input
+ <button
+ type="button"
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,
- ),
- )
+ ? "automation-setup-plugin-remove"
+ : `automation-setup-plugin-remove-${index}`
}
- className={formControlFieldClassName}
- />
- </Field>
+ 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>
- <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"
@@ -1984,40 +2276,88 @@ export function AutomationSetupPanel({
>
{`${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)}
+ </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(
- addOptionButtonClassName,
+ formControlFieldClassName,
streamingHighlightClassName(
- streamingField === "showTimeout",
+ streamingField === "timeoutSeconds",
),
)}
- >
- {t(I18nKey.AUTOMATION_SETUP$ADD_TIMEOUT)}
- </button>
- ) : null}
- </div>
- ) : null}
- </section>
-
- {statusMessage && (
- <p
- role="status"
- data-testid="automation-setup-status"
- className={cn(
- "text-sm",
- statusMessage.kind === "success"
- ? "text-green-400"
- : "text-red-400",
- )}
- >
- {statusMessage.text}
- </p>
- )}
+ />
+ </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>
@@ -2069,6 +2409,41 @@ function SetupKindCrossfade({
);
}
+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;
@@ -2552,10 +2927,12 @@ function EventSourceControl({
value,
options,
onChange,
+ onSelectCustom,
}: {
value: string;
options: string[];
onChange: (value: string) => void;
+ onSelectCustom: () => void;
}) {
const { t } = useTranslation("openhands");
const knownSources = knownEventSources(options);
@@ -2573,6 +2950,9 @@ function EventSourceControl({
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))
}
@@ -2624,9 +3004,9 @@ function EventSourceControl({
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
+ onSelectCustom();
setIsMenuOpen(false);
- inputRef.current?.focus();
- inputRef.current?.select();
+ queueMicrotask(() => inputRef.current?.focus());
}}
className="flex w-full items-center"
>
@@ -2650,6 +3030,7 @@ function EventFields({
eventTypeOptions,
customWebhook,
customWebhookRegistration,
+ usesExistingAutomationTestPayload,
updatedSuffixes,
streamingField,
setEventSource,
@@ -2666,6 +3047,7 @@ function EventFields({
eventTypeOptions: string[];
customWebhook: CustomWebhookFormState;
customWebhookRegistration: CustomWebhookCreateResponse | null;
+ usesExistingAutomationTestPayload: boolean;
updatedSuffixes: Partial<
Record<"eventSource" | "eventKey" | "eventFilter", string | undefined>
>;
@@ -2689,6 +3071,22 @@ function EventFields({
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">
@@ -2701,7 +3099,8 @@ function EventFields({
<EventSourceControl
value={eventSource}
options={eventSourceOptions}
- onChange={setEventSource}
+ onChange={handleEventSourceChange}
+ onSelectCustom={selectCustomEventSource}
/>
</Field>
<p
@@ -2989,45 +3388,60 @@ function EventFields({
</div>
) : null}
<div className="@min-[640px]:col-span-2">
- <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"
+ {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)]"
>
- <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}
+ <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>
diff --git a/src/components/features/automations/setup/automation-setup-prompt-stack.tsx b/src/components/features/automations/setup/automation-setup-prompt-stack.tsx
index 50b24f288b..0c63c2b64a 100644
--- a/src/components/features/automations/setup/automation-setup-prompt-stack.tsx
+++ b/src/components/features/automations/setup/automation-setup-prompt-stack.tsx
@@ -476,11 +476,11 @@ export function AutomationSetupPromptStack({
className="min-h-[120px] w-full resize-none border-0 bg-transparent p-0 text-sm text-content outline-none placeholder:text-tertiary-alt"
/>
<div className="flex min-w-0 items-center gap-2 pt-2">
- <SetupModelPill value={model} onChange={onModelChange} />
<SetupAgentProfilePill
value={agentProfileId}
onChange={onAgentProfileChange}
/>
+ <SetupModelPill value={model} onChange={onModelChange} />
</div>
<div
data-testid="automation-setup-prompt-grip"
diff --git a/src/components/features/conversation/conversation-overview-automations-panel.tsx b/src/components/features/conversation/conversation-overview-automations-panel.tsx
index 1690c4b622..a4f80b757a 100644
--- a/src/components/features/conversation/conversation-overview-automations-panel.tsx
+++ b/src/components/features/conversation/conversation-overview-automations-panel.tsx
@@ -1,15 +1,29 @@
-import { useEffect, useState } from "react";
+import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { AutomationCardSkeleton } from "#/components/features/automations/automation-card-skeleton";
import { AutomationGroup } from "#/components/features/automations/automation-group";
-import { AddAutomationModal } from "#/components/features/automations/add-automation-modal";
import { BackendNotConfigured } from "#/components/features/automations/backend-not-configured";
import { EmptyState } from "#/components/features/automations/empty-state";
import { ErrorState } from "#/components/features/automations/error-state";
import { useAutomations } from "#/hooks/query/use-automations";
import { useAutomationHealth } from "#/hooks/query/use-automation-health";
+import { useStartAutomationSetup } from "#/hooks/use-start-automation-setup";
import { I18nKey } from "#/i18n/declaration";
+/** Opens the setup page once when the drawer asks to add an automation. */
+function LaunchAutomationSetup() {
+ const { startSetup } = useStartAutomationSetup();
+ const launched = useRef(false);
+
+ useEffect(() => {
+ if (launched.current) return;
+ launched.current = true;
+ startSetup();
+ }, [startSetup]);
+
+ return null;
+}
+
interface ConversationOverviewAutomationsPanelProps {
openAdd: boolean;
}
@@ -21,7 +35,6 @@ export function ConversationOverviewAutomationsPanel({
openAdd,
}: ConversationOverviewAutomationsPanelProps) {
const { t } = useTranslation("openhands");
- const [isAddModalOpen, setIsAddModalOpen] = useState(openAdd);
const {
data: health,
isLoading: isHealthLoading,
@@ -31,10 +44,6 @@ export function ConversationOverviewAutomationsPanel({
enabled: health?.status === "ok",
});
- useEffect(() => {
- if (openAdd) setIsAddModalOpen(true);
- }, [openAdd]);
-
// Every state renders inside the same panel container so the drawer's
// DOM contract (one `conversation-overview-automations-panel` node) holds
// regardless of backend health or list contents.
@@ -49,10 +58,7 @@ export function ConversationOverviewAutomationsPanel({
body = (
<>
<EmptyState />
- <AddAutomationModal
- isOpen={isAddModalOpen}
- onClose={() => setIsAddModalOpen(false)}
- />
+ {openAdd ? <LaunchAutomationSetup /> : null}
</>
);
} else {
@@ -68,10 +74,7 @@ export function ConversationOverviewAutomationsPanel({
onDelete={NOOP}
onExport={NOOP}
/>
- <AddAutomationModal
- isOpen={isAddModalOpen}
- onClose={() => setIsAddModalOpen(false)}
- />
+ {openAdd ? <LaunchAutomationSetup /> : null}
</>
);
}
diff --git a/src/components/features/home/featured-automations/pinned-automation-card.tsx b/src/components/features/home/featured-automations/pinned-automation-card.tsx
index 16c4745114..d4a273ed4e 100644
--- a/src/components/features/home/featured-automations/pinned-automation-card.tsx
+++ b/src/components/features/home/featured-automations/pinned-automation-card.tsx
@@ -3,7 +3,6 @@ import { ExternalLink } from "lucide-react";
import { useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import { buildAutomationMetadataPills } from "#/components/features/automations/build-automation-pills";
-import { EditAutomationModal } from "#/components/features/automations/detail/edit-automation-modal";
import {
RunPhase,
shouldShowRunPhase,
@@ -358,14 +357,6 @@ export function PinnedAutomationCard({
</div>
) : null}
- {actions.editOpen ? (
- <EditAutomationModal
- automation={automation}
- isOpen={actions.editOpen}
- onClose={() => actions.setEditOpen(false)}
- />
- ) : null}
-
<TurnOffConfirmationModal
automationName={automation.name}
isOpen={actions.turnOffConfirmOpen}
diff --git a/src/components/features/home/featured-automations/running-automations-list.tsx b/src/components/features/home/featured-automations/running-automations-list.tsx
index 657ae8bbad..d5f20d37ef 100644
--- a/src/components/features/home/featured-automations/running-automations-list.tsx
+++ b/src/components/features/home/featured-automations/running-automations-list.tsx
@@ -2,7 +2,6 @@ import { Tooltip } from "@heroui/react";
import { Plus, Zap } from "lucide-react";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
-import { EditAutomationModal } from "#/components/features/automations/detail/edit-automation-modal";
import { RunStatusBadge } from "#/components/features/automations/detail/run-status-badge";
import { TurnOffConfirmationModal } from "#/components/features/automations/turn-off-confirmation-modal";
import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";
@@ -185,14 +184,6 @@ function RunningAutomationRow({
/>
</div>
- {actions.editOpen ? (
- <EditAutomationModal
- automation={automation}
- isOpen={actions.editOpen}
- onClose={() => actions.setEditOpen(false)}
- />
- ) : null}
-
<TurnOffConfirmationModal
automationName={automation.name}
isOpen={actions.turnOffConfirmOpen}
diff --git a/src/hooks/use-create-automation-setup-conversation.ts b/src/hooks/use-create-automation-setup-conversation.ts
new file mode 100644
index 0000000000..b710de8532
--- /dev/null
+++ b/src/hooks/use-create-automation-setup-conversation.ts
@@ -0,0 +1,63 @@
+import { useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";
+import { I18nKey } from "#/i18n/declaration";
+import { getApiErrorMessage } from "#/utils/api-error-message";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+
+interface AutomationSetupConversation {
+ conversation_id: string;
+}
+
+interface StartAutomationSetupConversationOptions {
+ query: string;
+ entryPoint: "automations_add" | "automation_edit" | "automation_draft_resume";
+ automationSetupTags?: Record<string, string>;
+ onSuccess: (
+ conversation: AutomationSetupConversation,
+ ) => void | Promise<void>;
+ onSettled?: () => void;
+}
+
+export function useCreateAutomationSetupConversation() {
+ const { t } = useTranslation("openhands");
+ const createConversation = useCreateConversation();
+
+ const startAutomationSetupConversation = useCallback(
+ ({
+ query,
+ entryPoint,
+ automationSetupTags,
+ onSuccess,
+ onSettled,
+ }: StartAutomationSetupConversationOptions) => {
+ const text = query.trim();
+ if (!text || createConversation.isPending) return false;
+
+ createConversation.mutate(
+ {
+ query: text,
+ automationSetup: true,
+ ...(automationSetupTags ? { automationSetupTags } : {}),
+ entryPoint,
+ },
+ {
+ onSuccess,
+ onError: (error) => {
+ displayErrorToast(
+ getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)),
+ );
+ },
+ onSettled,
+ },
+ );
+ return true;
+ },
+ [createConversation, t],
+ );
+
+ return {
+ startAutomationSetupConversation,
+ isPending: createConversation.isPending,
+ };
+}
diff --git a/src/hooks/use-home-automation-actions.ts b/src/hooks/use-home-automation-actions.ts
index 06e8455dab..567f24b71e 100644
--- a/src/hooks/use-home-automation-actions.ts
+++ b/src/hooks/use-home-automation-actions.ts
@@ -1,4 +1,5 @@
import { useCallback, useState } from "react";
+import { useOpenAutomationEditor } from "#/hooks/use-open-automation-editor";
import { useTranslation } from "react-i18next";
import { useNavigation } from "#/context/navigation-context";
import {
@@ -54,7 +55,7 @@ export function useHomeAutomationActions(
const toggleMutation = useToggleAutomation({ disableToast: true });
const cancelMutation = useCancelAutomationRun();
- const [editOpen, setEditOpen] = useState(false);
+ const { openEditor } = useOpenAutomationEditor();
const [turnOffConfirmOpen, setTurnOffConfirmOpen] = useState(false);
const isRunPending =
@@ -86,8 +87,8 @@ export function useHomeAutomationActions(
}, [automation.id, navigate]);
const openEdit = useCallback(() => {
- setEditOpen(true);
- }, []);
+ openEditor(automation);
+ }, [automation, openEditor]);
const requestTurnOff = useCallback(() => {
setTurnOffConfirmOpen(true);
@@ -138,8 +139,6 @@ export function useHomeAutomationActions(
isRunPending,
isCancelPending,
canCancel,
- editOpen,
- setEditOpen,
turnOffConfirmOpen,
runNow,
viewDetails,
diff --git a/src/hooks/use-open-automation-editor.ts b/src/hooks/use-open-automation-editor.ts
new file mode 100644
index 0000000000..0f26fd5138
--- /dev/null
+++ b/src/hooks/use-open-automation-editor.ts
@@ -0,0 +1,33 @@
+import { useCallback } from "react";
+import {
+ PENDING_AUTOMATION_SETUP_ID,
+ initializeAutomationFormSession,
+} from "#/api/automation-form-session";
+import { useNavigation } from "#/context/navigation-context";
+import type { Automation } from "#/types/automation";
+import { setupDraftFromAutomation } from "#/utils/automation-edit-draft";
+
+/**
+ * Open an existing automation in the setup page.
+ *
+ * Edit reuses the collapsed setup form before any conversation exists. The
+ * agent conversation starts only if the user sends a prompt from that form.
+ */
+export function useOpenAutomationEditor() {
+ const { navigate } = useNavigation();
+
+ const openEditor = useCallback(
+ (automation: Automation) => {
+ initializeAutomationFormSession(
+ PENDING_AUTOMATION_SETUP_ID,
+ setupDraftFromAutomation(automation),
+ );
+ navigate?.(
+ `/automations/setup?automationId=${encodeURIComponent(automation.id)}`,
+ );
+ },
+ [navigate],
+ );
+
+ return { openEditor };
+}
diff --git a/src/hooks/use-start-automation-setup.ts b/src/hooks/use-start-automation-setup.ts
new file mode 100644
index 0000000000..7c593e70d1
--- /dev/null
+++ b/src/hooks/use-start-automation-setup.ts
@@ -0,0 +1,85 @@
+import { useCallback } from "react";
+import {
+ PENDING_AUTOMATION_SETUP_ID,
+ clearAutomationFormSession,
+ getAutomationFormSession,
+ initializeAutomationFormSession,
+} from "#/api/automation-form-session";
+import { markAutomationSetupHandoff } from "#/api/automation-setup-handoff-store";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { useNavigation } from "#/context/navigation-context";
+import { useCreateAutomationSetupConversation } from "#/hooks/use-create-automation-setup-conversation";
+import { useTracking } from "#/hooks/use-tracking";
+import {
+ buildAutomationDraftTags,
+ buildAutomationEditTags,
+} from "#/utils/automation-draft-tags";
+
+/**
+ * Open a new automation on the setup form.
+ *
+ * The automations page used to create an agent conversation immediately.
+ * The form now opens with the conversation drawer hidden, and a conversation
+ * starts only after the user sends a prompt.
+ */
+export function useStartAutomationSetup() {
+ const active = useActiveBackend();
+ const { navigate } = useNavigation();
+ const { startAutomationSetupConversation, isPending } =
+ useCreateAutomationSetupConversation();
+ const { trackAutomationCreatedButton } = useTracking();
+
+ const startSetup = useCallback(() => {
+ trackAutomationCreatedButton({ backendKind: active.backend.kind });
+ clearAutomationFormSession(PENDING_AUTOMATION_SETUP_ID);
+ navigate?.("/automations/setup");
+ }, [active.backend.kind, navigate, trackAutomationCreatedButton]);
+
+ const startConversationFromPrompt = useCallback(
+ (prompt: string) => {
+ const draft = getAutomationFormSession(PENDING_AUTOMATION_SETUP_ID) ?? {
+ prompt: "",
+ kind: "prompt" as const,
+ };
+ const editingAutomationId = draft.editingAutomationId?.trim() || null;
+ let entryPoint:
+ | "automations_add"
+ | "automation_edit"
+ | "automation_draft_resume" = "automations_add";
+ let automationSetupTags: Record<string, string> | undefined;
+ if (editingAutomationId) {
+ entryPoint = "automation_edit";
+ automationSetupTags = buildAutomationEditTags(
+ null,
+ editingAutomationId,
+ );
+ } else if (draft.serverDraftId) {
+ entryPoint = "automation_draft_resume";
+ automationSetupTags = buildAutomationDraftTags(
+ null,
+ draft.serverDraftId,
+ draft.materializedAutomationId,
+ );
+ }
+ startAutomationSetupConversation({
+ query: prompt,
+ entryPoint,
+ automationSetupTags,
+ onSuccess: (conversation) => {
+ const conversationId = conversation.conversation_id;
+ initializeAutomationFormSession(conversationId, draft);
+ markAutomationSetupHandoff(conversationId);
+ clearAutomationFormSession(PENDING_AUTOMATION_SETUP_ID);
+ navigate?.(`/conversations/${conversationId}`);
+ },
+ });
+ },
+ [navigate, startAutomationSetupConversation],
+ );
+
+ return {
+ startSetup,
+ startConversationFromPrompt,
+ isPending,
+ };
+}
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index c5fe3d8ead..fa694508f4 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -46086,6 +46086,23 @@
"zh-CN": "Event source",
"zh-TW": "Event source"
},
+ "AUTOMATION_SETUP$EVENT_SOURCE_CUSTOM_PLACEHOLDER": {
+ "ar": "مثال: pagerduty",
+ "ca": "p. ex. pagerduty",
+ "de": "z. B. pagerduty",
+ "en": "e.g. pagerduty",
+ "es": "p. ej. pagerduty",
+ "fr": "p. ex. pagerduty",
+ "it": "es. pagerduty",
+ "ja": "例: pagerduty",
+ "ko-KR": "예: pagerduty",
+ "no": "f.eks. pagerduty",
+ "pt": "ex.: pagerduty",
+ "tr": "örn. pagerduty",
+ "uk": "напр. pagerduty",
+ "zh-CN": "例如 pagerduty",
+ "zh-TW": "例如 pagerduty"
+ },
"AUTOMATION_SETUP$EVENT_KEY": {
"ar": "Event key",
"ca": "Event key",
@@ -46596,6 +46613,40 @@
"zh-CN": "Custom Python",
"zh-TW": "Custom Python"
},
+ "AUTOMATION_SETUP$EXISTING_BUNDLE": {
+ "ar": "Existing code bundle",
+ "ca": "Existing code bundle",
+ "de": "Vorhandenes Code-Bundle",
+ "en": "Existing code bundle",
+ "es": "Paquete de código existente",
+ "fr": "Bundle de code existant",
+ "it": "Existing code bundle",
+ "ja": "既存のコードバンドル",
+ "ko-KR": "Existing code bundle",
+ "no": "Existing code bundle",
+ "pt": "Existing code bundle",
+ "tr": "Existing code bundle",
+ "uk": "Existing code bundle",
+ "zh-CN": "现有代码包",
+ "zh-TW": "現有程式碼套件"
+ },
+ "AUTOMATION_SETUP$EXISTING_BUNDLE_HELP": {
+ "ar": "This automation uses an existing bundle. To edit the code, ask the agent to download the tarball, make changes, and update the automation bundle.",
+ "ca": "This automation uses an existing bundle. To edit the code, ask the agent to download the tarball, make changes, and update the automation bundle.",
+ "de": "Diese Automation verwendet ein vorhandenes Bundle. Um den Code zu bearbeiten, bitten Sie den Agenten, den Tarball herunterzuladen, Änderungen vorzunehmen und das Automation-Bundle zu aktualisieren.",
+ "en": "This automation uses an existing bundle. To edit the code, ask the agent to download the tarball, make changes, and update the automation bundle.",
+ "es": "Esta automatización usa un paquete existente. Para editar el código, pide al agente que descargue el tarball, haga cambios y actualice el paquete de automatización.",
+ "fr": "Cette automatisation utilise un bundle existant. Pour modifier le code, demandez à l’agent de télécharger le tarball, d’apporter les changements et de mettre à jour le bundle d’automatisation.",
+ "it": "This automation uses an existing bundle. To edit the code, ask the agent to download the tarball, make changes, and update the automation bundle.",
+ "ja": "このオートメーションは既存のバンドルを使用します。コードを編集するには、エージェントに tarball をダウンロードして変更し、オートメーションバンドルを更新するよう依頼してください。",
+ "ko-KR": "This automation uses an existing bundle. To edit the code, ask the agent to download the tarball, make changes, and update the automation bundle.",
+ "no": "This automation uses an existing bundle. To edit the code, ask the agent to download the tarball, make changes, and update the automation bundle.",
+ "pt": "This automation uses an existing bundle. To edit the code, ask the agent to download the tarball, make changes, and update the automation bundle.",
+ "tr": "This automation uses an existing bundle. To edit the code, ask the agent to download the tarball, make changes, and update the automation bundle.",
+ "uk": "This automation uses an existing bundle. To edit the code, ask the agent to download the tarball, make changes, and update the automation bundle.",
+ "zh-CN": "此自动化使用现有代码包。若要编辑代码,请让代理下载 tarball、进行修改并更新自动化代码包。",
+ "zh-TW": "此自動化使用現有程式碼套件。若要編輯程式碼,請讓代理下載 tarball、進行修改並更新自動化程式碼套件。"
+ },
"AUTOMATION_SETUP$FILLED_BY_OPENHANDS": {
"en": "✦ Filled by OpenHands",
"ja": "✦ OpenHands が入力",
@@ -46698,6 +46749,40 @@
"zh-CN": "测试运行",
"zh-TW": "測試執行"
},
+ "AUTOMATION_SETUP$TEST_RUNS_EMPTY_DESCRIPTION": {
+ "ar": "شغّل اختبارًا لعرض النتائج هنا.",
+ "ca": "Executa una prova per veure els resultats aquí.",
+ "de": "Führen Sie einen Test aus, um die Ergebnisse hier zu sehen.",
+ "en": "Run a test to see results here.",
+ "es": "Ejecuta una prueba para ver los resultados aquí.",
+ "fr": "Lancez un test pour voir les résultats ici.",
+ "it": "Esegui un test per vedere i risultati qui.",
+ "ja": "テストを実行すると、結果がここに表示されます。",
+ "ko-KR": "테스트를 실행하면 결과가 여기에 표시됩니다.",
+ "no": "Kjør en test for å se resultatene her.",
+ "pt": "Execute um teste para ver os resultados aqui.",
+ "tr": "Sonuçları burada görmek için bir test çalıştırın.",
+ "uk": "Запустіть тест, щоб побачити результати тут.",
+ "zh-CN": "运行测试后,结果会显示在这里。",
+ "zh-TW": "執行測試後,結果會顯示在這裡。"
+ },
+ "AUTOMATION_SETUP$VIEW_TEST_RUNS": {
+ "ar": "عرض عمليات الاختبار",
+ "ca": "Mostra les execucions de prova",
+ "de": "Testläufe anzeigen",
+ "en": "View test runs",
+ "es": "Ver ejecuciones de prueba",
+ "fr": "Voir les exécutions de test",
+ "it": "Vedi esecuzioni di test",
+ "ja": "テスト実行を表示",
+ "ko-KR": "테스트 실행 보기",
+ "no": "Vis testkjøringer",
+ "pt": "Ver execuções de teste",
+ "tr": "Test çalıştırmalarını görüntüle",
+ "uk": "Переглянути тестові запуски",
+ "zh-CN": "查看测试运行",
+ "zh-TW": "查看測試執行"
+ },
"AUTOMATION_SETUP$TEST_DISPATCHED": {
"ar": "Test run started.",
"ca": "Test run started.",
@@ -47293,6 +47378,23 @@
"tr": "Bu olay otomasyonunu test etmeden önce geçerli bir JSON nesnesi girin.",
"uk": "Введіть дійсний JSON-об’єкт перед тестуванням цієї автоматизації події."
},
+ "AUTOMATION_SETUP$EXISTING_TEST_PAYLOAD_NOTICE": {
+ "en": "Existing automation tests use the backend’s default synthetic event payload. To test a custom payload, create or edit through a draft first. Support for testing existing automations with custom payloads is coming soon.",
+ "ja": "既存のオートメーションのテストでは、バックエンドのデフォルトの合成イベントペイロードが使用されます。カスタムペイロードをテストするには、まずドラフトで作成または編集してください。既存のオートメーションをカスタムペイロードでテストするサポートは近日対応予定です。",
+ "zh-CN": "现有自动化测试使用后端的默认合成事件载荷。若要测试自定义载荷,请先通过草稿创建或编辑。即将支持使用自定义载荷测试现有自动化。",
+ "zh-TW": "現有自動化測試會使用後端的預設合成事件酬載。若要測試自訂酬載,請先透過草稿建立或編輯。即將支援使用自訂酬載測試現有自動化。",
+ "ko-KR": "Existing automation tests use the backend’s default synthetic event payload. To test a custom payload, create or edit through a draft first. Support for testing existing automations with custom payloads is coming soon.",
+ "no": "Existing automation tests use the backend’s default synthetic event payload. To test a custom payload, create or edit through a draft first. Support for testing existing automations with custom payloads is coming soon.",
+ "ar": "Existing automation tests use the backend’s default synthetic event payload. To test a custom payload, create or edit through a draft first. Support for testing existing automations with custom payloads is coming soon.",
+ "de": "Tests bestehender Automationen verwenden die standardmäßige synthetische Ereignisnutzlast des Backends. Um eine benutzerdefinierte Nutzlast zu testen, erstellen oder bearbeiten Sie zuerst über einen Entwurf. Unterstützung für Tests bestehender Automationen mit benutzerdefinierten Nutzlasten folgt in Kürze.",
+ "fr": "Les tests des automatisations existantes utilisent la charge utile d’événement synthétique par défaut du backend. Pour tester une charge utile personnalisée, créez ou modifiez d’abord via un brouillon. La prise en charge du test des automatisations existantes avec des charges utiles personnalisées arrive bientôt.",
+ "it": "Existing automation tests use the backend’s default synthetic event payload. To test a custom payload, create or edit through a draft first. Support for testing existing automations with custom payloads is coming soon.",
+ "pt": "Existing automation tests use the backend’s default synthetic event payload. To test a custom payload, create or edit through a draft first. Support for testing existing automations with custom payloads is coming soon.",
+ "es": "Las pruebas de automatizaciones existentes usan la carga útil de evento sintética predeterminada del backend. Para probar una carga personalizada, crea o edita primero mediante un borrador. La compatibilidad para probar automatizaciones existentes con cargas personalizadas llegará pronto.",
+ "ca": "Existing automation tests use the backend’s default synthetic event payload. To test a custom payload, create or edit through a draft first. Support for testing existing automations with custom payloads is coming soon.",
+ "tr": "Existing automation tests use the backend’s default synthetic event payload. To test a custom payload, create or edit through a draft first. Support for testing existing automations with custom payloads is coming soon.",
+ "uk": "Existing automation tests use the backend’s default synthetic event payload. To test a custom payload, create or edit through a draft first. Support for testing existing automations with custom payloads is coming soon."
+ },
"AUTOMATION_SETUP$CUSTOM_WEBHOOK_TITLE": {
"en": "Register this as a custom webhook source",
"ja": "カスタム Webhook ソースとして登録",
diff --git a/src/routes.ts b/src/routes.ts
index 05a28dee45..4e50cac7ef 100644
--- a/src/routes.ts
+++ b/src/routes.ts
@@ -38,6 +38,7 @@ export default [
route("automations/git-sync", "routes/automation-git-sync.tsx"),
route("automations/templates", "routes/automation-templates.tsx"),
route("automations/new/:automationId", "routes/automation-setup-route.tsx"),
+ route("automations/setup", "routes/automation-setup-new.tsx"),
route("automations/:automationId", "routes/automation-detail.tsx"),
// Unknown URLs (including /settings/<x>) render inside the app shell.
route("*", "routes/not-found.tsx"),
diff --git a/src/routes/automation-detail.tsx b/src/routes/automation-detail.tsx
index 0b3550b201..7cbd279f60 100644
--- a/src/routes/automation-detail.tsx
+++ b/src/routes/automation-detail.tsx
@@ -36,7 +36,7 @@ import { NotFoundState } from "#/components/features/automations/detail/not-foun
import { ErrorState } from "#/components/features/automations/error-state";
import { BackendNotConfigured } from "#/components/features/automations/backend-not-configured";
import { DeleteConfirmationModal } from "#/components/features/automations/delete-confirmation-modal";
-import { EditAutomationModal } from "#/components/features/automations/detail/edit-automation-modal";
+import { useOpenAutomationEditor } from "#/hooks/use-open-automation-editor";
import { useTracking } from "#/hooks/use-tracking";
import {
useAutomationPermissions,
@@ -85,7 +85,7 @@ export default function AutomationDetail() {
const highlightedRunId = searchParams.get("run");
const { navigate } = useNavigation();
const [showDeleteModal, setShowDeleteModal] = useState(false);
- const [showEditModal, setShowEditModal] = useState(false);
+ const { openEditor } = useOpenAutomationEditor();
const {
data: healthData,
@@ -249,7 +249,7 @@ export default function AutomationDetail() {
<DetailHeader
automation={automation}
onToggle={handleToggle}
- onEdit={() => setShowEditModal(true)}
+ onEdit={() => openEditor(automation)}
onDelete={() => setShowDeleteModal(true)}
onExport={handleExport}
onDownloadTarball={() =>
@@ -284,13 +284,6 @@ export default function AutomationDetail() {
onConfirm={handleDelete}
onCancel={() => setShowDeleteModal(false)}
/>
- {showEditModal && (
- <EditAutomationModal
- automation={automation}
- isOpen={showEditModal}
- onClose={() => setShowEditModal(false)}
- />
- )}
</div>
</div>
</div>
diff --git a/src/routes/automation-setup-new.tsx b/src/routes/automation-setup-new.tsx
new file mode 100644
index 0000000000..eb4de48133
--- /dev/null
+++ b/src/routes/automation-setup-new.tsx
@@ -0,0 +1,165 @@
+import { useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+import { useTranslation } from "react-i18next";
+import { useSearchParams } from "react-router";
+import AutomationService from "#/api/automation-service/automation-service.api";
+import {
+ PENDING_AUTOMATION_SETUP_ID,
+ getAutomationFormSession,
+ initializeAutomationFormSession,
+ subscribeAutomationFormSession,
+} from "#/api/automation-form-session";
+import type { AutomationSetupDraft } from "#/api/automation-setup-types";
+import { setupDraftFromServerDraft } from "#/components/features/automations/setup/automation-setup-draft-service";
+import { AutomationSetupPanel } from "#/components/features/automations/setup/automation-setup-panel";
+import { InteractiveChatBox } from "#/components/features/chat/interactive-chat-box";
+import { ComposerDockedProvider } from "#/context/composer-docked-context";
+import { useStartAutomationSetup } from "#/hooks/use-start-automation-setup";
+import { I18nKey } from "#/i18n/declaration";
+import { buildAutomationDraftTags } from "#/utils/automation-draft-tags";
+import { setupDraftFromAutomation } from "#/utils/automation-edit-draft";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+
+const BLANK_DRAFT: AutomationSetupDraft = { prompt: "", kind: "prompt" };
+
+/**
+ * New automation form before any conversation exists.
+ *
+ * The agent drawer stays hidden. Sending the docked prompt is what creates
+ * the conversation and reveals the agent.
+ */
+export default function AutomationSetupNew() {
+ const { t } = useTranslation("openhands");
+ const [searchParams] = useSearchParams();
+ const automationId = searchParams.get("automationId")?.trim() ?? "";
+ const draftId = searchParams.get("draftId")?.trim() ?? "";
+ const { startConversationFromPrompt, isPending } = useStartAutomationSetup();
+ const [toolbarElement, setToolbarElement] = useState<HTMLDivElement | null>(
+ null,
+ );
+ const [composerTarget, setComposerTarget] = useState<HTMLDivElement | null>(
+ null,
+ );
+ const [draft, setDraft] = useState<AutomationSetupDraft | null>(() => {
+ const existing = getAutomationFormSession(PENDING_AUTOMATION_SETUP_ID);
+ return existing ?? (automationId || draftId ? null : BLANK_DRAFT);
+ });
+
+ useEffect(
+ () =>
+ subscribeAutomationFormSession(PENDING_AUTOMATION_SETUP_ID, (next) => {
+ setDraft(next ?? (automationId || draftId ? null : BLANK_DRAFT));
+ }),
+ [automationId, draftId],
+ );
+
+ useEffect(() => {
+ const existing = getAutomationFormSession(PENDING_AUTOMATION_SETUP_ID);
+ if (existing) {
+ setDraft(existing);
+ return undefined;
+ }
+
+ let cancelled = false;
+ const loadDraft = async () => {
+ try {
+ if (automationId) {
+ const automation =
+ await AutomationService.getAutomation(automationId);
+ const next = setupDraftFromAutomation(automation);
+ initializeAutomationFormSession(PENDING_AUTOMATION_SETUP_ID, next);
+ if (!cancelled) setDraft(next);
+ return;
+ }
+ if (draftId) {
+ const savedDraft = await AutomationService.getServerDraft(draftId);
+ const next = setupDraftFromServerDraft(savedDraft);
+ initializeAutomationFormSession(PENDING_AUTOMATION_SETUP_ID, next);
+ if (!cancelled) setDraft(next);
+ return;
+ }
+ if (!cancelled) setDraft(BLANK_DRAFT);
+ } catch (error) {
+ if (!cancelled) {
+ displayErrorToast(error instanceof Error ? error.message : null);
+ setDraft(BLANK_DRAFT);
+ }
+ }
+ };
+
+ void loadDraft();
+ return () => {
+ cancelled = true;
+ };
+ }, [automationId, draftId]);
+
+ const title = draft?.form?.name?.trim() || t(I18nKey.AUTOMATION_SETUP$TITLE);
+ const conversationTags = draft?.serverDraftId
+ ? buildAutomationDraftTags(
+ null,
+ draft.serverDraftId,
+ draft.materializedAutomationId,
+ )
+ : null;
+
+ return (
+ <div className="flex h-full min-h-0 flex-col overflow-hidden bg-base">
+ <header
+ data-testid="automation-setup-topbar"
+ className="flex h-10 min-h-10 shrink-0 items-center justify-between gap-2 border-b border-[var(--oh-border)] bg-base px-3"
+ >
+ <h2 className="min-w-0 truncate text-sm font-medium text-content">
+ {title}
+ </h2>
+ <div
+ ref={setToolbarElement}
+ data-testid="automation-setup-toolbar"
+ className="flex min-w-0 shrink-0 items-center gap-1.5"
+ />
+ </header>
+ <div className="relative flex min-h-0 flex-1 flex-col overflow-hidden">
+ {draft ? (
+ <AutomationSetupPanel
+ draft={draft}
+ conversationId={PENDING_AUTOMATION_SETUP_ID}
+ conversationTags={conversationTags}
+ toolbarPortal={toolbarElement}
+ showInlineHeader={false}
+ reserveComposerSpace
+ />
+ ) : (
+ <div
+ role="status"
+ className="flex flex-1 items-center justify-center text-sm text-[var(--oh-muted)]"
+ >
+ {t(I18nKey.AUTOMATION_SETUP$LOADING_DRAFT)}
+ </div>
+ )}
+ <div className="custom-scrollbar-always pointer-events-none absolute inset-0 z-20 overflow-y-scroll px-5 [scrollbar-gutter:stable] [&::-webkit-scrollbar-thumb]:bg-transparent">
+ <div className="relative mx-auto h-full w-full min-w-0 max-w-[800px]">
+ <div
+ ref={setComposerTarget}
+ data-testid="automation-setup-docked-composer"
+ className="pointer-events-auto absolute inset-x-0 bottom-5 overflow-visible rounded-[15px] shadow-[0_12px_40px_rgba(0,0,0,0.55)]"
+ />
+ </div>
+ </div>
+ {composerTarget
+ ? createPortal(
+ <ComposerDockedProvider enabled minimal>
+ <InteractiveChatBox
+ onSubmit={(content) => startConversationFromPrompt(content)}
+ disabled={isPending || !draft}
+ showGitControlBar={false}
+ placeholder={t(
+ I18nKey.AUTOMATION_SETUP$DOCKED_COMPOSER_PLACEHOLDER,
+ )}
+ />
+ </ComposerDockedProvider>,
+ composerTarget,
+ )
+ : null}
+ </div>
+ </div>
+ );
+}
diff --git a/src/routes/automations-list.tsx b/src/routes/automations-list.tsx
index 80e4b2a964..7e1833c7e7 100644
--- a/src/routes/automations-list.tsx
+++ b/src/routes/automations-list.tsx
@@ -1,5 +1,5 @@
import { useState, useMemo, useCallback, type ReactNode } from "react";
-import { RefreshCw, Trash2 } from "lucide-react";
+import { Pencil, RefreshCw, Trash2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
import { I18nKey } from "#/i18n/declaration";
@@ -20,6 +20,10 @@ import {
useImportAutomation,
} from "#/hooks/query/use-automations";
import { useAutomationHealth } from "#/hooks/query/use-automation-health";
+import {
+ PENDING_AUTOMATION_SETUP_ID,
+ initializeAutomationFormSession,
+} from "#/api/automation-form-session";
import type { AutomationSetupKind } from "#/api/automation-setup-types";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { useNavigation } from "#/context/navigation-context";
@@ -38,9 +42,9 @@ import { EmptyState } from "#/components/features/automations/empty-state";
import { ErrorState } from "#/components/features/automations/error-state";
import { BackendNotConfigured } from "#/components/features/automations/backend-not-configured";
import { DeleteConfirmationModal } from "#/components/features/automations/delete-confirmation-modal";
-import { EditAutomationModal } from "#/components/features/automations/detail/edit-automation-modal";
+import { useOpenAutomationEditor } from "#/hooks/use-open-automation-editor";
+import { useStartAutomationSetup } from "#/hooks/use-start-automation-setup";
import { AddAutomationMenu } from "#/components/features/automations/add-automation-menu";
-import { AddAutomationModal } from "#/components/features/automations/add-automation-modal";
import { ImportAutomationModal } from "#/components/features/automations/import-automation-modal";
import { RecommendedAutomationsLauncher } from "#/components/features/automations/recommended-automations-launcher";
import { BrandButton } from "#/components/features/settings/brand-button";
@@ -88,6 +92,7 @@ import { isDraftAutomation } from "#/utils/automation-state";
import { automationIconActionButtonClassName } from "#/components/features/automations/automation-action-button-classes";
import PlayIcon from "#/icons/play.svg?react";
import { StatusBadge } from "#/components/features/automations/status-badge";
+import { setupDraftFromServerDraft } from "#/components/features/automations/setup/automation-setup-draft-service";
const PAGE_SIZE = 50;
@@ -223,6 +228,16 @@ function SavedDraftsGroup({
</span>
</button>
<div className="flex shrink-0 items-center gap-1.5 pr-1.5">
+ <button
+ type="button"
+ data-testid={`automation-setup-draft-edit-${draft.id}`}
+ aria-label={t(I18nKey.AUTOMATIONS$EDIT)}
+ disabled={isBusy}
+ onClick={() => onResume(draft)}
+ className={automationIconActionButtonClassName}
+ >
+ <Pencil className="size-4" aria-hidden />
+ </button>
{canTestDirectly && !isBusy ? (
<StyledTooltip
content={t(I18nKey.AUTOMATION_SETUP$TEST_RUN)}
@@ -304,8 +319,8 @@ export default function AutomationsList() {
} | null>(null);
const [deleteDraftTarget, setDeleteDraftTarget] =
useState<AutomationDraftApiResponse | null>(null);
- const [editTarget, setEditTarget] = useState<Automation | null>(null);
- const [isAddAutomationOpen, setIsAddAutomationOpen] = useState(false);
+ const { openEditor } = useOpenAutomationEditor();
+ const { startSetup } = useStartAutomationSetup();
const [importSpec, setImportSpec] = useState<AutomationSpec | null>(null);
const [isImportOpen, setIsImportOpen] = useState(false);
@@ -456,9 +471,12 @@ export default function AutomationsList() {
});
};
- const handleResumeDraft = (_draft: AutomationDraftApiResponse) => {
- // Draft resume is intentionally wired in the follow-up PR once the setup
- // route can open without immediately starting an agent conversation.
+ const handleResumeDraft = (draft: AutomationDraftApiResponse) => {
+ initializeAutomationFormSession(
+ PENDING_AUTOMATION_SETUP_ID,
+ setupDraftFromServerDraft(draft),
+ );
+ navigate?.(`/automations/setup?draftId=${encodeURIComponent(draft.id)}`);
};
const handleTestDraft = (draft: AutomationDraftApiResponse) => {
@@ -487,9 +505,7 @@ export default function AutomationsList() {
const handleEditRequest = (id: string) => {
const automation = data?.automations.find((a) => a.id === id);
- if (automation) {
- setEditTarget(automation);
- }
+ if (automation) openEditor(automation);
};
const handleExport = (automation: Automation) => {
@@ -693,7 +709,7 @@ export default function AutomationsList() {
</BrandButton>
)}
<AddAutomationMenu
- onAdd={() => setIsAddAutomationOpen(true)}
+ onAdd={startSetup}
onImport={() => setIsImportOpen(true)}
/>
</div>
@@ -900,20 +916,6 @@ export default function AutomationsList() {
</div>
) : null}
- {/* Edit modal */}
- {editTarget && (
- <EditAutomationModal
- automation={editTarget}
- isOpen={editTarget !== null}
- onClose={() => setEditTarget(null)}
- />
- )}
-
- <AddAutomationModal
- isOpen={isAddAutomationOpen}
- onClose={() => setIsAddAutomationOpen(false)}
- />
-
<ImportAutomationModal
isOpen={isImportOpen}
spec={importSpec}
diff --git a/src/types/automation.ts b/src/types/automation.ts
index 27678407ef..4aec50e19a 100644
--- a/src/types/automation.ts
+++ b/src/types/automation.ts
@@ -95,6 +95,10 @@ export interface Automation {
* detail page uses it to point out which bundle file is the script.
*/
entrypoint?: string;
+ /** Service-owned upload identifier/path for custom automation bundles. */
+ tarball_path?: string | null;
+ /** Optional setup script path inside the custom automation bundle. */
+ setup_script_path?: string | null;
branch?: string;
/**
* Every repository the automation clones. The service layer derives it on
diff --git a/src/utils/automation-edit-draft.ts b/src/utils/automation-edit-draft.ts
new file mode 100644
index 0000000000..76e816c0f2
--- /dev/null
+++ b/src/utils/automation-edit-draft.ts
@@ -0,0 +1,122 @@
+/**
+ * Turn a saved automation into the setup-page draft the editor opens.
+ *
+ * Edit reuses the create form, so the draft has to carry the same fields
+ * the panel already knows how to render. `editingAutomationId` is what
+ * switches that page from "save draft / create" to "save / test".
+ */
+import {
+ type AutomationSetupDraft,
+ type AutomationSetupFormPatch,
+ type AutomationSetupFrequency,
+ type AutomationSetupKind,
+} from "#/api/automation-setup-types";
+import type { Automation } from "#/types/automation";
+import {
+ formatTimeOfDay,
+ parseCronSchedule,
+} from "#/utils/automation-schedule";
+
+const HOURLY_CRON = "0 * * * *";
+
+function setupKind(automation: Automation): AutomationSetupKind {
+ if ((automation.plugins?.length ?? 0) > 0) return "plugin";
+ if (!automation.prompt?.trim() && automation.entrypoint) return "custom";
+ return "prompt";
+}
+
+function eventKey(on: Automation["trigger"]["on"]): string {
+ if (Array.isArray(on)) return on.join(",");
+ return on ?? "";
+}
+
+/**
+ * Map a cron expression onto the setup form's frequency controls.
+ *
+ * Presets the shared parser already understands (daily, weekdays, weekly)
+ * stay presets. Hourly is recognized here because that parser treats
+ * `0 * * * *` as custom. Everything else, including one-time dates, stays
+ * a raw cron so we do not invent a date the expression does not contain.
+ */
+function scheduleFields(
+ schedule: string | undefined,
+ timezone: string | undefined,
+): AutomationSetupFormPatch {
+ const raw = schedule?.trim() ?? "";
+ const zone = timezone?.trim() ?? "";
+ if (raw === HOURLY_CRON) {
+ return {
+ triggerKind: "cron",
+ frequency: "hourly",
+ ...(zone ? { timezone: zone } : {}),
+ };
+ }
+
+ const parsed = parseCronSchedule(raw);
+ if (parsed.kind === "custom") {
+ return {
+ triggerKind: "cron",
+ frequency: "custom",
+ customSchedule: parsed.raw,
+ ...(zone ? { timezone: zone } : {}),
+ };
+ }
+
+ const frequency: AutomationSetupFrequency = parsed.kind;
+ return {
+ triggerKind: "cron",
+ frequency,
+ time: formatTimeOfDay(parsed.hour, parsed.minute),
+ ...(frequency === "weekly" ? { weekday: String(parsed.weekday ?? 1) } : {}),
+ ...(zone ? { timezone: zone } : {}),
+ };
+}
+
+/** Form values for one existing automation, ready to store on a conversation. */
+export function setupDraftFromAutomation(
+ automation: Automation,
+): AutomationSetupDraft {
+ const kind = setupKind(automation);
+ const prompt = automation.prompt ?? "";
+ const plugins = (automation.plugins ?? []).filter(
+ (plugin) => plugin.trim().length > 0,
+ );
+ const trigger = automation.trigger;
+ const form: AutomationSetupFormPatch = {
+ kind,
+ name: automation.name,
+ prompt,
+ repository: automation.repository ?? "",
+ model: automation.model ?? "",
+ agentProfileId: automation.agent_profile_id ?? "",
+ entrypoint: automation.entrypoint ?? "",
+ setupScriptPath: automation.setup_script_path ?? "",
+ ...(trigger.type === "event"
+ ? {
+ triggerKind: "event" as const,
+ eventSource: trigger.source ?? "",
+ eventKey: eventKey(trigger.on),
+ eventFilter: trigger.filter ?? "",
+ }
+ : scheduleFields(
+ trigger.schedule,
+ trigger.timezone ?? automation.timezone,
+ )),
+ };
+
+ if (automation.timeout != null) {
+ form.showTimeout = true;
+ form.timeoutSeconds = String(automation.timeout);
+ }
+
+ return {
+ prompt,
+ kind,
+ editingAutomationId: automation.id,
+ ...(kind === "custom" && automation.tarball_path
+ ? { existingCustomTarballPath: automation.tarball_path }
+ : {}),
+ ...(plugins.length > 0 ? { plugins } : {}),
+ form,
+ };
+}