🙌 OpenHands: AI-Driven Development
feat: add persisted automation draft management UI (#17242)
Rohit Malhotra235d6f3367e1
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.tsindex b3afb920c2..19dd6192e1 100644--- a/__tests__/api/agent-server-adapter.test.ts+++ b/__tests__/api/agent-server-adapter.test.ts@@ -857,6 +857,26 @@ describe("buildStartConversationRequest", () => {]);});+ it("adds automation setup tags to local conversation requests", () => {+ const payload = buildStartConversationRequest({+ settings: DEFAULT_SETTINGS,+ automationSetup: true,+ automationSetupTags: {+ automationdraftid: "draft-1",+ automationmaterializeddraftid: "auto-1",+ },+ });++ expect(payload.tags).toEqual(+ expect.objectContaining({+ automationsetup: "draft",+ automationdraftid: "draft-1",+ automationmaterializeddraftid: "auto-1",+ clientsource: "agentcanvas",+ }),+ );+ });+it.each([{automationSetup: false,diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.tsindex f11447309a..44f0b2bb0a 100644--- a/__tests__/api/agent-server-conversation-service.test.ts+++ b/__tests__/api/agent-server-conversation-service.test.ts@@ -1380,7 +1380,6 @@ describe("AgentServerConversationService", () => {});it("forwards parent_conversation_id, agent_type, and sandbox_id to the cloud createConversation payload", async () => {- // Arrangeconst requests = captureRequests(["post"], {id: "task-1",status: "WORKING",@@ -1391,7 +1390,6 @@ describe("AgentServerConversationService", () => {updated_at: "2024-01-01",});- // Actawait AgentServerConversationService.createConversation({metadata: null,parentConversationId: "parent-conv-1",@@ -1399,7 +1397,6 @@ describe("AgentServerConversationService", () => {sandboxId: "sandbox-9",});- // Assertexpect(requests).toHaveLength(1);const [request] = requests;expect(request.method).toBe("POST");@@ -1427,6 +1424,10 @@ describe("AgentServerConversationService", () => {await AgentServerConversationService.createConversation({initialUserMsg: "Create a daily report automation",automationSetup: true,+ automationSetupTags: {+ automationdraftid: "draft-1",+ automationmaterializeddraftid: "auto-1",+ },agentProfileKind: "openhands",});@@ -1436,7 +1437,11 @@ describe("AgentServerConversationService", () => {tags?: Record<string, string>;client_tools: Array<{ name: string }>;};- expect(body.tags).toEqual({ automationsetup: "draft" });+ expect(body.tags).toEqual({+ automationsetup: "draft",+ automationdraftid: "draft-1",+ automationmaterializeddraftid: "auto-1",+ });expect(body.client_tools.map((tool) => tool.name)).toEqual(["canvas_ui_control","launch_child_conversation",@@ -1471,16 +1476,13 @@ describe("AgentServerConversationService", () => {});it("routes readConversationFile to the cloud file endpoint with the file_path query param", async () => {- // Arrangeconst requests = captureRequests(["get"], "# PLAN content");- // Actconst content =await AgentServerConversationService.readConversationFile("conv-cloud-1",);- // Assertexpect(content).toBe("# PLAN content");expect(requests).toHaveLength(1);const [request] = requests;diff --git a/__tests__/api/automation-handlers.test.ts b/__tests__/api/automation-handlers.test.tsindex d82477344c..8c640702f9 100644--- a/__tests__/api/automation-handlers.test.ts+++ b/__tests__/api/automation-handlers.test.ts@@ -81,7 +81,13 @@ describe("Automation MSW Handlers", () => {// Assertexpect({ status: res.status, body: data }).toEqual({status: 200,- body: capabilitiesFixture.responses.supported.body,+ body: {+ ...capabilitiesFixture.responses.supported.body,+ features: [+ ...(capabilitiesFixture.responses.supported.body.features ?? []),+ "automationDrafts",+ ],+ },});});});diff --git a/__tests__/api/automation-service.test.ts b/__tests__/api/automation-service.test.tsindex 8187d12b8f..1111720ad9 100644--- a/__tests__/api/automation-service.test.ts+++ b/__tests__/api/automation-service.test.ts@@ -369,17 +369,6 @@ describe("AutomationService", () => {});});- describe("dispatchAutomation", () => {- it("posts to the dispatch endpoint", async () => {- mockPost.mockResolvedValue({ data: mockRun });-- const result = await AutomationService.dispatchAutomation("1");-- expect(mockPost).toHaveBeenCalledWith("/api/automation/v1/1/dispatch");- expect(result).toEqual(mockRun);- });- });-describe("deleteAutomation", () => {it("deletes an automation by id", async () => {mockDelete.mockResolvedValue({});@@ -514,19 +503,60 @@ describe("AutomationService", () => {);});- it("getAutomation routes to callCloudProxy with the id in the path", async () => {- mockCallCloudProxy.mockResolvedValue(mockAutomation);-- const result = await AutomationService.getAutomation("abc");-- expect(mockCallCloudProxy).toHaveBeenCalledWith({- backend: cloudBackend,- method: "GET",- path: "/api/automation/v1/abc",- headers: expectedAutomationTelemetryHeaders,- });- expect(result).toEqual(mockAutomation);- });+ it.each([+ {+ name: "getAutomation",+ arrange: () => mockAutomation,+ act: () => AutomationService.getAutomation("abc"),+ expectedRequest: { method: "GET", path: "/api/automation/v1/abc" },+ localMock: mockGet,+ },+ {+ name: "dispatchAutomation",+ arrange: () => mockRun,+ act: () => AutomationService.dispatchAutomation("abc"),+ expectedRequest: {+ method: "POST",+ path: "/api/automation/v1/abc/dispatch",+ },+ localMock: mockPost,+ },+ {+ name: "updateAutomation",+ arrange: () => ({ ...mockAutomation, enabled: false }),+ act: () =>+ AutomationService.updateAutomation("abc", { enabled: false }),+ expectedRequest: {+ method: "PATCH",+ path: "/api/automation/v1/abc",+ body: { enabled: false },+ },+ localMock: mockPatch,+ },+ {+ name: "deleteAutomation",+ arrange: () => undefined,+ act: () => AutomationService.deleteAutomation("abc"),+ expectedRequest: { method: "DELETE", path: "/api/automation/v1/abc" },+ localMock: mockDelete,+ },+ ])(+ "$name routes through callCloudProxy on cloud backends",+ async ({ arrange, act, expectedRequest, localMock }) => {+ const response = arrange();+ mockCallCloudProxy.mockResolvedValue(response);++ const result = await act();++ expect(mockCallCloudProxy).toHaveBeenCalledWith({+ backend: cloudBackend,+ headers: expectedAutomationTelemetryHeaders,+ ...expectedRequest,+ });+ expect(localMock).not.toHaveBeenCalled();+ expect(result).toEqual(response);+ },+ );it("getAutomation exposes preset_metadata repositories from the cloud proxy response", async () => {mockCallCloudProxy.mockResolvedValue({@@ -539,77 +569,6 @@ describe("AutomationService", () => {expect(result.repositories).toEqual([{ url: "acme/repo", ref: "main" }]);});- it("dispatchAutomation forwards method POST via callCloudProxy", async () => {- mockCallCloudProxy.mockResolvedValue(mockRun);-- const result = await AutomationService.dispatchAutomation("abc");-- expect(mockCallCloudProxy).toHaveBeenCalledWith({- backend: cloudBackend,- method: "POST",- path: "/api/automation/v1/abc/dispatch",- headers: expectedAutomationTelemetryHeaders,- });- expect(mockPost).not.toHaveBeenCalled();- expect(result).toEqual(mockRun);- });-- it("updateAutomation forwards method PATCH and body via callCloudProxy", async () => {- const updated = { ...mockAutomation, enabled: false };- mockCallCloudProxy.mockResolvedValue(updated);-- const result = await AutomationService.updateAutomation("abc", {- enabled: false,- });-- expect(mockCallCloudProxy).toHaveBeenCalledWith({- backend: cloudBackend,- method: "PATCH",- path: "/api/automation/v1/abc",- body: { enabled: false },- headers: expectedAutomationTelemetryHeaders,- });- expect(mockPatch).not.toHaveBeenCalled();- expect(result).toEqual(updated);- });-- it("deleteAutomation forwards method DELETE via callCloudProxy", async () => {- mockCallCloudProxy.mockResolvedValue(undefined);-- await AutomationService.deleteAutomation("abc");-- expect(mockCallCloudProxy).toHaveBeenCalledWith({- backend: cloudBackend,- method: "DELETE",- path: "/api/automation/v1/abc",- headers: expectedAutomationTelemetryHeaders,- });- expect(mockDelete).not.toHaveBeenCalled();- });-- it("dispatchAutomation forwards method POST via callCloudProxy", async () => {- const run = {- id: "run-1",- status: "PENDING",- conversation_id: null,- bash_command_id: null,- error_detail: null,- started_at: "2026-01-01T00:00:00Z",- completed_at: null,- };- mockCallCloudProxy.mockResolvedValue(run);-- const result = await AutomationService.dispatchAutomation("abc");-- expect(mockCallCloudProxy).toHaveBeenCalledWith({- backend: cloudBackend,- method: "POST",- path: "/api/automation/v1/abc/dispatch",- headers: expectedAutomationTelemetryHeaders,- });- expect(mockPost).not.toHaveBeenCalled();- expect(result).toEqual(run);- });it("checkHealth calls the cloud host with a fail-fast timeout and returns the upstream status", async () => {mockCallCloudProxy.mockResolvedValue({ status: "ok" });@@ -716,4 +675,269 @@ describe("AutomationService", () => {expect(config.baseURL).toBe("http://already-set:8000");});});++ describe("supportsAutomationDrafts", () => {+ it.each([+ {+ name: "advertised feature",+ capabilities: {+ ready: true,+ features: ["automationDrafts"],+ triggerKinds: [],+ eventSources: [],+ eventTypes: [],+ triggers: {},+ },+ expected: true,+ },+ {+ name: "missing feature",+ capabilities: {+ ready: true,+ features: ["presetPrompt"],+ triggerKinds: [],+ eventSources: [],+ eventTypes: [],+ triggers: {},+ },+ expected: false,+ },+ { name: "null capabilities", capabilities: null, expected: false },+ {+ name: "undefined capabilities",+ capabilities: undefined,+ expected: false,+ },+ ])("returns $expected for $name", ({ capabilities, expected }) => {+ expect(AutomationService.supportsAutomationDrafts(capabilities)).toBe(+ expected,+ );+ });+ });++ describe("createServerDraft", () => {+ it("posts the snake_case body to /v1/drafts and normalizes the response", async () => {+ const raw = {+ id: "draft-1",+ endpoint: "/v1/preset/prompt",+ name: "PR Reviewer",+ draft: { prompt: "review prs" },+ validation_errors: null,+ dispatchable: true,+ source_automation_id: null,+ materialized_automation_id: null,+ last_test_run_id: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };+ mockPost.mockResolvedValue({ data: raw });++ const result = await AutomationService.createServerDraft({+ endpoint: "/v1/preset/prompt",+ draft: { prompt: "review prs" } as never,+ name: "PR Reviewer",+ });++ expect(mockPost).toHaveBeenCalledWith("/api/automation/v1/drafts", {+ endpoint: "/v1/preset/prompt",+ draft: { prompt: "review prs" },+ name: "PR Reviewer",+ });+ expect(result.id).toBe("draft-1");+ expect(result.sourceAutomationId).toBeNull();+ expect(result.createdAt).toBe("2026-01-01T00:00:00Z");+ expect(result.dispatchable).toBe(true);+ });++ it("omits name and source_automation_id when not provided", async () => {+ mockPost.mockResolvedValue({+ data: { id: "draft-2", endpoint: "/v1/preset/prompt" },+ });++ await AutomationService.createServerDraft({+ endpoint: "/v1/preset/prompt",+ draft: {} as never,+ });++ const [, body] = mockPost.mock.calls[0];+ expect(body).not.toHaveProperty("name");+ expect(body).not.toHaveProperty("source_automation_id");+ });++ it("routes to callCloudProxy for cloud backends", async () => {+ mockGetActive.mockReturnValue({ backend: cloudBackend, orgId: "org-1" });+ mockCallCloudProxy.mockResolvedValue({ id: "cloud-draft" });++ const result = await AutomationService.createServerDraft({+ endpoint: "/v1/preset/prompt",+ draft: {} as never,+ });++ expect(mockCallCloudProxy).toHaveBeenCalledWith(+ expect.objectContaining({+ backend: cloudBackend,+ method: "POST",+ path: "/api/automation/v1/drafts",+ }),+ );+ expect(result.id).toBe("cloud-draft");+ });+ });++ describe("updateServerDraft", () => {+ it("patches only the provided fields", async () => {+ mockPatch.mockResolvedValue({+ data: { id: "draft-1", endpoint: "/v1/preset/prompt" },+ });++ await AutomationService.updateServerDraft("draft-1", {+ name: "New name",+ });++ expect(mockPatch).toHaveBeenCalledWith(+ "/api/automation/v1/drafts/draft-1",+ { name: "New name" },+ );+ });+ });++ describe("getServerDraft", () => {+ it("fetches and normalizes a single draft", async () => {+ mockGet.mockResolvedValue({+ data: {+ id: "draft-9",+ endpoint: "/v1",+ validation_errors: [+ { field: "name", code: "value_error", message: "required" },+ ],+ },+ });++ const result = await AutomationService.getServerDraft("draft-9");++ expect(mockGet).toHaveBeenCalledWith("/api/automation/v1/drafts/draft-9");+ expect(result.id).toBe("draft-9");+ expect(result.validationErrors?.[0].message).toBe("required");+ });+ });++ describe("deleteServerDraft", () => {+ it("deletes a draft by id", async () => {+ mockDelete.mockResolvedValue({});++ await AutomationService.deleteServerDraft("draft-1");++ expect(mockDelete).toHaveBeenCalledWith(+ "/api/automation/v1/drafts/draft-1",+ );+ });+ });++ describe("listServerDrafts", () => {+ it("lists drafts with pagination and normalizes the response", async () => {+ mockGet.mockResolvedValue({+ data: {+ drafts: [{ id: "d1", endpoint: "/v1/preset/prompt" }],+ total: 1,+ },+ });++ const result = await AutomationService.listServerDrafts({+ limit: 10,+ offset: 5,+ });++ expect(mockGet).toHaveBeenCalledWith(+ "/api/automation/v1/drafts?limit=10&offset=5",+ );+ expect(result.total).toBe(1);+ expect(result.drafts[0].id).toBe("d1");+ });++ it("routes to callCloudProxy for cloud backends", async () => {+ mockGetActive.mockReturnValue({ backend: cloudBackend, orgId: "org-1" });+ mockCallCloudProxy.mockResolvedValue({+ drafts: [],+ total: 0,+ });++ const result = await AutomationService.listServerDrafts({+ limit: 10,+ offset: 5,+ });++ expect(mockCallCloudProxy).toHaveBeenCalledWith(+ expect.objectContaining({+ backend: cloudBackend,+ method: "GET",+ path: "/api/automation/v1/drafts?limit=10&offset=5",+ }),+ );+ expect(result).toEqual({ drafts: [], total: 0 });+ });+ });++ describe("createCustomWebhook", () => {+ it("posts custom webhook configuration to the automation API", async () => {+ const webhook = {+ id: "webhook-1",+ org_id: "org-1",+ name: "Incident webhook",+ source: "incident-alerts",+ webhook_url:+ "https://app.all-hands.dev/v1/events/org-1/incident-alerts",+ event_key_expr: "event.type",+ signature_header: "X-Incident-Signature",+ signature_scheme: "hmac_sha256_hex",+ enabled: true,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ webhook_secret: "generated-secret",+ };+ mockPost.mockResolvedValue({ data: webhook });++ const result = await AutomationService.createCustomWebhook({+ name: "Incident webhook",+ source: "incident-alerts",+ event_key_expr: "event.type",+ signature_header: "X-Incident-Signature",+ signature_scheme: "hmac_sha256_hex",+ });++ expect(mockPost).toHaveBeenCalledWith("/api/automation/v1/webhooks", {+ name: "Incident webhook",+ source: "incident-alerts",+ event_key_expr: "event.type",+ signature_header: "X-Incident-Signature",+ signature_scheme: "hmac_sha256_hex",+ });+ expect(result).toEqual(webhook);+ });+ });++ describe("dispatchServerDraft", () => {+ it("posts to the dispatch endpoint and returns the run", async () => {+ mockPost.mockResolvedValue({ data: mockRun });++ const result = await AutomationService.dispatchServerDraft("draft-1");++ expect(mockPost).toHaveBeenCalledWith(+ "/api/automation/v1/drafts/draft-1/dispatch",+ );+ expect(result).toEqual(mockRun);+ });++ it("sends a synthetic event payload when provided", async () => {+ mockPost.mockResolvedValue({ data: mockRun });++ await AutomationService.dispatchServerDraft("draft-1", {+ eventPayload: { type: "issue.created", action: "opened" },+ });++ expect(mockPost).toHaveBeenCalledWith(+ "/api/automation/v1/drafts/draft-1/dispatch",+ { event_payload: { type: "issue.created", action: "opened" } },+ );+ });+ });});diff --git a/__tests__/components/automations/automation-card.test.tsx b/__tests__/components/automations/automation-card.test.tsxindex 9031778ffd..af093b0017 100644--- a/__tests__/components/automations/automation-card.test.tsx+++ b/__tests__/components/automations/automation-card.test.tsx@@ -116,6 +116,25 @@ describe("AutomationCard", () => {expect(card.className).not.toContain("border-border");});+ it("marks draft automations without labeling them inactive", () => {+ render(+ <AutomationCard+ automation={{ ...automation, enabled: false, state: "DRAFT" }}+ onToggle={vi.fn()}+ onRunNow={vi.fn()}+ onExport={vi.fn()}+ onDelete={vi.fn()}+ />,+ );++ expect(screen.getByTestId("active-status-badge-draft")).toHaveTextContent(+ I18nKey.AUTOMATIONS$DETAIL$DRAFT,+ );+ expect(+ screen.queryByTestId("active-status-badge-inactive"),+ ).not.toBeInTheDocument();+ });+it("renders title, description, and overflow pills", () => {render(<AutomationCarddiff --git a/__tests__/components/automations/automation-list-row.test.tsx b/__tests__/components/automations/automation-list-row.test.tsxindex e2ff941fd4..688b81b897 100644--- a/__tests__/components/automations/automation-list-row.test.tsx+++ b/__tests__/components/automations/automation-list-row.test.tsx@@ -8,6 +8,7 @@ import {type AutomationRun,} from "#/types/automation";import type { InterfaceListInsights } from "#/manifests/types";+import { I18nKey } from "#/i18n/declaration";vi.mock("react-i18next", () => ({useTranslation: () => ({@@ -121,6 +122,25 @@ describe("AutomationListRow", () => {);});+ it("marks draft automations separately from inactive rows", () => {+ render(+ <AutomationListRow+ automation={{ ...automation, enabled: false, state: "DRAFT" }}+ onToggle={vi.fn()}+ onRunNow={vi.fn()}+ onExport={vi.fn()}+ onDelete={vi.fn()}+ />,+ );++ expect(screen.getByTestId("active-status-badge-draft")).toHaveTextContent(+ I18nKey.AUTOMATIONS$DETAIL$DRAFT,+ );+ expect(+ screen.queryByTestId("active-status-badge-inactive"),+ ).not.toBeInTheDocument();+ });+it("shows last-run status, relative time, and a sparkline when insights are present", () => {const latestRun = createRun({started_at: new Date(Date.now() - 10 * 60_000).toISOString(),diff --git a/__tests__/components/automations/automation-setup-draft-service.test.ts b/__tests__/components/automations/automation-setup-draft-service.test.tsnew file mode 100644index 0000000000..7296135c96--- /dev/null+++ b/__tests__/components/automations/automation-setup-draft-service.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";+import { HttpError } from "@openhands/typescript-client";+import { extractDraftDispatchErrors } from "#/components/features/automations/setup/automation-setup-draft-service";++const detailEnvelope = {+ detail: {+ message: "Draft is not dispatchable",+ errors: [+ {+ field: "prompt",+ code: "required",+ message: "Prompt is required",+ },+ ],+ },+};++describe("extractDraftDispatchErrors", () => {+ it("reads FastAPI detail envelopes from axios draft dispatch errors", () => {+ const error = {+ isAxiosError: true,+ response: { data: detailEnvelope },+ };++ expect(extractDraftDispatchErrors(error)).toBe("Prompt is required");+ });++ it("reads FastAPI detail envelopes from SDK HttpError draft dispatch errors", () => {+ const error = new HttpError(422, "Unprocessable Entity", detailEnvelope);++ expect(extractDraftDispatchErrors(error)).toBe("Prompt is required");+ });++ it("falls back to the detail message when no field errors are present", () => {+ const error = new HttpError(422, "Unprocessable Entity", {+ detail: { message: "Draft is not dispatchable", errors: [] },+ });++ expect(extractDraftDispatchErrors(error)).toBe("Draft is not dispatchable");+ });+});diff --git a/__tests__/components/automations/automation-setup-panel.test.tsx b/__tests__/components/automations/automation-setup-panel.test.tsxindex a89ab5bee6..7346ba7e16 100644--- a/__tests__/components/automations/automation-setup-panel.test.tsx+++ b/__tests__/components/automations/automation-setup-panel.test.tsx@@ -1,6 +1,15 @@-import { act, render, screen, waitFor } from "@testing-library/react";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { HttpError } from "@openhands/typescript-client";import {NavigationProvider,type NavigationContextValue,@@ -11,19 +20,55 @@ import {AutomationSetupPanel,} from "#/components/features/automations/setup/automation-setup-panel";import AutomationService from "#/api/automation-service/automation-service.api";-import { initializeAutomationFormSession } from "#/api/automation-form-session";+import {+ getAutomationFormSession,+ initializeAutomationFormSession,+} from "#/api/automation-form-session";import type { AutomationSetupDraft } from "#/api/automation-setup-types";+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";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 { useDeploymentCapabilities } from "#/hooks/query/use-manifest-capabilities";+import type { AutomationDraftApiResponse } from "#/manifests/types";const mockNavigate = vi.fn();const mockToastSuccess = vi.fn();-const mockUseGitRepositories = vi.fn(() => ({- data: { pages: [] },+const createGitRepositoriesQueryResult = () => ({+ data: {+ pages: [+ {+ items: [+ {+ id: "1",+ full_name: "OpenHands/OpenHands",+ git_provider: "github",+ is_public: true,+ },+ {+ id: "2",+ full_name: "OpenHands/software-agent-sdk",+ git_provider: "github",+ is_public: true,+ },+ ],+ missing_token: false,+ next_page_id: null,+ },+ ],+ },isError: false,isLoading: false,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),onLoadMore: vi.fn(),+});+const mockUseGitRepositories = vi.fn(createGitRepositoriesQueryResult);++const { mockSendMessage } = vi.hoisted(() => ({+ mockSendMessage: vi.fn().mockResolvedValue({ queued: false }),}));vi.mock("react-hot-toast", () => ({@@ -31,63 +76,129 @@ vi.mock("react-hot-toast", () => ({}));vi.mock("react-i18next", () => ({- useTranslation: () => ({ t: (key: string) => key }),+ useTranslation: () => ({+ t: (key: string) => key,+ i18n: { language: "en" },+ }),}));vi.mock("#/utils/custom-toast-handlers", () => ({displayErrorToast: vi.fn(),}));+vi.mock(+ "#/api/conversation-service/agent-server-conversation-service.api",+ () => ({+ default: {+ updateConversationTags: vi.fn(+ async (_conversationId: string, tags: Record<string, string>) => ({+ tags,+ }),+ ),+ },+ }),+);+vi.mock("#/api/automation-service/automation-service.api", () => ({default: {validateDraft: vi.fn(),createAutomationDraft: vi.fn(),uploadAutomationTarball: vi.fn(),+ createServerDraft: vi.fn(),+ updateServerDraft: vi.fn(),+ getServerDraft: vi.fn(),+ deleteServerDraft: vi.fn(),+ listServerDrafts: vi.fn(),+ listAutomationRuns: vi.fn().mockResolvedValue({ runs: [], total: 0 }),+ dispatchServerDraft: vi.fn(),+ createCustomWebhook: vi.fn(),+ supportsAutomationDrafts: vi.fn(),},}));-vi.mock("#/utils/tar-gzip", () => ({- packTarGzip: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])),-}));--vi.mock("#/manifests/automation-interface", () => ({- automationDetailPath: (id: string) => `/automations/${id}`,- getAutomationEndpoint: (name: string) =>- name === "createPlugin"- ? "/v1/preset/plugin"- : name === "createBundle"- ? "/v1"- : "/v1/preset/prompt",+vi.mock("#/hooks/use-send-message", () => ({+ useSendMessage: () => ({ send: mockSendMessage }),}));-vi.mock("#/hooks/query/use-llm-profiles", () => ({- useLlmProfiles: () => ({- data: { active_profile: "default", profiles: [] },- isLoading: false,- }),+vi.mock("#/hooks/query/use-manifest-capabilities", () => ({+ useDeploymentCapabilities: vi.fn(() => ({ data: null, isLoading: false })),}));vi.mock("#/hooks/query/use-agent-profiles", () => ({useAgentProfiles: () => ({- data: { active_agent_profile_id: null, profiles: [] },+ data: {+ profiles: [+ {+ id: "agent-default",+ name: "default",+ agent_kind: "openhands",+ revision: 1,+ llm_profile_ref: "claude-opus-4-5-20251101",+ mcp_server_refs: null,+ },+ {+ id: "agent-reviewer",+ name: "reviewer",+ agent_kind: "openhands",+ revision: 1,+ llm_profile_ref: "fast",+ mcp_server_refs: null,+ },+ ],+ active_agent_profile_id: "agent-default",+ },isLoading: false,}),}));vi.mock("#/hooks/use-user-providers", () => ({- useUserProviders: () => ({ providers: [] }),+ useUserProviders: () => ({+ providers: ["github"],+ isLoadingSettings: false,+ }),}));vi.mock("#/hooks/query/use-git-repositories", () => ({useGitRepositories: () => mockUseGitRepositories(),}));+vi.mock("#/hooks/query/use-llm-profiles", () => ({+ useLlmProfiles: () => ({+ data: {+ profiles: [+ { name: "fast", model: "openai/gpt-4.1-mini" },+ {+ name: "claude-opus-4-5-20251101",+ model: "anthropic/claude-opus-4-5",+ },+ ],+ active_profile: "claude-opus-4-5-20251101",+ },+ isLoading: false,+ }),+}));++vi.mock("#/utils/tar-gzip", () => ({+ packTarGzip: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])),+}));++vi.mock("#/manifests/automation-interface", () => ({+ automationDetailPath: (id: string) => `/automations/${id}`,+ getAutomationEndpoint: (name: string) =>+ name === "createPlugin"+ ? "/v1/preset/plugin"+ : name === "createBundle"+ ? "/v1"+ : "/v1/preset/prompt",+}));+function renderPanel(draft: AutomationSetupDraft = {prompt: "Review every pull request",kind: "prompt",},conversationId = "conv-1",+ conversationTags: Record<string, string> | null | undefined = null,) {const value: NavigationContextValue = {currentPath: `/conversations/${conversationId}`,@@ -95,11 +206,20 @@ function renderPanel(isNavigating: false,navigate: mockNavigate,};+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });return render(- <NavigationProvider value={value}>- <AutomationSetupPanel draft={draft} conversationId={conversationId} />- </NavigationProvider>,+ <QueryClientProvider client={queryClient}>+ <NavigationProvider value={value}>+ <AutomationSetupPanel+ draft={draft}+ conversationId={conversationId}+ conversationTags={conversationTags}+ />+ </NavigationProvider>+ </QueryClientProvider>,);}@@ -107,36 +227,123 @@ describe("AutomationSetupPanel", () => {beforeEach(() => {window.sessionStorage.clear();vi.clearAllMocks();- mockUseGitRepositories.mockReturnValue({- data: { pages: [] },- isError: false,+ // By default the deployment does not advertise server-backed drafts, so+ // the panel falls back to the preflight-only Test path the existing+ // assertions cover. BE-draft tests override this per-test.+ vi.mocked(useDeploymentCapabilities).mockReturnValue({+ data: null,isLoading: false,- onLoadMore: vi.fn(),- });+ } as never);+ vi.mocked(AutomationService.supportsAutomationDrafts).mockReturnValue(+ false,+ );+ vi.mocked(+ AgentServerConversationService.updateConversationTags,+ ).mockImplementation(async (_conversationId, tags) => ({ tags }) as never);+ mockUseGitRepositories.mockReturnValue(createGitRepositoriesQueryResult());});afterEach(() => {vi.useRealTimers();});- it("switches between prompt, plugin, and custom form types", async () => {+ it("shows a one-time date when Once is selected and a time of day otherwise", async () => {+ const user = userEvent.setup();+ renderPanel();++ expect(+ screen.getByTestId("automation-setup-frequency-daily"),+ ).toHaveAttribute("aria-checked", "true");+ expect(screen.getByTestId("automation-setup-time")).toBeInTheDocument();+ expect(+ screen.queryByTestId("automation-setup-datetime"),+ ).not.toBeInTheDocument();++ await user.click(screen.getByTestId("automation-setup-frequency-once"));++ expect(screen.getByTestId("automation-setup-datetime")).toBeInTheDocument();+ expect(+ screen.queryByTestId("automation-setup-time"),+ ).not.toBeInTheDocument();+ expect(screen.getByTestId("automation-setup-timezone")).toHaveValue(+ "America/New_York",+ );+ });++ it("switches between prompt and custom, and reveals plugin fields on the prompt page", async () => {const user = userEvent.setup();renderPanel();expect(screen.getByTestId("automation-setup-prompt")).toHaveValue("Review every pull request",);- expect(screen.getByTestId("automation-setup-save-draft")).toBeDisabled();+ expect(+ screen.queryByTestId("automation-setup-kind-plugin"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("automation-setup-plugin-source"),+ ).not.toBeInTheDocument();await user.click(screen.getByTestId("automation-setup-add-plugin"));expect(screen.getByTestId("automation-setup-plugin-source"),).toBeInTheDocument();+ expect(screen.getByTestId("automation-setup-prompt")).toBeInTheDocument();await user.click(screen.getByTestId("automation-setup-kind-custom"));+ expect(+ screen.queryByTestId("automation-setup-plugin-source"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("automation-setup-add-plugin"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByText("AUTOMATION_SETUP$CUSTOM_PYTHON"),+ ).toBeInTheDocument();+ expect(+ screen.queryByText("AUTOMATION_SETUP$PYTHON_CODE"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("automation-setup-model"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-custom-code-grip"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-custom-code-scroll"),+ ).not.toHaveClass("p-4");+ expect(screen.getByTestId("automation-setup-custom-code")).toHaveClass(+ "p-0",+ );+ expect(+ screen.queryByTestId("automation-setup-entrypoint"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-custom-details-drawer"),+ ).toHaveClass("border-x", "border-b", "rounded-b-[15px]");+ await user.click(+ screen.getByTestId("automation-setup-custom-details-toggle"),+ );+ expect(+ screen.getByTestId("automation-setup-custom-details-drawer"),+ ).toContainElement(screen.getByTestId("automation-setup-entrypoint"));expect(screen.getByTestId("automation-setup-entrypoint")).toHaveValue("python3 main.py",);+ expect(+ screen+ .getByTestId("automation-setup-custom-code")+ .compareDocumentPosition(+ screen.getByTestId("automation-setup-entrypoint"),+ ) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(+ screen+ .getByTestId("automation-setup-entrypoint")+ .compareDocumentPosition(+ screen.getByTestId("automation-setup-setup-script"),+ ) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();expect(screen.getByTestId("automation-setup-setup-script-path"),).toHaveValue("setup.sh");@@ -157,9 +364,58 @@ describe("AutomationSetupPanel", () => {expect(screen.queryByTestId("automation-setup-prompt"),).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("automation-setup-repository"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-add-timeout"),+ ).toBeInTheDocument();++ await user.click(screen.getByTestId("automation-setup-kind-prompt"));+ expect(screen.getByTestId("automation-setup-prompt")).toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-repository"),+ ).not.toHaveTextContent("COMMON$OPTIONAL");+ expect(screen.getByTestId("automation-setup-prompt-drawer")).toHaveClass(+ "border-x",+ "border-b",+ );+ expect(+ screen.queryByTestId("automation-setup-entrypoint"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-plugin-source"),+ ).toBeInTheDocument();+ });++ it("removes an opened timeout or plugin from additional options", async () => {+ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-add-timeout"));+ expect(screen.getByTestId("automation-setup-timeout")).toBeInTheDocument();+ await user.click(screen.getByTestId("automation-setup-timeout-remove"));+ expect(+ screen.queryByTestId("automation-setup-timeout"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-add-timeout"),+ ).toBeInTheDocument();++ await user.click(screen.getByTestId("automation-setup-add-plugin"));+ expect(+ screen.getByTestId("automation-setup-plugin-source"),+ ).toBeInTheDocument();+ await user.click(screen.getByTestId("automation-setup-plugin-remove"));+ expect(+ screen.queryByTestId("automation-setup-plugin-source"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-add-plugin"),+ ).toBeInTheDocument();});- it("validates the prompt draft against the automation service", async () => {+ it("runs preflight validation without draft requests when draft capabilities are unsupported", async () => {vi.mocked(AutomationService.validateDraft).mockResolvedValue({valid: true,errors: [],@@ -170,6 +426,8 @@ describe("AutomationSetupPanel", () => {await user.click(screen.getByTestId("automation-setup-test"));+ expect(AutomationService.createServerDraft).not.toHaveBeenCalled();+ expect(AutomationService.updateServerDraft).not.toHaveBeenCalled();await waitFor(() =>expect(AutomationService.validateDraft).toHaveBeenCalledWith({endpoint: "/v1/preset/prompt",@@ -185,11 +443,88 @@ describe("AutomationSetupPanel", () => {}),);expect(screen.getByTestId("automation-setup-status")).toHaveTextContent(- "AUTOMATION_SETUP$TEST_PASSED",+ "AUTOMATION_SETUP$READY_TO_TEST",+ );+ });++ it("pins an automation model without changing the conversation profile", async () => {+ vi.mocked(AutomationService.createServerDraft).mockRejectedValue({+ response: { status: 404 },+ });+ vi.mocked(AutomationService.validateDraft).mockResolvedValue({+ valid: true,+ errors: [],+ });++ const user = userEvent.setup();+ renderPanel();++ expect(screen.getByTestId("automation-setup-model")).toHaveAttribute(+ "aria-label",+ "claude-opus-4-5-20251101",+ );+ await user.click(screen.getByTestId("automation-setup-model"));+ await user.click(screen.getByTestId("automation-setup-model-option-fast"));+ expect(screen.getByTestId("automation-setup-model")).toHaveAttribute(+ "aria-label",+ "fast",+ );++ await user.click(screen.getByTestId("automation-setup-test"));++ await waitFor(() =>+ expect(AutomationService.validateDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ draft: expect.objectContaining({ model: "fast" }),+ }),+ ),+ );+ });++ it("pins an automation agent profile without changing the conversation", async () => {+ vi.mocked(AutomationService.createServerDraft).mockRejectedValue({+ response: { status: 404 },+ });+ vi.mocked(AutomationService.validateDraft).mockResolvedValue({+ valid: true,+ errors: [],+ });++ const user = userEvent.setup();+ renderPanel();++ expect(+ screen.getByTestId("automation-setup-agent-profile"),+ ).toHaveAttribute("aria-label", "default");+ await user.click(screen.getByTestId("automation-setup-agent-profile"));+ await user.click(+ screen.getByTestId("automation-setup-agent-profile-option-reviewer"),+ );+ expect(+ screen.getByTestId("automation-setup-agent-profile"),+ ).toHaveAttribute("aria-label", "reviewer");+ expect(screen.getByTestId("automation-setup-model")).toHaveAttribute(+ "aria-label",+ "claude-opus-4-5-20251101",+ );++ await user.click(screen.getByTestId("automation-setup-test"));++ await waitFor(() =>+ expect(AutomationService.validateDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ draft: expect.objectContaining({+ agent_profile_id: "agent-reviewer",+ }),+ }),+ ),);});it("sends each comma-separated repository to the automation service", async () => {+ vi.mocked(AutomationService.createServerDraft).mockRejectedValue({+ response: { status: 404 },+ });vi.mocked(AutomationService.validateDraft).mockResolvedValue({valid: true,errors: [],@@ -202,7 +537,29 @@ describe("AutomationSetupPanel", () => {await user.click(screen.getByTestId("automation-setup-repository-custom"));await user.type(screen.getByTestId("automation-setup-repository-address"),- "OpenHands/OpenHands, https://gitlab.com/acme/project",+ "OpenHands/OpenHands",+ );+ await user.click(screen.getByTestId("automation-setup-repository-submit"));++ const addButton = screen.getByTestId("automation-setup-repository-add");+ const pill = screen.getByTestId("automation-setup-repository-value");+ expect(+ screen.getByTestId("automation-setup-repository-values"),+ ).toHaveClass("flex-wrap");+ expect(screen.getByTestId("automation-setup-kind-custom")).toHaveClass(+ "bg-tertiary",+ "text-content",+ );+ expect(+ addButton.compareDocumentPosition(pill) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();++ await user.click(screen.getByTestId("automation-setup-repository-add"));+ await user.click(screen.getByTestId("automation-setup-repository-custom"));+ await user.type(+ screen.getByTestId("automation-setup-repository-address"),+ "OpenHands/software-agent-sdk",);await user.click(screen.getByTestId("automation-setup-repository-submit"));await user.click(screen.getByTestId("automation-setup-test"));@@ -213,7 +570,7 @@ describe("AutomationSetupPanel", () => {draft: expect.objectContaining({repos: [{ url: "OpenHands/OpenHands", provider: "github" },- { url: "https://gitlab.com/acme/project" },+ { url: "OpenHands/software-agent-sdk", provider: "github" },],}),}),@@ -221,11 +578,43 @@ describe("AutomationSetupPanel", () => {);});+ it("adds a listed repository and keeps custom pinned to the address modal", async () => {+ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-repository-add"));+ const menu = screen.getByTestId("automation-setup-repository-menu");+ const custom = screen.getByTestId("automation-setup-repository-custom");+ expect(menu.lastElementChild).toContainElement(custom);+ expect(menu.className).toContain("top-full");+ expect(+ screen.queryByTestId("automation-setup-add-repository-modal"),+ ).not.toBeInTheDocument();++ await user.click(+ await screen.findByTestId(+ "automation-setup-repository-option-OpenHands/OpenHands",+ ),+ );+ expect(+ screen.getByTestId("automation-setup-repository-value"),+ ).toHaveTextContent("OpenHands/OpenHands");++ await user.click(screen.getByTestId("automation-setup-repository-add"));+ await user.click(screen.getByTestId("automation-setup-repository-custom"));+ expect(+ screen.getByTestId("automation-setup-add-repository-modal"),+ ).toBeInTheDocument();+ });+it("shows a repository loading error in the repository picker", async () => {mockUseGitRepositories.mockReturnValue({data: { pages: [] },isError: true,isLoading: false,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),onLoadMore: vi.fn(),});@@ -242,6 +631,45 @@ describe("AutomationSetupPanel", () => {).not.toBeInTheDocument();});+ it("filters the repository menu from the search and keeps a divider above custom", async () => {+ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-repository-add"));+ expect(+ await screen.findByTestId(+ "automation-setup-repository-option-OpenHands/OpenHands",+ ),+ ).toBeInTheDocument();+ const custom = screen.getByTestId("automation-setup-repository-custom");+ const divider = screen.getByTestId(+ "automation-setup-repository-custom-divider",+ );+ expect(+ divider.compareDocumentPosition(custom) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();++ await user.type(+ screen.getByTestId("automation-setup-repository-search"),+ "sdk",+ );++ expect(+ screen.queryByTestId(+ "automation-setup-repository-option-OpenHands/OpenHands",+ ),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId(+ "automation-setup-repository-option-OpenHands/software-agent-sdk",+ ),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-repository-custom"),+ ).toBeInTheDocument();+ });+it("streams agent form updates field by field without overwriting user edits", async () => {vi.useFakeTimers();const conversationId = "conv-agent-updates";@@ -317,26 +745,63 @@ describe("AutomationSetupPanel", () => {).toBeGreaterThan(0);});- it("creates plugin drafts with the selected plugin source", async () => {- vi.mocked(AutomationService.createAutomationDraft).mockResolvedValue({- id: "automation-1",+ it("shows a weekday dropdown for a weekly schedule", async () => {+ vi.mocked(AutomationService.createServerDraft).mockRejectedValue({+ response: { status: 404 },+ });+ vi.mocked(AutomationService.validateDraft).mockResolvedValue({+ valid: true,+ errors: [],});const user = userEvent.setup();- renderPanel({- prompt: "Summarize Slack blockers",- kind: "plugin",- plugins: ["github:org/blockers-plugin"],- });+ renderPanel();- await user.click(screen.getByTestId("automation-setup-create"));+ expect(+ screen.queryByTestId("automation-setup-weekday"),+ ).not.toBeInTheDocument();++ await user.click(screen.getByTestId("automation-setup-frequency-weekly"));+ const weekday = screen.getByTestId("automation-setup-weekday");+ expect(weekday).toHaveValue("1");+ expect(weekday.parentElement?.parentElement).toHaveTextContent(+ "AUTOMATION_SETUP$ON",+ );+ await user.selectOptions(weekday, "3");++ await user.click(screen.getByTestId("automation-setup-test"));await waitFor(() =>- expect(AutomationService.createAutomationDraft).toHaveBeenCalledWith(+ expect(AutomationService.validateDraft).toHaveBeenCalledWith(expect.objectContaining({- enabled: false,- prompt: "Summarize Slack blockers",- plugins: [{ source: "github:org/blockers-plugin" }],+ draft: expect.objectContaining({+ trigger: expect.objectContaining({ schedule: "0 9 * * 3" }),+ }),+ }),+ ),+ );+ });++ it("creates plugin drafts with the selected plugin source", async () => {+ vi.mocked(AutomationService.createAutomationDraft).mockResolvedValue({+ id: "automation-1",+ });++ const user = userEvent.setup();+ renderPanel({+ prompt: "Summarize Slack blockers",+ kind: "plugin",+ plugins: ["github:org/blockers-plugin"],+ });++ await user.click(screen.getByTestId("automation-setup-create"));++ await waitFor(() =>+ expect(AutomationService.createAutomationDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ enabled: false,+ prompt: "Summarize Slack blockers",+ plugins: [{ source: "github:org/blockers-plugin" }],}),"plugin",),@@ -344,6 +809,188 @@ describe("AutomationSetupPanel", () => {expect(mockNavigate).toHaveBeenCalledWith("/automations/automation-1");});+ it("hides the event filter until Add Event Filter is clicked", async () => {+ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByText("AUTOMATIONS$DETAIL$TRIGGER_EVENT"));+ expect(+ screen.queryByTestId("automation-setup-event-filter"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-event-key").parentElement,+ ).toContainElement(screen.getByTestId("automation-setup-add-event-filter"));+ expect(+ screen.getByTestId("automation-setup-add-event-filter"),+ ).toHaveTextContent("AUTOMATION_SETUP$ADD_FILTER");++ await user.click(screen.getByTestId("automation-setup-add-event-filter"));+ expect(+ screen.getByTestId("automation-setup-event-filter"),+ ).toBeInTheDocument();++ await user.click(+ screen.getByTestId("automation-setup-event-filter-remove"),+ );+ expect(+ screen.queryByTestId("automation-setup-event-filter"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-add-event-filter"),+ ).toBeInTheDocument();+ });++ it("asks the agent to fill the event trigger", async () => {+ const user = userEvent.setup();+ const showAgent = vi.fn();+ window.addEventListener(AUTOMATION_SETUP_SHOW_AGENT_EVENT, showAgent);+ renderPanel();++ await user.click(screen.getByText("AUTOMATIONS$DETAIL$TRIGGER_EVENT"));+ await user.click(screen.getByTestId("automation-setup-ask-agent"));++ expect(mockSendMessage).toHaveBeenCalledWith({+ action: "message",+ args: { content: "AUTOMATION_SETUP$ASK_AGENT_EVENT_PROMPT" },+ });+ expect(showAgent).toHaveBeenCalled();+ window.removeEventListener(AUTOMATION_SETUP_SHOW_AGENT_EVENT, showAgent);+ });++ it("shows a spinner in the repository menu while the list loads", async () => {+ mockUseGitRepositories.mockReturnValue({+ data: { pages: [] },+ isError: false,+ isLoading: true,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ onLoadMore: vi.fn(),+ });+ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-repository-add"));++ expect(+ screen.getByTestId("automation-setup-repository-loading"),+ ).toBeInTheDocument();+ });++ it("shows a settings secret tooltip when local repository token is missing", async () => {+ mockUseGitRepositories.mockReturnValue({+ data: {+ pages: [+ {+ items: [],+ missing_token: true,+ next_page_id: null,+ },+ ],+ },+ isError: false,+ isLoading: false,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ onLoadMore: vi.fn(),+ });+ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-repository-add"));++ expect(+ await screen.findByTestId("automation-setup-repository-token-tooltip"),+ ).toHaveAccessibleName("AUTOMATION_SETUP$GITHUB_TOKEN_REQUIRED_TOOLTIP");+ expect(+ screen.getByTestId("automation-setup-repository-custom"),+ ).toBeInTheDocument();+ });++ it("removes one plugin row from the module", async () => {+ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-add-plugin"));+ await user.click(screen.getByTestId("automation-setup-add-plugin"));+ expect(+ screen.getByTestId("automation-setup-plugin-source-1"),+ ).toBeInTheDocument();++ await user.click(screen.getByTestId("automation-setup-plugin-remove-1"));++ expect(+ screen.queryByTestId("automation-setup-plugin-source-1"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-plugin-source"),+ ).toBeInTheDocument();+ });++ it("creates a draft with every plugin that has a source", async () => {+ vi.mocked(AutomationService.createAutomationDraft).mockResolvedValue({+ id: "automation-plugins",+ });++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-add-plugin"));+ expect(screen.getByTestId("automation-setup-plugin-ref")).toHaveValue(+ "main",+ );+ expect(screen.getByTestId("automation-setup-plugin-remove")).toHaveClass(+ "size-6",+ );+ await user.type(+ screen.getByTestId("automation-setup-plugin-source"),+ "github:org/blockers-plugin",+ );+ await user.click(screen.getByTestId("automation-setup-add-plugin"));+ const pluginModule = screen.getByTestId("automation-setup-plugin-module");+ expect(pluginModule).toContainElement(+ screen.getByTestId("automation-setup-add-plugin"),+ );+ expect(pluginModule).toContainElement(+ screen.getByTestId("automation-setup-plugin-source-1"),+ );+ expect(+ within(pluginModule).getAllByText("AUTOMATION_SETUP$PLUGIN_SOURCE"),+ ).toHaveLength(1);+ expect(+ within(pluginModule).getAllByText("AUTOMATION_SETUP$PLUGIN_REF"),+ ).toHaveLength(1);+ expect(+ screen+ .getByTestId("automation-setup-plugin-ref")+ .compareDocumentPosition(+ screen.getByTestId("automation-setup-plugin-remove"),+ ) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(screen.getByTestId("automation-setup-plugin-ref-1")).toHaveValue(+ "main",+ );+ await user.type(+ screen.getByTestId("automation-setup-plugin-source-1"),+ "github:org/review-plugin",+ );++ await user.click(screen.getByTestId("automation-setup-create"));++ await waitFor(() =>+ expect(AutomationService.createAutomationDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ plugins: [+ { source: "github:org/blockers-plugin", ref: "main" },+ { source: "github:org/review-plugin", ref: "main" },+ ],+ }),+ "plugin",+ ),+ );+ });+it("creates custom bundle drafts with entrypoint and setup script path", async () => {vi.mocked(AutomationService.uploadAutomationTarball).mockResolvedValue("oh-internal://uploads/custom-archive",@@ -358,6 +1005,9 @@ describe("AutomationSetupPanel", () => {kind: "custom",});+ await user.click(+ screen.getByTestId("automation-setup-custom-details-toggle"),+ );await user.clear(screen.getByTestId("automation-setup-entrypoint"));await user.type(screen.getByTestId("automation-setup-entrypoint"),@@ -379,11 +1029,682 @@ describe("AutomationSetupPanel", () => {expect.objectContaining({tarball_path: "oh-internal://uploads/custom-archive",entrypoint: "python3 main.py --once",- enabled: false,setup_script_path: "setup.sh",}),"custom",);expect(mockNavigate).toHaveBeenCalledWith("/automations/automation-custom");});++ describe("server-backed drafts (PR OpenHands/automation#417)", () => {+ const dispatchableDraft: AutomationDraftApiResponse = {+ id: "draft-1",+ endpoint: "/v1/preset/prompt",+ name: "Review Every Pull Request",+ draft: {} as never,+ validationErrors: null,+ dispatchable: true,+ sourceAutomationId: null,+ materializedAutomationId: null,+ lastTestRunId: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ };++ beforeEach(() => {+ vi.mocked(AutomationService.supportsAutomationDrafts).mockReturnValue(+ true,+ );+ vi.mocked(useDeploymentCapabilities).mockReturnValue({+ data: {+ ready: true,+ features: ["automationDrafts"],+ triggerKinds: ["cron", "event"],+ eventSources: [],+ eventTypes: [],+ triggers: {},+ },+ isLoading: false,+ } as never);+ });++ it("tags the conversation as automation setup mode when opened", async () => {+ renderPanel();++ await waitFor(() =>+ expect(+ AgentServerConversationService.updateConversationTags,+ ).toHaveBeenCalledWith(+ "conv-1",+ expect.objectContaining({ automationsetup: "draft" }),+ ),+ );+ });++ it("does not overwrite tags before conversation tags have loaded", async () => {+ const value: NavigationContextValue = {+ currentPath: "/conversations/conv-1",+ conversationId: "conv-1",+ isNavigating: false,+ navigate: mockNavigate,+ };+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ });++ render(+ <QueryClientProvider client={queryClient}>+ <NavigationProvider value={value}>+ <AutomationSetupPanel+ draft={{ prompt: "Edit automation", kind: "prompt" }}+ conversationId="conv-1"+ />+ </NavigationProvider>+ </QueryClientProvider>,+ );++ await act(async () => {+ await Promise.resolve();+ });++ expect(+ AgentServerConversationService.updateConversationTags,+ ).not.toHaveBeenCalled();+ });++ it("omits an empty prompt when saving a partial prompt draft", async () => {+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue({+ ...dispatchableDraft,+ draft: { name: "New Automation" } as never,+ validationErrors: null,+ });++ const user = userEvent.setup();++ renderPanel({ prompt: "", kind: "prompt" });++ await user.click(screen.getByTestId("automation-setup-save-draft"));++ await waitFor(() =>+ expect(AutomationService.createServerDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ endpoint: "/v1/preset/prompt",+ draft: expect.not.objectContaining({ prompt: expect.any(String) }),+ }),+ ),+ );+ });++ it("creates a server draft on Save draft and updates it on the next save", async () => {+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue({+ ...dispatchableDraft,+ validationErrors: null,+ });+ vi.mocked(AutomationService.updateServerDraft).mockResolvedValue({+ ...dispatchableDraft,+ updatedAt: "2026-01-01T00:00:01.000Z",+ });++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-save-draft"));++ await waitFor(() =>+ expect(AutomationService.createServerDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ endpoint: "/v1/preset/prompt",+ draft: expect.objectContaining({+ prompt: "Review every pull request",+ }),+ }),+ ),+ );+ expect(screen.getByTestId("automation-setup-status")).toHaveTextContent(+ "AUTOMATION_SETUP$DRAFT_SAVED",+ );+ expect(+ screen.getByTestId("automation-setup-draft-details"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-draft-validity"),+ ).toHaveTextContent("AUTOMATION_SETUP$READY_TO_TEST");++ // Second save reuses the persisted id rather than creating again.+ await user.click(screen.getByTestId("automation-setup-save-draft"));+ await waitFor(() =>+ expect(AutomationService.updateServerDraft).toHaveBeenCalledWith(+ "draft-1",+ expect.objectContaining({ endpoint: "/v1/preset/prompt" }),+ ),+ );+ 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,+ }),+ );++ const user = userEvent.setup();+ renderPanel({ prompt: "Run a custom security check", kind: "custom" });++ await user.click(screen.getByTestId("automation-setup-save-draft"));++ await waitFor(() =>+ expect(AutomationService.createServerDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ endpoint: "/v1",+ draft: expect.objectContaining({+ tarball_path: "oh-internal://uploads/custom-archive",+ }),+ }),+ ),+ );+ await waitFor(() =>+ 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",+ );+ });++ it("tags the conversation with the server draft id after saving", async () => {+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue(+ dispatchableDraft,+ );++ const user = userEvent.setup();+ renderPanel(undefined, "conv-1", { existing: "tag" });++ await user.click(screen.getByTestId("automation-setup-save-draft"));++ await waitFor(() =>+ expect(+ AgentServerConversationService.updateConversationTags,+ ).toHaveBeenCalledWith(+ "conv-1",+ expect.objectContaining({+ existing: "tag",+ automationsetup: "draft",+ automationdraftid: "draft-1",+ }),+ ),+ );+ });++ it("hydrates a tagged server draft when the panel opens", async () => {+ vi.mocked(AutomationService.getServerDraft).mockResolvedValue({+ ...dispatchableDraft,+ name: "Saved Tagged Draft",+ draft: {+ prompt: "Use the persisted draft body",+ trigger: {+ type: "cron",+ schedule: "0 12 * * *",+ timezone: "UTC",+ },+ },+ });++ renderPanel({ prompt: "", kind: "prompt" }, "conv-1", {+ automationdraftid: "draft-1",+ });++ await waitFor(() =>+ expect(AutomationService.getServerDraft).toHaveBeenCalledWith(+ "draft-1",+ ),+ );+ expect(screen.getByTestId("automation-setup-name")).toHaveValue(+ "Saved Tagged Draft",+ );+ expect(screen.getByTestId("automation-setup-prompt")).toHaveValue(+ "Use the persisted draft body",+ );+ expect(+ screen.getByTestId("automation-setup-draft-details"),+ ).toBeInTheDocument();+ expect(getAutomationFormSession("conv-1")).toEqual(+ expect.objectContaining({+ serverDraftId: "draft-1",+ form: expect.objectContaining({+ prompt: "Use the persisted draft body",+ }),+ }),+ );+ });++ it("does not let the setup-mode tag write clobber a saved draft id", async () => {+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue(+ dispatchableDraft,+ );+ let resolveSetupTagWrite: (value: {+ tags: Record<string, string>;+ }) => void;+ const setupTagWrite = new Promise<{ tags: Record<string, string> }>(+ (resolve) => {+ resolveSetupTagWrite = resolve;+ },+ );+ vi.mocked(AgentServerConversationService.updateConversationTags)+ .mockImplementationOnce(() => setupTagWrite as never)+ .mockImplementationOnce(+ async (_conversationId, tags) => ({ tags }) as never,+ );++ const user = userEvent.setup();+ renderPanel(undefined, "conv-1", { existing: "tag" });++ await waitFor(() =>+ expect(+ AgentServerConversationService.updateConversationTags,+ ).toHaveBeenCalledTimes(1),+ );++ await user.click(screen.getByTestId("automation-setup-save-draft"));+ await waitFor(() =>+ expect(AutomationService.createServerDraft).toHaveBeenCalled(),+ );+ expect(+ AgentServerConversationService.updateConversationTags,+ ).toHaveBeenCalledTimes(1);++ resolveSetupTagWrite!({+ tags: { existing: "tag", automationsetup: "draft" },+ });++ await waitFor(() =>+ expect(+ AgentServerConversationService.updateConversationTags,+ ).toHaveBeenCalledTimes(2),+ );+ expect(+ vi.mocked(AgentServerConversationService.updateConversationTags).mock+ .calls[1][1],+ ).toEqual(+ expect.objectContaining({+ existing: "tag",+ automationsetup: "draft",+ automationdraftid: "draft-1",+ }),+ );+ });++ it("shows a missing-draft message and creates a fresh draft after a tagged draft was deleted", async () => {+ vi.mocked(AutomationService.getServerDraft).mockRejectedValue({+ response: { status: 404 },+ });+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue({+ ...dispatchableDraft,+ id: "draft-2",+ });++ const user = userEvent.setup();+ renderPanel(+ { prompt: "Recreate the automation", kind: "prompt" },+ "conv-1",+ { automationdraftid: "draft-missing" },+ );++ await screen.findByTestId("automation-setup-draft-missing");+ await user.click(screen.getByTestId("automation-setup-save-draft"));++ await waitFor(() =>+ expect(AutomationService.createServerDraft).toHaveBeenCalled(),+ );+ expect(AutomationService.updateServerDraft).not.toHaveBeenCalledWith(+ "draft-missing",+ expect.anything(),+ );+ expect(+ AgentServerConversationService.updateConversationTags,+ ).toHaveBeenCalledWith(+ "conv-1",+ expect.objectContaining({ automationdraftid: "draft-2" }),+ );+ });++ it("persists then dispatches the draft on Test", async () => {+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue(+ dispatchableDraft,+ );+ vi.mocked(AutomationService.updateServerDraft).mockResolvedValue(+ dispatchableDraft,+ );+ vi.mocked(AutomationService.dispatchServerDraft).mockResolvedValue({+ id: "run-1",+ status: "PENDING" as never,+ conversation_id: "conv-run-1",+ bash_command_id: null,+ error_detail: null,+ started_at: "2026-01-01T00:00:00.000Z",+ completed_at: null,+ });++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-test"));++ await waitFor(() =>+ expect(AutomationService.dispatchServerDraft).toHaveBeenCalledWith(+ "draft-1",+ ),+ );+ expect(AutomationService.validateDraft).not.toHaveBeenCalled();+ expect(screen.getByTestId("automation-setup-status")).toHaveTextContent(+ "AUTOMATION_SETUP$TEST_DISPATCHED",+ );+ 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 user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-test"));++ await waitFor(() =>+ expect(screen.getByTestId("automation-setup-status")).toHaveTextContent(+ "Minimum interval is 5 minutes.",+ ),+ );+ expect(AutomationService.dispatchServerDraft).not.toHaveBeenCalled();+ });++ it("shows a public URL notice and collapses the test payload for event triggers", async () => {+ const user = userEvent.setup();+ renderPanel();++ expect(+ screen.queryByTestId("automation-setup-event-public-url-notice"),+ ).not.toBeInTheDocument();++ await user.click(screen.getByText("AUTOMATIONS$DETAIL$TRIGGER_EVENT"));++ expect(+ screen.getByTestId("automation-setup-event-public-url-notice"),+ ).toHaveTextContent("AUTOMATION_SETUP$EVENT_PUBLIC_URL_NOTICE");+ expect(+ screen.getByTestId("automation-setup-event-public-url-notice"),+ ).not.toHaveClass("bg-tertiary");+ expect(+ screen+ .getByTestId("automation-setup-event-source")+ .compareDocumentPosition(+ screen.getByTestId("automation-setup-event-public-url-notice"),+ ) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(+ screen.queryByTestId("automation-setup-event-test-payload"),+ ).not.toBeInTheDocument();++ await user.click(+ screen.getByTestId("automation-setup-event-test-payload-toggle"),+ );+ expect(+ screen.getByTestId("automation-setup-event-test-payload"),+ ).toBeInTheDocument();++ await user.click(+ screen.getByTestId("automation-setup-event-test-payload-toggle"),+ );+ expect(+ screen.queryByTestId("automation-setup-event-test-payload"),+ ).not.toBeInTheDocument();+ });++ it("sends synthetic JSON payload when testing an event draft", async () => {+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue(+ dispatchableDraft,+ );+ vi.mocked(AutomationService.dispatchServerDraft).mockResolvedValue({+ id: "run-1",+ status: "PENDING" as never,+ conversation_id: "conv-run-1",+ bash_command_id: null,+ error_detail: null,+ started_at: "2026-01-01T00:00:00.000Z",+ completed_at: null,+ automation_id: "auto-draft-1",+ } as never);++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByText("AUTOMATIONS$DETAIL$TRIGGER_EVENT"));+ await user.click(+ screen.getByTestId("automation-setup-event-test-payload-toggle"),+ );+ const payloadInput = await screen.findByTestId(+ "automation-setup-event-test-payload",+ );+ fireEvent.change(payloadInput, {+ target: {+ value: JSON.stringify({ type: "issue.created", action: "opened" }),+ },+ });+ await user.click(screen.getByTestId("automation-setup-test"));++ await waitFor(() =>+ expect(AutomationService.dispatchServerDraft).toHaveBeenCalledWith(+ "draft-1",+ { eventPayload: { type: "issue.created", action: "opened" } },+ ),+ );+ });++ it("registers a custom webhook source before testing an event draft", async () => {+ vi.mocked(useDeploymentCapabilities).mockReturnValue({+ data: {+ ready: true,+ features: ["automationDrafts", "webhookDelivery"],+ triggerKinds: ["cron", "event"],+ eventSources: ["github", "linear"],+ eventTypes: ["issues.*", "issue_comment.created"],+ triggers: {},+ },+ isLoading: false,+ } as never);+ vi.mocked(AutomationService.createCustomWebhook).mockResolvedValue({+ id: "webhook-1",+ org_id: "org-1",+ name: "Incident webhook",+ source: "incident-alerts",+ webhook_url:+ "https://app.all-hands.dev/v1/events/org-1/incident-alerts",+ event_key_expr: "event.type",+ signature_header: "X-Incident-Signature",+ signature_scheme: "hmac_sha256_hex",+ enabled: true,+ created_at: "2026-01-01T00:00:00.000Z",+ updated_at: "2026-01-01T00:00:00.000Z",+ webhook_secret: "generated-secret",+ });+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue(+ dispatchableDraft,+ );+ vi.mocked(AutomationService.dispatchServerDraft).mockResolvedValue({+ id: "run-1",+ status: "PENDING" as never,+ conversation_id: "conv-run-1",+ bash_command_id: null,+ error_detail: null,+ started_at: "2026-01-01T00:00:00.000Z",+ completed_at: null,+ automation_id: "auto-draft-1",+ } as never);++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByText("AUTOMATIONS$DETAIL$TRIGGER_EVENT"));+ expect(+ screen.queryByTestId("automation-setup-custom-webhook-enabled"),+ ).not.toBeInTheDocument();+ expect(screen.getByTestId("automation-setup-event-source")).toHaveValue(+ "GitHub",+ );+ await user.click(screen.getByTestId("automation-setup-event-source"));+ expect(+ screen.queryByTestId("automation-setup-event-source-menu"),+ ).not.toBeInTheDocument();+ await user.click(+ screen.getByTestId("automation-setup-event-source-toggle"),+ );+ expect(+ screen.getByTestId("automation-setup-event-source-option-linear"),+ ).toBeInTheDocument();+ const custom = screen.getByTestId("automation-setup-event-source-custom");+ expect(+ screen+ .getByTestId("automation-setup-event-source-option-github")+ .compareDocumentPosition(custom) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(+ document.querySelector(+ '#automation-setup-event-key-options option[value="issues.*"]',+ ),+ ).not.toBeNull();+ await user.click(custom);+ fireEvent.change(screen.getByTestId("automation-setup-event-source"), {+ target: { value: "incident-alerts" },+ });+ expect(+ screen.getByTestId("automation-setup-custom-webhook-enabled"),+ ).toBeInTheDocument();+ await user.click(+ screen.getByTestId("automation-setup-event-source-toggle"),+ );+ expect(+ screen.getByTestId("automation-setup-event-source-option-github"),+ ).toBeInTheDocument();+ 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",+ );+ fireEvent.change(+ screen.getByTestId("automation-setup-custom-webhook-event-key-expr"),+ { target: { value: "event.type" } },+ );+ fireEvent.change(+ screen.getByTestId("automation-setup-custom-webhook-signature-header"),+ { target: { value: "X-Incident-Signature" } },+ );+ await user.click(screen.getByTestId("automation-setup-test"));++ await waitFor(() =>+ expect(AutomationService.createCustomWebhook).toHaveBeenCalledWith({+ name: "Incident webhook",+ source: "incident-alerts",+ event_key_expr: "event.type",+ signature_header: "X-Incident-Signature",+ signature_scheme: "hmac_sha256_hex",+ }),+ );+ expect(AutomationService.createServerDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ draft: expect.objectContaining({+ trigger: expect.objectContaining({+ type: "event",+ source: "incident-alerts",+ }),+ }),+ }),+ );+ });++ it("requires valid JSON before testing an event draft", async () => {+ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByText("AUTOMATIONS$DETAIL$TRIGGER_EVENT"));+ await user.click(+ screen.getByTestId("automation-setup-event-test-payload-toggle"),+ );+ const payloadInput = await screen.findByTestId(+ "automation-setup-event-test-payload",+ );+ fireEvent.change(payloadInput, { target: { value: "not json" } });+ await user.click(screen.getByTestId("automation-setup-test"));++ expect(screen.getByTestId("automation-setup-status")).toHaveTextContent(+ "AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_INVALID",+ );+ expect(AutomationService.createServerDraft).not.toHaveBeenCalled();+ expect(AutomationService.dispatchServerDraft).not.toHaveBeenCalled();+ });++ it("deletes the persisted draft after a successful create", async () => {+ vi.mocked(AutomationService.createServerDraft).mockResolvedValue(+ dispatchableDraft,+ );+ vi.mocked(AutomationService.deleteServerDraft).mockResolvedValue();+ vi.mocked(AutomationService.createAutomationDraft).mockResolvedValue({+ id: "automation-final",+ });++ const user = userEvent.setup();+ renderPanel();++ // Save first so a draft id exists, then finalize.+ await user.click(screen.getByTestId("automation-setup-save-draft"));+ await waitFor(() =>+ expect(AutomationService.createServerDraft).toHaveBeenCalled(),+ );++ await user.click(screen.getByTestId("automation-setup-create"));++ await waitFor(() =>+ expect(AutomationService.deleteServerDraft).toHaveBeenCalledWith(+ "draft-1",+ ),+ );+ expect(+ AgentServerConversationService.updateConversationTags,+ ).toHaveBeenCalledWith(+ "conv-1",+ expect.not.objectContaining({ automationdraftid: expect.any(String) }),+ );+ expect(mockNavigate).toHaveBeenCalledWith(+ "/automations/automation-final",+ );+ });+ });});diff --git a/__tests__/components/automations/detail/active-status-badge.test.tsx b/__tests__/components/automations/detail/active-status-badge.test.tsxindex 824ba8c06f..7c6dcdd803 100644--- a/__tests__/components/automations/detail/active-status-badge.test.tsx+++ b/__tests__/components/automations/detail/active-status-badge.test.tsx@@ -5,16 +5,25 @@ import { I18nKey } from "#/i18n/declaration";describe("ActiveStatusBadge", () => {it.each([- [true, I18nKey.AUTOMATIONS$DETAIL$ACTIVE, "active-status-badge-active"],[- false,+ { enabled: true },+ I18nKey.AUTOMATIONS$DETAIL$ACTIVE,+ "active-status-badge-active",+ ],+ [+ { enabled: false },I18nKey.AUTOMATIONS$DETAIL$INACTIVE,"active-status-badge-inactive",],+ [+ { enabled: false, state: "DRAFT" },+ I18nKey.AUTOMATIONS$DETAIL$DRAFT,+ "active-status-badge-draft",+ ],])(- "renders the matching label and testid when active=%s",- (active, labelKey, testId) => {- render(<ActiveStatusBadge active={active} />);+ "renders the matching label and testid for automation %o",+ (automation, labelKey, testId) => {+ render(<ActiveStatusBadge automation={automation} />);expect(screen.getByText(labelKey)).toBeInTheDocument();expect(screen.getByTestId(testId)).toBeInTheDocument();diff --git a/__tests__/components/automations/detail/detail-header.test.tsx b/__tests__/components/automations/detail/detail-header.test.tsxindex 6f31537938..2b5f509cc6 100644--- a/__tests__/components/automations/detail/detail-header.test.tsx+++ b/__tests__/components/automations/detail/detail-header.test.tsx@@ -34,6 +34,21 @@ function renderHeader();}+describe("DetailHeader — status badge", () => {+ it("labels draft automations as draft instead of inactive", () => {+ renderHeader({+ automation: { ...disabledAutomation, state: "DRAFT" },+ });++ expect(screen.getByTestId("active-status-badge-draft")).toHaveTextContent(+ I18nKey.AUTOMATIONS$DETAIL$DRAFT,+ );+ expect(+ screen.queryByTestId("active-status-badge-inactive"),+ ).not.toBeInTheDocument();+ });+});+describe("DetailHeader — enabled toggle gating", () => {it("hides the switch and Turn on when canToggle is false but keeps Delete", async () => {// Arrange — a manager who did not create this disabled automation.diff --git a/__tests__/components/automations/detail/disabled-reason-banner.test.tsx b/__tests__/components/automations/detail/disabled-reason-banner.test.tsxindex d3580b217b..b14caeddb5 100644--- a/__tests__/components/automations/detail/disabled-reason-banner.test.tsx+++ b/__tests__/components/automations/detail/disabled-reason-banner.test.tsx@@ -30,11 +30,27 @@ describe("DisabledReasonBanner", () => {it("renders nothing for an inactive automation with no recorded reason", () => {const { container } = render(- <DisabledReasonBanner automation={{ ...baseAutomation, disabled_reason: null }} />,+ <DisabledReasonBanner+ automation={{ ...baseAutomation, disabled_reason: null }}+ />,);expect(container.firstChild).toBeNull();});+ it("renders nothing for draft automations even if they carry a disable reason", () => {+ const { container } = render(+ <DisabledReasonBanner+ automation={{+ ...baseAutomation,+ state: "DRAFT",+ disabled_reason: "Automation moved to draft by user",+ }}+ />,+ );++ expect(container.firstChild).toBeNull();+ });+it("surfaces the automatic-pause reason text and timestamp", () => {const reason ="Paused automatically: auth — Invalid API key. This failed the last 3 runs and needs a configuration fix.";@@ -43,17 +59,24 @@ describe("DisabledReasonBanner", () => {automation={{...baseAutomation,disabled_reason: reason,- disabled_detail: { reason: "consecutive_permanent_failures", source: "consecutive_permanent_failures" },+ disabled_detail: {+ reason: "consecutive_permanent_failures",+ source: "consecutive_permanent_failures",+ },disabled_at: "2026-09-14T10:00:00Z",}}/>,);- expect(screen.getByTestId("automation-disabled-reason-banner")).toBeInTheDocument();- expect(screen.getByTestId("automation-disabled-reason-text")).toHaveTextContent(- reason,- );- expect(screen.getByTestId("automation-disabled-reason-timestamp")).toBeInTheDocument();+ expect(+ screen.getByTestId("automation-disabled-reason-banner"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("automation-disabled-reason-text"),+ ).toHaveTextContent(reason);+ expect(+ screen.getByTestId("automation-disabled-reason-timestamp"),+ ).toBeInTheDocument();});it("hides the timestamp when disabled_at is missing or invalid", () => {@@ -62,13 +85,18 @@ describe("DisabledReasonBanner", () => {automation={{...baseAutomation,disabled_reason: "Paused automatically: the last 5 runs all failed.",- disabled_detail: { reason: "consecutive_failures", source: "consecutive_failures" },+ disabled_detail: {+ reason: "consecutive_failures",+ source: "consecutive_failures",+ },disabled_at: null,}}/>,);- expect(screen.queryByTestId("automation-disabled-reason-timestamp")).toBeNull();+ expect(+ screen.queryByTestId("automation-disabled-reason-timestamp"),+ ).toBeNull();});it("hides the timestamp for an epoch/zero disabled_at", () => {@@ -77,13 +105,18 @@ describe("DisabledReasonBanner", () => {automation={{...baseAutomation,disabled_reason: "Paused automatically: the last 5 runs all failed.",- disabled_detail: { reason: "consecutive_failures", source: "consecutive_failures" },+ disabled_detail: {+ reason: "consecutive_failures",+ source: "consecutive_failures",+ },disabled_at: "1970-01-01T00:00:00Z",}}/>,);- expect(screen.queryByTestId("automation-disabled-reason-timestamp")).toBeNull();+ expect(+ screen.queryByTestId("automation-disabled-reason-timestamp"),+ ).toBeNull();});it("substitutes the manual-disable label", () => {@@ -98,9 +131,11 @@ describe("DisabledReasonBanner", () => {/>,);- expect(screen.getByTestId("automation-disabled-reason-text")).toHaveTextContent(- I18nKey.AUTOMATIONS$DETAIL$DISABLED_MANUAL,- );- expect(screen.queryByTestId("automation-disabled-reason-timestamp")).toBeNull();+ expect(+ screen.getByTestId("automation-disabled-reason-text"),+ ).toHaveTextContent(I18nKey.AUTOMATIONS$DETAIL$DISABLED_MANUAL);+ expect(+ screen.queryByTestId("automation-disabled-reason-timestamp"),+ ).toBeNull();});});diff --git a/__tests__/components/chat/chat-interface.test.tsx b/__tests__/components/chat/chat-interface.test.tsxindex 9c65d743c6..84b3806146 100644--- a/__tests__/components/chat/chat-interface.test.tsx+++ b/__tests__/components/chat/chat-interface.test.tsx@@ -301,6 +301,16 @@ describe("ChatInterface - Empty state", () => {expect(repoSuggestions).toContain(suggestion.textContent);});});++ it("hides the empty-state suggestions in an automation thread", () => {+ renderWithProviders(+ <MemoryRouter>+ <ChatInterface showEmptyStateSuggestions={false} />+ </MemoryRouter>,+ );++ expect(screen.queryByTestId("chat-suggestions")).not.toBeInTheDocument();+ });});describe("ChatInterface - Scroll-up loads older events", () => {diff --git a/__tests__/components/features/conversation-panel/conversation-panel-list-helpers.test.ts b/__tests__/components/features/conversation-panel/conversation-panel-list-helpers.test.tsindex 2453a0277f..e8dfc40a95 100644--- a/__tests__/components/features/conversation-panel/conversation-panel-list-helpers.test.ts+++ b/__tests__/components/features/conversation-panel/conversation-panel-list-helpers.test.ts@@ -21,6 +21,7 @@ import {UNNAMED_AUTOMATION_FACET,} from "#/components/features/conversation-panel/conversation-panel-list-helpers";import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";+import { I18nKey } from "#/i18n/declaration";import { ExecutionStatus } from "#/types/agent-server/core";const base: Omit<AppConversation, "id" | "title" | "workspace"> = {@@ -297,18 +298,19 @@ describe("conversation-panel-list-helpers", () => {["alpha-1", 1],]);+ expect([+ ...getGroupDiscoveryConversationIds(items, pageByConversationId, "local"),+ ]).toEqual(["none-1", "alpha-1"]);+expect([...getGroupDiscoveryConversationIds(items,pageByConversationId,"local",+ {+ forceIncludeConversationId: "none-2",+ },),- ]).toEqual(["none-1", "alpha-1"]);-- expect([- ...getGroupDiscoveryConversationIds(items, pageByConversationId, "local", {- forceIncludeConversationId: "none-2",- }),]).toEqual(["none-1", "alpha-1", "none-2"]);const grouped = groupConversations(items, "local", "updated", {@@ -737,6 +739,7 @@ describe("conversation-panel-list-helpers", () => {title: "internal title stamp",automationname: "Nightly Audit",automationtrigger: "cron",+ automationsetup: "draft",},},{@@ -751,15 +754,21 @@ describe("conversation-panel-list-helpers", () => {{ ...base, id: "t4", title: "t4", tags: null },];expect(collectTagFacets(conversations)).toEqual([+ "automationsetup=draft","origin=slack","owner=alice","project=fracture",]);});- it("formats bare-tag facets (empty value) as just the key", () => {+ it("formats bare-tag facets (empty value) and setup facets readably", () => {+ const t = (key: I18nKey) =>+ key === I18nKey.AUTOMATIONS$DETAIL$DRAFT ? "Draft" : "Automation setup";expect(formatTagFacetLabel("work=")).toBe("work");expect(formatTagFacetLabel("project=fracture")).toBe("project=fracture");+ expect(formatTagFacetLabel("automationsetup=draft", t)).toBe(+ "Automation setup: Draft",+ );});const tagFilterFixtures: AppConversation[] = [diff --git a/__tests__/components/features/conversation-panel/conversation-tag-chips.test.tsx b/__tests__/components/features/conversation-panel/conversation-tag-chips.test.tsxindex f528d77b8e..a3c9fce057 100644--- a/__tests__/components/features/conversation-panel/conversation-tag-chips.test.tsx+++ b/__tests__/components/features/conversation-panel/conversation-tag-chips.test.tsx@@ -204,6 +204,17 @@ describe("ConversationTagChips", () => {expect(chip).toHaveAttribute("title", "Work");});+ it("shows automation setup draft as a readable key/value chip", () => {+ renderWithProviders(+ <ConversationTagChips tags={[["automationsetup", "draft"]]} />,+ );++ const chip = screen.getByTestId("conversation-card-tag-chip");+ const expected = "AUTOMATION_SETUP$TITLE: AUTOMATIONS$DETAIL$DRAFT";+ expect(chip).toHaveTextContent(expected);+ expect(chip).toHaveAttribute("title", expected);+ });+it("safely truncates emoji values while preserving the full tooltip", () => {const longValue = "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀";renderWithProviders(<ConversationTagChips tags={[["mood", longValue]]} />);diff --git a/__tests__/components/features/conversation-panel/conversation-tag-display.test.ts b/__tests__/components/features/conversation-panel/conversation-tag-display.test.tsindex 4439618e45..830b112f92 100644--- a/__tests__/components/features/conversation-panel/conversation-tag-display.test.ts+++ b/__tests__/components/features/conversation-panel/conversation-tag-display.test.ts@@ -103,8 +103,13 @@ describe("getDisplayConversationTags", () => {automationid: "3f2b6c1e-1111-4222-8333-abcdefabcdef",automationname: "Nightly Audit",automationrunid: "run-0001",+ automationsetup: "draft",+ automationdraftid: "draft-1",+ automationmaterializeddraftid: "auto-draft-1",+ automationeditid: "auto-1",}),).toEqual([+ ["automationsetup", "draft"],["origin", "slack"],["env", "prod"],["owner", "alice"],@@ -113,14 +118,16 @@ describe("getDisplayConversationTags", () => {it("ranks priority keys by their normalized name", () => {// The reserved-key filter normalizes the key, so the priority lookup must- // too — otherwise a cloud-stamped `Origin` sorts alphabetically instead of- // leading the row.+ // too — otherwise cloud-stamped priority tags sort alphabetically instead+ // of leading the row.expect(getDisplayConversationTags({env: "prod",Origin: "slack",+ " AutomationSetup ": "draft",}),).toEqual([+ [" AutomationSetup ", "draft"],["Origin", "slack"],["env", "prod"],]);@@ -158,6 +165,7 @@ describe("getConversationTagLabelKind", () => {["repo_name", "repo"],["selected_branch", "branch"],["archiveworkspacepath", "workspace"],+ ["automationsetup", "automation_setup"],["Appmode", "app_mode"],["worktools", "work_tools"],["Workwsid", "work_wsid"],@@ -178,6 +186,10 @@ describe("getConversationTagLabel", () => {return "Branch";case I18nKey.CONVERSATION_PANEL$PREVIEW_WORKSPACE:return "Workspace";+ case I18nKey.AUTOMATION_SETUP$TITLE:+ return "Automation setup";+ case I18nKey.AUTOMATIONS$DETAIL$DRAFT:+ return "Draft";case I18nKey.CONVERSATION_PANEL$PREVIEW_APP_MODE:return "App mode";case I18nKey.CONVERSATION_PANEL$PREVIEW_WORK_TOOLS:@@ -195,6 +207,12 @@ describe("getConversationTagLabel", () => {expect(getConversationTagLabel("archiveworkspacepath", t)).toBe("Workspace",);+ expect(getConversationTagLabel("automationsetup", t)).toBe(+ "Automation setup",+ );+ expect(formatConversationTagTooltip("automationsetup", "draft", t)).toBe(+ "Automation setup: Draft",+ );expect(getConversationTagLabel("Appmode", t)).toBe("App mode");expect(getConversationTagLabel("worktools", t)).toBe("Work tools");expect(getConversationTagLabel("Workwsid", t)).toBe("Workspace ID");diff --git a/__tests__/components/features/conversation/conversation-main.test.tsx b/__tests__/components/features/conversation/conversation-main.test.tsxindex 08dca2aeae..a2cd4fe263 100644--- a/__tests__/components/features/conversation/conversation-main.test.tsx+++ b/__tests__/components/features/conversation/conversation-main.test.tsx@@ -13,6 +13,7 @@ let mockIsMobile = false;let mockIsRightPanelShown = false;let mockLeftWidth = 50;let mockHasAutomationSetupHandoff = false;+let mockActiveConversationTags: Record<string, string> | null = null;const mockNavigate = vi.fn();const mockSetHasRightPanelToggled = vi.fn();@@ -54,7 +55,7 @@ vi.mock("#/api/automation-setup-handoff-store", () => ({vi.mock("#/hooks/query/use-active-conversation", () => ({useActiveConversation: () => ({- data: { title: "Daily Morning Haiku" },+ data: { title: "Daily Morning Haiku", tags: mockActiveConversationTags },}),}));@@ -195,19 +196,35 @@ describe("ConversationMain - Layout Transition Stability", () => {mockIsRightPanelShown = false;mockLeftWidth = 50;mockHasAutomationSetupHandoff = false;+ mockActiveConversationTags = null;chatInterfaceUnmount.mockClear();mockNavigate.mockClear();mockSetHasRightPanelToggled.mockClear();mockSetIsRightPanelShown.mockClear();});+ it("opens automation setup mode when the conversation has a draft tag", async () => {+ mockActiveConversationTags = { automationsetup: "draft" };++ renderConversationMain();++ expect(+ await screen.findByTestId("automation-setup-panel"),+ ).toBeInTheDocument();+ expect(mockSetHasRightPanelToggled).toHaveBeenCalledWith(true);+ expect(mockSetIsRightPanelShown).toHaveBeenCalledWith(true);+ });+it.each([["desktop", false],["mobile", true],])("renders ChatInterface at %s width", (_name, isMobile) => {mockIsMobile = isMobile;renderConversationMain();- expect(screen.getByTestId("chat-interface")).toBeInTheDocument();+ expect(screen.getByTestId("chat-interface")).toHaveAttribute(+ "data-show-git-control-bar",+ "true",+ );});it.each([@@ -242,8 +259,7 @@ describe("ConversationMain - Layout Transition Stability", () => {expect(screen.getByTestId("chat-interface")).toBeInTheDocument();});- it("uses a single automation setup top bar with splash back navigation", async () => {- const user = userEvent.setup();+ it("uses a single automation setup top bar", () => {mockIsRightPanelShown = true;mockHasAutomationSetupHandoff = true;@@ -271,10 +287,9 @@ describe("ConversationMain - Layout Transition Stability", () => {"data-composer-placeholder","AUTOMATION_SETUP$CONVERSATION_COMPOSER_PLACEHOLDER",);-- await user.click(screen.getByTestId("automation-setup-back"));-- expect(mockNavigate).toHaveBeenCalledWith("/");+ expect(+ screen.queryByTestId("automation-setup-back"),+ ).not.toBeInTheDocument();});it("keeps the automation form on a narrow window and toggles to the styled conversation", async () => {diff --git a/__tests__/hooks/query/use-automations-backend-switch.test.tsx b/__tests__/hooks/query/use-automations-backend-switch.test.tsxindex c719380b1e..b2f0597518 100644--- a/__tests__/hooks/query/use-automations-backend-switch.test.tsx+++ b/__tests__/hooks/query/use-automations-backend-switch.test.tsx@@ -13,6 +13,7 @@ import {import { ActiveBackendProvider } from "#/contexts/active-backend-context";import {useAutomations,+ useAutomationDrafts,useCancelAutomationRun,useDispatchAutomation,useDeleteAutomation,@@ -48,6 +49,9 @@ vi.mock("#/api/automation-service/automation-service.api", () => ({deleteAutomation: vi.fn(),updateAutomation: vi.fn(),toggleAutomation: vi.fn(),+ listServerDrafts: vi.fn(),+ getCapabilities: vi.fn(),+ supportsAutomationDrafts: vi.fn(),},}));@@ -124,6 +128,25 @@ beforeEach(() => {vi.mocked(AutomationService.getAutomations).mockReset();vi.mocked(AutomationService.getAutomation).mockReset();vi.mocked(AutomationService.getAutomationRuns).mockReset();+ vi.mocked(AutomationService.listServerDrafts).mockReset();+ vi.mocked(AutomationService.listServerDrafts).mockResolvedValue({+ drafts: [],+ total: 0,+ });+ vi.mocked(AutomationService.getCapabilities).mockReset();+ vi.mocked(AutomationService.getCapabilities).mockResolvedValue({+ ready: true,+ features: ["automationDrafts"],+ triggerKinds: ["cron", "event"],+ eventSources: [],+ eventTypes: [],+ triggers: {},+ });+ vi.mocked(AutomationService.supportsAutomationDrafts).mockReset();+ vi.mocked(AutomationService.supportsAutomationDrafts).mockImplementation(+ (capabilities) =>+ Boolean(capabilities?.features?.includes("automationDrafts")),+ );vi.mocked(AutomationService.dispatchAutomation).mockReset();vi.mocked(AutomationService.dispatchAutomation).mockResolvedValue(automationRun,@@ -151,6 +174,70 @@ afterEach(() => {__resetActiveStoreForTests();});+describe("useAutomationDrafts — draft endpoint unavailability", () => {++ it("does not call the drafts endpoint when capabilities do not advertise drafts", async () => {+ vi.mocked(AutomationService.getCapabilities).mockResolvedValue({+ ready: true,+ features: [],+ triggerKinds: ["cron", "event"],+ eventSources: [],+ eventTypes: [],+ triggers: {},+ });++ const { result } = renderHook(() => useAutomationDrafts(), {+ wrapper: makeWrapper(),+ });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(result.current.data).toEqual({ drafts: [], total: 0 });+ expect(AutomationService.listServerDrafts).not.toHaveBeenCalled();+ });+ it("returns an empty draft list when the drafts fetch rejects with an axios-style error", async () => {+ const error = Object.assign(new Error("Not Found"), {+ response: { status: 404 },+ });+ vi.mocked(AutomationService.listServerDrafts).mockRejectedValue(error);++ const { result } = renderHook(() => useAutomationDrafts(), {+ wrapper: makeWrapper(),+ });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(result.current.data).toEqual({ drafts: [], total: 0 });+ });++ it("returns an empty draft list when the drafts fetch rejects with an SDK HttpError", async () => {+ // Cloud requests go through callCloudProxy, whose TypeScript client throws+ // an HttpError with `status` set directly on the error (not under `response`).+ const error = Object.assign(new Error("Not Found"), {+ name: "HttpError",+ status: 405,+ });+ vi.mocked(AutomationService.listServerDrafts).mockRejectedValue(error);++ const { result } = renderHook(() => useAutomationDrafts(), {+ wrapper: makeWrapper(),+ });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(result.current.data).toEqual({ drafts: [], total: 0 });+ });++ it("re-throws errors that are not draft-endpoint 404/405 responses", async () => {+ vi.mocked(AutomationService.listServerDrafts).mockRejectedValue(+ new Error("boom"),+ );++ const { result } = renderHook(() => useAutomationDrafts(), {+ wrapper: makeWrapper(),+ });++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(result.current.error).toBeInstanceOf(Error);+ });+});describe("automation hooks — backend switch", () => {it("useAutomations refetches when the active backend changes", async () => {// Arrange — mount under the local backend; capture the initial fetch.diff --git a/__tests__/hooks/query/use-task-polling.test.tsx b/__tests__/hooks/query/use-task-polling.test.tsxindex 50a69c78a6..49cc0f4ec4 100644--- a/__tests__/hooks/query/use-task-polling.test.tsx+++ b/__tests__/hooks/query/use-task-polling.test.tsx@@ -73,6 +73,7 @@ describe("useTaskPolling", () => {beforeEach(() => {vi.clearAllMocks();localStorage.clear();+ sessionStorage.clear();resetPendingTaskMessageLinkState();useOptimisticUserMessageStore.getState().clearPendingMessages();});@@ -80,6 +81,7 @@ describe("useTaskPolling", () => {afterEach(() => {queryClient?.clear();localStorage.clear();+ sessionStorage.clear();});it("moves pending task drafts onto the real conversation before redirecting", async () => {diff --git a/__tests__/hooks/use-auto-resize.test.tsx b/__tests__/hooks/use-auto-resize.test.tsxindex e524c5e8d9..2a7eb29503 100644--- a/__tests__/hooks/use-auto-resize.test.tsx+++ b/__tests__/hooks/use-auto-resize.test.tsx@@ -244,6 +244,20 @@ describe("automatic content-editable resizing", () => {expect(scenario.editable?.element.style.overflowY).toBe("hidden");});+ it("keeps an empty composer at the minimum height when the placeholder measures tall", () => {+ const scenario = createHookScenario({+ height: 20,+ maxHeight: 400,+ scrollHeight: 320,+ text: "",+ });++ scenario.animationFrames.flushAll();++ expect(scenario.editable?.element.style.height).toBe("20px");+ expect(scenario.editable?.element.style.overflowY).toBe("hidden");+ });+it("resizes without a height callback", () => {const scenario = createHookScenario({callbacks: false,diff --git a/__tests__/routes/automations-dashboard.test.tsx b/__tests__/routes/automations-dashboard.test.tsxindex 225e2bfd0f..ed2443d690 100644--- a/__tests__/routes/automations-dashboard.test.tsx+++ b/__tests__/routes/automations-dashboard.test.tsx@@ -55,6 +55,9 @@ vi.mock("#/api/automation-service/automation-service.api", () => ({default: {getAutomations: vi.fn(),getAutomationRuns: vi.fn(),+ listServerDrafts: vi.fn(),+ getCapabilities: vi.fn(),+ supportsAutomationDrafts: vi.fn(),checkHealth: vi.fn(),toggleAutomation: vi.fn(),updateAutomation: vi.fn(),@@ -141,6 +144,25 @@ beforeEach(() => {vi.mocked(AutomationService.checkHealth).mockReset();vi.mocked(AutomationService.checkHealth).mockResolvedValue({ status: "ok" });vi.mocked(AutomationService.getAutomations).mockReset();+ vi.mocked(AutomationService.listServerDrafts).mockReset();+ vi.mocked(AutomationService.listServerDrafts).mockResolvedValue({+ drafts: [],+ total: 0,+ });+ vi.mocked(AutomationService.getCapabilities).mockReset();+ vi.mocked(AutomationService.getCapabilities).mockResolvedValue({+ ready: true,+ features: ["automationDrafts"],+ triggerKinds: ["cron", "event"],+ eventSources: [],+ eventTypes: [],+ triggers: {},+ });+ vi.mocked(AutomationService.supportsAutomationDrafts).mockReset();+ vi.mocked(AutomationService.supportsAutomationDrafts).mockImplementation(+ (capabilities) =>+ Boolean(capabilities?.features?.includes("automationDrafts")),+ );vi.mocked(AutomationService.getAutomations).mockResolvedValue({automations: [okAutomation, brokenAutomation],total: 2,diff --git a/__tests__/routes/automations-list-behavior.test.tsx b/__tests__/routes/automations-list-behavior.test.tsxindex df9a46c895..a371665d54 100644--- a/__tests__/routes/automations-list-behavior.test.tsx+++ b/__tests__/routes/automations-list-behavior.test.tsx@@ -20,6 +20,12 @@ const mocks = vi.hoisted(() => ({isError: false,refetch: vi.fn(),},+ draftsState: {+ data: { drafts: [], total: 0 },+ isLoading: false,+ isError: false,+ refetch: vi.fn(),+ },dispatchState: {isPending: false,variables: undefined as string | undefined,@@ -28,12 +34,16 @@ const mocks = vi.hoisted(() => ({backendKind: "local" as "local" | "cloud",canManage: true,navigate: vi.fn(),+ useAutomationDrafts: vi.fn(),useAutomations: vi.fn(),useAutomationRunSummaries: vi.fn(),toggle: vi.fn(),remove: vi.fn(),+ removeDraft: vi.fn(),dispatch: vi.fn(),+ dispatchDraft: vi.fn(),importAutomation: vi.fn(),+ createConversation: vi.fn(),trackEnabled: vi.fn(),trackExported: vi.fn(),useTranslation: vi.fn(),@@ -88,17 +98,33 @@ vi.mock("#/hooks/query/use-automation-health", () => ({useAutomationHealth: () => mocks.healthState,}));+vi.mock("#/hooks/mutation/use-create-conversation", () => ({+ useCreateConversation: () => ({+ mutate: mocks.createConversation,+ isPending: false,+ }),+}));+vi.mock("#/hooks/query/use-automations", () => ({+ useAutomationDrafts: (options: unknown) => {+ mocks.useAutomationDrafts(options);+ return mocks.draftsState;+ },useAutomations: (options: unknown) => {mocks.useAutomations(options);return { ...mocks.automationsState, hasNextPage: false };},useToggleAutomation: () => ({ mutate: mocks.toggle }),useDeleteAutomation: () => ({ mutate: mocks.remove }),+ useDeleteAutomationDraft: () => ({ mutate: mocks.removeDraft }),useDispatchAutomation: () => ({mutate: mocks.dispatch,...mocks.dispatchState,}),+ useDispatchAutomationDraft: () => ({+ mutate: mocks.dispatchDraft,+ ...mocks.dispatchState,+ }),useImportAutomation: () => ({mutate: mocks.importAutomation,...mocks.importState,diff --git a/__tests__/routes/automations-list.test.tsx b/__tests__/routes/automations-list.test.tsxindex 469a36d07f..afe6bbbd93 100644--- a/__tests__/routes/automations-list.test.tsx+++ b/__tests__/routes/automations-list.test.tsx@@ -5,10 +5,11 @@ import userEvent from "@testing-library/user-event";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { MemoryRouter } from "react-router";import { HttpError } from "@openhands/typescript-client";-import { I18nKey } from "#/i18n/declaration";+import type { AutomationDraftListResponse } from "#/manifests/types";import AutomationService from "#/api/automation-service/automation-service.api";+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import { getCloudOrganizationMe } from "#/api/cloud/organization-service.api";import ProfilesService from "#/api/profiles-service/profiles-service.api";import {@@ -18,6 +19,21 @@ import {} from "#/api/backend-registry/active-store";import { ActiveBackendProvider } from "#/contexts/active-backend-context";import AutomationsList from "#/routes/automations-list";++vi.mock("#/components/shared/buttons/styled-tooltip", () => ({+ StyledTooltip: ({+ content,+ children,+ }: {+ content: React.ReactNode;+ children: React.ReactNode;+ }) => (+ <>+ {children}+ <span data-testid="styled-tooltip-content">{content}</span>+ </>+ ),+}));import type { Backend } from "#/api/backend-registry/types";import {AutomationRunStatus,@@ -26,14 +42,47 @@ import {} from "#/types/automation";import { AUTOMATION_STACK_SECTION_BOTTOM_CLASS } from "#/utils/automation-stack-section";+const mocks = vi.hoisted(() => ({+ createConversationMutate: vi.fn(),+ navigate: vi.fn(),+}));++vi.mock(+ "#/api/conversation-service/agent-server-conversation-service.api",+ () => ({+ default: {+ batchGetAppConversations: vi.fn(),+ updateConversationTags: vi.fn(),+ },+ }),+);++vi.mock("#/hooks/mutation/use-create-conversation", () => ({+ useCreateConversation: () => ({ mutate: mocks.createConversationMutate }),+}));++vi.mock("#/context/navigation-context", () => ({+ useNavigation: () => ({+ currentPath: "/automations",+ conversationId: null,+ isNavigating: false,+ navigate: mocks.navigate,+ }),+}));+vi.mock("#/api/automation-service/automation-service.api", () => ({default: {getAutomations: vi.fn(),+ listServerDrafts: vi.fn(),+ deleteServerDraft: vi.fn(),+ dispatchServerDraft: vi.fn(),updateAutomation: vi.fn(),toggleAutomation: vi.fn(),deleteAutomation: vi.fn(),dispatchAutomation: vi.fn(),checkHealth: vi.fn(),+ getCapabilities: vi.fn(),+ supportsAutomationDrafts: vi.fn(),},}));@@ -102,6 +151,49 @@ const listResponse: AutomationsResponse = {total: 1,};+const materializedDraftAutomation: Automation = {+ ...automation,+ id: "auto-draft-1",+ name: "Materialized test draft",+ enabled: false,+ state: "DRAFT",+};++const draftListResponse: AutomationDraftListResponse = {+ drafts: [+ {+ id: "draft-1",+ endpoint: "/v1/preset/prompt",+ name: "Saved setup draft",+ draft: { prompt: "Draft prompt" },+ validationErrors: null,+ dispatchable: true,+ sourceAutomationId: null,+ materializedAutomationId: "auto-draft-1",+ lastTestRunId: null,+ createdAt: "2026-01-02T00:00:00Z",+ updatedAt: "2026-01-02T00:00:00Z",+ },+ {+ id: "draft-event",+ endpoint: "/v1/preset/prompt",+ name: "Event setup draft",+ draft: {+ prompt: "Event prompt",+ trigger: { type: "event", source: "github", on: "pull_request" },+ },+ validationErrors: null,+ dispatchable: false,+ sourceAutomationId: null,+ materializedAutomationId: null,+ lastTestRunId: null,+ createdAt: "2026-01-03T00:00:00Z",+ updatedAt: "2026-01-03T00:00:00Z",+ },+ ],+ total: 2,+};+function renderList(queryClient?: QueryClient) {const client =queryClient ??@@ -129,10 +221,41 @@ beforeEach(() => {vi.mocked(AutomationService.checkHealth).mockResolvedValue({ status: "ok" });vi.mocked(AutomationService.getAutomations).mockReset();vi.mocked(AutomationService.getAutomations).mockResolvedValue(listResponse);+ vi.mocked(AutomationService.listServerDrafts).mockReset();+ vi.mocked(AutomationService.listServerDrafts).mockResolvedValue({+ drafts: [],+ total: 0,+ });+ vi.mocked(AutomationService.getCapabilities).mockReset();+ vi.mocked(AutomationService.getCapabilities).mockResolvedValue({+ ready: true,+ features: ["automationDrafts"],+ triggerKinds: ["cron", "event"],+ eventSources: [],+ eventTypes: [],+ triggers: {},+ });+ vi.mocked(AutomationService.supportsAutomationDrafts).mockReset();+ vi.mocked(AutomationService.supportsAutomationDrafts).mockImplementation(+ (capabilities) =>+ Boolean(capabilities?.features?.includes("automationDrafts")),+ );vi.mocked(AutomationService.updateAutomation).mockReset();vi.mocked(AutomationService.dispatchAutomation).mockReset();vi.mocked(AutomationService.deleteAutomation).mockReset();vi.mocked(AutomationService.deleteAutomation).mockResolvedValue(undefined);+ mocks.createConversationMutate.mockReset();+ mocks.navigate.mockReset();+ vi.mocked(+ AgentServerConversationService.batchGetAppConversations,+ ).mockReset();+ vi.mocked(+ AgentServerConversationService.batchGetAppConversations,+ ).mockResolvedValue([]);+ vi.mocked(AgentServerConversationService.updateConversationTags).mockReset();+ vi.mocked(+ AgentServerConversationService.updateConversationTags,+ ).mockResolvedValue({} as never);vi.mocked(ProfilesService.listProfiles).mockReset();vi.mocked(ProfilesService.listProfiles).mockResolvedValue({profiles: [],@@ -149,6 +272,180 @@ afterEach(() => {__resetActiveStoreForTests();});+describe("AutomationsList — draft sections", () => {++ it("does not request saved drafts when capabilities do not advertise drafts", async () => {+ vi.mocked(AutomationService.getCapabilities).mockResolvedValue({+ ready: true,+ features: [],+ triggerKinds: ["cron", "event"],+ eventSources: [],+ eventTypes: [],+ triggers: {},+ });++ renderList();++ await screen.findByText(automation.name);+ await waitFor(() =>+ expect(AutomationService.listServerDrafts).not.toHaveBeenCalled(),+ );+ expect(+ screen.queryByText(I18nKey.AUTOMATIONS$SAVED_DRAFTS),+ ).not.toBeInTheDocument();+ });+ it("renders saved setup drafts as actionable cards and hides materialized test artifacts", async () => {+ vi.mocked(AutomationService.getAutomations).mockResolvedValue({+ automations: [automation, materializedDraftAutomation],+ total: 2,+ });+ vi.mocked(AutomationService.listServerDrafts).mockResolvedValue(+ draftListResponse,+ );++ renderList();++ expect(+ await screen.findByText(I18nKey.AUTOMATIONS$SAVED_DRAFTS),+ ).toBeInTheDocument();+ expect(screen.getByText("Saved setup draft")).toBeInTheDocument();+ const draftCard = screen.getByTestId("automation-setup-draft-draft-1");+ expect(draftCard.parentElement).toHaveClass(+ "divide-y",+ "rounded-xl",+ "bg-surface",+ );+ expect(draftCard).toHaveClass("hover:bg-surface-raised");+ expect(+ within(draftCard).queryByText(I18nKey.AUTOMATIONS$DETAIL$DRAFT),+ ).not.toBeInTheDocument();+ expect(+ within(draftCard).getByTestId("automation-setup-draft-open-draft-1"),+ ).toBeInTheDocument();+ expect(+ within(draftCard).getByTestId("automation-setup-draft-resume-draft-1"),+ ).toBeInTheDocument();+ const activePlay = within(draftCard).getByTestId(+ "automation-setup-draft-test-draft-1",+ );+ expect(activePlay).toBeEnabled();+ expect(+ within(draftCard).getByTestId("styled-tooltip-content"),+ ).toHaveTextContent(I18nKey.AUTOMATION_SETUP$TEST_RUN);+ const inactivePlay = screen.getByTestId(+ "automation-setup-draft-test-draft-event",+ );+ expect(inactivePlay).toBeDisabled();+ expect(+ within(+ screen.getByTestId("automation-setup-draft-draft-event"),+ ).queryByTestId("styled-tooltip-content"),+ ).not.toBeInTheDocument();+ expect(+ within(draftCard).getByTestId("automation-setup-draft-delete-draft-1"),+ ).toBeInTheDocument();++ expect(+ screen.queryByText(I18nKey.AUTOMATIONS$MATERIALIZED_DRAFTS),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByText("Materialized test draft"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("automation-card-auto-draft-1"),+ ).not.toBeInTheDocument();+ });++ it("does not start a conversation when resuming a saved draft in this PR", async () => {+ const user = userEvent.setup();+ vi.mocked(AutomationService.listServerDrafts).mockResolvedValue(+ draftListResponse,+ );++ renderList();++ const draftCard = await screen.findByTestId(+ "automation-setup-draft-draft-1",+ );+ await user.click(+ within(draftCard).getByTestId("automation-setup-draft-resume-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 () => {+ const user = userEvent.setup();+ vi.mocked(AutomationService.getAutomations).mockResolvedValue(listResponse);+ vi.mocked(AutomationService.listServerDrafts).mockResolvedValue(+ draftListResponse,+ );+ vi.mocked(AutomationService.dispatchServerDraft).mockResolvedValue({+ id: "run-1",+ } as never);+ vi.mocked(AutomationService.deleteServerDraft).mockResolvedValue(undefined);++ renderList();++ const draftCard = await screen.findByTestId(+ "automation-setup-draft-draft-1",+ );+ await user.click(+ within(draftCard).getByTestId("automation-setup-draft-test-draft-1"),+ );+ await waitFor(() =>+ expect(AutomationService.dispatchServerDraft).toHaveBeenCalledWith(+ "draft-1",+ ),+ );++ await user.click(+ within(draftCard).getByTestId("automation-setup-draft-delete-draft-1"),+ );+ expect(+ screen.getByText(I18nKey.AUTOMATION_SETUP$DELETE_DRAFT_TITLE),+ ).toBeInTheDocument();+ await user.click(+ screen.getByTestId("automation-setup-draft-delete-confirm"),+ );+ await waitFor(() =>+ expect(AutomationService.deleteServerDraft).toHaveBeenCalledWith(+ "draft-1",+ ),+ );+ });++ it("treats a Cloud HttpError 404 from the drafts API as an empty drafts list", async () => {+ // Cloud draft calls run through callCloudProxy, which throws the shared+ // client's HttpError with `status` on the error itself (not under `response`).+ // A drafts-less automation service answers those routes with 404; the page+ // must degrade to an empty drafts list instead of the error banner.++ vi.mocked(AutomationService.getAutomations).mockResolvedValue(listResponse);+ vi.mocked(AutomationService.listServerDrafts).mockRejectedValue(+ new HttpError(404, "Not Found", { detail: "No such route" }),+ );++ renderList();++ await screen.findByText(automation.name);+ await waitFor(() => {+ expect(+ screen.queryByText(I18nKey.AUTOMATIONS$SAVED_DRAFTS),+ ).not.toBeInTheDocument();+ });+ expect(+ screen.queryByText(I18nKey.AUTOMATIONS$ERROR_TITLE),+ ).not.toBeInTheDocument();+ });+});+describe("AutomationsList — Edit from the row kebab", () => {it("opens the Edit modal pre-filled with the row's values when the active backend is local", async () => {// Arrange — local backend is active (default beforeEach); render the list@@ -385,50 +682,33 @@ describe("AutomationsList — Run now toasts", () => {expect(displayErrorToast).not.toHaveBeenCalled();});- it("does not dispatch when Run now is clicked on a disabled automation (grid view)", async () => {- // Arrange — single automation that is turned off.- const disabledAutomation: Automation = { ...automation, enabled: false };- vi.mocked(AutomationService.getAutomations).mockResolvedValue({- automations: [disabledAutomation],- total: 1,- });- const user = userEvent.setup();- renderList();- const button = await screen.findByTestId(- `automation-run-now-${disabledAutomation.id}`,- );-- // Act — userEvent honors the disabled attribute, so the click is suppressed.- await user.click(button);-- // Assert — the off-state gate prevents the dispatch API from firing.- expect(button).toBeDisabled();- expect(AutomationService.dispatchAutomation).not.toHaveBeenCalled();- });-- it("does not dispatch when Run now is clicked on a disabled automation (list view)", async () => {- // Arrange — pre-seed the stored view mode so the page mounts in list view,- // then return a single disabled automation.- window.localStorage.setItem("openhands-automations-view", "list");- const disabledAutomation: Automation = { ...automation, enabled: false };- vi.mocked(AutomationService.getAutomations).mockResolvedValue({- automations: [disabledAutomation],- total: 1,- });- const user = userEvent.setup();- renderList();- await screen.findByTestId(`automation-list-row-${disabledAutomation.id}`);- const button = screen.getByTestId(- `automation-run-now-${disabledAutomation.id}`,- );+ it.each([+ { viewMode: "grid", rowTestId: null },+ { viewMode: "list", rowTestId: `automation-list-row-${automation.id}` },+ ])(+ "does not dispatch when Run now is clicked on a disabled automation ($viewMode view)",+ async ({ viewMode, rowTestId }) => {+ if (viewMode === "list") {+ window.localStorage.setItem("openhands-automations-view", "list");+ }+ const disabledAutomation: Automation = { ...automation, enabled: false };+ vi.mocked(AutomationService.getAutomations).mockResolvedValue({+ automations: [disabledAutomation],+ total: 1,+ });+ const user = userEvent.setup();+ renderList();+ if (rowTestId) await screen.findByTestId(rowTestId);+ const button = await screen.findByTestId(+ `automation-run-now-${disabledAutomation.id}`,+ );- // Act- await user.click(button);+ await user.click(button);- // Assert- expect(button).toBeDisabled();- expect(AutomationService.dispatchAutomation).not.toHaveBeenCalled();- });+ expect(button).toBeDisabled();+ expect(AutomationService.dispatchAutomation).not.toHaveBeenCalled();+ },+ );it("shows an error toast when the dispatch API rejects", async () => {// Arrange — service rejects with a plain Error so the fallback branch fires.diff --git a/__tests__/routes/automations-subpages-absent.test.tsx b/__tests__/routes/automations-subpages-absent.test.tsxindex 245b0e994f..4813d8eb13 100644--- a/__tests__/routes/automations-subpages-absent.test.tsx+++ b/__tests__/routes/automations-subpages-absent.test.tsx@@ -34,6 +34,9 @@ vi.mock("#/api/automation-service/automation-service.api", () => ({default: {getAutomations: vi.fn(),getAutomationRuns: vi.fn(),+ listServerDrafts: vi.fn(),+ getCapabilities: vi.fn(),+ supportsAutomationDrafts: vi.fn(),checkHealth: vi.fn(),toggleAutomation: vi.fn(),updateAutomation: vi.fn(),@@ -81,6 +84,25 @@ beforeEach(() => {vi.mocked(AutomationService.checkHealth).mockReset();vi.mocked(AutomationService.checkHealth).mockResolvedValue({ status: "ok" });vi.mocked(AutomationService.getAutomations).mockReset();+ vi.mocked(AutomationService.listServerDrafts).mockReset();+ vi.mocked(AutomationService.listServerDrafts).mockResolvedValue({+ drafts: [],+ total: 0,+ });+ vi.mocked(AutomationService.getCapabilities).mockReset();+ vi.mocked(AutomationService.getCapabilities).mockResolvedValue({+ ready: true,+ features: ["automationDrafts"],+ triggerKinds: ["cron", "event"],+ eventSources: [],+ eventTypes: [],+ triggers: {},+ });+ vi.mocked(AutomationService.supportsAutomationDrafts).mockReset();+ vi.mocked(AutomationService.supportsAutomationDrafts).mockImplementation(+ (capabilities) =>+ Boolean(capabilities?.features?.includes("automationDrafts")),+ );vi.mocked(AutomationService.getAutomations).mockResolvedValue({automations: [automation],total: 1,diff --git a/__tests__/tools/automation-form-tool.test.ts b/__tests__/tools/automation-form-tool.test.tsindex 59ad277282..b7644d934b 100644--- a/__tests__/tools/automation-form-tool.test.ts+++ b/__tests__/tools/automation-form-tool.test.ts@@ -25,7 +25,14 @@ describe("automation_form_update client tool", () => {kind: { enum: ["prompt", "plugin", "custom"] },triggerKind: { enum: ["cron", "event"] },frequency: {- enum: ["hourly", "daily", "weekdays", "weekly", "custom"],+ enum: [+ "once",+ "hourly",+ "daily",+ "weekdays",+ "weekly",+ "custom",+ ],},customCode: { type: "string" },setupScript: { type: "string" },diff --git a/scripts/check-translation-completeness.cjs b/scripts/check-translation-completeness.cjsindex ad5b832153..ff4c48b137 100755--- a/scripts/check-translation-completeness.cjs+++ b/scripts/check-translation-completeness.cjs@@ -21,6 +21,7 @@ const IDENTICAL_VALUE_ALLOWLIST = new Set(['AUTOMATION_SETUP$MODEL_PLACEHOLDER','AUTOMATION_SETUP$PLUGIN_REF_PLACEHOLDER','AUTOMATION_SETUP$PLUGIN_SOURCE_PLACEHOLDER',+ 'AUTOMATION_SETUP$TEST_DISPATCHED','AUTOMATIONS$GIT_SYNC$PATH_PLACEHOLDER','AUTOMATIONS$GIT_SYNC$REPO_URL_PLACEHOLDER','BACKEND$CLOUD_TITLE',diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.tsindex 12149aeeb3..df604124e7 100644--- a/src/api/agent-server-adapter.ts+++ b/src/api/agent-server-adapter.ts@@ -34,6 +34,13 @@ import {SandboxStatus,} from "./conversation-service/agent-server-conversation-service.types";import { combineUsageMetrics } from "#/utils/conversation-metrics";+import {+ AUTOMATION_DRAFT_ID_TAG_KEY,+ AUTOMATION_EDIT_ID_TAG_KEY,+ AUTOMATION_MATERIALIZED_DRAFT_ID_TAG_KEY,+ AUTOMATION_SETUP_TAG_KEY,+ buildAutomationSetupModeTags,+} from "#/utils/automation-draft-tags";import {buildSkillEnablementFilter,findInvokedCatalogSkill,@@ -577,6 +584,12 @@ export const AUTOMATION_TAG_KEYS: readonly string[] = [* stay out of it — and users can't edit or spoof automation classification.* - ``localplannerparent`` → internal routing for the local planner; already* surfaced by the hidden-from-list planner filter+ * - ``automationsetup`` → user-visible setup-mode marker so users can find+ * setup conversations and filter by them+ * - ``automationdraftid`` / ``automationmaterializeddraftid`` → internal+ * routing for resuming server-backed automation setup drafts (the last one+ * links a resumed conversation to the automation materialized from its draft)+ * - ``automationeditid`` → the saved automation this setup page is editing*/export const RESERVED_CONVERSATION_TAG_KEYS: ReadonlySet<string> = new Set([ACP_SERVER_TAG_KEY,@@ -585,6 +598,9 @@ export const RESERVED_CONVERSATION_TAG_KEYS: ReadonlySet<string> = new Set([AUTOMATION_ID_TAG_KEY,AUTOMATION_NAME_TAG_KEY,AUTOMATION_RUN_ID_TAG_KEY,+ AUTOMATION_DRAFT_ID_TAG_KEY,+ AUTOMATION_MATERIALIZED_DRAFT_ID_TAG_KEY,+ AUTOMATION_EDIT_ID_TAG_KEY,"title","git_provider","repo_name",@@ -599,10 +615,14 @@ export const RESERVED_CONVERSATION_TAG_KEYS: ReadonlySet<string> = new Set([]);/**- * High-signal tag keys shown first in the chip row (before A–Z). Automations- * often stamp ``origin``; remaining free-form tags sort alphabetically.+ * High-signal tag keys shown first in the chip row (before A–Z). Automation+ * setup mode should be easy to spot and filter; automations often stamp+ * ``origin``; remaining free-form tags sort alphabetically.*/-export const PRIORITY_CONVERSATION_TAG_KEYS: readonly string[] = ["origin"];+export const PRIORITY_CONVERSATION_TAG_KEYS: readonly string[] = [+ AUTOMATION_SETUP_TAG_KEY,+ "origin",+];/*** User-facing subset of a conversation's server-side tags: everything except@@ -1198,6 +1218,7 @@ export interface StartConversationOptions {settings: Settings;query?: string;automationSetup?: boolean;+ automationSetupTags?: Record<string, string>;conversationInstructions?: string;plugins?: PluginSpec[];conversationId?: string;@@ -1384,13 +1405,20 @@ export function buildStartConversationRequest(// conversation to Canvas in telemetry (conversation_source = "canvas").// A profile launch resolves the ACP server server-side, so don't stamp the// tag from current settings (it may not match the launched profile).+ const baseTags = options.automationSetup+ ? buildAutomationSetupModeTags(options.automationSetupTags)+ : {};if (!options.agentProfileId && acpServerTag) {payload.tags = {+ ...baseTags,[ACP_SERVER_TAG_KEY]: acpServerTag,[CLIENT_SOURCE_TAG_KEY]: AGENT_CANVAS_SOURCE,};} else {- payload.tags = { [CLIENT_SOURCE_TAG_KEY]: AGENT_CANVAS_SOURCE };+ payload.tags = {+ ...baseTags,+ [CLIENT_SOURCE_TAG_KEY]: AGENT_CANVAS_SOURCE,+ };}// ``secrets_encrypted`` makes the agent-server decrypt request secrets at@@ -1722,6 +1750,7 @@ export async function buildStartConversationRequestWithEncryptedSettings(optionssettings: Settings;query?: string;automationSetup?: boolean;+ automationSetupTags?: Record<string, string>;conversationInstructions?: string;plugins?: PluginSpec[];conversationId?: string;diff --git a/src/api/automation-form-client-tool.ts b/src/api/automation-form-client-tool.tsindex d71781a141..908430fe03 100644--- a/src/api/automation-form-client-tool.ts+++ b/src/api/automation-form-client-tool.ts@@ -15,12 +15,14 @@ Useful fields:* name: short automation name.* prompt: natural-language instruction for prompt/plugin automations.* repository: optional GitHub repository URL or owner/repo for prompt/plugin automations.-* pluginSource and pluginRef: plugin source and optional ref for plugin automations.+* pluginSource and pluginRef: source and optional ref for the first plugin. The form can hold more than one plugin; these fields only change the first.* customCode, entrypoint, setupScriptPath, setupScript: custom Python bundle fields.* triggerKind: "cron" or "event".-* frequency: "hourly", "daily", "weekdays", "weekly", or "custom" for cron triggers.-* time, timezone, customSchedule: cron scheduling fields.+* frequency: "once", "hourly", "daily", "weekdays", "weekly", or "custom" for cron triggers.+* time, scheduleDateTime, timezone, weekday, customSchedule: cron scheduling fields. "scheduleDateTime" is a local "YYYY-MM-DDTHH:MM" value used when frequency is "once". "weekday" is "0" (Sunday) through "6" (Saturday) and applies when frequency is "weekly".* eventSource, eventKey, eventFilter: event trigger fields.+* model: LLM profile name for this automation. Leave empty to use the active profile. This does not change the conversation composer.+* agentProfileId: agent profile id for this automation. Leave empty to use the active agent profile. This does not change the conversation.* showTimeout and timeoutSeconds: optional timeout controls.Call this with only the fields you are changing. After calling it, briefly tell the user which fields you filled and ask them to review anything uncertain.`;@@ -49,14 +51,35 @@ export const AUTOMATION_FORM_UPDATE_CLIENT_TOOL: ClientToolSpec = {triggerKind: { type: "string", enum: ["cron", "event"] },frequency: {type: "string",- enum: ["hourly", "daily", "weekdays", "weekly", "custom"],+ enum: ["once", "hourly", "daily", "weekdays", "weekly", "custom"],},time: { type: "string", description: "24-hour HH:MM time." },+ scheduleDateTime: {+ type: "string",+ description:+ "Local date and time, YYYY-MM-DDTHH:MM, for a one-time schedule.",+ },timezone: { type: "string" },+ weekday: {+ type: "string",+ enum: ["0", "1", "2", "3", "4", "5", "6"],+ description:+ "Day of week for a weekly schedule. 0 is Sunday and 6 is Saturday.",+ },customSchedule: { type: "string", description: "Cron expression." },eventSource: { type: "string" },eventKey: { type: "string" },eventFilter: { type: "string" },+ model: {+ type: "string",+ description:+ "LLM profile name for this automation. Empty uses the active profile and does not change the conversation.",+ },+ agentProfileId: {+ type: "string",+ description:+ "Agent profile id for this automation. Empty uses the active agent profile and does not change the conversation.",+ },showTimeout: { type: "boolean" },timeoutSeconds: { type: "string" },},diff --git a/src/api/automation-form-session.ts b/src/api/automation-form-session.tsindex fa2b9f667c..d5909136b2 100644--- a/src/api/automation-form-session.ts+++ b/src/api/automation-form-session.ts@@ -1,3 +1,7 @@+import {+ resolveAutomationSetupPlugins,+ serializeAutomationSetupPluginList,+} from "#/api/automation-setup-plugins";import type {AutomationSetupDraft,AutomationSetupField,@@ -22,6 +26,7 @@ const AUTOMATION_SETUP_TRIGGER_KINDS: AutomationSetupTriggerKind[] = ["event",];const AUTOMATION_SETUP_FREQUENCIES: AutomationSetupFrequency[] = [+ "once","hourly","daily","weekdays",@@ -34,16 +39,21 @@ const STRING_FIELDS = ["repository","pluginSource","pluginRef",+ "pluginList","customCode","entrypoint","setupScriptPath","setupScript","time",+ "scheduleDateTime","timezone",+ "weekday","customSchedule","eventSource","eventKey","eventFilter",+ "model",+ "agentProfileId","timeoutSeconds",] as const satisfies readonly AutomationSetupField[];@@ -130,15 +140,29 @@ function normalizeDraft(value: AutomationSetupDraft): AutomationSetupDraft {(plugin): plugin is string => typeof plugin === "string",): [];- const pluginSource = form.pluginSource ?? plugins[0];+ const pluginEntries = resolveAutomationSetupPlugins(form, plugins);+ const pluginSources = pluginEntries+ .map((entry) => entry.source.trim())+ .filter(Boolean);const normalizedForm: AutomationSetupFormPatch = {...form,prompt,kind,- ...(pluginSource ? { pluginSource } : {}),+ pluginList:+ pluginEntries.length > 0+ ? serializeAutomationSetupPluginList(pluginEntries)+ : "",+ pluginSource: pluginEntries[0]?.source ?? "",+ pluginRef: pluginEntries[0]?.ref ?? "",};- const normalizedPlugins = pluginSource ? [pluginSource] : plugins;+ const normalizedPlugins = pluginSources;const fieldMetadata = normalizeFieldMetadata(value.fieldMetadata);+ const serverDraftId =+ typeof value.serverDraftId === "string" ? value.serverDraftId.trim() : "";+ const materializedAutomationId =+ typeof value.materializedAutomationId === "string"+ ? value.materializedAutomationId.trim()+ : null;const appliedAgentEventIds = Array.isArray(value.appliedAgentEventIds)? [...new Set(@@ -152,6 +176,8 @@ function normalizeDraft(value: AutomationSetupDraft): AutomationSetupDraft {kind,...(normalizedPlugins.length > 0 ? { plugins: normalizedPlugins } : {}),form: normalizedForm,+ ...(serverDraftId ? { serverDraftId } : {}),+ ...(materializedAutomationId ? { materializedAutomationId } : {}),...(fieldMetadata ? { fieldMetadata } : {}),...(appliedAgentEventIds && appliedAgentEventIds.length > 0? { appliedAgentEventIds }@@ -279,10 +305,6 @@ export function patchAutomationFormSession(form: nextForm,prompt: nextForm.prompt ?? existing.prompt,kind: nextForm.kind ?? existing.kind,- plugins:- typeof nextForm.pluginSource === "string" && nextForm.pluginSource- ? [nextForm.pluginSource]- : existing.plugins,fieldMetadata: nextMetadata,appliedAgentEventIds:options.source === "agent" && options.eventIddiff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.tsindex 636ab08ee6..8ef6b5655b 100644--- a/src/api/automation-service/automation-service.api.ts+++ b/src/api/automation-service/automation-service.api.ts@@ -35,6 +35,12 @@ import type {SetupEntry,SetupRequestBody,ValidateDraftResponse,+ AutomationDraftEndpoint,+ CreateAutomationDraftApiRequest,+ UpdateAutomationDraftApiRequest,+ AutomationDraftApiResponse,+ AutomationDraftListResponse,+ DraftValidationError,} from "#/manifests/types";import { withPresetSources } from "#/utils/automation-preset-sources";import { downloadBlob } from "#/utils/utils";@@ -49,11 +55,36 @@ import {AGENT_CANVAS_CLIENT_HEADERS,OPENHANDS_TELEMETRY_DISTINCT_ID_HEADER,} from "../client-source";+import { AUTOMATION_DRAFTS_FEATURE } from "#/constants/automation-form";const AUTOMATION_BASE_PATH = "/api/automation";type AutomationDraftCreateTarget = SetupEntry | "prompt" | "plugin" | "custom";+export interface CustomWebhookCreateRequest {+ name: string;+ source: string;+ event_key_expr?: string;+ signature_header?: string;+ signature_scheme?: string;+ webhook_secret?: string;+}++export interface CustomWebhookCreateResponse {+ id: string;+ org_id: string;+ name: string;+ source: string;+ webhook_url: string;+ event_key_expr: string;+ signature_header: string;+ signature_scheme: string;+ enabled: boolean;+ created_at: string;+ updated_at: string;+ webhook_secret?: string | null;+}+function automationCreateEndpointForTarget(target?: AutomationDraftCreateTarget,selectedAction?: string | null,@@ -169,6 +200,97 @@ function buildListQuery(return params.toString();}+const DRAFT_ENDPOINTS: readonly AutomationDraftEndpoint[] = [+ "/v1",+ "/v1/preset/prompt",+ "/v1/preset/plugin",+];++function isDraftEndpoint(value: unknown): value is AutomationDraftEndpoint {+ return (+ typeof value === "string" &&+ DRAFT_ENDPOINTS.includes(value as AutomationDraftEndpoint)+ );+}++function normalizeValidationErrors(+ value: unknown,+): DraftValidationError[] | null {+ if (!Array.isArray(value)) return null;+ if (value.length === 0) return null;+ const errors: DraftValidationError[] = [];+ for (const entry of value) {+ if (+ typeof entry === "object" &&+ entry !== null &&+ !Array.isArray(entry) &&+ typeof (entry as Record<string, unknown>).code === "string" &&+ typeof (entry as Record<string, unknown>).message === "string"+ ) {+ const record = entry as Record<string, unknown>;+ errors.push({+ code: record.code as string,+ message: record.message as string,+ field:+ typeof record.field === "string" ? (record.field as string) : null,+ });+ }+ }+ return errors.length > 0 ? errors : null;+}++/**+ * The service returns snake_case field names; the frontend reads camelCase.+ * Normalize defensively so a malformed payload never crashes the form.+ */+function normalizeDraftResponse(value: unknown): AutomationDraftApiResponse {+ const record = (value ?? {}) as Record<string, unknown>;+ const validationErrors = normalizeValidationErrors(+ record.validation_errors ?? record.validationErrors,+ );+ return {+ id: String(record.id ?? ""),+ endpoint: isDraftEndpoint(record.endpoint)+ ? (record.endpoint as AutomationDraftEndpoint)+ : "/v1/preset/prompt",+ name: typeof record.name === "string" && record.name ? record.name : null,+ draft: (record.draft ?? {}) as SetupRequestBody,+ validationErrors,+ dispatchable: record.dispatchable === true,+ sourceAutomationId:+ typeof (record.source_automation_id ?? record.sourceAutomationId) ===+ "string"+ ? String(record.source_automation_id ?? record.sourceAutomationId)+ : null,+ materializedAutomationId:+ typeof (+ record.materialized_automation_id ?? record.materializedAutomationId+ ) === "string"+ ? String(+ record.materialized_automation_id ??+ record.materializedAutomationId,+ )+ : null,+ lastTestRunId:+ typeof (record.last_test_run_id ?? record.lastTestRunId) === "string"+ ? String(record.last_test_run_id ?? record.lastTestRunId)+ : null,+ createdAt: String(record.created_at ?? record.createdAt ?? ""),+ updatedAt: String(record.updated_at ?? record.updatedAt ?? ""),+ };+}++function normalizeDraftListResponse(+ value: unknown,+): AutomationDraftListResponse {+ const record = (value ?? {}) as Record<string, unknown>;+ const drafts = Array.isArray(record.drafts) ? record.drafts : [];+ return {+ drafts: drafts.map(normalizeDraftResponse),+ total: typeof record.total === "number" ? record.total : 0,+ };+}+function buildImportedTrigger(spec: AutomationSpec): AutomationTrigger {if (spec.trigger.type === "event") {return {@@ -608,6 +730,39 @@ class AutomationService {return data;}+ static async createCustomWebhook(+ body: CustomWebhookCreateRequest,+ ): Promise<CustomWebhookCreateResponse> {+ const active = getActiveBackend().backend;+ const path = `${AUTOMATION_BASE_PATH}/v1/webhooks`;++ if (active.kind === "cloud") {+ return callCloudProxy<CustomWebhookCreateResponse>({+ backend: active,+ method: "POST",+ path,+ headers: await buildAutomationRequestHeaders(),+ body: body as unknown as Record<string, unknown>,+ });+ }++ const { data } =+ await localAutomationAxios.post<CustomWebhookCreateResponse>(path, body);+ return data;+ }++ /**+ * Whether the active deployment advertises server-backed automation drafts+ * (the `automationDrafts` feature from `OpenHands/automation` PR #417). The+ * persisted-draft form flow gates on this so older deployments keep working+ * with the client-only draft store.+ */+ static supportsAutomationDrafts(+ capabilities: DeploymentCapabilities | null | undefined,+ ): boolean {+ return Boolean(capabilities?.features?.includes(AUTOMATION_DRAFTS_FEATURE));+ }+/*** Validate a draft without creating it. An invalid draft is a 200 carrying* field-addressed errors; only a malformed envelope is a 4xx.@@ -670,6 +825,170 @@ class AutomationService {return data;}+ // --- Server-backed automation drafts (PR OpenHands/automation#417) ---+ //+ // Draft rows are the source of truth while the user is in the setup form. A+ // draft is materialized into a disabled automation only when it validates and+ // the user dispatches it for a test run. These endpoints are literal+ // (outside the interface manifest surface) like the git-sync paths.++ static async createServerDraft(+ body: CreateAutomationDraftApiRequest,+ ): Promise<AutomationDraftApiResponse> {+ const active = getActiveBackend().backend;+ const path = `${AUTOMATION_BASE_PATH}/v1/drafts`;+ const requestBody = {+ endpoint: body.endpoint,+ draft: body.draft,+ ...(body.name ? { name: body.name } : {}),+ ...(body.sourceAutomationId+ ? { source_automation_id: body.sourceAutomationId }+ : {}),+ };++ if (active.kind === "cloud") {+ const data = await callCloudProxy<AutomationDraftApiResponse>({+ backend: active,+ method: "POST",+ path,+ body: requestBody,+ headers: await buildAutomationRequestHeaders(),+ });+ return normalizeDraftResponse(data);+ }++ const { data } =+ await localAutomationAxios.post<AutomationDraftApiResponse>(+ path,+ requestBody,+ );+ return normalizeDraftResponse(data);+ }++ static async getServerDraft(+ draftId: string,+ ): Promise<AutomationDraftApiResponse> {+ const active = getActiveBackend().backend;+ const path = `${AUTOMATION_BASE_PATH}/v1/drafts/${encodeURIComponent(draftId)}`;++ if (active.kind === "cloud") {+ const data = await callCloudProxy<AutomationDraftApiResponse>({+ backend: active,+ method: "GET",+ path,+ headers: await buildAutomationRequestHeaders(),+ });+ return normalizeDraftResponse(data);+ }++ const { data } =+ await localAutomationAxios.get<AutomationDraftApiResponse>(path);+ return normalizeDraftResponse(data);+ }++ static async updateServerDraft(+ draftId: string,+ body: UpdateAutomationDraftApiRequest,+ ): Promise<AutomationDraftApiResponse> {+ const active = getActiveBackend().backend;+ const path = `${AUTOMATION_BASE_PATH}/v1/drafts/${encodeURIComponent(draftId)}`;+ const requestBody: Record<string, unknown> = {};+ if (body.endpoint !== undefined) requestBody.endpoint = body.endpoint;+ if (body.draft !== undefined) requestBody.draft = body.draft;+ if (body.name !== undefined) requestBody.name = body.name;++ if (active.kind === "cloud") {+ const data = await callCloudProxy<AutomationDraftApiResponse>({+ backend: active,+ method: "PATCH",+ path,+ body: requestBody,+ headers: await buildAutomationRequestHeaders(),+ });+ return normalizeDraftResponse(data);+ }++ const { data } =+ await localAutomationAxios.patch<AutomationDraftApiResponse>(+ path,+ requestBody,+ );+ return normalizeDraftResponse(data);+ }++ static async deleteServerDraft(draftId: string): Promise<void> {+ const active = getActiveBackend().backend;+ const path = `${AUTOMATION_BASE_PATH}/v1/drafts/${encodeURIComponent(draftId)}`;++ if (active.kind === "cloud") {+ await callCloudProxy<unknown>({+ backend: active,+ method: "DELETE",+ path,+ headers: await buildAutomationRequestHeaders(),+ });+ return;+ }++ await localAutomationAxios.delete(path);+ }++ static async listServerDrafts(+ params: { limit?: number; offset?: number } = {},+ ): Promise<AutomationDraftListResponse> {+ const { limit = 50, offset = 0 } = params;+ const active = getActiveBackend().backend;+ const path = `${AUTOMATION_BASE_PATH}/v1/drafts?${buildListQuery(limit, offset)}`;++ if (active.kind === "cloud") {+ const data = await callCloudProxy<AutomationDraftListResponse>({+ backend: active,+ method: "GET",+ path,+ headers: await buildAutomationRequestHeaders(),+ });+ return normalizeDraftListResponse(data);+ }++ const { data } =+ await localAutomationAxios.get<AutomationDraftListResponse>(path);+ return normalizeDraftListResponse(data);+ }++ /**+ * Test-dispatch a dispatchable draft. The service materializes the draft+ * body into a disabled automation and starts a manual run; the draft row+ * stays in place as the source of truth. Returns the created run.+ *+ * An undispatchable draft answers 422 with `{ message, errors }`; callers+ * should surface those errors rather than treating them as transport errors.+ */+ static async dispatchServerDraft(+ draftId: string,+ options: { eventPayload?: Record<string, unknown> } = {},+ ): Promise<AutomationRun> {+ const active = getActiveBackend().backend;+ const path = `${AUTOMATION_BASE_PATH}/v1/drafts/${encodeURIComponent(draftId)}/dispatch`;+ const body = options.eventPayload+ ? { event_payload: options.eventPayload }+ : undefined;++ if (active.kind === "cloud") {+ return callCloudProxy<AutomationRun>({+ backend: active,+ method: "POST",+ path,+ headers: await buildAutomationRequestHeaders(),+ body,+ });+ }++ const { data } = body+ ? await localAutomationAxios.post<AutomationRun>(path, body)+ : await localAutomationAxios.post<AutomationRun>(path);+ return data;+ }+/*** Upload a packed bundle, and return the `oh-internal://` path the create* call references.diff --git a/src/api/automation-setup-plugins.ts b/src/api/automation-setup-plugins.tsnew file mode 100644index 0000000000..d56842c41c--- /dev/null+++ b/src/api/automation-setup-plugins.ts@@ -0,0 +1,106 @@+/**+ * Plugin list for the automation setup form.+ *+ * The form still keeps `pluginSource` and `pluginRef` so the agent tool and+ * older drafts can fill the first plugin. Every plugin, including later ones+ * and an optional ref, lives in `pluginList` (a JSON string, so it survives+ * the string-only draft patch). When those disagree, the scalar fields win+ * for the first row and the rest of the list stays put.+ */++export interface AutomationSetupPluginEntry {+ source: string;+ ref: string;+}++/** Git ref prefilled on a newly added plugin card. */+export const DEFAULT_AUTOMATION_PLUGIN_REF = "main";++interface PluginFormFields {+ pluginList?: string;+ pluginSource?: string;+ pluginRef?: string;+}++/**+ * Parse the persisted plugin list.+ *+ * Invalid JSON and non-array values become an empty list so a corrupt draft+ * cannot throw while the panel is opening.+ */+export function parseAutomationSetupPluginList(+ value: string | undefined,+): AutomationSetupPluginEntry[] {+ if (!value?.trim()) return [];+ try {+ const parsed = JSON.parse(value) as unknown;+ if (!Array.isArray(parsed)) return [];+ return parsed.flatMap((entry) => {+ if (!entry || typeof entry !== "object") return [];+ const record = entry as Record<string, unknown>;+ return [+ {+ source: typeof record.source === "string" ? record.source : "",+ ref: typeof record.ref === "string" ? record.ref : "",+ },+ ];+ });+ } catch {+ return [];+ }+}++/** Serialize plugin rows for the string form field. */+export function serializeAutomationSetupPluginList(+ entries: AutomationSetupPluginEntry[],+): string {+ return JSON.stringify(+ entries.map((entry) => ({ source: entry.source, ref: entry.ref })),+ );+}++function overlayFirstPlugin(+ entries: AutomationSetupPluginEntry[],+ form: PluginFormFields,+): AutomationSetupPluginEntry[] {+ if (entries.length === 0) {+ if (!form.pluginSource && !form.pluginRef) return [];+ return [{ source: form.pluginSource ?? "", ref: form.pluginRef ?? "" }];+ }++ const first = entries[0];+ const source = form.pluginSource ?? first.source;+ const ref = form.pluginRef ?? first.ref;+ if (source === first.source && ref === first.ref) return entries;+ return [{ source, ref }, ...entries.slice(1)];+}++/**+ * The plugins the form should show and save.+ *+ * `pluginList` is canonical once it has been written. Older drafts that only+ * stored `plugins: string[]` or a single source still expand into rows.+ */+export function resolveAutomationSetupPlugins(+ form: PluginFormFields,+ draftPlugins: string[] = [],+): AutomationSetupPluginEntry[] {+ if (typeof form.pluginList === "string") {+ return overlayFirstPlugin(+ parseAutomationSetupPluginList(form.pluginList),+ form,+ );+ }++ if (draftPlugins.length > 1) {+ return overlayFirstPlugin(+ draftPlugins.map((source) => ({ source, ref: "" })),+ form,+ );+ }++ const source = form.pluginSource ?? draftPlugins[0] ?? "";+ const ref = form.pluginRef ?? "";+ if (!source && !ref) return [];+ return [{ source, ref }];+}diff --git a/src/api/automation-setup-types.ts b/src/api/automation-setup-types.tsindex 73268cbbf5..65491fd1aa 100644--- a/src/api/automation-setup-types.ts+++ b/src/api/automation-setup-types.ts@@ -1,6 +1,7 @@export type AutomationSetupKind = "prompt" | "plugin" | "custom";export type AutomationSetupTriggerKind = "cron" | "event";export type AutomationSetupFrequency =+ | "once"| "hourly"| "daily"| "weekdays"@@ -15,6 +16,7 @@ export interface AutomationSetupFormValues {repository: string;pluginSource: string;pluginRef: string;+ pluginList: string;customCode: string;entrypoint: string;setupScriptPath: string;@@ -22,11 +24,15 @@ export interface AutomationSetupFormValues {triggerKind: AutomationSetupTriggerKind;frequency: AutomationSetupFrequency;time: string;+ scheduleDateTime: string;timezone: string;+ weekday: string;customSchedule: string;eventSource: string;eventKey: string;eventFilter: string;+ model: string;+ agentProfileId: string;showTimeout: boolean;timeoutSeconds: string;}@@ -51,6 +57,8 @@ export interface AutomationSetupDraft {kind: AutomationSetupKind;plugins?: string[];form?: AutomationSetupFormPatch;+ serverDraftId?: string;+ materializedAutomationId?: string | null;fieldMetadata?: Partial<Record<AutomationSetupField, AutomationSetupFieldMetadata>>;diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.tsindex 37d112b37d..1b7b2e1388 100644--- a/src/api/conversation-service/agent-server-conversation-service.api.ts+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts@@ -404,6 +404,7 @@ function requireAppConversation(export interface CreateConversationOptions {initialUserMsg?: string;automationSetup?: boolean;+ automationSetupTags?: Record<string, string>;conversationInstructions?: string;plugins?: PluginSpec[];metadata?: ConversationMetadata | null;@@ -486,6 +487,7 @@ class AgentServerConversationService {const {initialUserMsg,automationSetup,+ automationSetupTags,conversationInstructions,plugins,metadata,@@ -539,7 +541,7 @@ class AgentServerConversationService {: {}),trigger: "gui",...(automationSetup- ? { tags: buildAutomationSetupModeTags(null) }+ ? { tags: buildAutomationSetupModeTags(automationSetupTags) }: {}),...(automationSetup && agentProfileKind !== "acp"? {@@ -579,6 +581,7 @@ class AgentServerConversationService {settings,query: initialUserMsg,automationSetup,+ automationSetupTags,conversationInstructions,plugins,conversationId,diff --git a/src/components/features/automations/automation-card.tsx b/src/components/features/automations/automation-card.tsxindex e90053d384..152c29b8c5 100644--- a/src/components/features/automations/automation-card.tsx+++ b/src/components/features/automations/automation-card.tsx@@ -28,6 +28,7 @@ import { toLatestRunState } from "./to-latest-run-state";import { RunPhase, shouldShowRunPhase } from "./detail/run-phase";import { resolveAutomationImpactStatement } from "#/utils/automation-catalog";import { RunStatusBadge } from "./detail/run-status-badge";+import { ActiveStatusBadge } from "./detail/active-status-badge";import { AutomationRunActivitySparkline } from "#/components/features/home/featured-automations/automation-run-activity-sparkline";import type { RunSummaryState } from "#/manifests/automation-insights";import type { InterfaceListInsights } from "#/manifests/types";@@ -36,6 +37,7 @@ import {shortenAutomationRunSummary,shouldShowAutomationRunSummaryHovercard,} from "#/components/features/home/featured-automations/automation-run-health";+import { isDraftAutomation } from "#/utils/automation-state";/** Run insights shown when the manifest declares the dashboard surface. */export interface AutomationInsightsProps {@@ -70,8 +72,10 @@ export function AutomationCard({const isOwner = useIsAutomationOwner(automation);// Write actions on a specific automation: manage OR creator (escape hatch).const canManage = hasManagePermission || isOwner;- // Non-creators may turn an automation off but not back on.- const canToggle = automation.enabled ? canManage : isOwner;+ const isDraft = isDraftAutomation(automation);+ // Non-creators may turn an automation off but not back on. Draft test+ // artifacts are finalized through the draft setup flow, not this toggle.+ const canToggle = isDraft ? false : automation.enabled ? canManage : isOwner;const scheduleLabel =automation.trigger.schedule_human || automation.trigger.type;@@ -114,6 +118,7 @@ export function AutomationCard({shouldShowAutomationRunSummaryHovercard(summary, shortSummary);const showPhase = shouldShowRunPhase(latestRun?.status);const disableAnimation = import.meta.env.MODE === "test";+ const showDraftBadge = isDraft;return (<div@@ -132,9 +137,14 @@ export function AutomationCard({><header className="flex flex-col gap-1.5"><div className="flex h-8 items-center justify-between gap-3">- <h3 className="min-w-0 flex-1 truncate text-sm font-semibold leading-none text-foreground">- {automation.name}- </h3>+ <div className="flex min-w-0 flex-1 items-center gap-2">+ <h3 className="min-w-0 truncate text-sm font-semibold leading-none text-foreground">+ {automation.name}+ </h3>+ {showDraftBadge ? (+ <ActiveStatusBadge automation={automation} compact />+ ) : null}+ </div><div className="flex shrink-0 items-center gap-0.5">{canManage ? (<StyledTooltipdiff --git a/src/components/features/automations/automation-list-row.tsx b/src/components/features/automations/automation-list-row.tsxindex d1397ee0c2..71ef5a9bc7 100644--- a/src/components/features/automations/automation-list-row.tsx+++ b/src/components/features/automations/automation-list-row.tsx@@ -21,6 +21,7 @@ import { automationIconActionButtonClassName } from "./automation-action-button-import { buildAutomationMenuItems } from "./build-automation-menu-items";import { automationActivityRowClassName } from "./automation-view-mode";import { RunStatusBadge } from "./detail/run-status-badge";+import { ActiveStatusBadge } from "./detail/active-status-badge";import { AutomationRunActivitySparkline } from "#/components/features/home/featured-automations/automation-run-activity-sparkline";import { AutomationHealthIndicator } from "#/components/features/home/featured-automations/automation-health-indicator";import {@@ -38,6 +39,7 @@ import {import type { AutomationInsightsProps } from "./automation-card";import { toLatestRunState } from "./to-latest-run-state";import { resolveAutomationImpactStatement } from "#/utils/automation-catalog";+import { isDraftAutomation } from "#/utils/automation-state";interface AutomationListRowProps {automation: Automation;@@ -66,8 +68,10 @@ export function AutomationListRow({const isOwner = useIsAutomationOwner(automation);// Write actions on a specific automation: manage OR creator (escape hatch).const canManage = hasManagePermission || isOwner;- // Non-creators may turn an automation off but not back on.- const canToggle = automation.enabled ? canManage : isOwner;+ const isDraft = isDraftAutomation(automation);+ // Non-creators may turn an automation off but not back on. Draft test+ // artifacts are finalized through the draft setup flow, not this toggle.+ const canToggle = isDraft ? false : automation.enabled ? canManage : isOwner;const handleView = () => {navigate?.(`/automations/${automation.id}`);@@ -115,6 +119,7 @@ export function AutomationListRow({const detailHref = `/automations/${encodeURIComponent(automation.id)}`;const statusLabelKey = getRunStatusLabelKey(runState);const disableAnimation = import.meta.env.MODE === "test";+ const showDraftBadge = isDraft;return (<li@@ -145,8 +150,13 @@ export function AutomationListRow({><AutomationHealthIndicator health={health} /></span>- <span className="truncate text-sm font-medium leading-5 text-foreground">- {automation.name}+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate text-sm font-medium leading-5 text-foreground">+ {automation.name}+ </span>+ {showDraftBadge ? (+ <ActiveStatusBadge automation={automation} compact />+ ) : null}</span>{hasMeta ? (<span className="col-start-2 mt-0.5 flex min-w-0 items-center gap-1.5 text-xs leading-4 text-text-secondary">diff --git a/src/components/features/automations/detail/active-status-badge.tsx b/src/components/features/automations/detail/active-status-badge.tsxindex f7a1d179fc..155ad55f65 100644--- a/src/components/features/automations/detail/active-status-badge.tsx+++ b/src/components/features/automations/detail/active-status-badge.tsx@@ -1,29 +1,55 @@import { useTranslation } from "react-i18next";import { I18nKey } from "#/i18n/declaration";+import type { Automation } from "#/types/automation";+import {+ getAutomationLifecycleState,+ type AutomationLifecycleState,+} from "#/utils/automation-state";import { cn } from "#/utils/utils";interface ActiveStatusBadgeProps {- active: boolean;+ automation: Pick<Automation, "enabled" | "state">;+ compact?: boolean;}-export function ActiveStatusBadge({ active }: ActiveStatusBadgeProps) {+const STATUS_DISPLAY: Record<+ AutomationLifecycleState,+ { testId: string; label: I18nKey; className: string }+> = {+ active: {+ testId: "active-status-badge-active",+ label: I18nKey.AUTOMATIONS$DETAIL$ACTIVE,+ className: "bg-semantic-success/15 text-semantic-success",+ },+ inactive: {+ testId: "active-status-badge-inactive",+ label: I18nKey.AUTOMATIONS$DETAIL$INACTIVE,+ className: "bg-surface-raised text-muted",+ },+ draft: {+ testId: "active-status-badge-draft",+ label: I18nKey.AUTOMATIONS$DETAIL$DRAFT,+ className: "bg-[var(--oh-warning)]/15 text-[var(--oh-warning)]",+ },+};++export function ActiveStatusBadge({+ automation,+ compact = false,+}: ActiveStatusBadgeProps) {const { t } = useTranslation("openhands");+ const display = STATUS_DISPLAY[getAutomationLifecycleState(automation)];return (<span- data-testid={- active ? "active-status-badge-active" : "active-status-badge-inactive"- }+ data-testid={display.testId}className={cn(- "inline-flex items-center rounded-full px-3 py-1 text-xs font-medium",- active- ? "bg-semantic-success/15 text-semantic-success"- : "bg-surface-raised text-muted",+ "inline-flex items-center rounded-full font-medium",+ compact ? "px-2 py-0.5 text-[10px]" : "px-3 py-1 text-xs",+ display.className,)}>- {active- ? t(I18nKey.AUTOMATIONS$DETAIL$ACTIVE)- : t(I18nKey.AUTOMATIONS$DETAIL$INACTIVE)}+ {t(display.label)}</span>);}diff --git a/src/components/features/automations/detail/detail-header.tsx b/src/components/features/automations/detail/detail-header.tsxindex 891c0ece97..86530620fc 100644--- a/src/components/features/automations/detail/detail-header.tsx+++ b/src/components/features/automations/detail/detail-header.tsx@@ -95,7 +95,7 @@ export function DetailHeader({<h1 className="text-xl font-medium text-content">{automation.name}</h1>- <ActiveStatusBadge active={automation.enabled} />+ <ActiveStatusBadge automation={automation} /></div><div className="flex items-center gap-2">{canManage && onRunNow && (diff --git a/src/components/features/automations/detail/disabled-reason-banner.tsx b/src/components/features/automations/detail/disabled-reason-banner.tsxindex b2b17b3918..bf0d8b859b 100644--- a/src/components/features/automations/detail/disabled-reason-banner.tsx+++ b/src/components/features/automations/detail/disabled-reason-banner.tsx@@ -1,6 +1,7 @@import { useTranslation } from "react-i18next";import { I18nKey } from "#/i18n/declaration";import type { Automation } from "#/types/automation";+import { isDraftAutomation } from "#/utils/automation-state";import { getDisablementReasonDisplay } from "#/utils/automation-disabled-reason";import {formatRelativeTime,@@ -27,6 +28,8 @@ export function DisabledReasonBanner({}: DisabledReasonBannerProps) {const { t, i18n } = useTranslation("openhands");+ if (isDraftAutomation(automation)) return null;+const display = getDisablementReasonDisplay(automation, t);if (!display) return null;diff --git a/src/components/features/automations/setup/automation-setup-draft-service.ts b/src/components/features/automations/setup/automation-setup-draft-service.tsnew file mode 100644index 0000000000..b7ccda2b95--- /dev/null+++ b/src/components/features/automations/setup/automation-setup-draft-service.ts@@ -0,0 +1,240 @@+import { isSdkHttpError } from "#/api/agent-server-compatibility";+import type {+ AutomationSetupFormValues,+ AutomationSetupKind,+} from "#/api/automation-setup-types";+import { serializeAutomationSetupPluginList } from "#/api/automation-setup-plugins";+import { getAutomationEndpoint } from "#/manifests/automation-interface";+import type {+ InterfaceEndpointName,+ AutomationDraftApiResponse,+ AutomationDraftEndpoint,+} from "#/manifests/types";+import { I18nKey } from "#/i18n/declaration";+import { getApiErrorBody } from "#/utils/api-error-message";+import type { AutomationRun } from "#/types/automation";++function asRecord(value: unknown): Record<string, unknown> | null {+ return value && typeof value === "object"+ ? (value as Record<string, unknown>)+ : null;+}++function getStringField(+ value: Record<string, unknown>,+ key: string,+): string | undefined {+ const field = value[key];+ return typeof field === "string" ? field : undefined;+}++function getFirstObject(+ value: Record<string, unknown>,+ key: string,+): Record<string, unknown> | null {+ const field = value[key];+ return Array.isArray(field) ? asRecord(field[0]) : null;+}++function getPluginEntries(+ value: Record<string, unknown>,+): { source: string; ref: string }[] {+ const field = value.plugins;+ if (!Array.isArray(field)) return [];+ return field.flatMap((item) => {+ const record = asRecord(item);+ if (!record) return [];+ return [+ {+ source: getStringField(record, "source") ?? "",+ ref: getStringField(record, "ref") ?? "",+ },+ ];+ });+}++export function formFromServerDraft(+ saved: AutomationDraftApiResponse,+ base: AutomationSetupFormValues,+): AutomationSetupFormValues {+ const body = saved.draft as Record<string, unknown>;+ const trigger = asRecord(body.trigger);+ const plugin = getPluginEntries(body);+ const savedPlugins =+ plugin.length > 0+ ? plugin+ : [+ {+ source: base.pluginSource,+ 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";++ 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),+ pluginSource: savedPlugins[0]?.source ?? "",+ pluginRef: savedPlugins[0]?.ref ?? "",+ pluginList:+ savedPlugins.length > 0+ ? serializeAutomationSetupPluginList(savedPlugins)+ : "",+ entrypoint: getStringField(body, "entrypoint") ?? base.entrypoint,+ setupScriptPath:+ getStringField(body, "setup_script_path") ?? base.setupScriptPath,+ triggerKind:+ getStringField(trigger ?? {}, "type") === "event" ? "event" : "cron",+ frequency: getStringField(trigger ?? {}, "schedule")+ ? "custom"+ : base.frequency,+ customSchedule:+ 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),+ eventFilter: getStringField(trigger ?? {}, "filter") ?? base.eventFilter,+ model: getStringField(body, "model") ?? base.model,+ agentProfileId:+ getStringField(body, "agent_profile_id") ?? base.agentProfileId,+ showTimeout: typeof body.timeout === "number" || base.showTimeout,+ timeoutSeconds:+ typeof body.timeout === "number"+ ? String(body.timeout)+ : base.timeoutSeconds,+ };+}++function endpointName(kind: AutomationSetupKind): InterfaceEndpointName {+ if (kind === "plugin") return "createPlugin";+ if (kind === "custom") return "createBundle";+ return "createPrompt";+}++export function presetKindForEndpoint(+ kind: AutomationSetupKind,+ pluginSource: string,+): AutomationSetupKind {+ if (kind === "custom") return "custom";+ return pluginSource.trim() ? "plugin" : "prompt";+}++export function draftEndpoint(+ kind: AutomationSetupKind,+ pluginSource = "",+): AutomationDraftEndpoint {+ const resolved = presetKindForEndpoint(kind, pluginSource);+ const path = getAutomationEndpoint(endpointName(resolved));+ if (+ path === "/v1" ||+ path === "/v1/preset/prompt" ||+ path === "/v1/preset/plugin"+ ) {+ return path;+ }+ return resolved === "plugin" ? "/v1/preset/plugin" : "/v1/preset/prompt";+}++export function draftValidationEndpoint(+ kind: AutomationSetupKind,+ pluginSource = "",+): string {+ return getAutomationEndpoint(+ endpointName(presetKindForEndpoint(kind, pluginSource)),+ );+}++export function getResponseStatus(error: unknown): number | null {+ if (isSdkHttpError(error)) return (error as { status: number }).status;+ if (!error || typeof error !== "object") return null;+ const response = (error as Record<string, unknown>).response;+ if (!response || typeof response !== "object") return null;+ const status = (response as Record<string, unknown>).status;+ return typeof status === "number" ? status : null;+}++export function isDraftEndpointUnavailable(error: unknown): boolean {+ const status = getResponseStatus(error);+ return status === 404 || status === 405;+}++function getDraftErrorPayload(error: unknown): Record<string, unknown> | null {+ const body = getApiErrorBody(error);+ const record = asRecord(body);+ if (!record) return null;+ return asRecord(record.detail) ?? record;+}++export function extractDraftDispatchErrors(error: unknown): string | null {+ const data = getDraftErrorPayload(error);+ if (!data) return null;+ const errors = data.errors;+ if (Array.isArray(errors) && errors.length > 0) {+ const first = errors[0] as Record<string, unknown> | undefined;+ if (first && typeof first.message === "string") return first.message;+ }+ const message = data.message;+ return typeof message === "string" ? message : null;+}++function draftRunFinishedSuccessfully(run: AutomationRun): boolean {+ return String(run.status).toUpperCase() === "COMPLETED";+}++function draftRunFinishedWithFailure(run: AutomationRun): boolean {+ const status = String(run.status).toUpperCase();+ return status === "FAILED" || status === "CANCELLED" || status === "SKIPPED";+}++export function getDraftExecutionStatusText(+ draft: AutomationDraftApiResponse,+ runs: AutomationRun[],+ t: (key: I18nKey) => string,+): string {+ const latestRun = runs[0];+ if (latestRun) {+ if (draftRunFinishedSuccessfully(latestRun)) {+ return t(I18nKey.AUTOMATION_SETUP$LATEST_TEST_PASSED);+ }+ if (draftRunFinishedWithFailure(latestRun)) {+ return t(I18nKey.AUTOMATION_SETUP$LATEST_TEST_FAILED);+ }+ return t(I18nKey.AUTOMATION_SETUP$LATEST_TEST_RUNNING);+ }+ return (+ draft.validationErrors?.[0]?.message ??+ t(I18nKey.AUTOMATION_SETUP$READY_TO_TEST)+ );+}++export function draftRunPageErrors(+ draft: AutomationDraftApiResponse | null,+ statusMessage: { kind: "success" | "error"; text: string } | null,+ runs: AutomationRun[],+): string[] {+ const messages: string[] = [];+ const add = (value: string | null | undefined) => {+ const text = value?.trim();+ if (text && !messages.includes(text)) messages.push(text);+ };+ for (const error of draft?.validationErrors ?? []) add(error.message);+ if (statusMessage?.kind === "error") add(statusMessage.text);+ const latestFailure = runs.find(draftRunFinishedWithFailure);+ add(latestFailure?.error_detail);+ return messages;+}diff --git a/src/components/features/automations/setup/automation-setup-panel.tsx b/src/components/features/automations/setup/automation-setup-panel.tsxindex 432a4a7e95..cb3179ec74 100644--- a/src/components/features/automations/setup/automation-setup-panel.tsx+++ b/src/components/features/automations/setup/automation-setup-panel.tsx@@ -1,23 +1,31 @@import {useCallback,useEffect,+ useLayoutEffect,+ useMemo,useRef,useState,type ReactNode,} from "react";import { createPortal } from "react-dom";+import { AnimatePresence, motion, useReducedMotion } from "framer-motion";import toast from "react-hot-toast";import { useTranslation } from "react-i18next";+import { useQueryClient } from "@tanstack/react-query";import {CalendarDays,+ ChevronDown,Code2,FileText,Globe2,- Plus,+ Info,X,Zap,} from "lucide-react";-import AutomationService from "#/api/automation-service/automation-service.api";+import AutomationService, {+ type CustomWebhookCreateResponse,+} from "#/api/automation-service/automation-service.api";+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";import {clearAutomationFormSession,initializeAutomationFormSession,@@ -29,45 +37,88 @@ import type {AutomationSetupField,AutomationSetupFormPatch,AutomationSetupFormValues,- AutomationSetupKind,} from "#/api/automation-setup-types";import {- automationDetailPath,- getAutomationEndpoint,-} from "#/manifests/automation-interface";+ DEFAULT_AUTOMATION_PLUGIN_REF,+ resolveAutomationSetupPlugins,+ serializeAutomationSetupPluginList,+ type AutomationSetupPluginEntry,+} from "#/api/automation-setup-plugins";+import { automationDetailPath } 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 { OptionalTag } from "#/components/features/settings/optional-tag";import { AutomationSetupPromptStack } from "#/components/features/automations/setup/automation-setup-prompt-stack";+import { ContextMenuListItem } from "#/components/features/context-menu/context-menu-list-item";+import { formatTriggerSourceLabel } from "#/components/features/home/featured-automations/automation-run-health";+import { useClickOutsideElement } from "#/hooks/use-click-outside-element";+import { usePromptTextareaResize } from "#/hooks/use-prompt-textarea-resize";+import { useSendMessage } from "#/hooks/use-send-message";import {+ formControlBorderClassName,formControlFieldClassName,+ formControlFocusWithinClassName,+ formControlHeightClassName,formControlMultilineFieldClassName,+ formControlRadiusClassName,+ formControlSurfaceClassName,formControlTransitionClassName,} from "#/utils/form-control-classes";+import { Divider } from "#/ui/divider";import { cn } from "#/utils/utils";+import { useDeploymentCapabilities } from "#/hooks/query/use-manifest-capabilities";+import {+ invalidateConversationQueries,+ patchConversationInCache,+} from "#/hooks/mutation/conversation-mutation-utils";import { displayErrorToast } from "#/utils/custom-toast-handlers";import { useNavigation } from "#/context/navigation-context";import type {- InterfaceEndpointName,+ AutomationDraftApiResponse,SetupRequestBody,} from "#/manifests/types";+import type { 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,+ draftValidationEndpoint,+ extractDraftDispatchErrors,+ formFromServerDraft,+ getDraftExecutionStatusText,+ getResponseStatus,+ isDraftEndpointUnavailable,+ presetKindForEndpoint,+} from "./automation-setup-draft-service";+import {+ buildAutomationDraftTags,+ buildAutomationSetupModeTags,+ getAutomationDraftIdFromTags,+ hasAutomationSetupModeTag,+ removeAutomationDraftTags,+} from "#/utils/automation-draft-tags";const DEFAULT_TIMEZONE = "America/New_York";const DEFAULT_TIME = "09:00";const DEFAULT_CUSTOM_SCHEDULE = "0 9 * * *";const DEFAULT_EVENT_SOURCE = "github";+/** Used when the deployment has not advertised its event sources yet. */+const FALLBACK_EVENT_SOURCES = ["github", "gitlab", "slack", "linear", "jira"];const DEFAULT_EVENT_KEY = "issue_comment.created";const DEFAULT_CUSTOM_ENTRYPOINT = "python3 main.py";-const addOptionButtonClassName = cn(- "inline-flex w-fit shrink-0 cursor-pointer items-center rounded-lg border border-[var(--oh-border)] bg-tertiary px-3 py-1.5 text-sm text-content hover:bg-interactive-hover",- formControlTransitionClassName,-);-const MAIN_PY_FILENAME = "main.py";const DEFAULT_CUSTOM_SETUP_SCRIPT_PATH = "setup.sh";const DEFAULT_CUSTOM_SETUP_SCRIPT = `#!/usr/bin/env bash:`;+const addOptionButtonClassName = cn(+ "inline-flex w-fit shrink-0 cursor-pointer items-center rounded-lg border border-[var(--oh-border)] bg-tertiary px-3 py-1.5 text-sm text-content hover:bg-interactive-hover",+ formControlTransitionClassName,+);const DEFAULT_TIMEOUT_SECONDS = "600";const PREFLIGHT_TARBALL_PATH ="oh-internal://uploads/00000000-0000-0000-0000-000000000000";@@ -75,18 +126,35 @@ export const AGENT_FIELD_STREAM_CHARACTER_DELAY_MS = 12;export const AGENT_FIELD_STREAM_SETTLE_DELAY_MS = 160;const FREQUENCIES = [+ "once","hourly","daily","weekdays","weekly","custom",] as const;+const TIMEZONE_OPTIONS = [+ "America/New_York",+ "America/Chicago",+ "America/Denver",+ "America/Los_Angeles",+ "America/Sao_Paulo",+ "Europe/London",+ "Europe/Paris",+ "Europe/Berlin",+ "Asia/Tokyo",+ "Asia/Shanghai",+ "Asia/Kolkata",+ "Australia/Sydney",+ "UTC",+] as const;const AUTOMATION_SETUP_FIELD_RENDER_ORDER: AutomationSetupField[] = ["kind","name","prompt","pluginSource","pluginRef",+ "pluginList","repository","customCode","entrypoint",@@ -95,20 +163,48 @@ const AUTOMATION_SETUP_FIELD_RENDER_ORDER: AutomationSetupField[] = ["triggerKind","frequency","time",+ "weekday",+ "scheduleDateTime","timezone","customSchedule","eventSource","eventKey","eventFilter",+ "model",+ "agentProfileId","showTimeout","timeoutSeconds",];++type CustomWebhookSignatureScheme =+ | "hmac_sha256_hex"+ | "standard_webhooks"+ | "slack_v0";++interface CustomWebhookFormState {+ enabled: boolean;+ name: string;+ eventKeyExpr: string;+ signatureHeader: string;+ signatureScheme: CustomWebhookSignatureScheme;+ webhookSecret: string;+}++const DEFAULT_CUSTOM_WEBHOOK_EVENT_KEY_EXPR = "type";+const DEFAULT_CUSTOM_WEBHOOK_SIGNATURE_HEADER = "X-Signature-256";+const DEFAULT_CUSTOM_WEBHOOK_SIGNATURE_SCHEME: CustomWebhookSignatureScheme =+ "hmac_sha256_hex";+const NON_CHARACTER_STREAM_FIELDS = new Set<AutomationSetupField>(["kind","triggerKind","frequency",+ "weekday",+ "model",+ "agentProfileId","showTimeout","time",+ "pluginList",]);const streamingFieldHighlightClassName ="rounded-xl ring-2 ring-[#D5C76B]/80 ring-offset-2 ring-offset-base shadow-[0_0_24px_rgba(213,199,107,0.24)]";@@ -125,21 +221,13 @@ export function parseAutomationSetupRepositories(value: string): string[] {});}-function buildRepositorySource(url: string): {- url: string;- provider?: "github";-} {- const isExplicitProviderUrl =- /^[a-z][a-z\d+.-]*:\/\//i.test(url) || url.startsWith("git@");- return isExplicitProviderUrl ? { url } : { url, provider: "github" };-}-type Frequency = (typeof FREQUENCIES)[number];type StatusMessage = { kind: "success" | "error"; text: string } | null;interface AutomationSetupPanelProps {draft: AutomationSetupDraft;conversationId?: string | null;+ conversationTags?: Record<string, string> | null;toolbarPortal?: HTMLElement | null;showInlineHeader?: boolean;reserveComposerSpace?: boolean;@@ -163,18 +251,51 @@ function deriveName(prompt: string): string {return name || "New Automation";}+function defaultScheduleDateTimeLocal(): string {+ const date = new Date();+ date.setSeconds(0, 0);+ date.setMinutes(0);+ date.setHours(date.getHours() + 1);+ const month = String(date.getMonth() + 1).padStart(2, "0");+ const day = String(date.getDate()).padStart(2, "0");+ const hour = String(date.getHours()).padStart(2, "0");+ const minute = String(date.getMinutes()).padStart(2, "0");+ return `${date.getFullYear()}-${month}-${day}T${hour}:${minute}`;+}++function onceCron(scheduleDateTime: string): string {+ const match = scheduleDateTime.match(+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/,+ );+ if (!match) return DEFAULT_CUSTOM_SCHEDULE;+ const minute = Number(match[5]);+ const hour = Number(match[4]);+ const day = Number(match[3]);+ const month = Number(match[2]);+ return `${minute} ${hour} ${day} ${month} *`;+}++function cronWeekday(weekday: string): number {+ const value = Number(weekday);+ if (!Number.isInteger(value) || value < 0 || value > 6) return 1;+ return value;+}+function toCron(time: string,frequency: Frequency,customSchedule: string,+ scheduleDateTime: string,+ weekday: string,): string {if (frequency === "custom") return customSchedule || DEFAULT_CUSTOM_SCHEDULE;+ if (frequency === "once") return onceCron(scheduleDateTime);if (frequency === "hourly") return "0 * * * *";const [hour = "9", minute = "0"] = time.split(":");const cronTime = `${Number(minute)} ${Number(hour)}`;if (frequency === "weekdays") return `${cronTime} * * 1-5`;- if (frequency === "weekly") return `${cronTime} * * 1`;+ if (frequency === "weekly") return `${cronTime} * * ${cronWeekday(weekday)}`;return `${cronTime} * * *`;}@@ -203,19 +324,53 @@ function streamingHighlightClassName(isStreaming: boolean) {return isStreaming ? streamingFieldHighlightClassName : undefined;}+function buildDefaultEventTestPayload(+ eventSource: string = DEFAULT_EVENT_SOURCE,+ eventKey: string = DEFAULT_EVENT_KEY,+): string {+ return `${JSON.stringify(+ {+ source: eventSource || DEFAULT_EVENT_SOURCE,+ event: eventKey || DEFAULT_EVENT_KEY,+ action: "test",+ },+ null,+ 2,+ )}\n`;+}++function parseEventTestPayload(value: string): Record<string, unknown> | null {+ const trimmed = value.trim();+ if (!trimmed) return null;+ try {+ const parsed = JSON.parse(trimmed) as unknown;+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ return null;+ }+ return parsed as Record<string, unknown>;+ } catch {+ return null;+ }+}+function buildInitialForm(draft: AutomationSetupDraft,): AutomationSetupFormValues {const form = draft.form ?? {};const prompt = form.prompt ?? draft.prompt;const kind = form.kind ?? draft.kind;+ const pluginEntries = resolveAutomationSetupPlugins(form, draft.plugins);return {kind,name: form.name ?? deriveName(prompt),prompt,repository: form.repository ?? "",- pluginSource: form.pluginSource ?? draft.plugins?.[0] ?? "",- pluginRef: form.pluginRef ?? "",+ pluginSource: pluginEntries[0]?.source ?? "",+ pluginRef: pluginEntries[0]?.ref ?? "",+ pluginList:+ pluginEntries.length > 0+ ? serializeAutomationSetupPluginList(pluginEntries)+ : "",customCode: form.customCode ?? buildStarterPython(prompt),entrypoint: form.entrypoint ?? DEFAULT_CUSTOM_ENTRYPOINT,setupScriptPath: form.setupScriptPath ?? DEFAULT_CUSTOM_SETUP_SCRIPT_PATH,@@ -223,24 +378,117 @@ function buildInitialForm(triggerKind: form.triggerKind ?? "cron",frequency: form.frequency ?? "daily",time: form.time ?? DEFAULT_TIME,+ weekday: form.weekday ?? "1",+ scheduleDateTime: form.scheduleDateTime ?? "",timezone: form.timezone ?? DEFAULT_TIMEZONE,customSchedule: form.customSchedule ?? DEFAULT_CUSTOM_SCHEDULE,eventSource: form.eventSource ?? DEFAULT_EVENT_SOURCE,eventKey: form.eventKey ?? DEFAULT_EVENT_KEY,eventFilter: form.eventFilter ?? "",+ model: form.model ?? "",+ agentProfileId: form.agentProfileId ?? "",showTimeout: form.showTimeout ?? false,timeoutSeconds: form.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS,};}-function endpointName(kind: AutomationSetupKind): InterfaceEndpointName {- if (kind === "plugin") return "createPlugin";- if (kind === "custom") return "createBundle";- return "createPrompt";+function DraftRunDetailsCard({+ draft,+ runs,+}: {+ draft: AutomationDraftApiResponse;+ runs: AutomationRun[];+}) {+ const { t, i18n } = useTranslation("openhands");+ const validationMessage = draft.validationErrors?.[0]?.message ?? null;+ const statusText = getDraftExecutionStatusText(draft, runs, t);++ return (+ <section+ data-testid="automation-setup-draft-details"+ className="rounded-2xl border border-[var(--oh-border)] bg-[var(--oh-surface)]"+ >+ <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)]",+ )}+ >+ {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>++ <div className="px-5 py-3">+ <h4 className="text-sm font-medium text-content">+ {t(I18nKey.AUTOMATION_SETUP$TEST_RUNS)}+ </h4>+ </div>+ {runs.length > 0 ? (+ <div>+ {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",+ )}+ >+ <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>+ )}+ </section>+ );}function frequencyLabelKey(frequency: Frequency): I18nKey {switch (frequency) {+ case "once":+ return I18nKey.AUTOMATION_SETUP$FREQUENCY_ONCE;case "hourly":return I18nKey.AUTOMATION_SETUP$FREQUENCY_HOURLY;case "daily":@@ -257,15 +505,32 @@ function frequencyLabelKey(frequency: Frequency): I18nKey {export function AutomationSetupPanel({draft,conversationId,+ conversationTags,toolbarPortal,showInlineHeader = true,reserveComposerSpace = false,}: AutomationSetupPanelProps) {- const [model, setModel] = useState("");- const [agentProfileId, setAgentProfileId] = useState("");const { t } = useTranslation("openhands");const { navigate } = useNavigation();+ const deploymentCapabilities = useDeploymentCapabilities();+ const eventSourceOptions = deploymentCapabilities.data?.eventSources ?? [];+ const eventTypeOptions = deploymentCapabilities.data?.eventTypes ?? [];const [form, setForm] = useState(() => buildInitialForm(draft));+ const [eventTestPayload, setEventTestPayload] = useState(() =>+ buildDefaultEventTestPayload(DEFAULT_EVENT_SOURCE, DEFAULT_EVENT_KEY),+ );+ const [isEventTestPayloadDirty, setIsEventTestPayloadDirty] = useState(false);+ const [customWebhook, setCustomWebhook] = useState<CustomWebhookFormState>({+ enabled: false,+ name: "",+ eventKeyExpr: DEFAULT_CUSTOM_WEBHOOK_EVENT_KEY_EXPR,+ signatureHeader: DEFAULT_CUSTOM_WEBHOOK_SIGNATURE_HEADER,+ signatureScheme: DEFAULT_CUSTOM_WEBHOOK_SIGNATURE_SCHEME,+ webhookSecret: "",+ });+ const [customWebhookRegistration, setCustomWebhookRegistration] =+ useState<CustomWebhookCreateResponse | null>(null);+const [fieldMetadata, setFieldMetadata] = useState(() => draft.fieldMetadata ?? {},);@@ -273,6 +538,33 @@ export function AutomationSetupPanel({const [isSubmitting, setIsSubmitting] = useState(false);const [streamingField, setStreamingField] =useState<AutomationSetupField | null>(null);+ // Server-backed draft from OpenHands/automation PR #439. Null until the+ // first save creates the draft row; the local store stays the reactive layer+ // the agent streams into, and the server row is the persisted source of truth.+ const [serverDraft, setServerDraft] =+ useState<AutomationDraftApiResponse | null>(null);+ const [draftRuns, setDraftRuns] = useState<AutomationRun[]>([]);+ const [isHydratingServerDraft, setIsHydratingServerDraft] = useState(false);+ const [saveState, setSaveState] = useState<+ "idle" | "saving" | "saved" | "error"+ >("idle");+ const [savedDraftRequestKey, setSavedDraftRequestKey] = useState<+ string | null+ >(null);+ const [isTaggedDraftMissing, setIsTaggedDraftMissing] = useState(false);+ const queryClient = useQueryClient();+ const latestConversationTagsRef = useRef(conversationTags);+ const conversationTagUpdateQueueRef = useRef<Promise<void>>(+ Promise.resolve(),+ );+ const propTaggedServerDraftId =+ getAutomationDraftIdFromTags(conversationTags);+ const [currentTaggedServerDraftId, setCurrentTaggedServerDraftId] = useState(+ propTaggedServerDraftId,+ );+ const taggedServerDraftId = currentTaggedServerDraftId;+ const serverDraftId =+ serverDraft?.id ?? (isTaggedDraftMissing ? null : taggedServerDraftId);const streamQueueRef = useRef<{field: AutomationSetupField;@@ -287,6 +579,141 @@ export function AutomationSetupPanel({const streamTimeoutsRef = useRef<number[]>([]);const processQueuedStreamsRef = useRef<() => void>(() => {});+ useEffect(() => {+ latestConversationTagsRef.current = conversationTags;+ }, [conversationTags]);++ useEffect(() => {+ setCurrentTaggedServerDraftId(propTaggedServerDraftId);+ }, [propTaggedServerDraftId]);++ const updateConversationTags = useCallback(+ async (+ buildNextTags: (+ tags: Record<string, string> | null | undefined,+ ) => Record<string, string>,+ ) => {+ if (!conversationId) return null;++ const update = conversationTagUpdateQueueRef.current+ .catch(() => undefined)+ .then(async () => {+ const nextTags = buildNextTags(latestConversationTagsRef.current);+ const updatedConversation =+ await AgentServerConversationService.updateConversationTags(+ conversationId,+ nextTags,+ );+ const savedTags = updatedConversation.tags ?? nextTags;+ latestConversationTagsRef.current = savedTags;+ patchConversationInCache(queryClient, conversationId, {+ tags: savedTags,+ });+ invalidateConversationQueries(queryClient, conversationId);+ return updatedConversation;+ });++ conversationTagUpdateQueueRef.current = update.then(+ () => undefined,+ () => undefined,+ );+ return update;+ },+ [conversationId, queryClient],+ );++ useEffect(() => {+ if (+ !conversationId ||+ conversationTags === undefined ||+ hasAutomationSetupModeTag(conversationTags)+ ) {+ return;+ }+ updateConversationTags((tags) => buildAutomationSetupModeTags(tags)).catch(+ (error: unknown) => {+ displayErrorToast(error instanceof Error ? error.message : null);+ },+ );+ }, [conversationId, conversationTags, updateConversationTags]);++ const saveDraftInFormSession = useCallback(+ (+ saved: AutomationDraftApiResponse,+ nextForm: AutomationSetupFormValues,+ ) => {+ if (!conversationId) return;+ initializeAutomationFormSession(conversationId, {+ ...draft,+ prompt: nextForm.prompt ?? draft.prompt,+ kind: nextForm.kind ?? draft.kind,+ form: nextForm,+ fieldMetadata,+ serverDraftId: saved.id,+ ...(saved.materializedAutomationId+ ? { materializedAutomationId: saved.materializedAutomationId }+ : {}),+ });+ },+ [conversationId, draft, fieldMetadata],+ );++ const updateConversationDraftTags = useCallback(+ async (draftId: string | null) => {+ if (!conversationId) return;+ await updateConversationTags((tags) =>+ draftId+ ? buildAutomationDraftTags(tags, draftId)+ : removeAutomationDraftTags(tags),+ );+ setCurrentTaggedServerDraftId(draftId);+ },+ [conversationId, updateConversationTags],+ );++ useEffect(() => {+ if (!taggedServerDraftId || serverDraft?.id === taggedServerDraftId) {+ return undefined;+ }++ let cancelled = false;+ setIsHydratingServerDraft(true);+ setSavedDraftRequestKey(null);+ setIsTaggedDraftMissing(false);++ AutomationService.getServerDraft(taggedServerDraftId)+ .then((saved) => {+ if (cancelled) return;+ const nextForm = formFromServerDraft(saved, buildInitialForm(draft));+ setServerDraft(saved);+ setDraftRuns([]);+ setForm(nextForm);+ saveDraftInFormSession(saved, nextForm);+ })+ .catch((error: unknown) => {+ if (cancelled) return;+ if (getResponseStatus(error) === 404) {+ setServerDraft(null);+ setIsTaggedDraftMissing(true);+ return;+ }+ displayErrorToast(error instanceof Error ? error.message : null);+ })+ .finally(() => {+ if (!cancelled) setIsHydratingServerDraft(false);+ });++ return () => {+ cancelled = true;+ };+ }, [+ conversationId,+ draft,+ saveDraftInFormSession,+ serverDraft?.id,+ taggedServerDraftId,+ ]);+const {kind,name,@@ -294,6 +721,7 @@ export function AutomationSetupPanel({repository,pluginSource,pluginRef,+ pluginList,customCode,entrypoint,setupScriptPath,@@ -301,15 +729,24 @@ export function AutomationSetupPanel({triggerKind,frequency,time,+ weekday,+ scheduleDateTime,timezone,customSchedule,eventSource,eventKey,eventFilter,+ model,+ agentProfileId,showTimeout,timeoutSeconds,} = form;+ useEffect(() => {+ if (isEventTestPayloadDirty) return;+ setEventTestPayload(buildDefaultEventTestPayload(eventSource, eventKey));+ }, [eventSource, eventKey, isEventTestPayloadDirty]);+const clearQueuedStreams = useCallback(() => {streamGenerationRef.current += 1;for (const timeoutId of streamTimeoutsRef.current) {@@ -487,6 +924,7 @@ export function AutomationSetupPanel({) => {clearQueuedStreams();setStatusMessage(null);+ setSaveState("idle");setForm((previous) => ({ ...previous, [field]: value }));if (!conversationId) return;patchAutomationFormSession(@@ -496,11 +934,63 @@ export function AutomationSetupPanel({);};+ const pluginEntries = useMemo(+ () =>+ resolveAutomationSetupPlugins(+ { pluginList, pluginSource, pluginRef },+ draft.plugins,+ ),+ [draft.plugins, pluginList, pluginRef, pluginSource],+ );+ const configuredPlugins = pluginEntries.flatMap((entry) => {+ const source = entry.source.trim();+ if (!source) return [];+ const ref = entry.ref.trim();+ return [{ source, ...(ref ? { ref } : {}) }];+ });+ const pluginEndpointSource = configuredPlugins[0]?.source ?? "";++ const writePlugins = (entries: AutomationSetupPluginEntry[]) => {+ const nextList =+ entries.length > 0 ? serializeAutomationSetupPluginList(entries) : "";+ const nextSource = entries[0]?.source ?? "";+ const nextRef = entries[0]?.ref ?? "";+ clearQueuedStreams();+ setStatusMessage(null);+ setSaveState("idle");+ setForm((previous) => ({+ ...previous,+ pluginList: nextList,+ pluginSource: nextSource,+ pluginRef: nextRef,+ }));+ if (!conversationId) return;+ patchAutomationFormSession(+ conversationId,+ {+ pluginList: nextList,+ pluginSource: nextSource,+ pluginRef: nextRef,+ },+ { source: "user" },+ );+ };+const agentUpdatedSuffix = (field: AutomationSetupField) =>fieldMetadata[field]?.updatedBy === "agent"? t(I18nKey.AUTOMATION_SETUP$FILLED_BY_OPENHANDS): undefined;+ const updateCustomWebhook = <FieldName extends keyof CustomWebhookFormState>(+ field: FieldName,+ value: CustomWebhookFormState[FieldName],+ ) => {+ setStatusMessage(null);+ setSaveState("idle");+ setCustomWebhookRegistration(null);+ setCustomWebhook((previous) => ({ ...previous, [field]: value }));+ };+const normalizedName = () => name.trim() || deriveName(prompt);const buildTrigger = () =>triggerKind === "event"@@ -512,35 +1002,34 @@ export function AutomationSetupPanel({}: {type: "cron",- schedule: toCron(time, frequency, customSchedule.trim()),+ schedule: toCron(+ time,+ frequency,+ customSchedule.trim(),+ scheduleDateTime,+ weekday,+ ),timezone: timezone.trim() || DEFAULT_TIMEZONE,};const buildPresetBody = (): SetupRequestBody => {+ const trimmedPrompt = prompt.trim();const body: SetupRequestBody = {name: normalizedName(),- prompt: prompt.trim(),+ ...(trimmedPrompt ? { prompt: trimmedPrompt } : {}),trigger: buildTrigger(),enabled: false,} as SetupRequestBody;- if (agentProfileId.trim()) {- body.agent_profile_id = agentProfileId.trim();- } else if (model.trim()) {- body.model = model.trim();- }const repositories = parseAutomationSetupRepositories(repository);if (repositories.length > 0) {- body.repos = repositories.map(buildRepositorySource);+ body.repos = repositories.map((url) => ({ url, provider: "github" }));}if (showTimeout && timeoutSeconds.trim())body.timeout = Number(timeoutSeconds);- if (kind === "plugin") {- body.plugins = [- {- source: pluginSource.trim(),- ...(pluginRef.trim() ? { ref: pluginRef.trim() } : {}),- },- ];+ if (configuredPlugins.length > 0) {+ body.plugins = configuredPlugins;}+ if (model.trim()) body.model = model.trim();+ if (agentProfileId.trim()) body.agent_profile_id = agentProfileId.trim();return body;};const buildCustomBody = (tarballPath: string): SetupRequestBody =>@@ -549,12 +1038,204 @@ export function AutomationSetupPanel({trigger: buildTrigger(),tarball_path: tarballPath,entrypoint: entrypoint.trim(),- enabled: false,setup_script_path: setupScriptPath.trim(),...(showTimeout && timeoutSeconds.trim()? { timeout: Number(timeoutSeconds) }: {}),}) as SetupRequestBody;+ /**+ * The request body sent to a server-backed draft. Custom drafts reference a+ * tarball path, but a draft is saved before the upload happens, so the+ * preflight stand-in path stands in until dispatch. Preset drafts carry the+ * same body the final create call would, minus the upload-only fields.+ */+ const draftRequestBody = (+ tarballPath: string = PREFLIGHT_TARBALL_PATH,+ ): SetupRequestBody =>+ kind === "custom" ? buildCustomBody(tarballPath) : buildPresetBody();+ const draftValidationByField = useMemo(() => {+ const byField = new Map<string, string>();+ for (const error of serverDraft?.validationErrors ?? []) {+ if (error.field && !byField.has(error.field)) {+ byField.set(error.field, error.message);+ }+ }+ return byField;+ }, [serverDraft?.validationErrors]);+ const fieldError = (field: string): string | undefined =>+ draftValidationByField.get(field);+ const normalizeDraftForDirtyCheck = (body: SetupRequestBody) => {+ if (kind !== "custom" || typeof body !== "object" || body === null) {+ return body;+ }+ return { ...body, tarball_path: PREFLIGHT_TARBALL_PATH };+ };+ const draftRequestKey = (+ endpoint: string,+ draftName: string,+ body: SetupRequestBody,+ ) =>+ JSON.stringify({+ endpoint,+ name: draftName,+ draft: normalizeDraftForDirtyCheck(body),+ customSource:+ kind === "custom"+ ? {+ customCode,+ setupScript,+ }+ : undefined,+ });+ const currentDraftRequestKey = useMemo(+ () =>+ draftRequestKey(+ draftEndpoint(kind, pluginEndpointSource),+ normalizedName(),+ draftRequestBody(),+ ),+ [+ kind,+ name,+ prompt,+ repository,+ pluginSource,+ pluginRef,+ pluginList,+ customCode,+ entrypoint,+ setupScriptPath,+ setupScript,+ triggerKind,+ frequency,+ time,+ weekday,+ scheduleDateTime,+ timezone,+ customSchedule,+ eventSource,+ eventKey,+ eventFilter,+ model,+ agentProfileId,+ showTimeout,+ timeoutSeconds,+ ],+ );+ const isDraftDirty = savedDraftRequestKey+ ? savedDraftRequestKey !== currentDraftRequestKey+ : !serverDraft ||+ draftRequestKey(+ serverDraft.endpoint,+ serverDraft.name ?? "",+ serverDraft.draft,+ ) !== currentDraftRequestKey;+ const wasHydratingServerDraftRef = useRef(false);+ useEffect(() => {+ if (isHydratingServerDraft) {+ wasHydratingServerDraftRef.current = true;+ return;+ }+ if (!wasHydratingServerDraftRef.current || !serverDraft) return;+ wasHydratingServerDraftRef.current = false;+ setSavedDraftRequestKey(currentDraftRequestKey);+ }, [currentDraftRequestKey, isHydratingServerDraft, serverDraft]);++ const ensureCustomWebhookSource = async (): Promise<boolean> => {+ if (triggerKind !== "event" || !customWebhook.enabled) return true;+ const source = eventSource.trim();+ if (!source) {+ setSaveState("error");+ setStatusMessage({+ kind: "error",+ text: t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SOURCE_REQUIRED),+ });+ return false;+ }+ if (customWebhookRegistration?.source === source) return true;++ try {+ const webhook = await AutomationService.createCustomWebhook({+ name:+ customWebhook.name.trim() ||+ t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_DEFAULT_NAME, { source }),+ source,+ event_key_expr:+ customWebhook.eventKeyExpr.trim() ||+ DEFAULT_CUSTOM_WEBHOOK_EVENT_KEY_EXPR,+ signature_header:+ customWebhook.signatureHeader.trim() ||+ DEFAULT_CUSTOM_WEBHOOK_SIGNATURE_HEADER,+ signature_scheme: customWebhook.signatureScheme,+ ...(customWebhook.webhookSecret.trim()+ ? { webhook_secret: customWebhook.webhookSecret.trim() }+ : {}),+ });+ setCustomWebhookRegistration(webhook);+ return true;+ } catch (error) {+ if (getResponseStatus(error) === 409) {+ setStatusMessage({+ kind: "success",+ text: t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_ALREADY_EXISTS, {+ source,+ }),+ });+ return true;+ }+ setSaveState("error");+ displayErrorToast(error instanceof Error ? error.message : null);+ return false;+ }+ };++ const uploadCustomArchive = async (): Promise<string> => {+ const archive = await packTarGzip([+ { name: MAIN_PY_FILENAME, content: customCode, mode: 0o644 },+ {+ name: setupScriptPath.trim(),+ content: setupScript,+ mode: 0o755,+ },+ ]);+ return AutomationService.uploadAutomationTarball(normalizedName(), archive);+ };+ const persistServerDraft = async (+ tarballPath?: string,+ ): Promise<AutomationDraftApiResponse> => {+ const body = draftRequestBody(tarballPath);+ const request = {+ endpoint: draftEndpoint(kind, pluginEndpointSource),+ draft: body,+ name: normalizedName(),+ };+ const saved = serverDraftId+ ? await AutomationService.updateServerDraft(serverDraftId, request)+ : await AutomationService.createServerDraft(request);+ setServerDraft(saved);+ saveDraftInFormSession(saved, form);+ setSavedDraftRequestKey(+ draftRequestKey(request.endpoint, request.name ?? "", request.draft),+ );+ setIsTaggedDraftMissing(false);+ await updateConversationDraftTags(saved.id);+ return saved;+ };+ const runPreflightValidation = async () => {+ const result = await AutomationService.validateDraft({+ endpoint: draftValidationEndpoint(kind, pluginEndpointSource),+ draft:+ kind === "custom"+ ? buildCustomBody(PREFLIGHT_TARBALL_PATH)+ : buildPresetBody(),+ });+ setStatusMessage({+ kind: result.valid ? "success" : "error",+ text: result.valid+ ? t(I18nKey.AUTOMATION_SETUP$READY_TO_TEST)+ : result.errors[0]?.message || t(I18nKey.SETUP$SUBMIT_FAILED),+ });+ };const validateRequiredFields = (): boolean => {if (!prompt.trim() && kind !== "custom") {setStatusMessage({@@ -563,7 +1244,10 @@ export function AutomationSetupPanel({});return false;}- if (kind === "plugin" && !pluginSource.trim()) {+ if (+ kind !== "custom" &&+ pluginEntries.some((entry) => entry.ref.trim() && !entry.source.trim())+ ) {setStatusMessage({kind: "error",text: t(I18nKey.AUTOMATION_SETUP$PLUGIN_REQUIRED),@@ -600,31 +1284,123 @@ export function AutomationSetupPanel({}return true;};- const handleSaveDraft = () => {- setStatusMessage({- kind: "success",- text: t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED),- });+ const handleSaveDraft = async () => {+ setIsSubmitting(true);+ setSaveState("saving");+ try {+ if (!(await ensureCustomWebhookSource())) return;+ if (!draftsSupported) {+ setSaveState("saved");+ setStatusMessage({+ kind: "success",+ text: t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED),+ });+ return;+ }+ const tarballPath =+ kind === "custom" ? await uploadCustomArchive() : undefined;+ const saved = await persistServerDraft(tarballPath);+ setSaveState("saved");+ setStatusMessage({+ kind: "success",+ text:+ saved.validationErrors?.[0]?.message ??+ t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED),+ });+ } catch (error) {+ if (isDraftEndpointUnavailable(error)) {+ setSaveState("saved");+ setStatusMessage({+ kind: "success",+ text: t(I18nKey.AUTOMATION_SETUP$DRAFT_SAVED),+ });+ return;+ }+ setSaveState("error");+ displayErrorToast(error instanceof Error ? error.message : null);+ } finally {+ setIsSubmitting(false);+ }};const handleTest = async () => {if (!validateRequiredFields()) return;+ const eventPayload =+ triggerKind === "event" ? parseEventTestPayload(eventTestPayload) : null;+ if (triggerKind === "event" && eventPayload === null) {+ setStatusMessage({+ kind: "error",+ text: t(I18nKey.AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_INVALID),+ });+ return;+ }setIsSubmitting(true);+ setSaveState("saving");try {- const result = await AutomationService.validateDraft({- endpoint: getAutomationEndpoint(endpointName(kind)),- draft:- kind === "custom"- ? buildCustomBody(PREFLIGHT_TARBALL_PATH)- : buildPresetBody(),+ if (!(await ensureCustomWebhookSource())) return;+ if (!draftsSupported) {+ setSaveState("saved");+ await runPreflightValidation();+ return;+ }++ // Persist the current form state as a draft first, then dispatch it.+ // The service materializes the validated draft body into a disabled+ // automation and starts a manual run; the draft row stays as source+ // of truth for further edits.+ const tarballPath =+ kind === "custom" ? await uploadCustomArchive() : undefined;+ const saved = await persistServerDraft(tarballPath);+ setSaveState("saved");++ if (!saved.dispatchable) {+ setStatusMessage({+ kind: "error",+ text:+ saved.validationErrors?.[0]?.message ??+ t(I18nKey.SETUP$SUBMIT_FAILED),+ });+ return;+ }++ const run = eventPayload+ ? await AutomationService.dispatchServerDraft(saved.id, {+ eventPayload,+ })+ : await AutomationService.dispatchServerDraft(saved.id);+ const materializedAutomationId =+ typeof (run as unknown as Record<string, unknown>).automation_id ===+ "string"+ ? String((run as unknown as Record<string, unknown>).automation_id)+ : saved.materializedAutomationId;+ setServerDraft({+ ...saved,+ materializedAutomationId,+ lastTestRunId: run.id,});+ setDraftRuns((previous) => [+ run,+ ...previous.filter((existing) => existing.id !== run.id),+ ]);setStatusMessage({- kind: result.valid ? "success" : "error",- text: result.valid- ? t(I18nKey.AUTOMATION_SETUP$TEST_PASSED)- : result.errors[0]?.message || t(I18nKey.SETUP$SUBMIT_FAILED),+ kind: "success",+ text: t(I18nKey.AUTOMATION_SETUP$TEST_DISPATCHED),});} catch (error) {- displayErrorToast(error instanceof Error ? error.message : null);+ if (isDraftEndpointUnavailable(error)) {+ setSaveState("saved");+ await runPreflightValidation();+ return;+ }+ setSaveState("error");+ const dispatchError = extractDraftDispatchErrors(error);+ if (dispatchError) {+ setStatusMessage({+ kind: "error",+ text: dispatchError,+ });+ } else {+ displayErrorToast(error instanceof Error ? error.message : null);+ }} finally {setIsSubmitting(false);}@@ -632,21 +1408,12 @@ export function AutomationSetupPanel({const handleCreate = async () => {if (!validateRequiredFields()) return;setIsSubmitting(true);+ setSaveState(serverDraftId ? "saving" : saveState);try {+ if (!(await ensureCustomWebhookSource())) return;let created: Record<string, unknown>;if (kind === "custom") {- const archive = await packTarGzip([- { name: MAIN_PY_FILENAME, content: customCode, mode: 0o644 },- {- name: setupScriptPath.trim(),- content: setupScript,- mode: 0o755,- },- ]);- const tarballPath = await AutomationService.uploadAutomationTarball(- normalizedName(),- archive,- );+ const tarballPath = await uploadCustomArchive();created = await AutomationService.createAutomationDraft(buildCustomBody(tarballPath),kind,@@ -654,10 +1421,25 @@ export function AutomationSetupPanel({} else {created = await AutomationService.createAutomationDraft(buildPresetBody(),- kind,+ presetKindForEndpoint(kind, pluginEndpointSource),);}+ setSaveState("saved");toast.success(t(I18nKey.AUTOMATION_SETUP$CREATED));+ // The draft has been finalized into a real automation; drop the+ // persisted draft row so it does not linger as an incomplete setup.+ if (serverDraftId) {+ try {+ await AutomationService.deleteServerDraft(serverDraftId);+ } catch {+ // Cleanup is best-effort; the automation was created either way.+ }+ try {+ await updateConversationDraftTags(null);+ } catch {+ // Tag cleanup is best-effort once the automation exists.+ }+ }if (typeof created.id === "string")navigate(automationDetailPath(created.id));} catch (error) {@@ -667,16 +1449,65 @@ export function AutomationSetupPanel({}};+ useEffect(() => {+ const automationId = serverDraft?.materializedAutomationId;+ if (!automationId) {+ setDraftRuns([]);+ return undefined;+ }++ let cancelled = false;+ AutomationService.listAutomationRuns(automationId, { limit: 10, offset: 0 })+ .then((response) => {+ if (!cancelled && response.runs.length > 0) setDraftRuns(response.runs);+ })+ .catch(() => {+ if (!cancelled) setDraftRuns((previous) => previous);+ });++ return () => {+ cancelled = true;+ };+ }, [serverDraft?.materializedAutomationId]);++ const saveStateLabel = () => {+ if (saveState === "saving") return t(I18nKey.AUTOMATION_SETUP$SAVING);+ if (saveState === "error") return t(I18nKey.AUTOMATION_SETUP$SAVE_FAILED);+ if (serverDraft && !isDraftDirty) {+ return t(I18nKey.AUTOMATION_SETUP$SAVED_JUST_NOW);+ }+ if (isDraftDirty) return t(I18nKey.AUTOMATION_SETUP$UNSAVED_CHANGES);+ return null;+ };+const compactToolbarButtonClassName = "!h-7 !min-h-7 !px-2.5 !text-xs";+ const visiblePluginEntries = kind === "custom" ? [] : pluginEntries;+ const addPlugin = () =>+ writePlugins([+ ...pluginEntries,+ { source: "", ref: DEFAULT_AUTOMATION_PLUGIN_REF },+ ]);+ const saveStateText = saveStateLabel();+ const draftsSupported = AutomationService.supportsAutomationDrafts(+ deploymentCapabilities.data,+ );const renderToolbarActions = () => (<div className="flex shrink-0 items-center gap-1.5">+ {saveStateText ? (+ <span+ data-testid="automation-setup-save-state"+ className="shrink-0 text-xs text-[var(--oh-muted)]"+ >+ {saveStateText}+ </span>+ ) : null}<BrandButtontype="button"variant="secondary"testId="automation-setup-save-draft"className={compactToolbarButtonClassName}- isDisabled+ isDisabled={isSubmitting}onClick={handleSaveDraft}>{t(I18nKey.AUTOMATION_SETUP$SAVE_DRAFT)}@@ -687,6 +1518,7 @@ export function AutomationSetupPanel({testId="automation-setup-test"className={compactToolbarButtonClassName}isDisabled={isSubmitting}+ aria-busy={isSubmitting}onClick={handleTest}>{t(I18nKey.AUTOMATION_SETUP$TEST)}@@ -697,6 +1529,7 @@ export function AutomationSetupPanel({testId="automation-setup-create"className={compactToolbarButtonClassName}isDisabled={isSubmitting}+ aria-busy={isSubmitting}onClick={handleCreate}>{t(I18nKey.AUTOMATIONS$CREATE_AUTOMATION_BUTTON)}@@ -735,6 +1568,7 @@ export function AutomationSetupPanel({label={t(I18nKey.AUTOMATIONS$NAME)}suffix={agentUpdatedSuffix("name")}isStreaming={streamingField === "name"}+ errorText={fieldError("name")}><inputdata-testid="automation-setup-name"@@ -745,12 +1579,43 @@ export function AutomationSetupPanel({/></Field>+ {isHydratingServerDraft ? (+ <p+ data-testid="automation-setup-draft-loading"+ className="rounded-2xl border border-[var(--oh-border)] bg-[var(--oh-surface)] px-5 py-4 text-sm text-muted"+ >+ {t(I18nKey.AUTOMATION_SETUP$LOADING_DRAFT)}+ </p>+ ) : null}++ {isTaggedDraftMissing ? (+ <p+ data-testid="automation-setup-draft-missing"+ className="rounded-2xl border border-[var(--oh-warning)]/40 bg-[var(--oh-warning)]/10 px-5 py-4 text-sm text-[var(--oh-warning)]"+ >+ {t(I18nKey.AUTOMATION_SETUP$DRAFT_MISSING)}+ </p>+ ) : null}++ {serverDraft ? (+ <DraftRunDetailsCard draft={serverDraft} runs={draftRuns} />+ ) : 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><buttontype="button"@@ -778,48 +1643,55 @@ export function AutomationSetupPanel({: t(I18nKey.AUTOMATION_SETUP$TYPE_CUSTOM)}</button></div>- {kind !== "custom" ? (- <AutomationSetupPromptStack- prompt={prompt}- repository={repository}- updatedSuffix={agentUpdatedSuffix("prompt")}- repositorySuffix={agentUpdatedSuffix("repository")}- showTitle={false}- isStreaming={streamingField === "prompt"}- onPromptChange={(value) => updateField("prompt", value)}- onRepositoryChange={(value) =>- updateField("repository", value)- }- model={model}- onModelChange={setModel}- agentProfileId={agentProfileId}- onAgentProfileChange={setAgentProfileId}- />- ) : (- <CustomCodeFields- code={customCode}- entrypoint={entrypoint}- setupScriptPath={setupScriptPath}- setupScript={setupScript}- updatedSuffixes={{- customCode: agentUpdatedSuffix("customCode"),- entrypoint: agentUpdatedSuffix("entrypoint"),- setupScriptPath: agentUpdatedSuffix("setupScriptPath"),- setupScript: agentUpdatedSuffix("setupScript"),- }}- streamingField={streamingField}- onCodeChange={(value) => updateField("customCode", value)}- onEntrypointChange={(value) =>- updateField("entrypoint", value)- }- onSetupScriptPathChange={(value) =>- updateField("setupScriptPath", value)- }- onSetupScriptChange={(value) =>- updateField("setupScript", value)- }- />- )}+ <SetupKindCrossfade+ 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)+ }+ />+ ) : (+ <CustomCodeFields+ code={customCode}+ entrypoint={entrypoint}+ setupScriptPath={setupScriptPath}+ setupScript={setupScript}+ updatedSuffixes={{+ customCode: agentUpdatedSuffix("customCode"),+ entrypoint: agentUpdatedSuffix("entrypoint"),+ setupScriptPath: agentUpdatedSuffix("setupScriptPath"),+ setupScript: agentUpdatedSuffix("setupScript"),+ }}+ streamingField={streamingField}+ onCodeChange={(value) => updateField("customCode", value)}+ onEntrypointChange={(value) =>+ updateField("entrypoint", value)+ }+ onSetupScriptPathChange={(value) =>+ updateField("setupScriptPath", value)+ }+ onSetupScriptChange={(value) =>+ updateField("setupScript", value)+ }+ />+ )}+ </SetupKindCrossfade></div><section className="flex flex-col gap-2.5">@@ -852,6 +1724,8 @@ export function AutomationSetupPanel({<ScheduleFieldsfrequency={frequency}time={time}+ weekday={weekday}+ scheduleDateTime={scheduleDateTime}timezone={timezone}customSchedule={customSchedule}updatedSuffixes={{@@ -861,8 +1735,20 @@ export function AutomationSetupPanel({customSchedule: agentUpdatedSuffix("customSchedule"),}}streamingField={streamingField}- setFrequency={(value) => updateField("frequency", value)}+ 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)@@ -873,6 +1759,11 @@ export function AutomationSetupPanel({eventSource={eventSource}eventKey={eventKey}eventFilter={eventFilter}+ eventTestPayload={eventTestPayload}+ eventSourceOptions={eventSourceOptions}+ eventTypeOptions={eventTypeOptions}+ customWebhook={customWebhook}+ customWebhookRegistration={customWebhookRegistration}updatedSuffixes={{eventSource: agentUpdatedSuffix("eventSource"),eventKey: agentUpdatedSuffix("eventKey"),@@ -882,6 +1773,11 @@ export function AutomationSetupPanel({setEventSource={(value) => updateField("eventSource", value)}setEventKey={(value) => updateField("eventKey", value)}setEventFilter={(value) => updateField("eventFilter", value)}+ setEventTestPayload={(value) => {+ setIsEventTestPayloadDirty(true);+ setEventTestPayload(value);+ }}+ setCustomWebhookField={updateCustomWebhook}/>)}@@ -889,131 +1785,223 @@ export function AutomationSetupPanel({<span className="text-sm">{t(I18nKey.AUTOMATION_SETUP$ADDITIONAL_OPTIONS)}</span>- {kind === "plugin" ? (+ {visiblePluginEntries.length > 0 ? (<divdata-testid="automation-setup-plugin-module"className="flex flex-col gap-3 rounded-xl border border-[var(--oh-border)] bg-base-secondary p-4">- <div className="flex min-w-0 items-end gap-2">- <div className="grid min-w-0 flex-1 gap-3 md:grid-cols-[2fr_1fr]">- <Field- label={t(I18nKey.AUTOMATION_SETUP$PLUGIN_SOURCE)}- suffix={agentUpdatedSuffix("pluginSource")}- isStreaming={streamingField === "pluginSource"}- >- <input- data-testid="automation-setup-plugin-source"- value={pluginSource}- placeholder={t(- I18nKey.AUTOMATION_SETUP$PLUGIN_SOURCE_PLACEHOLDER,- )}- onChange={(event) =>- updateField("pluginSource", event.target.value)+ {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}- className={formControlFieldClassName}- />- </Field>- <Field- label={t(I18nKey.AUTOMATION_SETUP$PLUGIN_REF)}- suffix={agentUpdatedSuffix("pluginRef")}- isStreaming={streamingField === "pluginRef"}+ isStreaming={+ index === 0 && streamingField === "pluginSource"+ }+ >+ <input+ data-testid={+ index === 0+ ? "automation-setup-plugin-source"+ : `automation-setup-plugin-source-${index}`+ }+ value={entry.source}+ aria-label={+ index === 0+ ? undefined+ : t(I18nKey.AUTOMATION_SETUP$PLUGIN_SOURCE)+ }+ placeholder={t(+ I18nKey.AUTOMATION_SETUP$PLUGIN_SOURCE_PLACEHOLDER,+ )}+ onChange={(event) =>+ writePlugins(+ pluginEntries.map((plugin, entryIndex) =>+ entryIndex === index+ ? { ...plugin, source: event.target.value }+ : plugin,+ ),+ )+ }+ className={formControlFieldClassName}+ />+ </Field>+ <Field+ label={t(I18nKey.AUTOMATION_SETUP$PLUGIN_REF)}+ showLabel={index === 0}+ suffix={+ index === 0+ ? agentUpdatedSuffix("pluginRef")+ : undefined+ }+ isStreaming={+ index === 0 && streamingField === "pluginRef"+ }+ >+ <input+ data-testid={+ index === 0+ ? "automation-setup-plugin-ref"+ : `automation-setup-plugin-ref-${index}`+ }+ value={entry.ref}+ aria-label={+ index === 0+ ? undefined+ : t(I18nKey.AUTOMATION_SETUP$PLUGIN_REF)+ }+ placeholder={t(+ I18nKey.AUTOMATION_SETUP$PLUGIN_REF_PLACEHOLDER,+ )}+ onChange={(event) =>+ writePlugins(+ pluginEntries.map((plugin, entryIndex) =>+ entryIndex === index+ ? { ...plugin, ref: event.target.value }+ : plugin,+ ),+ )+ }+ className={formControlFieldClassName}+ />+ </Field>+ </div>+ <div+ className={cn(+ "flex shrink-0 items-center",+ index === 0 && formControlHeightClassName,+ )}>- <input- data-testid="automation-setup-plugin-ref"- value={pluginRef}- placeholder={t(- I18nKey.AUTOMATION_SETUP$PLUGIN_REF_PLACEHOLDER,- )}- onChange={(event) =>- updateField("pluginRef", event.target.value)+ <button+ type="button"+ data-testid={+ index === 0+ ? "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>- <button- type="button"- data-testid="automation-setup-plugin-remove"- aria-label={t(I18nKey.COMMON$REMOVE)}- onClick={() => {- updateField("pluginSource", "");- updateField("pluginRef", "");- updateField("kind", "prompt");- }}- className={cn(- "flex size-9 shrink-0 items-center justify-center rounded-lg border border-[var(--oh-border)] text-[var(--oh-muted)] hover:bg-white/5 hover:text-white",- formControlTransitionClassName,- )}- >- <X className="size-4" aria-hidden />- </button>- </div>- </div>- ) : null}- {showTimeout ? (- <div className="flex min-w-0 items-end gap-2">- <div className="min-w-0 flex-1">- <Field- label={t(I18nKey.AUTOMATION_SETUP$TIMEOUT_SECONDS)}- suffix={agentUpdatedSuffix("timeoutSeconds")}- isStreaming={streamingField === "timeoutSeconds"}- >- <input- data-testid="automation-setup-timeout"- type="number"- min="1"- value={timeoutSeconds}- onChange={(event) =>- updateField("timeoutSeconds", event.target.value)- }- className={formControlFieldClassName}- />- </Field>- </div>+ ))}<buttontype="button"- data-testid="automation-setup-timeout-remove"- aria-label={t(I18nKey.COMMON$REMOVE)}- onClick={() => updateField("showTimeout", false)}+ data-testid="automation-setup-add-plugin"+ onClick={addPlugin}className={cn(- "flex size-9 shrink-0 items-center justify-center rounded-lg border border-[var(--oh-border)] text-[var(--oh-muted)] hover:bg-white/5 hover:text-white",- formControlTransitionClassName,+ addOptionButtonClassName,+ streamingHighlightClassName(+ streamingField === "pluginSource",+ ),)}>- <X className="size-4" aria-hidden />+ {`${t(I18nKey.BUTTON$ADD)} ${t(I18nKey.AUTOMATION_SETUP$TYPE_PLUGIN)}`}</button></div>) : null}- <div className="flex flex-wrap items-center gap-2">- {kind !== "plugin" ? (- <button- type="button"- data-testid="automation-setup-add-plugin"- onClick={() => updateField("kind", "plugin")}- className={cn(addOptionButtonClassName, "gap-1.5")}- >- <Plus className="size-4" aria-hidden />- {`${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)}+ {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,- "gap-1.5",+ formControlFieldClassName,streamingHighlightClassName(- streamingField === "showTimeout",+ streamingField === "timeoutSeconds",),)}- >- <Plus className="size-4" aria-hidden />- {t(I18nKey.AUTOMATION_SETUP$ADD_TIMEOUT)}- </button>- ) : null}- </div>+ />+ </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>{statusMessage && (@@ -1037,6 +2025,59 @@ export function AutomationSetupPanel({);}+const SETUP_KIND_CROSSFADE_SECONDS = 0.15;++function SetupKindCrossfade({+ view,+ children,+}: {+ view: "prompt" | "custom";+ children: ReactNode;+}) {+ const reduceMotion = useReducedMotion();+ if (reduceMotion || import.meta.env.MODE === "test") {+ return children;+ }++ return (+ <div className="relative">+ <AnimatePresence initial={false}>+ <motion.div+ key={view}+ data-testid="automation-setup-kind-crossfade"+ data-kind={view}+ className="w-full"+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{+ opacity: 0,+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ pointerEvents: "none",+ }}+ transition={{+ duration: SETUP_KIND_CROSSFADE_SECONDS,+ ease: "easeInOut",+ }}+ >+ {children}+ </motion.div>+ </AnimatePresence>+ </div>+ );+}++const CUSTOM_CODE_LINE_HEIGHT_PX = 20;+const CUSTOM_CODE_PAD_PX = 16;+const CUSTOM_CODE_VISIBLE_LINES = 12;+/** Top inset plus whole lines, so the scrollbar sits on the card edge and the clip falls between lines. */+const CUSTOM_CODE_MIN_HEIGHT =+ CUSTOM_CODE_PAD_PX + CUSTOM_CODE_VISIBLE_LINES * CUSTOM_CODE_LINE_HEIGHT_PX;+const CUSTOM_CODE_MAX_HEIGHT =+ CUSTOM_CODE_PAD_PX + 28 * CUSTOM_CODE_LINE_HEIGHT_PX;+function CustomCodeFields({code,entrypoint,@@ -1066,118 +2107,282 @@ function CustomCodeFields({onSetupScriptChange: (value: string) => void;}) {const { t } = useTranslation("openhands");+ const reduceMotion = useReducedMotion();+ const textareaRef = useRef<HTMLTextAreaElement>(null);+ const frameRef = useRef<HTMLDivElement>(null);+ const [detailsOpen, setDetailsOpen] = useState(+ () =>+ entrypoint !== DEFAULT_CUSTOM_ENTRYPOINT ||+ setupScriptPath !== DEFAULT_CUSTOM_SETUP_SCRIPT_PATH ||+ setupScript !== DEFAULT_CUSTOM_SETUP_SCRIPT,+ );+ const { gripRef, isGripDragging, handleGripMouseDown, handleGripTouchStart } =+ usePromptTextareaResize(frameRef, {+ minHeight: CUSTOM_CODE_MIN_HEIGHT,+ maxHeight: CUSTOM_CODE_MAX_HEIGHT,+ contentKey: code,+ });++ useLayoutEffect(() => {+ const textarea = textareaRef.current;+ if (!textarea) return;+ textarea.style.height = "0px";+ textarea.style.height = `${textarea.scrollHeight}px`;+ }, [code]);+return (- <div className="flex flex-col gap-4">- <div className="grid gap-3 md:grid-cols-[2fr_1fr]">- <Field- label={t(I18nKey.AUTOMATION_SETUP$ENTRYPOINT)}- suffix={updatedSuffixes.entrypoint}- isStreaming={streamingField === "entrypoint"}+ <div className="relative w-full">+ <div+ data-streaming-active={+ streamingField === "customCode" ? "true" : undefined+ }+ className={cn(+ "relative z-10 -mb-[15px] overflow-hidden rounded-[15px] border border-[var(--oh-border)] bg-[var(--oh-surface)]",+ streamingHighlightClassName(streamingField === "customCode"),+ )}+ >+ <div+ ref={frameRef}+ data-testid="automation-setup-custom-code-scroll"+ className="custom-scrollbar-always min-h-[256px] overflow-x-hidden">- <input- data-testid="automation-setup-entrypoint"- value={entrypoint}- onChange={(event) => onEntrypointChange(event.target.value)}- className={formControlFieldClassName}- />- </Field>- <Field- label={t(I18nKey.AUTOMATION_SETUP$SETUP_SCRIPT_PATH)}- suffix={updatedSuffixes.setupScriptPath}- isStreaming={streamingField === "setupScriptPath"}+ <div className="px-4 pt-4 pb-4">+ <textarea+ ref={textareaRef}+ data-testid="automation-setup-custom-code"+ aria-label={t(I18nKey.AUTOMATION_SETUP$CUSTOM_PYTHON)}+ rows={CUSTOM_CODE_VISIBLE_LINES}+ value={code}+ onChange={(event) => onCodeChange(event.target.value)}+ spellCheck={false}+ className="block w-full resize-none overflow-hidden border-0 bg-transparent p-0 font-mono text-sm leading-5 text-content outline-none"+ />+ </div>+ </div>+ <div+ data-testid="automation-setup-custom-code-grip"+ className="group absolute bottom-0 left-0 z-20 h-3 w-full">- <input- data-testid="automation-setup-setup-script-path"- value={setupScriptPath}- onChange={(event) => onSetupScriptPathChange(event.target.value)}- className={formControlFieldClassName}+ <div+ className="absolute inset-0 z-[1] cursor-ns-resize select-none"+ onMouseDown={handleGripMouseDown}+ onTouchStart={handleGripTouchStart}+ aria-hidden+ />+ <div+ ref={gripRef}+ className={cn(+ "pointer-events-none absolute bottom-0 left-0 z-[2] h-px w-full bg-white transition-opacity duration-200",+ isGripDragging+ ? "opacity-100"+ : "opacity-0 group-hover:opacity-100",+ )}/>- </Field>+ </div></div>- <Field- label={t(I18nKey.AUTOMATION_SETUP$PYTHON_CODE)}- suffix={updatedSuffixes.customCode}- isStreaming={streamingField === "customCode"}- >- <textarea- data-testid="automation-setup-custom-code"- rows={12}- value={code}- onChange={(event) => onCodeChange(event.target.value)}- spellCheck={false}- className={cn(- formControlMultilineFieldClassName,- "font-mono text-xs",- )}- />- </Field>- <Field- label={t(I18nKey.AUTOMATION_SETUP$SETUP_SCRIPT)}- suffix={updatedSuffixes.setupScript}- isStreaming={streamingField === "setupScript"}+ <div+ data-testid="automation-setup-custom-details-drawer"+ className="rounded-b-[15px] border-x border-b border-[var(--oh-border)] bg-[var(--oh-surface-raised)] px-4 pb-2 pt-[calc(15px+0.5rem)]">- <textarea- data-testid="automation-setup-setup-script"- rows={4}- value={setupScript}- onChange={(event) => onSetupScriptChange(event.target.value)}- spellCheck={false}- className={cn(- formControlMultilineFieldClassName,- "font-mono text-xs",- )}- />- </Field>+ <button+ type="button"+ data-testid="automation-setup-custom-details-toggle"+ aria-expanded={detailsOpen}+ aria-controls="automation-setup-custom-details"+ onClick={() => setDetailsOpen((open) => !open)}+ className="flex w-full items-center gap-2 text-left text-sm"+ >+ <ChevronDown+ className={cn(+ "size-4 shrink-0 text-[var(--oh-muted)] transition-transform duration-200 motion-reduce:transition-none",+ detailsOpen && "rotate-180",+ )}+ aria-hidden+ />+ {t(I18nKey.AUTOMATION_SETUP$SHOW_ENTRYPOINT_AND_SETUP)}+ </button>+ <CustomDetailsReveal open={detailsOpen} instant={reduceMotion}>+ <div className="flex flex-col gap-4 pt-3">+ <div className="grid gap-3 md:grid-cols-[2fr_1fr]">+ <Field+ label={t(I18nKey.AUTOMATION_SETUP$ENTRYPOINT)}+ suffix={updatedSuffixes.entrypoint}+ isStreaming={streamingField === "entrypoint"}+ >+ <input+ data-testid="automation-setup-entrypoint"+ value={entrypoint}+ onChange={(event) => onEntrypointChange(event.target.value)}+ className={formControlFieldClassName}+ />+ </Field>+ <Field+ label={t(I18nKey.AUTOMATION_SETUP$SETUP_SCRIPT_PATH)}+ suffix={updatedSuffixes.setupScriptPath}+ isStreaming={streamingField === "setupScriptPath"}+ >+ <input+ data-testid="automation-setup-setup-script-path"+ value={setupScriptPath}+ onChange={(event) =>+ onSetupScriptPathChange(event.target.value)+ }+ className={formControlFieldClassName}+ />+ </Field>+ </div>+ <Field+ label={t(I18nKey.AUTOMATION_SETUP$SETUP_SCRIPT)}+ suffix={updatedSuffixes.setupScript}+ isStreaming={streamingField === "setupScript"}+ >+ <textarea+ data-testid="automation-setup-setup-script"+ rows={4}+ value={setupScript}+ onChange={(event) => onSetupScriptChange(event.target.value)}+ spellCheck={false}+ className={cn(+ formControlMultilineFieldClassName,+ "font-mono text-xs",+ )}+ />+ </Field>+ </div>+ </CustomDetailsReveal>+ </div></div>);}+const CUSTOM_DETAILS_REVEAL_SECONDS = 0.22;++function CustomDetailsReveal({+ open,+ instant,+ children,+}: {+ open: boolean;+ instant: boolean | null;+ children: ReactNode;+}) {+ if (instant || import.meta.env.MODE === "test") {+ if (!open) return null;+ return <div id="automation-setup-custom-details">{children}</div>;+ }++ return (+ <AnimatePresence initial={false}>+ {open ? (+ <motion.div+ id="automation-setup-custom-details"+ initial={{ height: 0, opacity: 0 }}+ animate={{ height: "auto", opacity: 1 }}+ exit={{ height: 0, opacity: 0 }}+ transition={{+ duration: CUSTOM_DETAILS_REVEAL_SECONDS,+ ease: "easeInOut",+ }}+ className="overflow-hidden"+ >+ {children}+ </motion.div>+ ) : null}+ </AnimatePresence>+ );+}++function frequencyTabClassName(selected: boolean) {+ return cn(+ "inline-flex h-full shrink-0 items-center rounded-md px-1.5 text-sm",+ formControlTransitionClassName,+ selected+ ? cn(+ formControlBorderClassName,+ formControlSurfaceClassName,+ "border-[var(--oh-interactive-hover)] text-content",+ )+ : "border border-transparent text-[var(--oh-muted)] hover:text-content",+ );+}++const WEEKDAY_KEYS: I18nKey[] = [+ I18nKey.AUTOMATIONS$WEEKDAY_SUN,+ I18nKey.AUTOMATIONS$WEEKDAY_MON,+ I18nKey.AUTOMATIONS$WEEKDAY_TUE,+ I18nKey.AUTOMATIONS$WEEKDAY_WED,+ I18nKey.AUTOMATIONS$WEEKDAY_THU,+ I18nKey.AUTOMATIONS$WEEKDAY_FRI,+ I18nKey.AUTOMATIONS$WEEKDAY_SAT,+];+function ScheduleFields({frequency,time,+ weekday,+ scheduleDateTime,timezone,customSchedule,updatedSuffixes,streamingField,setFrequency,setTime,+ setWeekday,+ setScheduleDateTime,setTimezone,setCustomSchedule,}: {frequency: Frequency;time: string;+ weekday: string;+ scheduleDateTime: string;timezone: string;customSchedule: string;updatedSuffixes: Partial<Record<- "frequency" | "time" | "timezone" | "customSchedule",+ "frequency" | "time" | "scheduleDateTime" | "timezone" | "customSchedule",string | undefined>>;streamingField: AutomationSetupField | null;setFrequency: (value: Frequency) => void;setTime: (value: string) => void;+ setWeekday: (value: string) => void;+ setScheduleDateTime: (value: string) => void;setTimezone: (value: string) => void;setCustomSchedule: (value: string) => void;}) {const { t } = useTranslation("openhands");- const atUpdatedSuffix = updatedSuffixes.time ?? updatedSuffixes.timezone;+ const atUpdatedSuffix =+ updatedSuffixes.time ??+ updatedSuffixes.scheduleDateTime ??+ updatedSuffixes.timezone;+ const showTime =+ frequency === "daily" || frequency === "weekdays" || frequency === "weekly";+ const timezoneChoices = TIMEZONE_OPTIONS.includes(+ timezone as (typeof TIMEZONE_OPTIONS)[number],+ )+ ? TIMEZONE_OPTIONS+ : [timezone, ...TIMEZONE_OPTIONS];+return (<section className="flex flex-col gap-2.5"><div className="flex min-w-0 items-center gap-2">- <span className="shrink-0 text-sm">- {t(I18nKey.AUTOMATION_SETUP$FREQUENCY)}+ <span className="flex shrink-0 items-center gap-2 text-sm">+ <span>{t(I18nKey.AUTOMATION_SETUP$FREQUENCY)}</span>+ {updatedSuffixes.frequency && (+ <span className="text-xs font-normal text-[var(--oh-muted)]">+ {updatedSuffixes.frequency}+ </span>+ )}</span>- {updatedSuffixes.frequency ? (- <span className="shrink-0 text-xs text-[var(--oh-muted)]">- {updatedSuffixes.frequency}- </span>- ) : null}<divrole="radiogroup"aria-label={t(I18nKey.AUTOMATION_SETUP$FREQUENCY)}className={cn(- "inline-flex max-w-full min-w-0 items-center gap-0.5 overflow-x-auto rounded-lg bg-[var(--oh-surface-raised)] p-0.5",+ formControlHeightClassName,+ formControlRadiusClassName,+ "inline-flex max-w-full min-w-0 items-center gap-0.5 overflow-x-auto bg-[var(--oh-surface-raised)] p-0.5",streamingHighlightClassName(streamingField === "frequency"),)}>@@ -1189,108 +2394,278 @@ function ScheduleFields({data-testid={`automation-setup-frequency-${item}`}aria-checked={frequency === item}onClick={() => setFrequency(item)}- className={cn(- "inline-flex h-8 shrink-0 items-center rounded-md px-3 text-sm",- formControlTransitionClassName,- frequency === item- ? "border border-[var(--oh-interactive-hover)] bg-base-secondary text-content"- : "border border-transparent text-[var(--oh-muted)] hover:text-content",- )}+ className={frequencyTabClassName(frequency === item)}>{t(frequencyLabelKey(item))}</button>))}</div></div>- <div className="flex w-full min-w-0 items-center gap-4 overflow-x-auto">+ <div+ data-testid="automation-setup-at-row"+ className="flex w-full min-w-0 items-center gap-4 overflow-x-auto"+ >{frequency === "custom" ? (- <Field- label={t(I18nKey.AUTOMATION_SETUP$TYPE_CUSTOM)}- suffix={updatedSuffixes.customSchedule}- isStreaming={streamingField === "customSchedule"}- >+ <label className="flex shrink-0 items-center gap-2.5">+ <span className="shrink-0 text-sm text-content">+ {t(I18nKey.AUTOMATION_SETUP$TYPE_CUSTOM)}+ </span><inputdata-testid="automation-setup-custom-schedule"value={customSchedule}onChange={(event) => setCustomSchedule(event.target.value)}className={cn(formControlFieldClassName, "w-[14rem]")}/>- </Field>- ) : (- <>- <label className="flex shrink-0 items-center gap-2.5">- <span className="shrink-0 text-sm text-content">- {t(I18nKey.AUTOMATION_SETUP$AT)}- </span>- <div- data-streaming-active={- streamingField === "time" ? "true" : undefined- }- className={cn(- "relative",- streamingHighlightClassName(streamingField === "time"),- )}- >- <input- data-testid="automation-setup-time"- type="time"- value={time}- onChange={(event) => setTime(event.target.value)}- className={cn(formControlFieldClassName, "w-[9.5rem]")}- />- </div>- </label>+ </label>+ ) : null}+ {frequency === "once" ? (+ <div className="flex shrink-0 items-center gap-2.5">+ <span className="shrink-0 text-sm text-content">+ {t(I18nKey.AUTOMATION_SETUP$AT)}+ </span>+ <input+ aria-label={t(I18nKey.AUTOMATION_SETUP$AT)}+ data-testid="automation-setup-datetime"+ type="datetime-local"+ value={scheduleDateTime || defaultScheduleDateTimeLocal()}+ onChange={(event) => setScheduleDateTime(event.target.value)}+ className={cn(formControlFieldClassName, "w-[15rem]")}+ />+ </div>+ ) : null}+ {showTime ? (+ <div className="flex shrink-0 items-center gap-2.5">+ <span className="shrink-0 text-sm text-content">+ {t(I18nKey.AUTOMATION_SETUP$AT)}+ </span>+ <input+ aria-label={t(I18nKey.AUTOMATION_SETUP$AT)}+ data-testid="automation-setup-time"+ type="time"+ value={time}+ onChange={(event) => setTime(event.target.value)}+ className={cn(formControlFieldClassName, "w-[9.5rem]")}+ />+ </div>+ ) : null}+ {frequency === "weekly" ? (+ <div className="flex shrink-0 items-center gap-2.5">+ <span className="shrink-0 text-sm text-content">+ {t(I18nKey.AUTOMATION_SETUP$ON)}+ </span><div- data-streaming-active={- streamingField === "timezone" ? "true" : undefined- }className={cn(- "relative shrink-0",- streamingHighlightClassName(streamingField === "timezone"),+ "relative w-fit shrink-0",+ streamingHighlightClassName(streamingField === "weekday"),)}><select- aria-label={t(I18nKey.AUTOMATIONS$TIMEZONE)}- data-testid="automation-setup-timezone"- value={timezone}- onChange={(event) => setTimezone(event.target.value)}- className={cn(formControlFieldClassName, "w-[15rem] pl-9")}+ aria-label={t(I18nKey.AUTOMATIONS$WEEKDAY)}+ data-testid="automation-setup-weekday"+ value={weekday}+ onChange={(event) => setWeekday(event.target.value)}+ className={cn(+ formControlFieldClassName,+ "w-auto appearance-none pr-8",+ )}>- <option value={timezone}>{timezone}</option>- {timezone !== DEFAULT_TIMEZONE ? (- <option value={DEFAULT_TIMEZONE}>{DEFAULT_TIMEZONE}</option>- ) : null}+ {WEEKDAY_KEYS.map((key, index) => (+ <option key={key} value={String(index)}>+ {t(key)}+ </option>+ ))}</select>- <Globe2- className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-[var(--oh-muted)]"+ <ChevronDown+ className="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-[var(--oh-muted)]"aria-hidden/></div>- {atUpdatedSuffix ? (- <span className="shrink-0 text-xs text-[var(--oh-muted)]">- {atUpdatedSuffix}- </span>- ) : null}- </>+ </div>+ ) : null}+ <div+ data-streaming-active={+ streamingField === "timezone" ? "true" : undefined+ }+ className={cn(+ "relative w-[16rem] shrink-0",+ streamingHighlightClassName(streamingField === "timezone"),+ )}+ >+ <Globe2+ className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-[var(--oh-muted)]"+ aria-hidden+ />+ <select+ aria-label={t(I18nKey.AUTOMATIONS$TIMEZONE)}+ data-testid="automation-setup-timezone"+ value={timezone}+ onChange={(event) => setTimezone(event.target.value)}+ className={cn(+ formControlFieldClassName,+ "appearance-none pl-9 pr-8",+ )}+ >+ {timezoneChoices.map((option) => (+ <option key={option} value={option}>+ {option}+ </option>+ ))}+ </select>+ <ChevronDown+ className="pointer-events-none absolute right-3 top-1/2 size-4 -translate-y-1/2 text-[var(--oh-muted)]"+ aria-hidden+ />+ </div>+ {atUpdatedSuffix && (+ <span className="shrink-0 text-xs font-normal text-[var(--oh-muted)]">+ {atUpdatedSuffix}+ </span>)}</div></section>);}+function knownEventSources(options: string[]) {+ return options.length > 0 ? options : FALLBACK_EVENT_SOURCES;+}++function eventSourceInputValue(value: string, knownSources: string[]) {+ const match = knownSources.find(+ (source) => source.toLowerCase() === value.trim().toLowerCase(),+ );+ return match ? formatTriggerSourceLabel(match) : value;+}++function commitEventSourceInput(typed: string, knownSources: string[]) {+ const normalized = typed.trim().toLowerCase();+ const match = knownSources.find((source) => {+ return (+ source.toLowerCase() === normalized ||+ formatTriggerSourceLabel(source).toLowerCase() === normalized+ );+ });+ return match ?? typed;+}++function EventSourceControl({+ value,+ options,+ onChange,+}: {+ value: string;+ options: string[];+ onChange: (value: string) => void;+}) {+ const { t } = useTranslation("openhands");+ const knownSources = knownEventSources(options);+ const [isMenuOpen, setIsMenuOpen] = useState(false);+ const inputRef = useRef<HTMLInputElement>(null);+ const triggerRef = useRef<HTMLButtonElement>(null);+ const menuRef = useClickOutsideElement<HTMLDivElement>(+ () => setIsMenuOpen(false),+ triggerRef,+ );++ return (+ <div className="relative">+ <input+ ref={inputRef}+ data-testid="automation-setup-event-source"+ value={eventSourceInputValue(value, knownSources)}+ onChange={(event) =>+ onChange(commitEventSourceInput(event.target.value, knownSources))+ }+ className={cn(formControlFieldClassName, "pr-9")}+ />+ <button+ ref={triggerRef}+ type="button"+ data-testid="automation-setup-event-source-toggle"+ aria-label={t(I18nKey.AUTOMATION_SETUP$EVENT_SOURCE)}+ aria-haspopup="menu"+ aria-expanded={isMenuOpen}+ className="absolute top-1/2 right-2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-[var(--oh-muted)] hover:bg-white/10 hover:text-white"+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => setIsMenuOpen((open) => !open)}+ >+ <ChevronDown className="size-4 shrink-0" aria-hidden />+ </button>+ {isMenuOpen ? (+ <div+ ref={menuRef}+ role="menu"+ data-testid="automation-setup-event-source-menu"+ className="absolute top-full left-0 z-[60] mt-1 flex max-h-72 w-full flex-col overflow-hidden rounded-md border border-border-subtle bg-tertiary py-1 shadow-lg"+ >+ <div className="min-h-0 flex-1 overflow-y-auto px-1">+ {knownSources.map((source) => (+ <ContextMenuListItem+ key={source}+ testId={`automation-setup-event-source-option-${source}`}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ onChange(source);+ setIsMenuOpen(false);+ }}+ className="flex w-full items-center"+ >+ <span className="truncate">+ {formatTriggerSourceLabel(source)}+ </span>+ </ContextMenuListItem>+ ))}+ </div>+ <Divider inset="menu" />+ <div className="shrink-0 px-1">+ <ContextMenuListItem+ testId="automation-setup-event-source-custom"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ setIsMenuOpen(false);+ inputRef.current?.focus();+ inputRef.current?.select();+ }}+ className="flex w-full items-center"+ >+ <span className="truncate">+ {t(I18nKey.AUTOMATION_SETUP$TYPE_CUSTOM)}+ </span>+ </ContextMenuListItem>+ </div>+ </div>+ ) : null}+ </div>+ );+}+function EventFields({eventSource,eventKey,eventFilter,+ eventTestPayload,+ eventSourceOptions,+ eventTypeOptions,+ customWebhook,+ customWebhookRegistration,updatedSuffixes,streamingField,setEventSource,setEventKey,setEventFilter,+ setEventTestPayload,+ setCustomWebhookField,}: {eventSource: string;eventKey: string;eventFilter: string;+ eventTestPayload: string;+ eventSourceOptions: string[];+ eventTypeOptions: string[];+ customWebhook: CustomWebhookFormState;+ customWebhookRegistration: CustomWebhookCreateResponse | null;updatedSuffixes: Partial<Record<"eventSource" | "eventKey" | "eventFilter", string | undefined>>;@@ -1298,63 +2673,384 @@ function EventFields({setEventSource: (value: string) => void;setEventKey: (value: string) => void;setEventFilter: (value: string) => void;+ setEventTestPayload: (value: string) => void;+ setCustomWebhookField: <FieldName extends keyof CustomWebhookFormState>(+ field: FieldName,+ value: CustomWebhookFormState[FieldName],+ ) => void;}) {const { t } = useTranslation("openhands");+ const { send } = useSendMessage();+ const [isEventFilterOpen, setIsEventFilterOpen] = useState(+ () => eventFilter.trim().length > 0,+ );+ const [isTestPayloadOpen, setIsTestPayloadOpen] = useState(false);+ const showEventFilter =+ isEventFilterOpen ||+ eventFilter.trim().length > 0 ||+ streamingField === "eventFilter";return (- <section className="grid gap-3 md:grid-cols-2">- <Field- label={t(I18nKey.AUTOMATION_SETUP$EVENT_SOURCE)}- suffix={updatedSuffixes.eventSource}- isStreaming={streamingField === "eventSource"}- >- <input- data-testid="automation-setup-event-source"- value={eventSource}- onChange={(event) => setEventSource(event.target.value)}- className={formControlFieldClassName}- />- </Field>- <Field- label={t(I18nKey.AUTOMATION_SETUP$EVENT_KEY)}- suffix={updatedSuffixes.eventKey}- isStreaming={streamingField === "eventKey"}- >- <input- data-testid="automation-setup-event-key"- value={eventKey}- onChange={(event) => setEventKey(event.target.value)}- className={formControlFieldClassName}- />- </Field>- <div className="md:col-span-2">- <Field- label={t(I18nKey.AUTOMATION_SETUP$EVENT_FILTER)}- suffix={updatedSuffixes.eventFilter ?? t(I18nKey.COMMON$OPTIONAL)}- isStreaming={streamingField === "eventFilter"}- >- <input- data-testid="automation-setup-event-filter"- value={eventFilter}- onChange={(event) => setEventFilter(event.target.value)}- className={formControlFieldClassName}- />- </Field>- </div>- </section>+ <div className="@container min-w-0">+ <section className="grid gap-3 @min-[640px]:grid-cols-2">+ <div className="flex min-w-0 flex-col gap-1.5">+ <Field+ label={t(I18nKey.AUTOMATION_SETUP$EVENT_SOURCE)}+ suffix={updatedSuffixes.eventSource}+ isStreaming={streamingField === "eventSource"}+ >+ <EventSourceControl+ value={eventSource}+ options={eventSourceOptions}+ onChange={setEventSource}+ />+ </Field>+ <p+ role="note"+ data-testid="automation-setup-event-public-url-notice"+ className="flex items-start gap-1.5 text-xs leading-4 text-[var(--oh-muted)]"+ >+ <Info className="mt-0.5 size-3.5 shrink-0" aria-hidden />+ {t(I18nKey.AUTOMATION_SETUP$EVENT_PUBLIC_URL_NOTICE)}+ </p>+ </div>+ <div className="flex min-w-0 flex-wrap items-end gap-2 self-start">+ <div+ className={cn(+ "flex min-w-48 flex-1 flex-col gap-2",+ streamingHighlightClassName(streamingField === "eventKey"),+ )}+ >+ <label+ htmlFor="automation-setup-event-key"+ className="flex shrink-0 items-center gap-2 text-sm"+ >+ {t(I18nKey.AUTOMATION_SETUP$EVENT_KEY)}+ {updatedSuffixes.eventKey ? (+ <span className="font-normal text-[var(--oh-muted)]">+ {updatedSuffixes.eventKey}+ </span>+ ) : null}+ </label>+ <div+ className={cn(+ "flex w-full min-w-0 overflow-hidden",+ formControlHeightClassName,+ formControlRadiusClassName,+ formControlBorderClassName,+ formControlSurfaceClassName,+ formControlTransitionClassName,+ formControlFocusWithinClassName,+ streamingHighlightClassName(streamingField === "eventFilter"),+ )}+ >+ <input+ id="automation-setup-event-key"+ data-testid="automation-setup-event-key"+ value={eventKey}+ list="automation-setup-event-key-options"+ onChange={(event) => setEventKey(event.target.value)}+ className="min-w-0 flex-1 border-0 bg-transparent px-3 text-sm text-contrast outline-none"+ />+ <datalist id="automation-setup-event-key-options">+ {eventTypeOptions.map((eventType) => (+ <option key={eventType} value={eventType} />+ ))}+ </datalist>+ {showEventFilter ? null : (+ <button+ type="button"+ data-testid="automation-setup-add-event-filter"+ onClick={() => setIsEventFilterOpen(true)}+ className="inline-flex shrink-0 items-center border-l border-[var(--oh-border)] bg-tertiary px-3 text-sm text-content hover:bg-interactive-hover"+ >+ {t(I18nKey.AUTOMATION_SETUP$ADD_FILTER)}+ </button>+ )}+ </div>+ </div>+ <button+ type="button"+ data-testid="automation-setup-ask-agent"+ className={cn(addOptionButtonClassName, "h-9 gap-1.5")}+ onClick={() => {+ requestAutomationSetupAgent();+ void send({+ action: "message",+ args: {+ content: t(I18nKey.AUTOMATION_SETUP$ASK_AGENT_EVENT_PROMPT),+ },+ });+ }}+ >+ <SparkleIcon className="size-3.5 shrink-0" aria-hidden />+ {t(I18nKey.AUTOMATION_SETUP$ASK_AGENT)}+ </button>+ </div>+ {showEventFilter ? (+ <div className="@min-[640px]:col-span-2">+ <div className="relative">+ <button+ type="button"+ data-testid="automation-setup-event-filter-remove"+ aria-label={`${t(I18nKey.COMMON$REMOVE)} ${t(I18nKey.AUTOMATION_SETUP$EVENT_FILTER)}`}+ className="absolute right-0 top-0 inline-flex size-6 items-center justify-center rounded-md text-[var(--oh-muted)] hover:bg-white/10 hover:text-white"+ onClick={() => {+ setIsEventFilterOpen(false);+ setEventFilter("");+ }}+ >+ <X className="size-4" aria-hidden />+ </button>+ <Field+ label={t(I18nKey.AUTOMATION_SETUP$EVENT_FILTER)}+ suffix={+ updatedSuffixes.eventFilter ?? t(I18nKey.COMMON$OPTIONAL)+ }+ isStreaming={streamingField === "eventFilter"}+ >+ <input+ data-testid="automation-setup-event-filter"+ value={eventFilter}+ onChange={(event) => setEventFilter(event.target.value)}+ className={formControlFieldClassName}+ />+ </Field>+ </div>+ </div>+ ) : null}+ {eventSource.trim() !== "" &&+ !(+ eventSourceOptions.length > 0+ ? eventSourceOptions+ : FALLBACK_EVENT_SOURCES+ ).includes(eventSource.trim()) ? (+ <div className="@min-[640px]:col-span-2">+ <section className="rounded-xl border border-[var(--oh-border)] p-3">+ <div className="flex items-start gap-3 text-sm">+ <input+ id="automation-setup-custom-webhook-enabled"+ type="checkbox"+ data-testid="automation-setup-custom-webhook-enabled"+ checked={customWebhook.enabled}+ onChange={(event) =>+ setCustomWebhookField("enabled", event.target.checked)+ }+ className="mt-1"+ />+ <label+ htmlFor="automation-setup-custom-webhook-enabled"+ className="flex flex-col gap-1"+ >+ <span>+ {t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_TITLE)}+ </span>+ <span className="text-xs font-normal leading-5 text-[var(--oh-muted)]">+ {t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_DESCRIPTION)}+ </span>+ </label>+ </div>+ {customWebhook.enabled && (+ <div className="mt-3 grid gap-3 md:grid-cols-2">+ <Field+ label={t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_NAME)}+ >+ <input+ data-testid="automation-setup-custom-webhook-name"+ value={customWebhook.name}+ onChange={(event) =>+ setCustomWebhookField("name", event.target.value)+ }+ className={formControlFieldClassName}+ placeholder={t(+ I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_NAME_PLACEHOLDER,+ )}+ />+ </Field>+ <Field+ label={t(+ I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_EVENT_KEY_EXPR,+ )}+ >+ <input+ data-testid="automation-setup-custom-webhook-event-key-expr"+ value={customWebhook.eventKeyExpr}+ onChange={(event) =>+ setCustomWebhookField(+ "eventKeyExpr",+ event.target.value,+ )+ }+ className={formControlFieldClassName}+ />+ </Field>+ <Field+ label={t(+ I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_HEADER,+ )}+ >+ <input+ data-testid="automation-setup-custom-webhook-signature-header"+ value={customWebhook.signatureHeader}+ onChange={(event) =>+ setCustomWebhookField(+ "signatureHeader",+ event.target.value,+ )+ }+ className={formControlFieldClassName}+ />+ </Field>+ <Field+ label={t(+ I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME,+ )}+ >+ <select+ data-testid="automation-setup-custom-webhook-signature-scheme"+ value={customWebhook.signatureScheme}+ onChange={(event) =>+ setCustomWebhookField(+ "signatureScheme",+ event.target.value as CustomWebhookSignatureScheme,+ )+ }+ className={formControlFieldClassName}+ >+ <option value="hmac_sha256_hex">+ {t(+ I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME_HMAC,+ )}+ </option>+ <option value="standard_webhooks">+ {t(+ I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME_STANDARD,+ )}+ </option>+ <option value="slack_v0">+ {t(+ I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME_SLACK,+ )}+ </option>+ </select>+ </Field>+ <div className="md:col-span-2">+ <Field+ label={t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SECRET)}+ suffix={t(I18nKey.COMMON$OPTIONAL)}+ >+ <input+ data-testid="automation-setup-custom-webhook-secret"+ type="password"+ value={customWebhook.webhookSecret}+ onChange={(event) =>+ setCustomWebhookField(+ "webhookSecret",+ event.target.value,+ )+ }+ className={formControlFieldClassName}+ placeholder={t(+ I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SECRET_PLACEHOLDER,+ )}+ />+ </Field>+ <p className="mt-2 text-xs leading-5 text-[var(--oh-muted)]">+ {t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_SECRET_HELP)}+ </p>+ </div>+ {customWebhookRegistration && (+ <div+ data-testid="automation-setup-custom-webhook-result"+ className="md:col-span-2 rounded-lg border border-[var(--oh-success)]/40 bg-[var(--oh-success)]/10 p-3 text-xs leading-5 text-white"+ >+ <p className="font-medium">+ {t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_CREATED)}+ </p>+ <p className="break-all">+ {t(I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_URL, {+ url: customWebhookRegistration.webhook_url,+ })}+ </p>+ {customWebhookRegistration.webhook_secret && (+ <p className="break-all">+ {t(+ I18nKey.AUTOMATION_SETUP$CUSTOM_WEBHOOK_GENERATED_SECRET,+ {+ secret: customWebhookRegistration.webhook_secret,+ },+ )}+ </p>+ )}+ </div>+ )}+ </div>+ )}+ </section>+ </div>+ ) : null}+ <div className="@min-[640px]:col-span-2">+ <button+ type="button"+ data-testid="automation-setup-event-test-payload-toggle"+ aria-expanded={isTestPayloadOpen}+ aria-controls="automation-setup-event-test-payload-panel"+ onClick={() => setIsTestPayloadOpen((open) => !open)}+ className="flex w-full items-center gap-2 text-left text-sm"+ >+ <ChevronDown+ className={cn(+ "size-4 shrink-0 text-[var(--oh-muted)] transition-transform duration-200 motion-reduce:transition-none",+ isTestPayloadOpen && "rotate-180",+ )}+ aria-hidden+ />+ {t(I18nKey.AUTOMATION_SETUP$TEST_EVENT_PAYLOAD)}+ </button>+ {isTestPayloadOpen ? (+ <div+ id="automation-setup-event-test-payload-panel"+ className="flex flex-col gap-2 pt-2"+ >+ <textarea+ data-testid="automation-setup-event-test-payload"+ value={eventTestPayload}+ onChange={(event) => setEventTestPayload(event.target.value)}+ className={cn(+ formControlMultilineFieldClassName,+ "min-h-44 font-mono",+ )}+ placeholder={t(+ I18nKey.AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_PLACEHOLDER,+ )}+ />+ <p className="text-xs leading-5 text-[var(--oh-muted)]">+ {t(I18nKey.AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_DESCRIPTION)}+ </p>+ </div>+ ) : null}+ </div>+ </section>+ </div>);}function Field({label,+ showLabel = true,+ labelClassName,suffix,horizontal = false,isStreaming = false,+ errorText,children,}: {label: string;+ showLabel?: boolean;+ labelClassName?: string;suffix?: string;horizontal?: boolean;isStreaming?: boolean;+ errorText?: string;children: ReactNode;}) {return (@@ -1366,13 +3062,28 @@ function Field({streamingHighlightClassName(isStreaming),)}>- <span className="flex items-center gap-2 text-sm font-semibold text-white">- {label}- {suffix && (- <span className="font-normal text-[var(--oh-muted)]">{suffix}</span>- )}- </span>+ {showLabel ? (+ <span+ className={cn(+ "flex shrink-0 items-center gap-2 text-sm",+ labelClassName,+ )}+ >+ <span>{label}</span>+ {suffix && (+ <span className="font-normal text-[var(--oh-muted)]">{suffix}</span>+ )}+ </span>+ ) : null}<div className="min-w-0 flex-1">{children}</div>+ {errorText ? (+ <span+ role="alert"+ className="text-xs leading-5 text-[var(--oh-warning)]"+ >+ {errorText}+ </span>+ ) : null}</label>);}@@ -1393,21 +3104,24 @@ function TriggerCard({return (<buttontype="button"- aria-pressed={selected}+ role="radio"+ aria-checked={selected}onClick={onClick}className={cn(- "flex items-start gap-3 rounded-xl border p-4 text-left",+ "rounded-lg border px-3 py-2.5 text-left",formControlTransitionClassName,selected- ? "border-white/20 bg-white/10 text-white"- : "border-[var(--oh-border)] bg-base-secondary text-[var(--oh-muted)] hover:bg-white/5 hover:text-white",+ ? "border-[var(--oh-interactive-hover)] bg-surface-raised text-content"+ : "border-[var(--oh-border)] bg-transparent text-content hover:border-[var(--oh-interactive-hover)] hover:bg-surface-raised",)}>- <span className="mt-0.5 text-[var(--oh-muted)]">{icon}</span>- <span className="flex flex-col gap-1">- <span className="text-sm font-semibold">{title}</span>- <span className="text-xs leading-5 text-[var(--oh-muted)]">- {description}+ <span className="flex items-start gap-2">+ <span className="mt-0.5 text-muted">{icon}</span>+ <span className="min-w-0">+ <span className="block text-sm font-medium">{title}</span>+ <span className="mt-1 block text-xs text-[var(--oh-text-tertiary)]">+ {description}+ </span></span></span></button>diff --git a/src/components/features/conversation-panel/conversation-active-tag-filters.tsx b/src/components/features/conversation-panel/conversation-active-tag-filters.tsxindex c6f34fdef8..7e51ab98a9 100644--- a/src/components/features/conversation-panel/conversation-active-tag-filters.tsx+++ b/src/components/features/conversation-panel/conversation-active-tag-filters.tsx@@ -65,7 +65,7 @@ export function ConversationActiveTagFilters({onClick={() => onToggleFacet(facet)}className={chipClassName}>- <span className="truncate">{formatTagFacetLabel(facet)}</span>+ <span className="truncate">{formatTagFacetLabel(facet, t)}</span><X className="h-3 w-3 shrink-0" aria-hidden /></button>))}diff --git a/src/components/features/conversation-panel/conversation-card/conversation-tag-chips.tsx b/src/components/features/conversation-panel/conversation-card/conversation-tag-chips.tsxindex c4a5213921..43a37ad694 100644--- a/src/components/features/conversation-panel/conversation-card/conversation-tag-chips.tsx+++ b/src/components/features/conversation-panel/conversation-card/conversation-tag-chips.tsx@@ -7,6 +7,7 @@ import {computeVisibleTagChipCount,formatConversationTagTooltip,getConversationTagLabel,+ getConversationTagValueLabel,truncateTagChipValue,} from "./conversation-tag-display";import {@@ -341,7 +342,7 @@ export function ConversationTagChips({ tags }: ConversationTagChipsProps) {className="m-0 whitespace-normal break-words text-left leading-4 text-foreground"title={value}>- {value}+ {getConversationTagValueLabel(key, value, t)}</dd></div>))}diff --git a/src/components/features/conversation-panel/conversation-card/conversation-tag-display.ts b/src/components/features/conversation-panel/conversation-card/conversation-tag-display.tsindex 73206c3823..eec7d7a546 100644--- a/src/components/features/conversation-panel/conversation-card/conversation-tag-display.ts+++ b/src/components/features/conversation-panel/conversation-card/conversation-tag-display.ts@@ -4,6 +4,14 @@*/import { I18nKey } from "#/i18n/declaration";+import {+ AUTOMATION_SETUP_TAG_KEY,+ AUTOMATION_SETUP_TAG_VALUE,+} from "#/utils/automation-draft-tags";++export function isAutomationSetupTagKey(key: string): boolean {+ return key.trim().toLowerCase() === AUTOMATION_SETUP_TAG_KEY;+}/** Max characters shown on a chip before hard truncation with an ellipsis. */export const TAG_CHIP_VALUE_MAX_LENGTH = 14;@@ -23,6 +31,7 @@ export type ConversationTagLabelKind =| "repo"| "branch"| "workspace"+ | "automation_setup"| "app_mode"| "work_tools"| "work_wsid"@@ -55,6 +64,8 @@ export function getConversationTagLabelKind(case "workspace":case "working_dir":return "workspace";+ case AUTOMATION_SETUP_TAG_KEY:+ return "automation_setup";case "appmode":case "app_mode":case "mode":@@ -104,6 +115,8 @@ export function getConversationTagLabel(return t(I18nKey.CONVERSATION_PANEL$PREVIEW_BRANCH);case "workspace":return t(I18nKey.CONVERSATION_PANEL$PREVIEW_WORKSPACE);+ case "automation_setup":+ return t(I18nKey.AUTOMATION_SETUP$TITLE);case "app_mode":return t(I18nKey.CONVERSATION_PANEL$PREVIEW_APP_MODE);case "work_tools":@@ -115,7 +128,18 @@ export function getConversationTagLabel(}}-/** ``Branch: main`` — used by chip ``title`` tooltips. Bare tags (empty+export function getConversationTagValueLabel(+ key: string,+ value: string,+ t: (key: I18nKey) => string,+): string {+ if (isAutomationSetupTagKey(key) && value === AUTOMATION_SETUP_TAG_VALUE) {+ return t(I18nKey.AUTOMATIONS$DETAIL$DRAFT);+ }+ return value;+}++/** ``Branch: main`` - used by chip ``title`` tooltips. Bare tags (empty* value) show the label alone, no dangling colon. */export function formatConversationTagTooltip(key: string,@@ -123,7 +147,8 @@ export function formatConversationTagTooltip(t: (key: I18nKey) => string,): string {const label = getConversationTagLabel(key, t);- return value ? `${label}: ${value}` : label;+ const valueLabel = getConversationTagValueLabel(key, value, t);+ return valueLabel ? `${label}: ${valueLabel}` : label;}/**diff --git a/src/components/features/conversation-panel/conversation-card/conversation-tag-icons.ts b/src/components/features/conversation-panel/conversation-card/conversation-tag-icons.tsindex c020a9bd5b..8b0f269c5d 100644--- a/src/components/features/conversation-panel/conversation-card/conversation-tag-icons.ts+++ b/src/components/features/conversation-panel/conversation-card/conversation-tag-icons.ts@@ -34,6 +34,7 @@ import {import { FaBitbucket, FaGithub, FaGitlab } from "react-icons/fa6";import type { IconType } from "react-icons/lib";import SlackIcon from "#/icons/slack.svg?react";+import { AUTOMATION_SETUP_TAG_KEY } from "#/utils/automation-draft-tags";/*** Any icon renderable inside a tag chip / overflow row. Lucide, react-icons,@@ -89,6 +90,7 @@ const KEY_ICONS: Record<string, ConversationTagIcon> = {channel: Hash,email: Mails,automation: Zap,+ [AUTOMATION_SETUP_TAG_KEY]: Zap,webhook: Webhook,agent: Bot,project: SquareKanban,diff --git a/src/components/features/conversation-panel/conversation-layouts-menu.tsx b/src/components/features/conversation-panel/conversation-layouts-menu.tsxindex 506c2b3ed6..e4133ae6f3 100644--- a/src/components/features/conversation-panel/conversation-layouts-menu.tsx+++ b/src/components/features/conversation-panel/conversation-layouts-menu.tsx@@ -246,7 +246,7 @@ export function ConversationLayoutsMenu({<MenuRowkey={facet}icon={Tag}- label={formatTagFacetLabel(facet)}+ label={formatTagFacetLabel(facet, t)}selected={preferences.selectedTagFacets.includes(facet)}testId={`tag-facet-row-${facet}`}onClick={() => preferences.toggleTagFacet(facet)}diff --git a/src/components/features/conversation-panel/conversation-panel-list-helpers.ts b/src/components/features/conversation-panel/conversation-panel-list-helpers.tsindex aa25b3253a..9bad00677f 100644--- a/src/components/features/conversation-panel/conversation-panel-list-helpers.ts+++ b/src/components/features/conversation-panel/conversation-panel-list-helpers.ts@@ -2,11 +2,20 @@ import type { AppConversation } from "#/api/conversation-service/agent-server-coimport type { BackendKind } from "#/api/backend-registry/types";import type { LocalWorkspace } from "#/types/workspace";import type { Provider } from "#/types/settings";+import type { I18nKey } from "#/i18n/declaration";import {AUTOMATION_NAME_TAG_KEY,AUTOMATION_TAG_KEYS,getDisplayConversationTags,} from "#/api/agent-server-adapter";+import {+ getConversationTagLabel,+ getConversationTagValueLabel,+} from "./conversation-card/conversation-tag-display";+import {+ AUTOMATION_SETUP_TAG_KEY,+ AUTOMATION_SETUP_TAG_VALUE,+} from "#/utils/automation-draft-tags";export type ConversationSortField = "created" | "updated";export type ThreadScope = "all" | "relevant";@@ -312,7 +321,23 @@ export function collectTagFacets(* renders as just the key. Matching keeps the raw `key=value` form — this is* label-only.*/-export function formatTagFacetLabel(facet: string): string {+export function formatTagFacetLabel(+ facet: string,+ t?: (key: I18nKey) => string,+): string {+ const separatorIndex = facet.indexOf("=");+ const key = separatorIndex === -1 ? facet : facet.slice(0, separatorIndex);+ const value = separatorIndex === -1 ? "" : facet.slice(separatorIndex + 1);+ if (+ key.trim().toLowerCase() === AUTOMATION_SETUP_TAG_KEY &&+ value === AUTOMATION_SETUP_TAG_VALUE+ ) {+ const label = t ? getConversationTagLabel(key, t) : "Automation setup";+ const valueLabel = t+ ? getConversationTagValueLabel(key, value, t)+ : "Draft";+ return `${label}: ${valueLabel}`;+ }return facet.endsWith("=") ? facet.slice(0, -1) : facet;}diff --git a/src/components/features/conversation/conversation-main/conversation-main.tsx b/src/components/features/conversation/conversation-main/conversation-main.tsxindex da18b05d4b..616ae23dd7 100644--- a/src/components/features/conversation/conversation-main/conversation-main.tsx+++ b/src/components/features/conversation/conversation-main/conversation-main.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from "react";+import { FileText, MessageSquare } from "lucide-react";import { useTranslation } from "react-i18next";-import { ArrowLeft, FileText, MessageSquare } from "lucide-react";import { cn } from "#/utils/utils";import { ChatActionTooltip } from "#/components/features/chat/chat-action-tooltip";import BlockDrawerLeftIcon from "#/icons/block-drawer-left.svg?react";@@ -24,12 +24,9 @@ import {import { SidebarMobileMenuToggle } from "#/components/features/sidebar/sidebar-mobile-menu-toggle";import { ConversationOverviewDrawer } from "../conversation-overview-drawer";import { useConversationOverviewDrawerOptional } from "../conversation-overview-drawer-context";-import { useNavigation } from "#/context/navigation-context";import { useActiveConversation } from "#/hooks/query/use-active-conversation";import { I18nKey } from "#/i18n/declaration";-import { formControlTransitionClassName } from "#/utils/form-control-classes";--const SPLASH_ROUTE = "/";+import { hasAutomationSetupModeTag } from "#/utils/automation-draft-tags";const BLANK_AUTOMATION_SETUP_DRAFT: AutomationSetupDraft = {prompt: "",@@ -81,16 +78,14 @@ function getDesktopTabPanelClass(isRightPanelShown: boolean) {export function ConversationMain() {const { t } = useTranslation("openhands");- const { navigate } = useNavigation();const { conversationId } = useConversationId();const { data: conversation } = useActiveConversation();const isMobile = useBreakpoint();const isSidebarRailHidden = useBreakpoint(SIDEBAR_RAIL_COLLAPSE_MAX_WIDTH);const { isRightPanelShown, setHasRightPanelToggled, setIsRightPanelShown } =useConversationStore();- const [isAutomationSetupMode, setIsAutomationSetupMode] = useState(() =>- consumeAutomationSetupHandoff(conversationId),- );+ const [isAutomationSetupModeHandoff, setIsAutomationSetupModeHandoff] =+ useState(() => consumeAutomationSetupHandoff(conversationId));const [automationToolbarElement, setAutomationToolbarElement] =useState<HTMLDivElement | null>(null);const [isAutomationAgentHidden, setIsAutomationAgentHidden] = useState(false);@@ -100,6 +95,11 @@ export function ConversationMain() {useState<HTMLDivElement | null>(null);const overviewDrawer = useConversationOverviewDrawerOptional();const isSecondaryDrawerOpen = Boolean(overviewDrawer?.section);+ const hasTaggedAutomationSetupMode = hasAutomationSetupModeTag(+ conversation?.tags,+ );+ const isAutomationSetupMode =+ isAutomationSetupModeHandoff || hasTaggedAutomationSetupMode;const automationSetupDraft = isAutomationSetupMode? BLANK_AUTOMATION_SETUP_DRAFT: null;@@ -115,7 +115,9 @@ export function ConversationMain() {});useEffect(() => {- setIsAutomationSetupMode(consumeAutomationSetupHandoff(conversationId));+ setIsAutomationSetupModeHandoff(+ consumeAutomationSetupHandoff(conversationId),+ );}, [conversationId]);useEffect(() => {@@ -130,10 +132,6 @@ export function ConversationMain() {}}, [automationSetupDraft]);- const handleBackToSplash = () => {- navigate(SPLASH_ROUTE);- };-useEffect(() => {const showAgent = () => {setIsAutomationAgentHidden(false);@@ -148,7 +146,10 @@ export function ConversationMain() {const agentToggleLabel = isAutomationAgentHidden? t(I18nKey.AUTOMATION_SETUP$SHOW_AGENT): t(I18nKey.AUTOMATION_SETUP$HIDE_AGENT);- const setupTitle = conversation?.title || t(I18nKey.AUTOMATION_SETUP$TITLE);+ const setupTitle =+ automationSetupDraft?.form?.name?.trim() ||+ conversation?.title ||+ t(I18nKey.AUTOMATION_SETUP$TITLE);return (<div@@ -176,26 +177,12 @@ export function ConversationMain() {><div className="flex min-w-0 flex-1 items-center gap-2">{isSidebarRailHidden ? <SidebarMobileMenuToggle /> : null}- {!isMobile ? (- <button- type="button"- data-testid="automation-setup-back"- aria-label={t(I18nKey.AUTOMATION_SETUP$BACK_LABEL)}- onClick={handleBackToSplash}- className={cn(- "flex size-7 items-center justify-center rounded-lg text-[var(--oh-muted)] hover:bg-white/10 hover:text-white",- formControlTransitionClassName,- )}- >- <ArrowLeft className="size-4" aria-hidden />- </button>- ) : null}- <h1+ <h2data-testid="automation-setup-conversation-title"- className="min-w-0 truncate text-sm font-semibold text-content"+ className="min-w-0 truncate text-sm font-medium text-content">{setupTitle}- </h1>+ </h2></div>{isMobile ? (<div@@ -369,6 +356,7 @@ export function ConversationMain() {<AutomationSetupPaneldraft={automationSetupDraft}conversationId={conversationId}+ conversationTags={conversation?.tags}toolbarPortal={automationToolbarElement}showInlineHeader={false}reserveComposerSpace@@ -406,6 +394,7 @@ export function ConversationMain() {<AutomationSetupPaneldraft={automationSetupDraft}conversationId={conversationId}+ conversationTags={conversation?.tags}toolbarPortal={automationToolbarElement}showInlineHeader={false}reserveComposerSpace={showDockedComposer}@@ -424,6 +413,10 @@ export function ConversationMain() {</>)}{showDockedComposer ? (+ // The setup form scrolls in a padded column with a stable+ // scrollbar gutter. This overlay has to be a scroll container+ // with the same gutter, or the composer centers in a wider+ // box and sits off the fields.<AutomationSetupDockedComposeronTarget={setComposerDockTarget}/>diff --git a/src/components/features/home/home-launcher-mode-toggle.tsx b/src/components/features/home/home-launcher-mode-toggle.tsxindex d96c28d15a..b748f9d1a4 100644--- a/src/components/features/home/home-launcher-mode-toggle.tsx+++ b/src/components/features/home/home-launcher-mode-toggle.tsx@@ -154,8 +154,8 @@ export function HomeLauncherModeToggle({"relative inline-flex items-center gap-2 rounded-full px-5 py-2","cursor-pointer transition-colors",isActive- ? "text-content"- : "text-[var(--oh-muted)] hover:text-content",+ ? "text-white"+ : "text-[var(--oh-muted)] hover:text-white",disableAnimation &&isActive &&"bg-[var(--oh-interactive-hover)]",diff --git a/src/components/shared/buttons/back-nav-button.tsx b/src/components/shared/buttons/back-nav-button.tsxindex ce1a5c1b91..8a8d649e28 100644--- a/src/components/shared/buttons/back-nav-button.tsx+++ b/src/components/shared/buttons/back-nav-button.tsx@@ -5,7 +5,8 @@ import { formControlBackNavButtonClassName } from "#/utils/form-control-classes"import { BackNavButtonContent } from "./back-nav-button-content";type BackNavButtonBaseProps = {- children: React.ReactNode;+ children?: React.ReactNode;+ ariaLabel?: string;testId?: string;className?: string;};@@ -30,7 +31,7 @@ export function BackNavButton(props: BackNavButtonAsButtonProps,): React.JSX.Element;export function BackNavButton(props: BackNavButtonProps) {- const { children, testId, className } = props;+ const { children, ariaLabel, testId, className } = props;const classes = cn(formControlBackNavButtonClassName, className);if ("to" in props) {@@ -39,6 +40,7 @@ export function BackNavButton(props: BackNavButtonProps) {to={props.to}onClick={props.onClick}data-testid={testId}+ aria-label={ariaLabel}className={classes}><BackNavButtonContent>{children}</BackNavButtonContent>@@ -51,6 +53,7 @@ export function BackNavButton(props: BackNavButtonProps) {type="button"onClick={props.onClick}data-testid={testId}+ aria-label={ariaLabel}className={classes}><BackNavButtonContent>{children}</BackNavButtonContent>diff --git a/src/constants/automation-form.ts b/src/constants/automation-form.tsindex 6e3a568d59..293ebcf429 100644--- a/src/constants/automation-form.ts+++ b/src/constants/automation-form.ts@@ -6,3 +6,11 @@ export const AUTOMATION_FORM_UPDATE_TOOL_NAME = "automation_form_update";*/export const AUTOMATION_FORM_UPDATE_ACTION_KIND =`ClientAction_${AUTOMATION_FORM_UPDATE_TOOL_NAME}` as const;++/**+ * The capabilities feature flag the automation service advertises (see+ * `OpenHands/automation` PR #417) when server-backed automation drafts are+ * available. The setup form gates the persisted-draft flow on this so a+ * deployment that predates the endpoints falls back to client-only state.+ */+export const AUTOMATION_DRAFTS_FEATURE = "automationDrafts";diff --git a/src/hooks/mutation/use-create-conversation.ts b/src/hooks/mutation/use-create-conversation.tsindex ca2bf2a62d..821eeec00b 100644--- a/src/hooks/mutation/use-create-conversation.ts+++ b/src/hooks/mutation/use-create-conversation.ts@@ -34,6 +34,7 @@ import {export interface CreateConversationVariables {query?: string;automationSetup?: boolean;+ automationSetupTags?: Record<string, string>;repository?: {name: string;gitProvider: Provider;@@ -106,6 +107,7 @@ export const useCreateConversation = ({const {query,automationSetup,+ automationSetupTags,conversationInstructions,plugins,repository,@@ -284,6 +286,7 @@ export const useCreateConversation = ({await AgentServerConversationService.createConversation({initialUserMsg: query,automationSetup,+ ...(automationSetupTags ? { automationSetupTags } : {}),conversationInstructions,plugins,metadata: repositorydiff --git a/src/hooks/query/use-automations.ts b/src/hooks/query/use-automations.tsindex 8274495025..b363fd9f5e 100644--- a/src/hooks/query/use-automations.ts+++ b/src/hooks/query/use-automations.ts@@ -2,9 +2,12 @@ import {type InfiniteData,useInfiniteQuery,useMutation,+ useQuery,useQueryClient,} from "@tanstack/react-query";import AutomationService from "#/api/automation-service/automation-service.api";+import { useDeploymentCapabilities } from "#/hooks/query/use-manifest-capabilities";+import { isSdkHttpStatusError } from "#/api/agent-server-compatibility";import { useActiveBackend } from "#/contexts/active-backend-context";import { useTracking } from "#/hooks/use-tracking";import { uniqueById } from "#/utils/unique-by-id";@@ -14,12 +17,32 @@ import type {AutomationSpec,AutomationsResponse,} from "#/types/automation";+import type { AutomationDraftListResponse } from "#/manifests/types";import {AUTOMATION_DETAIL_QUERY_KEY,AUTOMATION_RUNS_QUERY_KEY,} from "./use-automation-detail";export const AUTOMATIONS_QUERY_KEY = ["automations"] as const;+export const AUTOMATION_DRAFTS_QUERY_KEY = ["automation-drafts"] as const;++function getResponseStatus(error: unknown): number | null {+ if (!error || typeof error !== "object") return null;+ const response = (error as Record<string, unknown>).response;+ if (!response || typeof response !== "object") return null;+ const status = (response as Record<string, unknown>).status;+ return typeof status === "number" ? status : null;+}++function isDraftEndpointUnavailable(error: unknown): boolean {+ const status = getResponseStatus(error);+ return (+ status === 404 ||+ status === 405 ||+ isSdkHttpStatusError(error, 404) ||+ isSdkHttpStatusError(error, 405)+ );+}// The automation service caps `limit` at 100, so lists page by offset.const AUTOMATIONS_PAGE_SIZE = 50;@@ -43,6 +66,44 @@ interface UseAutomationsOptions {enabled?: boolean;}+interface UseAutomationDraftsOptions {+ limit?: number;+ offset?: number;+ enabled?: boolean;+}++export function useAutomationDrafts(options: UseAutomationDraftsOptions = {}) {+ const { limit = AUTOMATIONS_PAGE_SIZE, offset = 0, enabled = true } = options;+ const active = useActiveBackend();+ const deploymentCapabilities = useDeploymentCapabilities();+ const supportsAutomationDrafts = AutomationService.supportsAutomationDrafts(+ deploymentCapabilities.data,+ );++ return useQuery<AutomationDraftListResponse>({+ queryKey: [+ ...AUTOMATION_DRAFTS_QUERY_KEY,+ { limit, offset },+ active.backend.id,+ active.orgId,+ supportsAutomationDrafts,+ ],+ queryFn: async () => {+ if (!supportsAutomationDrafts) return { drafts: [], total: 0 };+ try {+ return await AutomationService.listServerDrafts({ limit, offset });+ } catch (error) {+ if (isDraftEndpointUnavailable(error)) {+ return { drafts: [], total: 0 };+ }+ throw error;+ }+ },+ staleTime: 0,+ enabled: enabled && !deploymentCapabilities.isLoading,+ });+}+/*** The org's automations, newest first, one page at a time. `data` joins the* loaded pages into one `AutomationsResponse` and `fetchNextPage` loads the@@ -104,6 +165,7 @@ export function useToggleAutomation({meta: { disableToast },onSuccess: (_data, variables) => {queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });+ queryClient.invalidateQueries({ queryKey: AUTOMATION_DRAFTS_QUERY_KEY });queryClient.invalidateQueries({ queryKey: AUTOMATION_DETAIL_QUERY_KEY });if (!variables.enabled) {trackAutomationDisableButton({ backendKind: active.backend.kind });@@ -112,6 +174,29 @@ export function useToggleAutomation({});}+export function useDeleteAutomationDraft() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (id: string) => AutomationService.deleteServerDraft(id),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: AUTOMATION_DRAFTS_QUERY_KEY });+ queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });+ },+ });+}++export function useDispatchAutomationDraft() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (id: string) => AutomationService.dispatchServerDraft(id),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: AUTOMATION_DRAFTS_QUERY_KEY });+ queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });+ queryClient.invalidateQueries({ queryKey: ["user", "conversations"] });+ },+ });+}+export function useImportAutomation() {const queryClient = useQueryClient();const active = useActiveBackend();diff --git a/src/hooks/use-auto-resize.ts b/src/hooks/use-auto-resize.tsindex 7eec544a34..550cab583e 100644--- a/src/hooks/use-auto-resize.ts+++ b/src/hooks/use-auto-resize.ts@@ -273,6 +273,19 @@ export const useAutoResize = (return;}+ // An empty field's scroll height includes the placeholder. While the chat+ // column is still width 0 (the agent panel animating open), that+ // placeholder wraps and the measurement locks in a tall box. Empty text+ // stays on one line unless the user resized it.+ if (textIsEmpty && !hasUserResizedRef.current) {+ applyResizeStrategy(element, {+ finalHeight: minHeight,+ overflowY: "hidden",+ });+ executeHeightCallback(minHeight, onHeightChange);+ return;+ }+// Measure element heightsconst measurements = measureElementHeights(element, minHeight);const { currentHeight, contentHeight } = measurements;diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 4c586496b1..c5fe3d8ead 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -46052,6 +46052,23 @@"zh-CN": "At","zh-TW": "At"},+ "AUTOMATION_SETUP$ON": {+ "ar": "في",+ "ca": "El",+ "de": "Am",+ "en": "On",+ "es": "El",+ "fr": "Le",+ "it": "Il",+ "ja": "毎週",+ "ko-KR": "매주",+ "no": "På",+ "pt": "Em",+ "tr": "Her",+ "uk": "У",+ "zh-CN": "每",+ "zh-TW": "每"+ },"AUTOMATION_SETUP$EVENT_SOURCE": {"ar": "Event source","ca": "Event source",@@ -46086,6 +46103,74 @@"zh-CN": "Event key","zh-TW": "Event key"},+ "AUTOMATION_SETUP$ASK_AGENT": {+ "ar": "اسأل الوكيل",+ "ca": "Pregunta a l’agent",+ "de": "Agent fragen",+ "en": "Ask Agent",+ "es": "Preguntar al agente",+ "fr": "Demander à l’agent",+ "it": "Chiedi all’agente",+ "ja": "エージェントに聞く",+ "ko-KR": "에이전트에게 묻기",+ "no": "Spør agenten",+ "pt": "Perguntar ao agente",+ "tr": "Ajana sor",+ "uk": "Запитати агента",+ "zh-CN": "询问智能体",+ "zh-TW": "詢問代理"+ },+ "AUTOMATION_SETUP$ASK_AGENT_EVENT_PROMPT": {+ "ar": "ساعدني في ضبط مشغّل الحدث. اسأل عمّا يجب أن يبدأ هذه الأتمتة، ثم املأ مصدر الحدث ومفتاح الحدث وأي عامل تصفية.",+ "ca": "Ajuda’m a configurar el disparador de l’esdeveniment. Pregunta què ha d’iniciar aquesta automatització i després omple l’origen, la clau i el filtre de l’esdeveniment.",+ "de": "Hilf mir, den Ereignisauslöser festzulegen. Frag, was diese Automatisierung starten soll, und fülle dann Ereignisquelle, Ereignisschlüssel und einen eventuellen Ereignisfilter aus.",+ "en": "Help me set the event trigger. Ask what should start this automation, then fill the event source, event key, and any event filter.",+ "es": "Ayúdame a configurar el disparador del evento. Pregunta qué debe iniciar esta automatización y luego completa el origen del evento, la clave del evento y cualquier filtro.",+ "fr": "Aide-moi à définir le déclencheur d’événement. Demande ce qui doit lancer cette automatisation, puis renseigne la source, la clé et le filtre d’événement.",+ "it": "Aiutami a impostare il trigger dell’evento. Chiedi cosa deve avviare questa automazione, poi compila origine, chiave ed eventuale filtro dell’evento.",+ "ja": "イベントトリガーの設定を手伝ってください。この自動化を開始する条件を尋ねてから、イベントソース、イベントキー、イベントフィルターを入力してください。",+ "ko-KR": "이벤트 트리거 설정을 도와주세요. 이 자동화를 시작할 조건을 물은 다음 이벤트 소스, 이벤트 키, 이벤트 필터를 채워 주세요.",+ "no": "Hjelp meg å sette hendelsesutløseren. Spør hva som skal starte denne automatiseringen, og fyll deretter inn hendelseskilde, hendelsesnøkkel og eventuelt filter.",+ "pt": "Ajude-me a definir o gatilho do evento. Pergunte o que deve iniciar esta automação e depois preencha a origem, a chave e o filtro do evento.",+ "tr": "Olay tetikleyicisini ayarlamama yardım et. Bu otomasyonu neyin başlatması gerektiğini sor, ardından olay kaynağını, olay anahtarını ve varsa olay süzgecini doldur.",+ "uk": "Допоможи налаштувати тригер події. Запитай, що має запускати цю автоматизацію, а потім заповни джерело події, ключ події та фільтр.",+ "zh-CN": "请帮我设置事件触发器。先问清什么情况应启动此自动化,然后填写事件来源、事件键和事件过滤器。",+ "zh-TW": "請幫我設定事件觸發器。先問清楚什麼情況應啟動此自動化,然後填寫事件來源、事件鍵和事件篩選器。"+ },+ "AUTOMATION_SETUP$EVENT_PUBLIC_URL_NOTICE": {+ "ar": "تحتاج مصادر الأحداث إلى عنوان URL عام لإرسال خطافات الويب إلى هذا المثيل.",+ "ca": "Els orígens d’esdeveniments necessiten un URL públic per enviar webhooks a aquesta instància.",+ "de": "Ereignisquellen brauchen eine öffentliche URL, um Webhooks an diese Instanz zu senden.",+ "en": "Event sources need a public URL to deliver webhooks to this instance.",+ "es": "Los orígenes de eventos necesitan una URL pública para enviar webhooks a esta instancia.",+ "fr": "Les sources d’événements ont besoin d’une URL publique pour envoyer des webhooks à cette instance.",+ "it": "Le origini evento richiedono un URL pubblico per inviare webhook a questa istanza.",+ "ja": "イベントソースがこのインスタンスに Webhook を届けるには、公開 URL が必要です。",+ "ko-KR": "이벤트 소스가 이 인스턴스로 웹훅을 보내려면 공개 URL이 필요합니다.",+ "no": "Hendelseskilder trenger en offentlig URL for å levere webhooks til denne instansen.",+ "pt": "As origens de evento precisam de um URL público para enviar webhooks a esta instância.",+ "tr": "Olay kaynaklarının bu örneğe webhook gönderebilmesi için genel bir URL gerekir.",+ "uk": "Джерелам подій потрібна публічна URL-адреса, щоб надсилати вебхуки до цього екземпляра.",+ "zh-CN": "事件来源需要公网 URL,才能把 Webhook 发送到此实例。",+ "zh-TW": "事件來源需要公開 URL,才能將 Webhook 傳送到此執行個體。"+ },+ "AUTOMATION_SETUP$ADD_FILTER": {+ "ar": "إضافة عامل تصفية",+ "ca": "Afegeix un filtre",+ "de": "Filter hinzufügen",+ "en": "Add Filter",+ "es": "Añadir filtro",+ "fr": "Ajouter un filtre",+ "it": "Aggiungi filtro",+ "ja": "フィルターを追加",+ "ko-KR": "필터 추가",+ "no": "Legg til filter",+ "pt": "Adicionar filtro",+ "tr": "Filtre ekle",+ "uk": "Додати фільтр",+ "zh-CN": "添加过滤器",+ "zh-TW": "新增篩選器"+ },"AUTOMATION_SETUP$EVENT_FILTER": {"ar": "Event filter","ca": "Event filter",@@ -46307,6 +46392,23 @@"zh-CN": "设置脚本","zh-TW": "設定指令碼"},+ "AUTOMATION_SETUP$SHOW_ENTRYPOINT_AND_SETUP": {+ "ar": "نقطة الدخول والإعداد",+ "ca": "Punt d’entrada i configuració",+ "de": "Einstiegspunkt und Setup",+ "en": "Entrypoint and setup",+ "es": "Punto de entrada y configuración",+ "fr": "Point d’entrée et installation",+ "it": "Punto di ingresso e configurazione",+ "ja": "エントリーポイントとセットアップ",+ "ko-KR": "진입점 및 설정",+ "no": "Inngangspunkt og oppsett",+ "pt": "Ponto de entrada e configuração",+ "tr": "Giriş noktası ve kurulum",+ "uk": "Точка входу та налаштування",+ "zh-CN": "入口点与设置",+ "zh-TW": "進入點與設定"+ },"AUTOMATION_SETUP$ENTRYPOINT_REQUIRED": {"ar": "أضف أمر نقطة دخول قبل المتابعة.","ca": "Afegeix una ordre de punt d’entrada abans de continuar.",@@ -46510,5 +46612,1008 @@"de": "✦ Von OpenHands ausgefüllt","uk": "✦ Заповнено OpenHands","ca": "✦ Emplenat per OpenHands"+ },+ "AUTOMATION_SETUP$DRAFT_STATUS_TITLE": {+ "ar": "تم حفظ المسودة",+ "ca": "Esborrany desat",+ "de": "Entwurf gespeichert",+ "en": "Draft saved",+ "es": "Borrador guardado",+ "fr": "Brouillon enregistré",+ "it": "Bozza salvata",+ "ja": "下書きを保存しました",+ "ko-KR": "초안 저장됨",+ "no": "Utkast lagret",+ "pt": "Rascunho salvo",+ "tr": "Taslak kaydedildi",+ "uk": "Чернетку збережено",+ "zh-CN": "草稿已保存",+ "zh-TW": "草稿已儲存"+ },+ "AUTOMATION_SETUP$DRAFT_STATUS_DESCRIPTION": {+ "ar": "تم حفظ هذه المسودة في خدمة الأتمتة. تظهر عمليات التشغيل الاختبارية أدناه.",+ "ca": "Aquest esborrany s'ha desat al servei d'automatització. Les execucions de prova apareixen a sota.",+ "de": "Dieser Entwurf ist im Automatisierungsdienst gespeichert. Testläufe werden unten angezeigt.",+ "en": "This draft is saved on the automation service. Test runs appear below.",+ "es": "Este borrador está guardado en el servicio de automatización. Las ejecuciones de prueba aparecen abajo.",+ "fr": "Ce brouillon est enregistré dans le service d’automatisation. Les exécutions de test s’affichent ci-dessous.",+ "it": "Questa bozza è salvata nel servizio di automazione. Le esecuzioni di test appaiono sotto.",+ "ja": "この下書きは自動化サービスに保存されています。テスト実行は下に表示されます。",+ "ko-KR": "이 초안은 자동화 서비스에 저장되었습니다. 테스트 실행은 아래에 표시됩니다.",+ "no": "Dette utkastet er lagret i automatiseringstjenesten. Testkjøringer vises nedenfor.",+ "pt": "Este rascunho foi salvo no serviço de automação. As execuções de teste aparecem abaixo.",+ "tr": "Bu taslak otomasyon hizmetine kaydedildi. Test çalıştırmaları aşağıda görünür.",+ "uk": "Цю чернетку збережено в сервісі автоматизації. Тестові запуски відображаються нижче.",+ "zh-CN": "此草稿已保存在自动化服务中。测试运行显示在下方。",+ "zh-TW": "此草稿已儲存在自動化服務中。測試執行會顯示在下方。"+ },+ "AUTOMATION_SETUP$LAST_SAVED": {+ "ar": "آخر حفظ",+ "ca": "Últim desament",+ "de": "Zuletzt gespeichert",+ "en": "Last saved",+ "es": "Último guardado",+ "fr": "Dernier enregistrement",+ "it": "Ultimo salvataggio",+ "ja": "最終保存",+ "ko-KR": "마지막 저장",+ "no": "Sist lagret",+ "pt": "Salvo por último",+ "tr": "Son kaydetme",+ "uk": "Востаннє збережено",+ "zh-CN": "上次保存",+ "zh-TW": "上次儲存"+ },+ "AUTOMATION_SETUP$TEST_AUTOMATION": {+ "ar": "أتمتة اختبارية",+ "ca": "Automatització de prova",+ "de": "Testautomatisierung",+ "en": "Test automation",+ "es": "Automatización de prueba",+ "fr": "Automatisation de test",+ "it": "Automazione di test",+ "ja": "テスト自動化",+ "ko-KR": "테스트 자동화",+ "no": "Testautomatisering",+ "pt": "Automação de teste",+ "tr": "Test otomasyonu",+ "uk": "Тестова автоматизація",+ "zh-CN": "测试自动化",+ "zh-TW": "測試自動化"+ },+ "AUTOMATION_SETUP$TEST_RUNS": {+ "ar": "عمليات التشغيل الاختبارية",+ "ca": "Execucions de prova",+ "de": "Testläufe",+ "en": "Test runs",+ "es": "Ejecuciones de prueba",+ "fr": "Exécutions de test",+ "it": "Esecuzioni di test",+ "ja": "テスト実行",+ "ko-KR": "테스트 실행",+ "no": "Testkjøringer",+ "pt": "Execuções de teste",+ "tr": "Test çalıştırmaları",+ "uk": "Тестові запуски",+ "zh-CN": "测试运行",+ "zh-TW": "測試執行"+ },+ "AUTOMATION_SETUP$TEST_DISPATCHED": {+ "ar": "Test run started.",+ "ca": "Test run started.",+ "de": "Test run started.",+ "en": "Test run started.",+ "es": "Test run started.",+ "fr": "Test run started.",+ "it": "Test run started.",+ "ja": "Test run started.",+ "ko-KR": "Test run started.",+ "no": "Test run started.",+ "pt": "Test run started.",+ "tr": "Test run started.",+ "uk": "Test run started.",+ "zh-CN": "Test run started.",+ "zh-TW": "Test run started."+ },+ "AUTOMATIONS$DETAIL$DRAFT": {+ "ar": "مسودة",+ "ca": "Esborrany",+ "de": "Entwurf",+ "en": "Draft",+ "es": "Borrador",+ "fr": "Brouillon",+ "it": "Bozza",+ "ja": "下書き",+ "ko-KR": "초안",+ "no": "Utkast",+ "pt": "Rascunho",+ "tr": "Taslak",+ "uk": "Чернетка",+ "zh-CN": "草稿",+ "zh-TW": "草稿"+ },+ "AUTOMATION_SETUP$LOADING_DRAFT": {+ "ar": "جارٍ تحميل المسودة…",+ "ca": "S’està carregant l’esborrany…",+ "de": "Entwurf wird geladen…",+ "en": "Loading saved draft…",+ "es": "Cargando borrador guardado…",+ "fr": "Chargement du brouillon enregistré…",+ "it": "Caricamento della bozza salvata…",+ "ja": "保存済みの下書きを読み込んでいます…",+ "ko-KR": "저장된 초안을 불러오는 중…",+ "no": "Laster lagret utkast…",+ "pt": "Carregando rascunho salvo…",+ "tr": "Kaydedilmiş taslak yükleniyor…",+ "uk": "Завантаження збереженої чернетки…",+ "zh-CN": "正在加载已保存的草稿…",+ "zh-TW": "正在載入已儲存的草稿…"+ },+ "AUTOMATION_SETUP$DRAFT_MISSING": {+ "ar": "لم تعد المسودة موجودة كجزء من هذه المحادثة. يمكنك متابعة الحديث مع الوكيل لإنشاء نموذج أتمتة جديد.",+ "ca": "L’esborrany ja no existeix com a part d’aquesta conversa. Pots continuar conversant amb l’agent per crear un formulari d’automatització nou.",+ "de": "Der Entwurf existiert nicht mehr als Teil dieser Unterhaltung. Du kannst weiter mit dem Agenten sprechen, um ein neues Automatisierungsformular zu erstellen.",+ "en": "The draft no longer exists as part of this conversation. Continue chatting with the agent to create a fresh automation form.",+ "es": "El borrador ya no existe como parte de esta conversación. Puedes seguir conversando con el agente para crear un nuevo formulario de automatización.",+ "fr": "Le brouillon n’existe plus dans cette conversation. Continuez à discuter avec l’agent pour créer un nouveau formulaire d’automatisation.",+ "it": "La bozza non esiste più come parte di questa conversazione. Continua a parlare con l’agente per creare un nuovo modulo di automazione.",+ "ja": "この会話に関連付けられていた下書きは存在しなくなりました。エージェントとの会話を続けて、新しい自動化フォームを作成できます。",+ "ko-KR": "이 대화에 연결된 초안이 더 이상 존재하지 않습니다. 에이전트와 계속 대화하여 새 자동화 양식을 만들 수 있습니다.",+ "no": "Utkastet finnes ikke lenger som en del av denne samtalen. Fortsett å chatte med agenten for å opprette et nytt automatiseringsskjema.",+ "pt": "O rascunho não existe mais como parte desta conversa. Continue conversando com o agente para criar um novo formulário de automação.",+ "tr": "Taslak artık bu konuşmanın parçası olarak mevcut değil. Yeni bir otomasyon formu oluşturmak için ajanla sohbet etmeye devam edebilirsiniz.",+ "uk": "Чернетка більше не існує як частина цієї розмови. Продовжуйте спілкуватися з агентом, щоб створити нову форму автоматизації.",+ "zh-CN": "该草稿已不再属于此对话。你可以继续与智能体对话以创建新的自动化表单。",+ "zh-TW": "該草稿已不再屬於此對話。你可以繼續與代理對話以建立新的自動化表單。"+ },+ "AUTOMATIONS$SAVED_DRAFTS": {+ "ar": "المسودات",+ "ca": "Esborranys",+ "de": "Entwürfe",+ "en": "Drafts",+ "es": "Borradores",+ "fr": "Brouillons",+ "it": "Bozze",+ "ja": "下書き",+ "ko-KR": "초안",+ "no": "Utkast",+ "pt": "Rascunhos",+ "tr": "Taslaklar",+ "uk": "Чернетки",+ "zh-CN": "草稿",+ "zh-TW": "草稿"+ },+ "AUTOMATIONS$SAVED_DRAFTS_DESCRIPTION": {+ "ar": "نموذج إعداد محفوظ قبل إنشاء الأتمتة.",+ "ca": "Formulari de configuració desat abans de crear l’automatització.",+ "de": "Ein Einrichtungsformular, das vor dem Erstellen der Automatisierung gespeichert wurde.",+ "en": "Setup form saved before an automation is created.",+ "es": "Formulario de configuración guardado antes de crear una automatización.",+ "fr": "Formulaire de configuration enregistré avant la création d’une automatisation.",+ "it": "Modulo di configurazione salvato prima della creazione di un’automazione.",+ "ja": "自動化を作成する前に保存されたセットアップフォームです。",+ "ko-KR": "자동화가 생성되기 전에 저장된 설정 양식입니다.",+ "no": "Oppsettskjema lagret før en automatisering opprettes.",+ "pt": "Formulário de configuração salvo antes de uma automação ser criada.",+ "tr": "Bir otomasyon oluşturulmadan önce kaydedilen kurulum formu.",+ "uk": "Форма налаштування, збережена до створення автоматизації.",+ "zh-CN": "在创建自动化之前保存的设置表单。",+ "zh-TW": "在建立自動化之前儲存的設定表單。"+ },+ "AUTOMATIONS$MATERIALIZED_DRAFTS": {+ "ar": "أتمتات مسودة للاختبار",+ "ca": "Automatitzacions d’esborrany de prova",+ "de": "Test-Entwurfsautomatisierungen",+ "en": "Test draft automations",+ "es": "Automatizaciones de borrador de prueba",+ "fr": "Automatisations brouillon de test",+ "it": "Automazioni bozza di test",+ "ja": "テスト用下書き自動化",+ "ko-KR": "테스트 초안 자동화",+ "no": "Testutkast-automatiseringer",+ "pt": "Automações de rascunho de teste",+ "tr": "Test taslak otomasyonları",+ "uk": "Тестові чернетки автоматизацій",+ "zh-CN": "测试草稿自动化",+ "zh-TW": "測試草稿自動化"+ },+ "AUTOMATIONS$UNTITLED_DRAFT": {+ "ar": "مسودة بلا عنوان",+ "ca": "Esborrany sense títol",+ "de": "Unbenannter Entwurf",+ "en": "Untitled draft",+ "es": "Borrador sin título",+ "fr": "Brouillon sans titre",+ "it": "Bozza senza titolo",+ "ja": "無題の下書き",+ "ko-KR": "제목 없는 초안",+ "no": "Uten navn",+ "pt": "Rascunho sem título",+ "tr": "Adsız taslak",+ "uk": "Чернетка без назви",+ "zh-CN": "无标题草稿",+ "zh-TW": "未命名草稿"+ },+ "AUTOMATION_SETUP$READY_TO_TEST": {+ "en": "Ready to test",+ "ja": "テスト準備完了",+ "zh-CN": "已准备好测试",+ "zh-TW": "已準備好測試",+ "ko-KR": "테스트 준비 완료",+ "no": "Klar til å teste",+ "ar": "جاهز للاختبار",+ "de": "Bereit zum Testen",+ "fr": "Prêt à tester",+ "it": "Pronto per il test",+ "pt": "Pronto para testar",+ "es": "Listo para probar",+ "ca": "A punt per provar",+ "tr": "Test etmeye hazır",+ "uk": "Готово до тестування"+ },+ "AUTOMATION_SETUP$NEEDS_CHANGES": {+ "en": "Needs changes",+ "ja": "変更が必要",+ "zh-CN": "需要修改",+ "zh-TW": "需要修改",+ "ko-KR": "변경 필요",+ "no": "Trenger endringer",+ "ar": "يحتاج إلى تغييرات",+ "de": "Änderungen erforderlich",+ "fr": "Modifications requises",+ "it": "Richiede modifiche",+ "pt": "Precisa de alterações",+ "es": "Necesita cambios",+ "ca": "Necessita canvis",+ "tr": "Değişiklik gerekiyor",+ "uk": "Потрібні зміни"+ },+ "AUTOMATION_SETUP$SAVE_AND_TEST": {+ "en": "Save & test",+ "ja": "保存してテスト",+ "zh-CN": "保存并测试",+ "zh-TW": "儲存並測試",+ "ko-KR": "저장 및 테스트",+ "no": "Lagre og test",+ "ar": "احفظ واختبر",+ "de": "Speichern und testen",+ "fr": "Enregistrer et tester",+ "it": "Salva e testa",+ "pt": "Salvar e testar",+ "es": "Guardar y probar",+ "ca": "Desa i prova",+ "tr": "Kaydet ve test et",+ "uk": "Зберегти й протестувати"+ },+ "AUTOMATION_SETUP$TEST_RUN": {+ "en": "Test Run",+ "ja": "テスト実行",+ "zh-CN": "测试运行",+ "zh-TW": "測試執行",+ "ko-KR": "테스트 실행",+ "no": "Testkjøring",+ "ar": "تشغيل اختباري",+ "de": "Testlauf",+ "fr": "Exécution de test",+ "it": "Esecuzione di test",+ "pt": "Execução de teste",+ "es": "Ejecución de prueba",+ "ca": "Execució de prova",+ "tr": "Test çalıştırması",+ "uk": "Тестовий запуск"+ },+ "AUTOMATION_SETUP$TEST_DRAFT": {+ "en": "Test draft",+ "ja": "下書きをテスト",+ "zh-CN": "测试草稿",+ "zh-TW": "測試草稿",+ "ko-KR": "초안 테스트",+ "no": "Test utkast",+ "ar": "اختبر المسودة",+ "de": "Entwurf testen",+ "fr": "Tester le brouillon",+ "it": "Testa bozza",+ "pt": "Testar rascunho",+ "es": "Probar borrador",+ "ca": "Prova l’esborrany",+ "tr": "Taslağı test et",+ "uk": "Протестувати чернетку"+ },+ "AUTOMATION_SETUP$STARTING_TEST": {+ "en": "Starting test…",+ "ja": "テストを開始中…",+ "zh-CN": "正在开始测试…",+ "zh-TW": "正在開始測試…",+ "ko-KR": "테스트 시작 중…",+ "no": "Starter test…",+ "ar": "جارٍ بدء الاختبار…",+ "de": "Test wird gestartet…",+ "fr": "Démarrage du test…",+ "it": "Avvio del test…",+ "pt": "Iniciando teste…",+ "es": "Iniciando prueba…",+ "ca": "Iniciant la prova…",+ "tr": "Test başlatılıyor…",+ "uk": "Запуск тесту…"+ },+ "AUTOMATION_SETUP$SAVING": {+ "en": "Saving…",+ "ja": "保存中…",+ "zh-CN": "正在保存…",+ "zh-TW": "正在儲存…",+ "ko-KR": "저장 중…",+ "no": "Lagrer…",+ "ar": "جارٍ الحفظ…",+ "de": "Wird gespeichert…",+ "fr": "Enregistrement…",+ "it": "Salvataggio…",+ "pt": "Salvando…",+ "es": "Guardando…",+ "ca": "Desant…",+ "tr": "Kaydediliyor…",+ "uk": "Збереження…"+ },+ "AUTOMATION_SETUP$SAVE_FAILED": {+ "en": "Save failed",+ "ja": "保存に失敗しました",+ "zh-CN": "保存失败",+ "zh-TW": "儲存失敗",+ "ko-KR": "저장 실패",+ "no": "Lagring mislyktes",+ "ar": "فشل الحفظ",+ "de": "Speichern fehlgeschlagen",+ "fr": "Échec de l’enregistrement",+ "it": "Salvataggio non riuscito",+ "pt": "Falha ao salvar",+ "es": "Error al guardar",+ "ca": "No s’ha pogut desar",+ "tr": "Kaydetme başarısız",+ "uk": "Не вдалося зберегти"+ },+ "AUTOMATION_SETUP$SAVED_JUST_NOW": {+ "en": "Saved just now",+ "ja": "たった今保存しました",+ "zh-CN": "刚刚已保存",+ "zh-TW": "剛剛已儲存",+ "ko-KR": "방금 저장됨",+ "no": "Lagret nå nettopp",+ "ar": "تم الحفظ للتو",+ "de": "Gerade gespeichert",+ "fr": "Enregistré à l’instant",+ "it": "Salvato ora",+ "pt": "Salvo agora",+ "es": "Guardado ahora",+ "ca": "Desat ara mateix",+ "tr": "Az önce kaydedildi",+ "uk": "Щойно збережено"+ },+ "AUTOMATION_SETUP$UNSAVED_CHANGES": {+ "en": "Unsaved changes",+ "ja": "未保存の変更",+ "zh-CN": "未保存的更改",+ "zh-TW": "未儲存的變更",+ "ko-KR": "저장되지 않은 변경 사항",+ "no": "Ulagrede endringer",+ "ar": "تغييرات غير محفوظة",+ "de": "Nicht gespeicherte Änderungen",+ "fr": "Modifications non enregistrées",+ "it": "Modifiche non salvate",+ "pt": "Alterações não salvas",+ "es": "Cambios sin guardar",+ "ca": "Canvis no desats",+ "tr": "Kaydedilmemiş değişiklikler",+ "uk": "Незбережені зміни"+ },+ "AUTOMATION_SETUP$LATEST_TEST_PASSED": {+ "en": "Latest test passed",+ "ja": "最新のテストに合格",+ "zh-CN": "最新测试已通过",+ "zh-TW": "最新測試已通過",+ "ko-KR": "최신 테스트 통과",+ "no": "Siste test bestått",+ "ar": "نجح أحدث اختبار",+ "de": "Letzter Test bestanden",+ "fr": "Dernier test réussi",+ "it": "Ultimo test superato",+ "pt": "Último teste aprovado",+ "es": "Última prueba aprobada",+ "ca": "Última prova superada",+ "tr": "Son test geçti",+ "uk": "Останній тест пройдено"+ },+ "AUTOMATION_SETUP$LATEST_TEST_FAILED": {+ "en": "Latest test failed",+ "ja": "最新のテストに失敗",+ "zh-CN": "最新测试失败",+ "zh-TW": "最新測試失敗",+ "ko-KR": "최신 테스트 실패",+ "no": "Siste test feilet",+ "ar": "فشل أحدث اختبار",+ "de": "Letzter Test fehlgeschlagen",+ "fr": "Dernier test échoué",+ "it": "Ultimo test non riuscito",+ "pt": "Último teste falhou",+ "es": "Última prueba fallida",+ "ca": "Última prova fallida",+ "tr": "Son test başarısız",+ "uk": "Останній тест не пройдено"+ },+ "AUTOMATION_SETUP$LATEST_TEST_RUNNING": {+ "en": "Latest test running",+ "ja": "最新のテストを実行中",+ "zh-CN": "最新测试正在运行",+ "zh-TW": "最新測試正在執行",+ "ko-KR": "최신 테스트 실행 중",+ "no": "Siste test kjører",+ "ar": "أحدث اختبار قيد التشغيل",+ "de": "Letzter Test läuft",+ "fr": "Dernier test en cours",+ "it": "Ultimo test in esecuzione",+ "pt": "Último teste em execução",+ "es": "Última prueba en curso",+ "ca": "Última prova en execució",+ "tr": "Son test çalışıyor",+ "uk": "Останній тест виконується"+ },+ "AUTOMATION_SETUP$DRAFT_TYPE": {+ "en": "Type:",+ "ja": "種類:",+ "zh-CN": "类型:",+ "zh-TW": "類型:",+ "ko-KR": "유형:",+ "no": "Type:",+ "ar": "النوع:",+ "de": "Typ:",+ "fr": "Type :",+ "it": "Tipo:",+ "pt": "Tipo:",+ "es": "Tipo:",+ "ca": "Tipus:",+ "tr": "Tür:",+ "uk": "Тип:"+ },+ "AUTOMATION_SETUP$DRAFT_TRIGGER": {+ "en": "Trigger:",+ "ja": "トリガー:",+ "zh-CN": "触发器:",+ "zh-TW": "觸發條件:",+ "ko-KR": "트리거:",+ "no": "Utløser:",+ "ar": "المشغّل:",+ "de": "Auslöser:",+ "fr": "Déclencheur :",+ "it": "Attivatore:",+ "pt": "Gatilho:",+ "es": "Activador:",+ "ca": "Activador:",+ "tr": "Tetikleyici:",+ "uk": "Тригер:"+ },+ "AUTOMATION_SETUP$DRAFT_VALIDATION": {+ "en": "Validation:",+ "ja": "検証:",+ "zh-CN": "验证:",+ "zh-TW": "驗證:",+ "ko-KR": "검증:",+ "no": "Validering:",+ "ar": "التحقق:",+ "de": "Validierung:",+ "fr": "Validation :",+ "it": "Convalida:",+ "pt": "Validação:",+ "es": "Validación:",+ "ca": "Validació:",+ "tr": "Doğrulama:",+ "uk": "Перевірка:"+ },+ "AUTOMATION_SETUP$LATEST_TEST": {+ "en": "Latest test:",+ "ja": "最新のテスト:",+ "zh-CN": "最新测试:",+ "zh-TW": "最新測試:",+ "ko-KR": "최신 테스트:",+ "no": "Siste test:",+ "ar": "أحدث اختبار:",+ "de": "Letzter Test:",+ "fr": "Dernier test :",+ "it": "Ultimo test:",+ "pt": "Último teste:",+ "es": "Última prueba:",+ "ca": "Última prova:",+ "tr": "Son test:",+ "uk": "Останній тест:"+ },+ "AUTOMATION_SETUP$RESUME_DRAFT": {+ "en": "Resume draft",+ "ja": "下書きを再開",+ "zh-CN": "继续草稿",+ "zh-TW": "繼續草稿",+ "ko-KR": "초안 재개",+ "no": "Fortsett utkast",+ "ar": "استئناف المسودة",+ "de": "Entwurf fortsetzen",+ "fr": "Reprendre le brouillon",+ "it": "Riprendi bozza",+ "pt": "Retomar rascunho",+ "es": "Reanudar borrador",+ "ca": "Reprèn l’esborrany",+ "tr": "Taslağı sürdür",+ "uk": "Продовжити чернетку"+ },+ "AUTOMATION_SETUP$RESUMING_DRAFT": {+ "en": "Resuming…",+ "ja": "再開中…",+ "zh-CN": "正在继续…",+ "zh-TW": "正在繼續…",+ "ko-KR": "재개 중…",+ "no": "Fortsetter…",+ "ar": "جارٍ الاستئناف…",+ "de": "Wird fortgesetzt…",+ "fr": "Reprise…",+ "it": "Ripresa…",+ "pt": "Retomando…",+ "es": "Reanudando…",+ "ca": "Reprenent…",+ "tr": "Sürdürülüyor…",+ "uk": "Продовження…"+ },+ "AUTOMATION_SETUP$DELETE_DRAFT": {+ "en": "Delete draft",+ "ja": "下書きを削除",+ "zh-CN": "删除草稿",+ "zh-TW": "刪除草稿",+ "ko-KR": "초안 삭제",+ "no": "Slett utkast",+ "ar": "حذف المسودة",+ "de": "Entwurf löschen",+ "fr": "Supprimer le brouillon",+ "it": "Elimina bozza",+ "pt": "Excluir rascunho",+ "es": "Eliminar borrador",+ "ca": "Suprimeix l’esborrany",+ "tr": "Taslağı sil",+ "uk": "Видалити чернетку"+ },+ "AUTOMATION_SETUP$DELETE_DRAFT_TITLE": {+ "en": "Delete draft?",+ "ja": "下書きを削除しますか?",+ "zh-CN": "删除草稿?",+ "zh-TW": "刪除草稿?",+ "ko-KR": "초안을 삭제할까요?",+ "no": "Slette utkast?",+ "ar": "حذف المسودة؟",+ "de": "Entwurf löschen?",+ "fr": "Supprimer le brouillon ?",+ "it": "Eliminare la bozza?",+ "pt": "Excluir rascunho?",+ "es": "¿Eliminar borrador?",+ "ca": "Vols suprimir l’esborrany?",+ "tr": "Taslak silinsin mi?",+ "uk": "Видалити чернетку?"+ },+ "AUTOMATION_SETUP$DELETE_DRAFT_MESSAGE": {+ "en": "Delete “{{name}}”? This removes the saved setup draft, but does not delete any final automations.",+ "ja": "「{{name}}」を削除しますか?保存済みのセットアップ下書きだけが削除され、完成したオートメーションは削除されません。",+ "zh-CN": "删除“{{name}}”?这会移除已保存的设置草稿,但不会删除任何最终自动化。",+ "zh-TW": "刪除「{{name}}」?這會移除已儲存的設定草稿,但不會刪除任何最終自動化。",+ "ko-KR": "“{{name}}”을(를) 삭제할까요? 저장된 설정 초안만 삭제되며 최종 자동화는 삭제되지 않습니다.",+ "no": "Slette «{{name}}»? Dette fjerner det lagrede oppsettsutkastet, men sletter ingen ferdige automatiseringer.",+ "ar": "هل تريد حذف “{{name}}”؟ سيؤدي هذا إلى إزالة مسودة الإعداد المحفوظة، لكنه لن يحذف أي أتمتات نهائية.",+ "de": "„{{name}}“ löschen? Dadurch wird der gespeicherte Setup-Entwurf entfernt, endgültige Automationen werden jedoch nicht gelöscht.",+ "fr": "Supprimer « {{name}} » ? Cela supprime le brouillon de configuration enregistré, mais ne supprime aucune automatisation finale.",+ "it": "Eliminare “{{name}}”? Questa operazione rimuove la bozza di configurazione salvata, ma non elimina automazioni finali.",+ "pt": "Excluir “{{name}}”? Isso remove o rascunho de configuração salvo, mas não exclui automações finais.",+ "es": "¿Eliminar “{{name}}”? Esto elimina el borrador de configuración guardado, pero no elimina automatizaciones finales.",+ "ca": "Vols suprimir “{{name}}”? Això elimina l’esborrany de configuració desat, però no suprimeix cap automatització final.",+ "tr": "“{{name}}” silinsin mi? Bu işlem kayıtlı kurulum taslağını kaldırır, ancak tamamlanmış otomasyonları silmez.",+ "uk": "Видалити «{{name}}»? Це прибере збережену чернетку налаштування, але не видалить жодної фінальної автоматизації."+ },+ "AUTOMATION_SETUP$DRAFT_DELETED": {+ "en": "Draft deleted.",+ "ja": "下書きを削除しました。",+ "zh-CN": "草稿已删除。",+ "zh-TW": "草稿已刪除。",+ "ko-KR": "초안이 삭제되었습니다.",+ "no": "Utkast slettet.",+ "ar": "تم حذف المسودة.",+ "de": "Entwurf gelöscht.",+ "fr": "Brouillon supprimé.",+ "it": "Bozza eliminata.",+ "pt": "Rascunho excluído.",+ "es": "Borrador eliminado.",+ "ca": "Esborrany suprimit.",+ "tr": "Taslak silindi.",+ "uk": "Чернетку видалено."+ },+ "AUTOMATION_SETUP$TEST_EVENT_PAYLOAD": {+ "en": "Test event payload",+ "ja": "テストイベントペイロード",+ "zh-CN": "测试事件载荷",+ "zh-TW": "測試事件酬載",+ "ko-KR": "테스트 이벤트 페이로드",+ "no": "Testhendelseslast",+ "ar": "حمولة حدث الاختبار",+ "de": "Test-Ereignisnutzlast",+ "fr": "Charge utile d’événement de test",+ "it": "Payload evento di test",+ "pt": "Payload do evento de teste",+ "es": "Carga útil del evento de prueba",+ "ca": "Càrrega útil de l’esdeveniment de prova",+ "tr": "Test olay yükü",+ "uk": "Тестове корисне навантаження події"+ },+ "AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_DESCRIPTION": {+ "en": "Save & test sends this JSON as a synthetic event payload. Use values that satisfy your event filter.",+ "ja": "保存してテストすると、この JSON が合成イベントペイロードとして送信されます。イベントフィルターを満たす値を使用してください。",+ "zh-CN": "“保存并测试”会将此 JSON 作为合成事件载荷发送。请使用满足事件筛选器的值。",+ "zh-TW": "「儲存並測試」會將此 JSON 作為合成事件酬載送出。請使用符合事件篩選器的值。",+ "ko-KR": "저장 및 테스트는 이 JSON을 합성 이벤트 페이로드로 보냅니다. 이벤트 필터를 만족하는 값을 사용하세요.",+ "no": "Lagre og test sender denne JSON-en som en syntetisk hendelseslast. Bruk verdier som oppfyller hendelsesfilteret.",+ "ar": "يرسل إجراء الحفظ والاختبار JSON هذا كحمولة حدث اصطناعية. استخدم قيماً تطابق عامل تصفية الحدث.",+ "de": "Speichern und testen sendet dieses JSON als synthetische Ereignisnutzlast. Verwende Werte, die deinen Ereignisfilter erfüllen.",+ "fr": "Enregistrer et tester envoie ce JSON comme charge utile d’événement synthétique. Utilisez des valeurs qui satisfont votre filtre d’événement.",+ "it": "Salva e testa invia questo JSON come payload evento sintetico. Usa valori che soddisfano il filtro evento.",+ "pt": "Salvar e testar envia este JSON como uma carga de evento sintética. Use valores que atendam ao filtro de evento.",+ "es": "Guardar y probar envía este JSON como una carga útil de evento sintética. Usa valores que satisfagan tu filtro de evento.",+ "ca": "Desa i prova envia aquest JSON com a càrrega útil d’esdeveniment sintètica. Fes servir valors que compleixin el filtre d’esdeveniments.",+ "tr": "Kaydet ve test et, bu JSON’u sentetik olay yükü olarak gönderir. Olay filtrenizi karşılayan değerler kullanın.",+ "uk": "Зберегти й протестувати надсилає цей JSON як синтетичне корисне навантаження події. Використовуйте значення, які відповідають фільтру подій."+ },+ "AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_PLACEHOLDER": {+ "en": "Enter a JSON object to use as the test event payload",+ "ja": "テストイベントペイロードとして使用する JSON オブジェクトを入力",+ "zh-CN": "输入要用作测试事件载荷的 JSON 对象",+ "zh-TW": "輸入要用作測試事件酬載的 JSON 物件",+ "ko-KR": "테스트 이벤트 페이로드로 사용할 JSON 객체를 입력하세요",+ "no": "Angi et JSON-objekt som testhendelseslast",+ "ar": "أدخل كائن JSON لاستخدامه كحمولة حدث اختبار",+ "de": "JSON-Objekt für die Test-Ereignisnutzlast eingeben",+ "fr": "Saisissez un objet JSON à utiliser comme charge utile d’événement de test",+ "it": "Inserisci un oggetto JSON da usare come payload evento di test",+ "pt": "Insira um objeto JSON para usar como payload do evento de teste",+ "es": "Introduce un objeto JSON para usarlo como carga útil del evento de prueba",+ "ca": "Introdueix un objecte JSON per utilitzar-lo com a càrrega útil de prova",+ "tr": "Test olay yükü olarak kullanılacak bir JSON nesnesi girin",+ "uk": "Введіть JSON-об’єкт для використання як тестове корисне навантаження події"+ },+ "AUTOMATION_SETUP$TEST_EVENT_PAYLOAD_INVALID": {+ "en": "Enter a valid JSON object before testing this event automation.",+ "ja": "このイベントオートメーションをテストする前に、有効な JSON オブジェクトを入力してください。",+ "zh-CN": "测试此事件自动化之前,请输入有效的 JSON 对象。",+ "zh-TW": "測試此事件自動化之前,請輸入有效的 JSON 物件。",+ "ko-KR": "이 이벤트 자동화를 테스트하기 전에 유효한 JSON 객체를 입력하세요.",+ "no": "Angi et gyldig JSON-objekt før du tester denne hendelsesautomatiseringen.",+ "ar": "أدخل كائن JSON صالحاً قبل اختبار أتمتة الحدث هذه.",+ "de": "Gib ein gültiges JSON-Objekt ein, bevor du diese Ereignisautomation testest.",+ "fr": "Saisissez un objet JSON valide avant de tester cette automatisation d’événement.",+ "it": "Inserisci un oggetto JSON valido prima di testare questa automazione evento.",+ "pt": "Insira um objeto JSON válido antes de testar esta automação de evento.",+ "es": "Introduce un objeto JSON válido antes de probar esta automatización de evento.",+ "ca": "Introdueix un objecte JSON vàlid abans de provar aquesta automatització d’esdeveniment.",+ "tr": "Bu olay otomasyonunu test etmeden önce geçerli bir JSON nesnesi girin.",+ "uk": "Введіть дійсний JSON-об’єкт перед тестуванням цієї автоматизації події."+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_TITLE": {+ "en": "Register this as a custom webhook source",+ "ja": "カスタム Webhook ソースとして登録",+ "zh-CN": "Register this as a custom webhook source",+ "zh-TW": "Register this as a custom webhook source",+ "ko-KR": "Register this as a custom webhook source",+ "no": "Register this as a custom webhook source",+ "ar": "Register this as a custom webhook source",+ "de": "Register this as a custom webhook source",+ "fr": "Register this as a custom webhook source",+ "it": "Register this as a custom webhook source",+ "pt": "Register this as a custom webhook source",+ "es": "Register this as a custom webhook source",+ "ca": "Register this as a custom webhook source",+ "tr": "Register this as a custom webhook source",+ "uk": "Register this as a custom webhook source"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_DESCRIPTION": {+ "en": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "ja": "イベントソースが一覧にない場合に使用します。OpenHands は保存またはテストの前に Webhook URL を作成します。",+ "zh-CN": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "zh-TW": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "ko-KR": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "no": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "ar": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "de": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "fr": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "it": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "pt": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "es": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "ca": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "tr": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation.",+ "uk": "Use this when the event source is not already listed. OpenHands will create a webhook URL for the source before saving or testing the automation."+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_NAME": {+ "en": "Webhook name",+ "ja": "Webhook 名",+ "zh-CN": "Webhook name",+ "zh-TW": "Webhook name",+ "ko-KR": "Webhook name",+ "no": "Webhook name",+ "ar": "Webhook name",+ "de": "Webhook name",+ "fr": "Webhook name",+ "it": "Webhook name",+ "pt": "Webhook name",+ "es": "Webhook name",+ "ca": "Webhook name",+ "tr": "Webhook name",+ "uk": "Webhook name"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_NAME_PLACEHOLDER": {+ "en": "Incident webhook",+ "ja": "インシデント Webhook",+ "zh-CN": "Incident webhook",+ "zh-TW": "Incident webhook",+ "ko-KR": "Incident webhook",+ "no": "Incident webhook",+ "ar": "Incident webhook",+ "de": "Incident webhook",+ "fr": "Incident webhook",+ "it": "Incident webhook",+ "pt": "Incident webhook",+ "es": "Incident webhook",+ "ca": "Incident webhook",+ "tr": "Incident webhook",+ "uk": "Incident webhook"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_EVENT_KEY_EXPR": {+ "en": "Event key expression",+ "ja": "イベントキー式",+ "zh-CN": "Event key expression",+ "zh-TW": "Event key expression",+ "ko-KR": "Event key expression",+ "no": "Event key expression",+ "ar": "Event key expression",+ "de": "Event key expression",+ "fr": "Event key expression",+ "it": "Event key expression",+ "pt": "Event key expression",+ "es": "Event key expression",+ "ca": "Event key expression",+ "tr": "Event key expression",+ "uk": "Event key expression"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_HEADER": {+ "en": "Signature header",+ "ja": "署名ヘッダー",+ "zh-CN": "Signature header",+ "zh-TW": "Signature header",+ "ko-KR": "Signature header",+ "no": "Signature header",+ "ar": "Signature header",+ "de": "Signature header",+ "fr": "Signature header",+ "it": "Signature header",+ "pt": "Signature header",+ "es": "Signature header",+ "ca": "Signature header",+ "tr": "Signature header",+ "uk": "Signature header"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME": {+ "en": "Signature scheme",+ "ja": "署名方式",+ "zh-CN": "Signature scheme",+ "zh-TW": "Signature scheme",+ "ko-KR": "Signature scheme",+ "no": "Signature scheme",+ "ar": "Signature scheme",+ "de": "Signature scheme",+ "fr": "Signature scheme",+ "it": "Signature scheme",+ "pt": "Signature scheme",+ "es": "Signature scheme",+ "ca": "Signature scheme",+ "tr": "Signature scheme",+ "uk": "Signature scheme"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME_HMAC": {+ "en": "HMAC SHA-256 hex",+ "ja": "HMAC SHA-256 16進",+ "zh-CN": "HMAC SHA-256 hex",+ "zh-TW": "HMAC SHA-256 hex",+ "ko-KR": "HMAC SHA-256 hex",+ "no": "HMAC SHA-256 hex",+ "ar": "HMAC SHA-256 hex",+ "de": "HMAC SHA-256 hex",+ "fr": "HMAC SHA-256 hex",+ "it": "HMAC SHA-256 hex",+ "pt": "HMAC SHA-256 hex",+ "es": "HMAC SHA-256 hex",+ "ca": "HMAC SHA-256 hex",+ "tr": "HMAC SHA-256 hex",+ "uk": "HMAC SHA-256 hex"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME_STANDARD": {+ "en": "Standard Webhooks",+ "ja": "標準 Webhooks",+ "zh-CN": "标准 Webhooks",+ "zh-TW": "標準 Webhooks",+ "ko-KR": "표준 Webhooks",+ "no": "Standard-webhooks",+ "ar": "Webhooks القياسية",+ "de": "Standard-Webhooks",+ "fr": "Webhooks standard",+ "it": "Webhook standard",+ "pt": "Webhooks padrão",+ "es": "Webhooks estándar",+ "ca": "Webhooks estàndard",+ "tr": "Standart Webhooks",+ "uk": "Стандартні Webhooks"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_SIGNATURE_SCHEME_SLACK": {+ "en": "Slack v0",+ "ja": "Slack v0 署名",+ "zh-CN": "Slack v0 签名",+ "zh-TW": "Slack v0 簽章",+ "ko-KR": "Slack v0 서명",+ "no": "Slack v0-signatur",+ "ar": "توقيع Slack v0",+ "de": "Slack-v0-Signatur",+ "fr": "Signature Slack v0",+ "it": "Firma Slack v0",+ "pt": "Assinatura Slack v0",+ "es": "Firma Slack v0",+ "ca": "Signatura Slack v0",+ "tr": "Slack v0 imzası",+ "uk": "Підпис Slack v0"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_SECRET": {+ "en": "Signing secret",+ "ja": "署名シークレット",+ "zh-CN": "Signing secret",+ "zh-TW": "Signing secret",+ "ko-KR": "Signing secret",+ "no": "Signing secret",+ "ar": "Signing secret",+ "de": "Signing secret",+ "fr": "Signing secret",+ "it": "Signing secret",+ "pt": "Signing secret",+ "es": "Signing secret",+ "ca": "Signing secret",+ "tr": "Signing secret",+ "uk": "Signing secret"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_SECRET_PLACEHOLDER": {+ "en": "Leave blank to generate one",+ "ja": "生成する場合は空欄のまま",+ "zh-CN": "Leave blank to generate one",+ "zh-TW": "Leave blank to generate one",+ "ko-KR": "Leave blank to generate one",+ "no": "Leave blank to generate one",+ "ar": "Leave blank to generate one",+ "de": "Leave blank to generate one",+ "fr": "Leave blank to generate one",+ "it": "Leave blank to generate one",+ "pt": "Leave blank to generate one",+ "es": "Leave blank to generate one",+ "ca": "Leave blank to generate one",+ "tr": "Leave blank to generate one",+ "uk": "Leave blank to generate one"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_SECRET_HELP": {+ "en": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "ja": "外部サービスから署名シークレットが提供されている場合はここに貼り付けます。ない場合は OpenHands が生成し、登録後に一度だけ表示します。",+ "zh-CN": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "zh-TW": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "ko-KR": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "no": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "ar": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "de": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "fr": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "it": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "pt": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "es": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "ca": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "tr": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration.",+ "uk": "If the external service already gave you a signing secret, paste it here. Otherwise OpenHands generates one and shows it once after registration."+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_CREATED": {+ "en": "Custom webhook source registered.",+ "ja": "カスタム Webhook ソースを登録しました。",+ "zh-CN": "Custom webhook source registered.",+ "zh-TW": "Custom webhook source registered.",+ "ko-KR": "Custom webhook source registered.",+ "no": "Custom webhook source registered.",+ "ar": "Custom webhook source registered.",+ "de": "Custom webhook source registered.",+ "fr": "Custom webhook source registered.",+ "it": "Custom webhook source registered.",+ "pt": "Custom webhook source registered.",+ "es": "Custom webhook source registered.",+ "ca": "Custom webhook source registered.",+ "tr": "Custom webhook source registered.",+ "uk": "Custom webhook source registered."+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_URL": {+ "en": "Webhook URL: {{url}}",+ "ja": "Webhook の URL: {{url}}",+ "zh-CN": "Webhook URL: {{url}}",+ "zh-TW": "Webhook URL: {{url}}",+ "ko-KR": "Webhook URL: {{url}}",+ "no": "Webhook URL: {{url}}",+ "ar": "Webhook URL: {{url}}",+ "de": "Webhook URL: {{url}}",+ "fr": "Webhook URL: {{url}}",+ "it": "Webhook URL: {{url}}",+ "pt": "Webhook URL: {{url}}",+ "es": "Webhook URL: {{url}}",+ "ca": "Webhook URL: {{url}}",+ "tr": "Webhook URL: {{url}}",+ "uk": "Webhook URL: {{url}}"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_GENERATED_SECRET": {+ "en": "Generated signing secret: {{secret}}",+ "ja": "生成された署名シークレット: {{secret}}",+ "zh-CN": "Generated signing secret: {{secret}}",+ "zh-TW": "Generated signing secret: {{secret}}",+ "ko-KR": "Generated signing secret: {{secret}}",+ "no": "Generated signing secret: {{secret}}",+ "ar": "Generated signing secret: {{secret}}",+ "de": "Generated signing secret: {{secret}}",+ "fr": "Generated signing secret: {{secret}}",+ "it": "Generated signing secret: {{secret}}",+ "pt": "Generated signing secret: {{secret}}",+ "es": "Generated signing secret: {{secret}}",+ "ca": "Generated signing secret: {{secret}}",+ "tr": "Generated signing secret: {{secret}}",+ "uk": "Generated signing secret: {{secret}}"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_SOURCE_REQUIRED": {+ "en": "Enter an event source before registering a custom webhook.",+ "ja": "カスタム Webhook を登録する前にイベントソースを入力してください。",+ "zh-CN": "Enter an event source before registering a custom webhook.",+ "zh-TW": "Enter an event source before registering a custom webhook.",+ "ko-KR": "Enter an event source before registering a custom webhook.",+ "no": "Enter an event source before registering a custom webhook.",+ "ar": "Enter an event source before registering a custom webhook.",+ "de": "Enter an event source before registering a custom webhook.",+ "fr": "Enter an event source before registering a custom webhook.",+ "it": "Enter an event source before registering a custom webhook.",+ "pt": "Enter an event source before registering a custom webhook.",+ "es": "Enter an event source before registering a custom webhook.",+ "ca": "Enter an event source before registering a custom webhook.",+ "tr": "Enter an event source before registering a custom webhook.",+ "uk": "Enter an event source before registering a custom webhook."+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_DEFAULT_NAME": {+ "en": "{{source}} webhook",+ "ja": "{{source}} Webhook",+ "zh-CN": "{{source}} webhook",+ "zh-TW": "{{source}} webhook",+ "ko-KR": "{{source}} webhook",+ "no": "{{source}} webhook",+ "ar": "{{source}} webhook",+ "de": "{{source}} webhook",+ "fr": "{{source}} webhook",+ "it": "{{source}} webhook",+ "pt": "{{source}} webhook",+ "es": "{{source}} webhook",+ "ca": "{{source}} webhook",+ "tr": "{{source}} webhook",+ "uk": "{{source}} webhook"+ },+ "AUTOMATION_SETUP$CUSTOM_WEBHOOK_ALREADY_EXISTS": {+ "en": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "ja": "Webhook ソース {{source}} はすでに存在するため、この自動化は既存のソースを使用します。",+ "zh-CN": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "zh-TW": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "ko-KR": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "no": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "ar": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "de": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "fr": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "it": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "pt": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "es": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "ca": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "tr": "Webhook source {{source}} already exists, so this automation will use the existing source.",+ "uk": "Webhook source {{source}} already exists, so this automation will use the existing source."}}diff --git a/src/manifests/types.ts b/src/manifests/types.tsindex 60ff403e11..f18fc8aa2d 100644--- a/src/manifests/types.ts+++ b/src/manifests/types.ts@@ -267,6 +267,62 @@ export interface ValidateDraftResponse {sampleEventMatched?: boolean | null;}+/**+ * The creation endpoint a server-backed draft is validated and materialized+ * against. Mirrors the service's `DraftEndpoint` literal. `"/v1"` is the raw+ * path an entry shipping its own tarball uses; the other two are presets.+ */+export type AutomationDraftEndpoint =+ | "/v1"+ | "/v1/preset/prompt"+ | "/v1/preset/plugin";++/** `POST /v1/drafts` — create a server-backed automation setup draft. */+export interface CreateAutomationDraftApiRequest {+ endpoint: AutomationDraftEndpoint;+ /** The request body that would be sent to that endpoint. */+ draft: SetupRequestBody;+ name?: string;+ /** Catalog entry or automation the draft was derived from (logged only). */+ sourceAutomationId?: string;+}++/** `PATCH /v1/drafts/{id}` — partially update a server-backed draft. */+export interface UpdateAutomationDraftApiRequest {+ endpoint?: AutomationDraftEndpoint;+ draft?: SetupRequestBody;+ name?: string;+}++/**+ * `GET/PATCH/POST /v1/drafts[/{id}]` — a persisted draft record.+ *+ * The draft row is the source of truth while editing. `dispatchable` and+ * `validationErrors` are refreshed by the service on every create/update, so+ * the form can show live validity without a separate validate call.+ */+export interface AutomationDraftApiResponse {+ id: string;+ endpoint: AutomationDraftEndpoint;+ name: string | null;+ /** The request body that would be sent to the draft's endpoint. */+ draft: SetupRequestBody;+ validationErrors: DraftValidationError[] | null;+ dispatchable: boolean;+ sourceAutomationId: string | null;+ /** Materialized automation row used for test dispatch, if any. */+ materializedAutomationId: string | null;+ lastTestRunId: string | null;+ createdAt: string;+ updatedAt: string;+}++/** `GET /v1/drafts` — paginated list of persisted drafts. */+export interface AutomationDraftListResponse {+ drafts: AutomationDraftApiResponse[];+ total: number;+}+/*** Host-owned shape of the production Automation interface manifest, published* by `@openhands/extensions/automations` as `AUTOMATION_INTERFACE`.diff --git a/src/mocks/automation-handlers.ts b/src/mocks/automation-handlers.tsindex abb588f996..03577ffacc 100644--- a/src/mocks/automation-handlers.ts+++ b/src/mocks/automation-handlers.ts@@ -1,8 +1,11 @@import { http, HttpResponse, delay } from "msw";import capabilitiesFixture from "@openhands/extensions/testing/automations/capabilities.json";import type {+ AutomationDraftApiResponse,+ AutomationDraftListResponse,DeploymentCapabilities,DraftValidationError,+ SetupRequestBody,ValidateDraftResponse,} from "#/manifests/types";import type {@@ -18,8 +21,16 @@ import { MOCK_AUTOMATION_RUNS } from "./automation-runs.mock";// The "supported" deployment from the published contract fixtures. Discovery// and preflight answer with it, so the setup flow runs against the same// reference data the extensions contract is verified against.-const CAPABILITIES: DeploymentCapabilities =- capabilitiesFixture.responses.supported.body;+const CAPABILITIES: DeploymentCapabilities = {+ ...capabilitiesFixture.responses.supported.body,+ // The drafts feature (OpenHands/automation PR #417) ships after the pinned+ // extensions package, so the fixture does not advertise it yet. Augment it+ // here so the persisted-draft form flow is exercised in mock mode.+ features: [+ ...(capabilitiesFixture.responses.supported.body.features ?? []),+ "automationDrafts",+ ],+};interface DraftTrigger {type?: string;@@ -96,11 +107,76 @@ const automations = new Map<string, Automation>(MOCK_AUTOMATIONS_RESPONSE.automations.map((a) => [a.id, { ...a }]),);+// Server-backed automation drafts (OpenHands/automation PR #417). Held in+// memory for the mock session; the service treats the draft row as the source+// of truth while editing and materializes it on dispatch.+interface MockDraft {+ id: string;+ endpoint: string;+ name: string | null;+ draft_body: Record<string, unknown>;+ validation_errors: DraftValidationError[] | null;+ dispatchable: boolean;+ source_automation_id: string | null;+ materialized_automation_id: string | null;+ last_test_run_id: string | null;+ created_at: string;+ updated_at: string;+}++const drafts = new Map<string, MockDraft>();++function toDraftResponse(draft: MockDraft): AutomationDraftApiResponse {+ return {+ id: draft.id,+ endpoint: draft.endpoint as AutomationDraftApiResponse["endpoint"],+ name: draft.name,+ draft: draft.draft_body as SetupRequestBody,+ validationErrors: draft.validation_errors,+ dispatchable: draft.dispatchable,+ sourceAutomationId: draft.source_automation_id,+ materializedAutomationId: draft.materialized_automation_id,+ lastTestRunId: draft.last_test_run_id,+ createdAt: draft.created_at,+ updatedAt: draft.updated_at,+ };+}++function validateMockDraft(+ endpoint: string,+ body: Record<string, unknown>,+): DraftValidationError[] {+ const errors: DraftValidationError[] = [];+ const name = body.name;+ if (typeof name !== "string" || !name.trim()) {+ errors.push({+ field: "name",+ code: "value_error",+ message: "A name is required.",+ });+ }+ // Preset drafts need a prompt; the raw endpoint needs a tarball_path instead.+ if (endpoint !== "/v1") {+ const prompt = body.prompt;+ if (typeof prompt !== "string" || !prompt.trim()) {+ errors.push({+ field: "prompt",+ code: "value_error",+ message: "A prompt is required.",+ });+ }+ }+ const trigger = body.trigger as DraftTrigger | undefined;+ errors.push(...validateDraftTrigger(trigger));+ return errors;+}+export const resetAutomationMockData = () => {automations.clear();MOCK_AUTOMATIONS_RESPONSE.automations.forEach((a) => {automations.set(a.id, { ...a });});+ drafts.clear();};export const AUTOMATION_HANDLERS = [@@ -198,6 +274,141 @@ export const AUTOMATION_HANDLERS = [return HttpResponse.json(automation, { status: 201 });}),+ // --- Server-backed automation drafts (OpenHands/automation PR #417) ---++ // POST /api/automation/v1/drafts — Create a persisted draft+ http.post("*/api/automation/v1/drafts", async ({ request }) => {+ await delay(200);+ const body = (await request.clone().json()) as {+ endpoint?: string;+ draft?: Record<string, unknown>;+ name?: string;+ source_automation_id?: string;+ };+ const endpoint = body.endpoint ?? "/v1/preset/prompt";+ const draftBody = body.draft ?? {};+ const now = new Date().toISOString();+ const errors = validateMockDraft(endpoint, draftBody);+ const draft: MockDraft = {+ id: crypto.randomUUID(),+ endpoint,+ name: typeof body.name === "string" && body.name ? body.name : null,+ draft_body: draftBody,+ validation_errors: errors.length > 0 ? errors : null,+ dispatchable: errors.length === 0,+ source_automation_id: body.source_automation_id ?? null,+ materialized_automation_id: null,+ last_test_run_id: null,+ created_at: now,+ updated_at: now,+ };+ drafts.set(draft.id, draft);+ return HttpResponse.json(draft, { status: 201 });+ }),++ // GET /api/automation/v1/drafts — List persisted drafts+ http.get("*/api/automation/v1/drafts", async ({ request }) => {+ await delay(200);+ const url = new URL(request.url);+ const limit = Number(url.searchParams.get("limit") ?? "50");+ const offset = Number(url.searchParams.get("offset") ?? "0");+ const all = Array.from(drafts.values()).sort((a, b) =>+ b.updated_at.localeCompare(a.updated_at),+ );+ const page = all.slice(offset, offset + limit);+ const response: AutomationDraftListResponse = {+ drafts: page.map(toDraftResponse),+ total: all.length,+ };+ return HttpResponse.json(response);+ }),++ // GET /api/automation/v1/drafts/{id} — Get a draft+ http.get("*/api/automation/v1/drafts/:id", async ({ params }) => {+ await delay(200);+ const draft = drafts.get(params.id as string);+ if (!draft) {+ return HttpResponse.json(+ { detail: "Automation draft not found" },+ { status: 404 },+ );+ }+ return HttpResponse.json(draft);+ }),++ // PATCH /api/automation/v1/drafts/{id} — Update a draft+ http.patch("*/api/automation/v1/drafts/:id", async ({ params, request }) => {+ await delay(200);+ const draft = drafts.get(params.id as string);+ if (!draft) {+ return HttpResponse.json(+ { detail: "Automation draft not found" },+ { status: 404 },+ );+ }+ const body = (await request.clone().json()) as {+ endpoint?: string;+ draft?: Record<string, unknown>;+ name?: string;+ };+ if (body.endpoint !== undefined) draft.endpoint = body.endpoint;+ if (body.draft !== undefined) draft.draft_body = body.draft;+ if (body.name !== undefined) draft.name = body.name ? body.name : null;+ const errors = validateMockDraft(draft.endpoint, draft.draft_body);+ draft.validation_errors = errors.length > 0 ? errors : null;+ draft.dispatchable = errors.length === 0;+ draft.updated_at = new Date().toISOString();+ return HttpResponse.json(draft);+ }),++ // DELETE /api/automation/v1/drafts/{id} — Delete a draft+ http.delete("*/api/automation/v1/drafts/:id", async ({ params }) => {+ await delay(200);+ const existed = drafts.delete(params.id as string);+ if (!existed) {+ return HttpResponse.json(+ { detail: "Automation draft not found" },+ { status: 404 },+ );+ }+ return new HttpResponse(null, { status: 204 });+ }),++ // POST /api/automation/v1/drafts/{id}/dispatch — Test-dispatch a draft+ http.post("*/api/automation/v1/drafts/:id/dispatch", async ({ params }) => {+ await delay(200);+ const draft = drafts.get(params.id as string);+ if (!draft) {+ return HttpResponse.json(+ { detail: "Automation draft not found" },+ { status: 404 },+ );+ }+ const errors = validateMockDraft(draft.endpoint, draft.draft_body);+ if (errors.length > 0) {+ draft.validation_errors = errors;+ draft.dispatchable = false;+ return HttpResponse.json(+ { detail: { message: "Draft is not dispatchable", errors } },+ { status: 422 },+ );+ }+ draft.validation_errors = null;+ draft.dispatchable = true;+ draft.updated_at = new Date().toISOString();+ const run: AutomationRun = {+ id: crypto.randomUUID(),+ status: AutomationRunStatus.PENDING,+ conversation_id: crypto.randomUUID(),+ bash_command_id: null,+ error_detail: null,+ started_at: new Date().toISOString(),+ completed_at: null,+ };+ draft.last_test_run_id = run.id;+ return HttpResponse.json(run, { status: 201 });+ }),+// POST /api/automation/v1/preset/:kind — Create a prompt/plugin automationhttp.post("*/api/automation/v1/preset/:kind", async ({ params, request }) => {await delay(200);diff --git a/src/routes/automation-detail.tsx b/src/routes/automation-detail.tsxindex f61bfa97cb..0b3550b201 100644--- a/src/routes/automation-detail.tsx+++ b/src/routes/automation-detail.tsx@@ -44,6 +44,7 @@ import {} from "#/hooks/use-automation-permissions";import AutomationService from "#/api/automation-service/automation-service.api";import type { Automation } from "#/types/automation";+import { isDraftAutomation } from "#/utils/automation-state";import {getAutomationExportFilename,serializeAutomation,@@ -235,8 +236,10 @@ export default function AutomationDetail() {creatorQuery.data?.email ??(creatorQuery.isError ? automation.user_id : null);}- // Non-creators may turn an automation off but not back on.- const canToggle = automation.enabled ? canManage : isOwner;+ const isDraft = isDraftAutomation(automation);+ // Non-creators may turn an automation off but not back on. Draft test+ // artifacts are finalized through the draft setup flow, not this toggle.+ const canToggle = isDraft ? false : automation.enabled ? canManage : isOwner;return (<div className="min-h-full">diff --git a/src/routes/automations-list.tsx b/src/routes/automations-list.tsxindex 1cf31db74f..80e4b2a964 100644--- a/src/routes/automations-list.tsx+++ b/src/routes/automations-list.tsx@@ -1,6 +1,7 @@import { useState, useMemo, useCallback, type ReactNode } from "react";-import { RefreshCw } from "lucide-react";+import { RefreshCw, Trash2 } from "lucide-react";import { useTranslation } from "react-i18next";+import type { TFunction } from "i18next";import { I18nKey } from "#/i18n/declaration";import {displaySuccessToast,@@ -9,19 +10,25 @@ import {} from "#/utils/custom-toast-handlers";import { getApiErrorMessage } from "#/utils/api-error-message";import {+ useAutomationDrafts,useAutomations,useToggleAutomation,useDeleteAutomation,+ useDeleteAutomationDraft,useDispatchAutomation,+ useDispatchAutomationDraft,useImportAutomation,} from "#/hooks/query/use-automations";import { useAutomationHealth } from "#/hooks/query/use-automation-health";+import type { AutomationSetupKind } from "#/api/automation-setup-types";import { useActiveBackend } from "#/contexts/active-backend-context";import { useNavigation } from "#/context/navigation-context";import { SearchInput } from "#/components/features/automations/search-input";import { AutomationGroup } from "#/components/features/automations/automation-group";import { AutomationViewToggle } from "#/components/features/automations/automation-view-toggle";import {+ automationActivityListClassName,+ automationActivityRowClassName,readStoredAutomationViewMode,writeStoredAutomationViewMode,type AutomationViewMode,@@ -37,6 +44,7 @@ import { AddAutomationModal } from "#/components/features/automations/add-automaimport { 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";+import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";import { useTracking } from "#/hooks/use-tracking";import {useAutomationCreatorFilterUserId,@@ -61,6 +69,7 @@ import {} from "#/manifests/automation-insights";import { interpolateValues } from "#/manifests/manifest-template";import type {+ AutomationDraftApiResponse,DashboardCreatedByValue,DashboardSortValue,DashboardStatusValue,@@ -75,6 +84,12 @@ import { ManifestOverviewTiles } from "#/components/features/manifest/manifest-oimport { ManifestSubpageLayout } from "#/components/features/manifest/manifest-subpage-layout";import { cn, downloadBlob } from "#/utils/utils";import { uniqueById } from "#/utils/unique-by-id";+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";++const PAGE_SIZE = 50;/*** The page renders the interface manifest's copy, so without an admitted@@ -88,6 +103,176 @@ export const clientLoader = () => {return null;};+function getDraftKind(draft: AutomationDraftApiResponse): AutomationSetupKind {+ if (draft.endpoint === "/v1") return "custom";+ if (draft.endpoint === "/v1/preset/plugin") return "plugin";+ return "prompt";+}++function getDraftTriggerSummary(+ draft: AutomationDraftApiResponse,+ t: TFunction,+) {+ const trigger = draft.draft.trigger as Record<string, unknown> | undefined;+ if (!trigger || typeof trigger !== "object") return null;+ if (trigger.type === "event") {+ const source = typeof trigger.source === "string" ? trigger.source : null;+ const event = Array.isArray(trigger.on)+ ? trigger.on+ .filter((item): item is string => typeof item === "string")+ .join(", ")+ : typeof trigger.on === "string"+ ? trigger.on+ : null;+ return (+ [source, event].filter(Boolean).join(" · ") ||+ t(I18nKey.AUTOMATIONS$DETAIL$TRIGGER_EVENT)+ );+ }+ const schedule =+ typeof trigger.schedule === "string" ? trigger.schedule : null;+ return schedule ?? t(I18nKey.AUTOMATIONS$DETAIL$TRIGGER_SCHEDULE);+}++function isEventTriggeredDraft(draft: AutomationDraftApiResponse): boolean {+ const trigger = draft.draft.trigger as Record<string, unknown> | undefined;+ return Boolean(+ trigger && typeof trigger === "object" && trigger.type === "event",+ );+}++function matchesSavedDraftSearch(+ draft: AutomationDraftApiResponse,+ searchQuery: string,+): boolean {+ const normalized = searchQuery.trim().toLowerCase();+ if (!normalized) return true;+ return [+ draft.name ?? draft.id,+ String(draft.draft.prompt ?? ""),+ getDraftKind(draft),+ getDraftTriggerSummary(draft, ((key: string) => key) as TFunction) ?? "",+ ]+ .join("\n")+ .toLowerCase()+ .includes(normalized);+}++interface SavedDraftsGroupProps {+ drafts: AutomationDraftApiResponse[];+ onResume: (draft: AutomationDraftApiResponse) => void;+ onDelete: (draft: AutomationDraftApiResponse) => void;+ onTest: (draft: AutomationDraftApiResponse) => void;+ resumingDraftId: string | null;+ deletingDraftId: string | null;+ testingDraftId: string | null;+}++function SavedDraftsGroup({+ drafts,+ onResume,+ onDelete,+ onTest,+ resumingDraftId,+ deletingDraftId,+ testingDraftId,+}: SavedDraftsGroupProps) {+ const { t } = useTranslation("openhands");+ if (drafts.length === 0) return null;++ return (+ <section>+ <div className="flex items-center">+ <h2 className="text-base font-semibold text-foreground">+ {t(I18nKey.AUTOMATIONS$SAVED_DRAFTS)}+ </h2>+ <StatusBadge count={drafts.length} />+ </div>+ <ul className={cn(automationActivityListClassName, "mt-3")}>+ {drafts.map((draft) => {+ const title = draft.name ?? t(I18nKey.AUTOMATIONS$UNTITLED_DRAFT);+ const isResuming = resumingDraftId === draft.id;+ const isDeleting = deletingDraftId === draft.id;+ const isTesting = testingDraftId === draft.id;+ const canTestDirectly =+ draft.dispatchable && !isEventTriggeredDraft(draft);+ const isBusy = isResuming || isDeleting || isTesting;+ return (+ <li+ key={draft.id}+ data-testid={`automation-setup-draft-${draft.id}`}+ className={automationActivityRowClassName}+ >+ <button+ type="button"+ data-testid={`automation-setup-draft-resume-${draft.id}`}+ className="flex min-w-0 flex-1 items-center px-3 py-2.5 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus"+ disabled={isBusy}+ aria-label={+ isResuming+ ? t(I18nKey.AUTOMATION_SETUP$RESUMING_DRAFT)+ : title+ }+ onClick={() => onResume(draft)}+ >+ <span+ data-testid={`automation-setup-draft-open-${draft.id}`}+ className="block min-w-0 truncate text-sm font-medium leading-5 text-foreground"+ >+ {title}+ </span>+ </button>+ <div className="flex shrink-0 items-center gap-1.5 pr-1.5">+ {canTestDirectly && !isBusy ? (+ <StyledTooltip+ content={t(I18nKey.AUTOMATION_SETUP$TEST_RUN)}+ placement="top"+ >+ <button+ type="button"+ data-testid={`automation-setup-draft-test-${draft.id}`}+ aria-label={t(I18nKey.AUTOMATION_SETUP$TEST_DRAFT)}+ onClick={() => onTest(draft)}+ className={automationIconActionButtonClassName}+ >+ <PlayIcon className="size-4 shrink-0" aria-hidden />+ </button>+ </StyledTooltip>+ ) : (+ <button+ type="button"+ data-testid={`automation-setup-draft-test-${draft.id}`}+ aria-label={+ isTesting+ ? t(I18nKey.AUTOMATION_SETUP$STARTING_TEST)+ : t(I18nKey.AUTOMATION_SETUP$TEST_DRAFT)+ }+ disabled+ onClick={() => onTest(draft)}+ className={automationIconActionButtonClassName}+ >+ <PlayIcon className="size-4 shrink-0" aria-hidden />+ </button>+ )}+ <button+ type="button"+ data-testid={`automation-setup-draft-delete-${draft.id}`}+ aria-label={t(I18nKey.AUTOMATION_SETUP$DELETE_DRAFT)}+ disabled={isDeleting || isResuming || isTesting}+ onClick={() => onDelete(draft)}+ className={automationIconActionButtonClassName}+ >+ <Trash2 className="size-4" aria-hidden />+ </button>+ </div>+ </li>+ );+ })}+ </ul>+ </section>+ );+}+export default function AutomationsList() {const { t } = useTranslation("openhands");const interfaceCopy = getInterfaceCopy();@@ -112,10 +297,13 @@ export default function AutomationsList() {const [viewMode, setViewMode] = useState<AutomationViewMode>(() =>readStoredAutomationViewMode(),);+ const [draftLimit, setDraftLimit] = useState(PAGE_SIZE);const [deleteTarget, setDeleteTarget] = useState<{id: string;name: string;} | null>(null);+ const [deleteDraftTarget, setDeleteDraftTarget] =+ useState<AutomationDraftApiResponse | null>(null);const [editTarget, setEditTarget] = useState<Automation | null>(null);const [isAddAutomationOpen, setIsAddAutomationOpen] = useState(false);const [importSpec, setImportSpec] = useState<AutomationSpec | null>(null);@@ -162,6 +350,16 @@ export default function AutomationsList() {// The overview tiles summarize the org list above the filters, so they read// it unfiltered; with no creator selected this is the same query as above.const { data: orgData } = useAutomations({ enabled: isBackendHealthy });+ const {+ data: draftsData,+ isLoading: isDraftsLoading,+ isError: isDraftsError,+ refetch: refetchDrafts,+ } = useAutomationDrafts({+ limit: draftLimit,+ offset: 0,+ enabled: isBackendHealthy,+ });const runSummaryAutomations = useMemo(() =>uniqueById([@@ -178,7 +376,9 @@ export default function AutomationsList() {useTracking();const toggleMutation = useToggleAutomation();const deleteMutation = useDeleteAutomation();+ const deleteDraftMutation = useDeleteAutomationDraft();const dispatchMutation = useDispatchAutomation();+ const dispatchDraftMutation = useDispatchAutomationDraft();const importMutation = useImportAutomation();const visible = useMemo(() => {@@ -215,11 +415,21 @@ export default function AutomationsList() {runSummaries,]);+ const visibleSavedDrafts = useMemo(+ () =>+ (draftsData?.drafts ?? []).filter((draft) =>+ matchesSavedDraftSearch(draft, searchQuery),+ ),+ [draftsData?.drafts, searchQuery],+ );const activeAutomations = useMemo(- () => visible.filter((a) => a.enabled),+ () => visible.filter((a) => a.enabled && !isDraftAutomation(a)),+ [visible],+ );+ const inactive = useMemo(+ () => visible.filter((a) => !a.enabled && !isDraftAutomation(a)),[visible],);- const inactive = useMemo(() => visible.filter((a) => !a.enabled), [visible]);const handleToggle = (id: string, currentEnabled: boolean) => {const willEnable = !currentEnabled;@@ -246,6 +456,28 @@ 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 handleTestDraft = (draft: AutomationDraftApiResponse) => {+ dispatchDraftMutation.mutate(draft.id, {+ onSuccess: () => {+ displaySuccessToast(t(I18nKey.AUTOMATION_SETUP$TEST_DISPATCHED));+ },+ onError: (error) => {+ displayErrorToast(+ getApiErrorMessage(error, t(I18nKey.AUTOMATIONS$RUN_NOW_ERROR)),+ );+ },+ });+ };++ const handleDeleteDraftRequest = (draft: AutomationDraftApiResponse) => {+ setDeleteDraftTarget(draft);+ };+const handleDeleteRequest = (id: string) => {const automation = data?.automations.find((a) => a.id === id);if (automation) {@@ -317,6 +549,19 @@ export default function AutomationsList() {}};+ const handleDeleteDraftConfirm = () => {+ if (!deleteDraftTarget) return;+ deleteDraftMutation.mutate(deleteDraftTarget.id, {+ onSuccess: () => {+ displaySuccessToast(t(I18nKey.AUTOMATION_SETUP$DRAFT_DELETED));+ },+ onError: (error) => {+ displayErrorToast(getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)));+ },+ onSettled: () => setDeleteDraftTarget(null),+ });+ };+const handleViewModeChange = useCallback((view: AutomationViewMode) => {setViewMode(view);writeStoredAutomationViewMode(view);@@ -368,17 +613,26 @@ export default function AutomationsList() {</div>);+ const hasMoreDrafts = draftsData+ ? draftsData.total > draftsData.drafts.length+ : false;+ const hasMore = Boolean(hasNextPage || hasMoreDrafts);// A failed refetch or Load more keeps the loaded rows; Load more retries.- const isListError = isError && !data;+ const isListError = (isError && !data) || (isDraftsError && !draftsData);// Whether the org has any automations comes from the unfiltered list, so an// empty filtered response shows the filtered empty state with Clear filters.- const hasNoAutomations = !isListError && orgData?.total === 0;+ const hasNoAutomations =+ !isListError && orgData?.total === 0 && (draftsData?.total ?? 0) === 0;// The previous filter's rows stand in while the next page loads; when none// of them match, show loading rather than a no-match that is not final. An// empty org keeps its empty state instead.const isListLoading =!hasNoAutomations &&- (isLoading || (isPlaceholderData && visible.length === 0));+ (isLoading ||+ isDraftsLoading ||+ (isPlaceholderData &&+ visible.length === 0 &&+ visibleSavedDrafts.length === 0));// Show loading state while checking healthif (isHealthLoading) {@@ -492,66 +746,102 @@ export default function AutomationsList() {</div>)}- {isListError && !isLoading && <ErrorState onRetry={refetch} />}+ {isListError && !(isLoading || isDraftsLoading) && (+ <ErrorState+ onRetry={() => {+ void refetch();+ void refetchDrafts();+ }}+ />+ )}{hasNoAutomations && <EmptyState />}- {!isListLoading && !isListError && data && !hasNoAutomations && (- <>- {dashboard && visible.length === 0 ? (- <AutomationsFilteredEmptyState onClear={handleClearFilters} />- ) : (- <>- <AutomationGroup- title={t(I18nKey.AUTOMATIONS$ACTIVE)}- count={activeAutomations.length}- automations={activeAutomations}- view={viewMode}- onToggle={handleToggle}- onRunNow={handleRunNow}- runPendingId={- dispatchMutation.isPending- ? (dispatchMutation.variables ?? null)- : null- }- onDelete={handleDeleteRequest}- onExport={handleExport}- onEdit={handleEditRequest}- insights={groupInsights}- />- <AutomationGroup- title={t(I18nKey.AUTOMATIONS$INACTIVE)}- count={inactive.length}- automations={inactive}- view={viewMode}- onToggle={handleToggle}- onRunNow={handleRunNow}- runPendingId={- dispatchMutation.isPending- ? (dispatchMutation.variables ?? null)- : null- }- onDelete={handleDeleteRequest}- onExport={handleExport}- onEdit={handleEditRequest}- insights={groupInsights}- />- </>- )}- {/* Also under the filtered empty state: the matches may be on a- page that is not loaded yet. */}- {hasNextPage && (- <button- type="button"- onClick={() => fetchNextPage()}- disabled={isFetching}- className="self-center rounded-lg border border-border px-6 py-2 text-sm text-contrast hover:bg-surface-raised disabled:cursor-not-allowed disabled:opacity-50"- >- {t(I18nKey.AUTOMATIONS$LOAD_MORE)}- </button>- )}- </>- )}+ {!isListLoading &&+ !isListError &&+ data &&+ draftsData &&+ !hasNoAutomations &&+ (dashboard &&+ visible.length === 0 &&+ visibleSavedDrafts.length === 0 ? (+ <AutomationsFilteredEmptyState onClear={handleClearFilters} />+ ) : (+ <>+ <SavedDraftsGroup+ drafts={visibleSavedDrafts}+ onResume={handleResumeDraft}+ onDelete={handleDeleteDraftRequest}+ onTest={handleTestDraft}+ resumingDraftId={null}+ deletingDraftId={+ deleteDraftMutation.isPending+ ? (deleteDraftMutation.variables ?? null)+ : null+ }+ testingDraftId={+ dispatchDraftMutation.isPending+ ? (dispatchDraftMutation.variables ?? null)+ : null+ }+ />+ <AutomationGroup+ title={t(I18nKey.AUTOMATIONS$ACTIVE)}+ count={activeAutomations.length}+ automations={activeAutomations}+ view={viewMode}+ onToggle={handleToggle}+ onRunNow={handleRunNow}+ runPendingId={+ dispatchMutation.isPending+ ? (dispatchMutation.variables ?? null)+ : null+ }+ onDelete={handleDeleteRequest}+ onExport={handleExport}+ onEdit={handleEditRequest}+ insights={groupInsights}+ />+ <AutomationGroup+ title={t(I18nKey.AUTOMATIONS$INACTIVE)}+ count={inactive.length}+ automations={inactive}+ view={viewMode}+ onToggle={handleToggle}+ onRunNow={handleRunNow}+ runPendingId={+ dispatchMutation.isPending+ ? (dispatchMutation.variables ?? null)+ : null+ }+ onDelete={handleDeleteRequest}+ onExport={handleExport}+ onEdit={handleEditRequest}+ insights={groupInsights}+ />+ </>+ ))}++ {!isListLoading &&+ !isListError &&+ data &&+ draftsData &&+ !hasNoAutomations &&+ hasMore && (+ <button+ type="button"+ onClick={() => {+ if (hasNextPage) void fetchNextPage();+ if (hasMoreDrafts) {+ setDraftLimit((prev) => prev + PAGE_SIZE);+ }+ }}+ disabled={isFetching || isDraftsLoading}+ className="self-center rounded-lg border border-border px-6 py-2 text-sm text-contrast hover:bg-surface-raised disabled:cursor-not-allowed disabled:opacity-50"+ >+ {t(I18nKey.AUTOMATIONS$LOAD_MORE)}+ </button>+ )}</div>{/* The launcher lives on the templates sub-page in dashboard mode */}@@ -569,6 +859,47 @@ export default function AutomationsList() {onCancel={() => setDeleteTarget(null)}/>+ {deleteDraftTarget ? (+ <div className="fixed inset-0 z-50 flex items-center justify-center">+ <button+ type="button"+ className="absolute inset-0 bg-black/60"+ aria-label={t(I18nKey.BUTTON$CLOSE)}+ onClick={() => setDeleteDraftTarget(null)}+ />+ <div className="relative w-full max-w-sm rounded-xl border border-border bg-surface p-6">+ <h2 className="text-lg font-semibold text-content">+ {t(I18nKey.AUTOMATION_SETUP$DELETE_DRAFT_TITLE)}+ </h2>+ <p className="mt-2 text-sm text-muted">+ {t(I18nKey.AUTOMATION_SETUP$DELETE_DRAFT_MESSAGE, {+ name:+ deleteDraftTarget.name ??+ t(I18nKey.AUTOMATIONS$UNTITLED_DRAFT),+ })}+ </p>+ <div className="mt-6 flex justify-end gap-3">+ <button+ type="button"+ onClick={() => setDeleteDraftTarget(null)}+ className="rounded-lg border border-border px-4 py-2 text-sm text-contrast hover:bg-surface-raised"+ >+ {t(I18nKey.AUTOMATIONS$CANCEL)}+ </button>+ <button+ type="button"+ data-testid="automation-setup-draft-delete-confirm"+ onClick={handleDeleteDraftConfirm}+ disabled={deleteDraftMutation.isPending}+ className="rounded-lg bg-danger px-4 py-2 text-sm text-white hover:bg-danger/80 disabled:cursor-not-allowed disabled:opacity-60"+ >+ {t(I18nKey.AUTOMATION_SETUP$DELETE_DRAFT)}+ </button>+ </div>+ </div>+ </div>+ ) : null}+{/* Edit modal */}{editTarget && (<EditAutomationModaldiff --git a/src/types/automation.ts b/src/types/automation.tsindex 2f1377ff69..27678407ef 100644--- a/src/types/automation.ts+++ b/src/types/automation.ts@@ -32,11 +32,15 @@ export interface AutomationRepository {ref?: string;}+export type AutomationState = "ACTIVE" | "INACTIVE" | "DRAFT";+export interface Automation {id: string;name: string;trigger: AutomationTrigger;enabled: boolean;+ /** Backend automation lifecycle state. Prefer this over deprecated `enabled` when present. */+ state?: AutomationState | string | null;/*** Human-readable reason the automation was last disabled (the latest* disablement event overwrites this). Mirrors the automation service'sdiff --git a/src/utils/automation-draft-tags.ts b/src/utils/automation-draft-tags.tsindex 43374db127..d17e766de3 100644--- a/src/utils/automation-draft-tags.ts+++ b/src/utils/automation-draft-tags.ts@@ -1,6 +1,38 @@export const AUTOMATION_SETUP_TAG_KEY = "automationsetup";+export const AUTOMATION_DRAFT_ID_TAG_KEY = "automationdraftid";+export const AUTOMATION_MATERIALIZED_DRAFT_ID_TAG_KEY =+ "automationmaterializeddraftid";+/** Existing automation opened in the setup page, rather than a new draft. */+export const AUTOMATION_EDIT_ID_TAG_KEY = "automationeditid";export const AUTOMATION_SETUP_TAG_VALUE = "draft";+export function getAutomationDraftIdFromTags(+ tags: Record<string, string> | null | undefined,+): string | null {+ const draftId = tags?.[AUTOMATION_DRAFT_ID_TAG_KEY]?.trim();+ return draftId || null;+}++export function getAutomationMaterializedDraftIdFromTags(+ tags: Record<string, string> | null | undefined,+): string | null {+ const draftId = tags?.[AUTOMATION_MATERIALIZED_DRAFT_ID_TAG_KEY]?.trim();+ return draftId || null;+}++export function getAutomationEditIdFromTags(+ tags: Record<string, string> | null | undefined,+): string | null {+ const automationId = tags?.[AUTOMATION_EDIT_ID_TAG_KEY]?.trim();+ return automationId || null;+}++export function hasAutomationSetupModeTag(+ tags: Record<string, string> | null | undefined,+): boolean {+ return tags?.[AUTOMATION_SETUP_TAG_KEY] === AUTOMATION_SETUP_TAG_VALUE;+}+export function buildAutomationSetupModeTags(tags: Record<string, string> | null | undefined,): Record<string, string> {@@ -9,3 +41,46 @@ export function buildAutomationSetupModeTags([AUTOMATION_SETUP_TAG_KEY]: AUTOMATION_SETUP_TAG_VALUE,};}++/**+ * Mark a conversation as the editor for one saved automation.+ *+ * The setup-mode tag opens the form. The edit id tells Save and Test+ * which automation to update, and is kept separate from draft ids so+ * editing does not resume an unrelated server draft.+ */+export function buildAutomationEditTags(+ tags: Record<string, string> | null | undefined,+ automationId: string,+): Record<string, string> {+ return {+ ...buildAutomationSetupModeTags(tags),+ [AUTOMATION_EDIT_ID_TAG_KEY]: automationId,+ };+}++export function buildAutomationDraftTags(+ tags: Record<string, string> | null | undefined,+ draftId: string,+ materializedDraftId?: string | null,+): Record<string, string> {+ const next: Record<string, string> = {+ ...buildAutomationSetupModeTags(tags),+ [AUTOMATION_DRAFT_ID_TAG_KEY]: draftId,+ };+ if (materializedDraftId) {+ next[AUTOMATION_MATERIALIZED_DRAFT_ID_TAG_KEY] = materializedDraftId;+ }+ return next;+}++export function removeAutomationDraftTags(+ tags: Record<string, string> | null | undefined,+): Record<string, string> {+ const next = { ...(tags ?? {}) };+ delete next[AUTOMATION_SETUP_TAG_KEY];+ delete next[AUTOMATION_DRAFT_ID_TAG_KEY];+ delete next[AUTOMATION_MATERIALIZED_DRAFT_ID_TAG_KEY];+ delete next[AUTOMATION_EDIT_ID_TAG_KEY];+ return next;+}diff --git a/src/utils/automation-state.ts b/src/utils/automation-state.tsnew file mode 100644index 0000000000..e7f424199a--- /dev/null+++ b/src/utils/automation-state.ts@@ -0,0 +1,22 @@+import type { Automation } from "#/types/automation";++export const AUTOMATION_STATE_ACTIVE = "ACTIVE";+export const AUTOMATION_STATE_INACTIVE = "INACTIVE";+export const AUTOMATION_STATE_DRAFT = "DRAFT";++export type AutomationLifecycleState = "active" | "inactive" | "draft";++type AutomationStateSource = Pick<Automation, "enabled" | "state">;++export function getAutomationLifecycleState(+ automation: AutomationStateSource,+): AutomationLifecycleState {+ if (automation.state === AUTOMATION_STATE_DRAFT) return "draft";+ if (automation.state === AUTOMATION_STATE_ACTIVE) return "active";+ if (automation.state === AUTOMATION_STATE_INACTIVE) return "inactive";+ return automation.enabled ? "active" : "inactive";+}++export function isDraftAutomation(automation: AutomationStateSource): boolean {+ return getAutomationLifecycleState(automation) === "draft";+}