🙌 OpenHands: AI-Driven Development
feat(automations): export and import automations as portable JSON files (#1660)
Matt Van Hornf3bbc9a1acda
diff --git a/__tests__/components/automations/automation-card.test.tsx b/__tests__/components/automations/automation-card.test.tsxindex b129200ea8..71ae1b1965 100644--- a/__tests__/components/automations/automation-card.test.tsx+++ b/__tests__/components/automations/automation-card.test.tsx@@ -33,6 +33,7 @@ describe("AutomationCard", () => {automation={automation}onToggle={vi.fn()}onRunNow={vi.fn()}+ onExport={vi.fn()}onDelete={vi.fn()}/>,);@@ -52,6 +53,7 @@ describe("AutomationCard", () => {automation={automation}onToggle={vi.fn()}onRunNow={vi.fn()}+ onExport={vi.fn()}onDelete={vi.fn()}/>,);diff --git a/__tests__/components/automations/automation-list-row.test.tsx b/__tests__/components/automations/automation-list-row.test.tsxindex 9eeeace0ce..80a3c7ffec 100644--- a/__tests__/components/automations/automation-list-row.test.tsx+++ b/__tests__/components/automations/automation-list-row.test.tsx@@ -35,6 +35,7 @@ describe("AutomationListRow", () => {automation={automation}onToggle={vi.fn()}onRunNow={vi.fn()}+ onExport={vi.fn()}onDelete={vi.fn()}/>,);@@ -62,6 +63,7 @@ describe("AutomationListRow", () => {automation={automation}onToggle={vi.fn()}onRunNow={vi.fn()}+ onExport={vi.fn()}onDelete={vi.fn()}/>,);diff --git a/src/api/automation-service/automation-service.api.test.ts b/src/api/automation-service/automation-service.api.test.tsnew file mode 100644index 0000000000..21b52e3221--- /dev/null+++ b/src/api/automation-service/automation-service.api.test.ts@@ -0,0 +1,219 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import type { Backend } from "#/api/backend-registry/types";+import type { Automation, AutomationSpec } from "#/types/automation";+import AutomationService from "./automation-service.api";++const { localAxios, axiosRequest } = vi.hoisted(() => ({+ localAxios: {+ interceptors: { request: { use: vi.fn() } },+ get: vi.fn(),+ post: vi.fn(),+ patch: vi.fn(),+ delete: vi.fn(),+ },+ axiosRequest: vi.fn(),+}));++vi.mock("axios", () => ({+ default: {+ create: () => localAxios,+ request: axiosRequest,+ post: vi.fn(),+ },+}));++const localBackend: Backend = {+ id: "local-test",+ name: "Local test backend",+ host: "http://localhost:3000",+ apiKey: "test-session-key",+ kind: "local",+};++const cloudBackend: Backend = {+ id: "cloud-test",+ name: "Cloud test backend",+ host: "https://app.example.test",+ apiKey: "cloud-api-key",+ kind: "cloud",+};++const spec: AutomationSpec = {+ name: "Imported review",+ prompt: "Review open pull requests.",+ trigger: {+ type: "cron",+ schedule: "0 9 * * *",+ schedule_human: "Daily at 09:00",+ },+ enabled: true,+ repository: "openhands/agent-canvas",+ branch: "main",+ plugins: ["github:openhands/extensions"],+ model: "fast",+ timezone: "America/Los_Angeles",+};++const createdAutomation: Automation = {+ id: "created-automation",+ name: spec.name,+ prompt: spec.prompt,+ trigger: { type: "cron", schedule: spec.trigger.schedule },+ enabled: true,+ model: spec.model,+ created_at: "2026-07-10T00:00:00Z",+ updated_at: "2026-07-10T00:00:00Z",+};++describe("AutomationService.createAutomation", () => {+ beforeEach(() => {+ setRegisteredBackends([localBackend]);+ setActiveSelection({ backendId: localBackend.id });+ localAxios.post.mockResolvedValue({ data: createdAutomation });+ localAxios.patch.mockImplementation(+ async (_path: string, body: Partial<Automation>) => ({+ data: { ...createdAutomation, ...body },+ }),+ );+ });++ afterEach(() => {+ setActiveSelection(null);+ setRegisteredBackends([]);+ vi.clearAllMocks();+ });++ it("creates plugin automations through the preset API and disables them", async () => {+ const created = await AutomationService.createAutomation(spec);++ expect(localAxios.post).toHaveBeenCalledWith(+ "/api/automation/v1/preset/plugin",+ {+ name: spec.name,+ prompt: spec.prompt,+ model: spec.model,+ trigger: {+ type: "event",+ source: "agent-canvas-import",+ on: expect.stringMatching(/^pending\./),+ },+ repos: [+ {+ url: spec.repository,+ ref: spec.branch,+ provider: "github",+ },+ ],+ plugins: [{ source: spec.plugins![0] }],+ },+ {+ baseURL: localBackend.host,+ headers: { "X-Session-API-Key": localBackend.apiKey },+ },+ );+ expect(localAxios.patch).toHaveBeenCalledWith(+ "/api/automation/v1/created-automation",+ {+ trigger: {+ type: "cron",+ schedule: spec.trigger.schedule,+ timezone: spec.timezone,+ },+ enabled: false,+ },+ {+ baseURL: localBackend.host,+ headers: { "X-Session-API-Key": localBackend.apiKey },+ },+ );+ expect(created.enabled).toBe(false);+ });++ it("uses the prompt preset path when no plugins are configured", async () => {+ await AutomationService.createAutomation({+ ...spec,+ plugins: undefined,+ });++ expect(localAxios.post).toHaveBeenCalledWith(+ "/api/automation/v1/preset/prompt",+ expect.not.objectContaining({ plugins: expect.anything() }),+ expect.any(Object),+ );+ });++ it("applies the imported event trigger while disabling the automation", async () => {+ const eventTrigger = {+ type: "event",+ source: "github",+ on: ["pull_request.opened", "pull_request.synchronize"],+ filter: "repository.full_name == 'openhands/agent-canvas'",+ };++ await AutomationService.createAutomation({+ ...spec,+ trigger: eventTrigger,+ });++ expect(localAxios.patch).toHaveBeenCalledWith(+ "/api/automation/v1/created-automation",+ { trigger: eventTrigger, enabled: false },+ expect.any(Object),+ );+ });++ it("uses the selected cloud backend and organization for both requests", async () => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });+ axiosRequest+ .mockResolvedValueOnce({ data: createdAutomation })+ .mockResolvedValueOnce({+ data: { ...createdAutomation, enabled: false },+ });++ const created = await AutomationService.createAutomation(spec);++ expect(axiosRequest).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ url: `${cloudBackend.host}/api/automation/v1/preset/plugin`,+ method: "POST",+ headers: expect.objectContaining({+ Authorization: `Bearer ${cloudBackend.apiKey}`,+ "X-Org-Id": "org-1",+ }),+ }),+ );+ expect(axiosRequest).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ url: `${cloudBackend.host}/api/automation/v1/created-automation`,+ method: "PATCH",+ data: expect.objectContaining({ enabled: false }),+ headers: expect.objectContaining({ "X-Org-Id": "org-1" }),+ }),+ );+ expect(created.enabled).toBe(false);+ });++ it("removes the inert automation when disabling it fails", async () => {+ const updateError = new Error("update failed");+ localAxios.patch.mockRejectedValueOnce(updateError);++ await expect(AutomationService.createAutomation(spec)).rejects.toBe(+ updateError,+ );++ expect(localAxios.delete).toHaveBeenCalledWith(+ "/api/automation/v1/created-automation",+ {+ baseURL: localBackend.host,+ headers: { "X-Session-API-Key": localBackend.apiKey },+ },+ );+ });+});diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.tsindex 56eab82f87..8cf7e6d644 100644--- a/src/api/automation-service/automation-service.api.ts+++ b/src/api/automation-service/automation-service.api.ts@@ -2,9 +2,12 @@ import axios from "axios";import type {Automation,AutomationRun,+ AutomationSpec,+ AutomationTrigger,AutomationsResponse,AutomationRunsResponse,} from "#/types/automation";+import type { Backend, ResolvedActiveBackend } from "../backend-registry/types";import {getActiveBackend,getEffectiveLocalBackend,@@ -26,6 +29,10 @@ export interface AutomationHealthResponse {const localAutomationAxios = axios.create();localAutomationAxios.interceptors.request.use((config) => {+ // Import uses an explicit baseURL/header pair so its POST, PATCH, and+ // cleanup stay pinned to the backend selected when the mutation started.+ if (config.baseURL) return config;+// Resolve the local backend on every call so it tracks the// currently-active local backend (and any host/key edits made via the// manage-backends UI), rather than freezing whatever value the@@ -37,7 +44,7 @@ localAutomationAxios.interceptors.request.use((config) => {const backend = getEffectiveLocalBackend();if (!backend) throw new NoBackendAvailableError();// eslint-disable-next-line no-param-reassign- if (!config.baseURL) config.baseURL = backend.host;+ config.baseURL = backend.host;const apiKey = backend.apiKey?.trim();if (apiKey) {@@ -53,6 +60,83 @@ function buildPaginationQuery(limit: number, offset: number): string {return params.toString();}+function buildImportedTrigger(spec: AutomationSpec): AutomationTrigger {+ if (spec.trigger.type === "event") {+ return {+ type: "event",+ source: spec.trigger.source,+ on: spec.trigger.on,+ ...(spec.trigger.filter && { filter: spec.trigger.filter }),+ };+ }++ return {+ type: "cron",+ schedule: spec.trigger.schedule,+ timezone: spec.timezone ?? spec.trigger.timezone ?? "UTC",+ };+}++function generatePendingImportEvent(): string {+ if (+ typeof crypto !== "undefined" &&+ typeof crypto.randomUUID === "function"+ ) {+ return `pending.${crypto.randomUUID()}`;+ }+ return `pending.${Date.now()}.${Math.random().toString(36).slice(2, 10)}`;+}++function buildCreateAutomationRequest(spec: AutomationSpec) {+ if (!spec.prompt) {+ throw new Error("An automation prompt is required for import.");+ }++ const repos = spec.repository+ ? [+ {+ url: spec.repository,+ ...(spec.branch && { ref: spec.branch }),+ ...(!spec.repository.includes("://") &&+ !spec.repository.startsWith("git@") && { provider: "github" }),+ },+ ]+ : undefined;++ return {+ path: `${AUTOMATION_BASE_PATH}/v1/preset/${spec.plugins?.length ? "plugin" : "prompt"}`,+ body: {+ name: spec.name,+ prompt: spec.prompt,+ // Preset creation defaults to enabled. A unique event trigger keeps the+ // new record inert until the real trigger and disabled state are applied+ // together in the follow-up PATCH.+ trigger: {+ type: "event",+ source: "agent-canvas-import",+ on: generatePendingImportEvent(),+ },+ ...(spec.model && { model: spec.model }),+ ...(repos && { repos }),+ ...(spec.plugins?.length && {+ plugins: spec.plugins.map((source) => ({ source })),+ }),+ },+ };+}++function buildPinnedLocalConfig(backend: Backend) {+ const apiKey = backend.apiKey.trim();+ return {+ baseURL: backend.host,+ ...(apiKey && { headers: { "X-Session-API-Key": apiKey } }),+ };+}++function buildPinnedCloudHeaders(active: ResolvedActiveBackend) {+ return active.orgId ? { "X-Org-Id": active.orgId } : undefined;+}+class AutomationService {static async listAutomations(params: { limit?: number; offset?: number } = {},@@ -98,6 +182,76 @@ class AutomationService {return data;}+ static async createAutomation(spec: AutomationSpec): Promise<Automation> {+ const active = getActiveBackend();+ const { path, body } = buildCreateAutomationRequest(spec);++ let created: Automation;+ if (active.backend.kind === "cloud") {+ created = await callCloudProxy<Automation>({+ backend: active.backend,+ method: "POST",+ path,+ body,+ headers: buildPinnedCloudHeaders(active),+ });+ } else {+ const { data } = await localAutomationAxios.post<Automation>(+ path,+ body,+ buildPinnedLocalConfig(active.backend),+ );+ created = data;+ }++ const updatePath = `${AUTOMATION_BASE_PATH}/v1/${encodeURIComponent(created.id)}`;+ const updateBody: Partial<Automation> = {+ trigger: buildImportedTrigger(spec),+ enabled: false,+ };++ try {+ if (active.backend.kind === "cloud") {+ return await callCloudProxy<Automation>({+ backend: active.backend,+ method: "PATCH",+ path: updatePath,+ body: updateBody,+ headers: buildPinnedCloudHeaders(active),+ });+ }++ const { data } = await localAutomationAxios.patch<Automation>(+ updatePath,+ updateBody,+ buildPinnedLocalConfig(active.backend),+ );+ return data;+ } catch (updateError) {+ try {+ if (active.backend.kind === "cloud") {+ await callCloudProxy<unknown>({+ backend: active.backend,+ method: "DELETE",+ path: updatePath,+ headers: buildPinnedCloudHeaders(active),+ });+ } else {+ await localAutomationAxios.delete(+ updatePath,+ buildPinnedLocalConfig(active.backend),+ );+ }+ } catch (cleanupError) {+ throw new AggregateError(+ [updateError, cleanupError],+ "Failed to disable the imported automation and clean it up.",+ );+ }+ throw updateError;+ }+ }+static async updateAutomation(id: string,body: Partial<Automation>,diff --git a/src/components/features/automations/automation-card.tsx b/src/components/features/automations/automation-card.tsxindex bbaf8ee354..c13a07d4a3 100644--- a/src/components/features/automations/automation-card.tsx+++ b/src/components/features/automations/automation-card.tsx@@ -24,6 +24,7 @@ interface AutomationCardProps {onRunNow: (id: string) => void;isRunPending?: boolean;onDelete: (id: string) => void;+ onExport: (automation: Automation) => void;onEdit?: (id: string) => void;}@@ -33,6 +34,7 @@ export function AutomationCard({onRunNow,isRunPending = false,onDelete,+ onExport,onEdit,}: AutomationCardProps) {const { navigate } = useNavigation();@@ -57,6 +59,7 @@ export function AutomationCard({onRunNow,isRunPending,onView: handleView,+ onExport,onEdit,onToggle,onDelete,diff --git a/src/components/features/automations/automation-group.tsx b/src/components/features/automations/automation-group.tsxindex 6f4acf8124..b7b09ccfeb 100644--- a/src/components/features/automations/automation-group.tsx+++ b/src/components/features/automations/automation-group.tsx@@ -21,6 +21,7 @@ interface AutomationGroupProps {onRunNow: (id: string) => void;runPendingId?: string | null;onDelete: (id: string) => void;+ onExport: (automation: Automation) => void;onEdit?: (id: string) => void;}@@ -33,6 +34,7 @@ export function AutomationGroup({onRunNow,runPendingId = null,onDelete,+ onExport,onEdit,}: AutomationGroupProps) {if (automations.length === 0) return null;@@ -54,6 +56,7 @@ export function AutomationGroup({onRunNow={onRunNow}isRunPending={runPendingId === automation.id}onDelete={onDelete}+ onExport={onExport}onEdit={onEdit}/>))}@@ -71,6 +74,7 @@ export function AutomationGroup({onRunNow={onRunNow}isRunPending={runPendingId === automation.id}onDelete={onDelete}+ onExport={onExport}onEdit={onEdit}/>))}diff --git a/src/components/features/automations/automation-list-row.tsx b/src/components/features/automations/automation-list-row.tsxindex df43e31445..c8e911569e 100644--- a/src/components/features/automations/automation-list-row.tsx+++ b/src/components/features/automations/automation-list-row.tsx@@ -25,6 +25,7 @@ interface AutomationListRowProps {onRunNow: (id: string) => void;isRunPending?: boolean;onDelete: (id: string) => void;+ onExport: (automation: Automation) => void;onEdit?: (id: string) => void;}@@ -34,6 +35,7 @@ export function AutomationListRow({onRunNow,isRunPending = false,onDelete,+ onExport,onEdit,}: AutomationListRowProps) {const { navigate } = useNavigation();@@ -58,6 +60,7 @@ export function AutomationListRow({onRunNow,isRunPending,onView: handleView,+ onExport,onEdit,onToggle,onDelete,diff --git a/src/components/features/automations/build-automation-menu-items.tsx b/src/components/features/automations/build-automation-menu-items.tsxindex 2b8bb445d0..9401a239ca 100644--- a/src/components/features/automations/build-automation-menu-items.tsx+++ b/src/components/features/automations/build-automation-menu-items.tsx@@ -1,4 +1,4 @@-import { FileText } from "lucide-react";+import { Download, FileText } from "lucide-react";import PlayIcon from "#/icons/play.svg?react";import PowerIcon from "#/icons/power.svg?react";import TrashIcon from "#/icons/trash.svg?react";@@ -14,6 +14,7 @@ interface BuildAutomationMenuItemsOptions {onRunNow: (id: string) => void;isRunPending: boolean;onView: () => void;+ onExport: (automation: Automation) => void;onEdit?: (id: string) => void;onToggle: (id: string, enabled: boolean) => void;onDelete: (id: string) => void;@@ -26,6 +27,7 @@ export function buildAutomationMenuItems({onRunNow,isRunPending,onView,+ onExport,onEdit,onToggle,onDelete,@@ -46,6 +48,11 @@ export function buildAutomationMenuItems({icon: <FileText className="size-4" aria-hidden />,onClick: onView,},+ {+ label: t(I18nKey.AUTOMATIONS$EXPORT),+ icon: <Download className="size-4" aria-hidden />,+ onClick: () => onExport(automation),+ },...(canManage && onEdit? [{diff --git a/src/components/features/automations/detail/detail-header.tsx b/src/components/features/automations/detail/detail-header.tsxindex 5d4c359e26..1d85736b94 100644--- a/src/components/features/automations/detail/detail-header.tsx+++ b/src/components/features/automations/detail/detail-header.tsx@@ -1,7 +1,6 @@import { useTranslation } from "react-i18next";import { I18nKey } from "#/i18n/declaration";import type { Automation } from "#/types/automation";-import AutomationService from "#/api/automation-service/automation-service.api";import { ToggleSwitch } from "#/components/features/automations/toggle-switch";import { KebabMenu } from "#/components/features/automations/kebab-menu";import PowerIcon from "#/icons/power.svg?react";@@ -21,6 +20,8 @@ interface DetailHeaderProps {*/onEdit?: () => void;onDelete: () => void;+ onExport: () => void;+ onDownloadTarball: () => void;onRunNow?: () => void;isRunningNow?: boolean;}@@ -30,6 +31,8 @@ export function DetailHeader({onToggle,onEdit,onDelete,+ onExport,+ onDownloadTarball,onRunNow,isRunningNow = false,}: DetailHeaderProps) {@@ -53,12 +56,15 @@ export function DetailHeader({icon: <PowerIcon className="size-4" />,onClick: onToggle,},+ {+ label: t(I18nKey.AUTOMATIONS$EXPORT),+ icon: <DownloadIcon className="size-4" />,+ onClick: onExport,+ },{label: t(I18nKey.AUTOMATIONS$DOWNLOAD_TARBALL),icon: <DownloadIcon className="size-4" />,- onClick: () => {- AutomationService.downloadTarball(automation.id, automation.name);- },+ onClick: onDownloadTarball,},{label: t(I18nKey.AUTOMATIONS$DELETE),diff --git a/src/components/features/automations/import-automation-modal.test.tsx b/src/components/features/automations/import-automation-modal.test.tsxnew file mode 100644index 0000000000..205eccc042--- /dev/null+++ b/src/components/features/automations/import-automation-modal.test.tsx@@ -0,0 +1,70 @@+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vitest";+import type { AutomationSpec } from "#/types/automation";+import { I18nKey } from "#/i18n/declaration";+import { ImportAutomationModal } from "./import-automation-modal";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("#/components/shared/modals/modal-backdrop", () => ({+ ModalBackdrop: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+}));++vi.mock("#/components/shared/modals/modal-close-button", () => ({+ ModalCloseButton: () => (+ // eslint-disable-next-line i18next/no-literal-string+ <button type="button">close</button>+ ),+}));++const spec: AutomationSpec = {+ name: "Review new pull requests",+ prompt: "Review each new pull request and summarize any risks.",+ trigger: {+ type: "event",+ source: "github",+ on: "pull_request.opened",+ },+ enabled: true,+ plugins: ["github:openhands/extensions", "github:acme/review-tools"],+};++describe("ImportAutomationModal", () => {+ it("previews the parsed automation before import", () => {+ const markup = renderToStaticMarkup(+ <ImportAutomationModal+ isOpen+ spec={spec}+ isImporting={false}+ onClose={vi.fn()}+ onImport={vi.fn()}+ />,+ );++ expect(markup).toContain('data-testid="import-automation-modal"');+ expect(markup).toContain(spec.name);+ expect(markup).toContain("github: pull_request.opened");+ expect(markup).toContain(spec.prompt!);+ expect(markup).toContain(spec.plugins!.join(", "));+ expect(markup).toContain(I18nKey.AUTOMATIONS$IMPORT_DISABLED_NOTICE);+ expect(markup).toContain('data-testid="import-automation-confirm"');+ });++ it("does not render without a parsed spec", () => {+ const markup = renderToStaticMarkup(+ <ImportAutomationModal+ isOpen+ spec={null}+ isImporting={false}+ onClose={vi.fn()}+ onImport={vi.fn()}+ />,+ );++ expect(markup).toBe("");+ });+});diff --git a/src/components/features/automations/import-automation-modal.tsx b/src/components/features/automations/import-automation-modal.tsxnew file mode 100644index 0000000000..50232ffd91--- /dev/null+++ b/src/components/features/automations/import-automation-modal.tsx@@ -0,0 +1,129 @@+import { useTranslation } from "react-i18next";+import { I18nKey } from "#/i18n/declaration";+import type { AutomationSpec } from "#/types/automation";+import { formatEventOn } from "#/utils/automation-schedule";+import { cn } from "#/utils/utils";+import { modalTitleLgClassName } from "#/utils/modal-classes";+import { BrandButton } from "#/components/features/settings/brand-button";+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";+import { ModalCloseButton } from "#/components/shared/modals/modal-close-button";++interface ImportAutomationModalProps {+ isOpen: boolean;+ spec: AutomationSpec | null;+ isImporting: boolean;+ onClose: () => void;+ onImport: () => void;+}++function PreviewField({ label, value }: { label: string; value: string }) {+ return (+ <div className="flex flex-col gap-1">+ <dt className="text-xs font-medium uppercase tracking-wide text-muted">+ {label}+ </dt>+ <dd className="whitespace-pre-wrap break-words text-sm text-content">+ {value}+ </dd>+ </div>+ );+}++export function ImportAutomationModal({+ isOpen,+ spec,+ isImporting,+ onClose,+ onImport,+}: ImportAutomationModalProps) {+ const { t } = useTranslation("openhands");++ if (!isOpen || !spec) return null;++ const trigger =+ spec.trigger.type === "event"+ ? [spec.trigger.source, formatEventOn(spec.trigger.on)]+ .filter(Boolean)+ .join(": ")+ : [+ spec.trigger.schedule_human ?? spec.trigger.schedule,+ spec.timezone ?? spec.trigger.timezone,+ ]+ .filter(Boolean)+ .join(" · ");++ return (+ <ModalBackdrop+ onClose={isImporting ? undefined : onClose}+ closeOnEscape={!isImporting}+ closeOnBackdropClick={!isImporting}+ aria-label={t(I18nKey.AUTOMATIONS$IMPORT)}+ >+ <div+ data-testid="import-automation-modal"+ className="relative flex max-h-[85vh] w-[min(36rem,calc(100vw-2rem))] flex-col rounded-xl border border-[var(--oh-border)] bg-base-secondary"+ >+ <ModalCloseButton+ onClose={onClose}+ testId="import-automation-modal-close"+ disabled={isImporting}+ />+ <header className="px-6 pb-4 pt-6">+ <h2 className={cn("pr-6", modalTitleLgClassName)}>+ {t(I18nKey.AUTOMATIONS$IMPORT)}+ </h2>+ <p className="mt-2 text-sm text-tertiary-light">+ {t(I18nKey.AUTOMATIONS$IMPORT_PREVIEW_DESCRIPTION)}+ </p>+ </header>++ <dl className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto border-y border-[var(--oh-border)] px-6 py-5">+ <PreviewField label={t(I18nKey.AUTOMATIONS$NAME)} value={spec.name} />+ <PreviewField+ label={t(I18nKey.AUTOMATIONS$DETAIL$TRIGGER)}+ value={trigger}+ />+ <PreviewField+ label={t(I18nKey.AUTOMATIONS$PROMPT)}+ value={spec.prompt ?? ""}+ />+ {spec.plugins && spec.plugins.length > 0 ? (+ <PreviewField+ label={t(I18nKey.AUTOMATIONS$DETAIL$PLUGINS)}+ value={spec.plugins.join(", ")}+ />+ ) : null}+ </dl>++ <footer className="px-6 py-5">+ <p className="mb-4 text-sm text-tertiary-light">+ {t(I18nKey.AUTOMATIONS$IMPORT_DISABLED_NOTICE)}+ </p>+ <div className="flex justify-end gap-3">+ <BrandButton+ testId="import-automation-cancel"+ type="button"+ variant="secondary"+ onClick={onClose}+ isDisabled={isImporting}+ >+ {t(I18nKey.AUTOMATIONS$CANCEL)}+ </BrandButton>+ <BrandButton+ testId="import-automation-confirm"+ type="button"+ variant="primary"+ onClick={onImport}+ isDisabled={isImporting}+ aria-busy={isImporting}+ >+ {isImporting+ ? t(I18nKey.AUTOMATIONS$IMPORTING)+ : t(I18nKey.AUTOMATIONS$IMPORT)}+ </BrandButton>+ </div>+ </footer>+ </div>+ </ModalBackdrop>+ );+}diff --git a/src/hooks/query/use-automations.ts b/src/hooks/query/use-automations.tsindex aff5d37013..32cb4f7377 100644--- a/src/hooks/query/use-automations.ts+++ b/src/hooks/query/use-automations.ts@@ -2,7 +2,7 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import AutomationService from "#/api/automation-service/automation-service.api";import { useActiveBackend } from "#/contexts/active-backend-context";import { useTracking } from "#/hooks/use-tracking";-import type { Automation } from "#/types/automation";+import type { Automation, AutomationSpec } from "#/types/automation";import {AUTOMATION_DETAIL_QUERY_KEY,AUTOMATION_RUNS_QUERY_KEY,@@ -49,6 +49,20 @@ export function useToggleAutomation() {});}+export function useImportAutomation() {+ const queryClient = useQueryClient();+ const active = useActiveBackend();+ const { trackAutomationImported } = useTracking();+ return useMutation({+ mutationFn: (spec: AutomationSpec) =>+ AutomationService.createAutomation({ ...spec, enabled: false }),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });+ trackAutomationImported({ backendKind: active.backend.kind });+ },+ });+}+export function useUpdateAutomation() {const queryClient = useQueryClient();const active = useActiveBackend();diff --git a/src/hooks/use-tracking.ts b/src/hooks/use-tracking.tsindex 7043c64706..72e5209276 100644--- a/src/hooks/use-tracking.ts+++ b/src/hooks/use-tracking.ts@@ -218,6 +218,22 @@ export const useTracking = () => {track("automation_edited", { backend_kind: backendKind });};+ const trackAutomationExported = ({+ backendKind,+ }: {+ backendKind: BackendKind;+ }) => {+ track("automation_exported", { backend_kind: backendKind });+ };++ const trackAutomationImported = ({+ backendKind,+ }: {+ backendKind: BackendKind;+ }) => {+ track("automation_imported", { backend_kind: backendKind });+ };+const trackBackendAdded = ({backendKind,connectionMethod,@@ -308,6 +324,8 @@ export const useTracking = () => {trackAutomationDeleted,trackAutomationDeactivated,trackAutomationEdited,+ trackAutomationExported,+ trackAutomationImported,trackBackendAdded,trackOnboardingStarted,trackOnboardingStepViewed,diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 292c61657d..1238157551 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -12545,6 +12545,142 @@"uk": "Додати автоматизацію","ca": "Afegeix automatització"},+ "AUTOMATIONS$IMPORT": {+ "en": "Import automation",+ "ja": "オートメーションをインポート",+ "zh-CN": "导入自动化",+ "zh-TW": "匯入自動化",+ "ko-KR": "자동화 가져오기",+ "no": "Importer automatisering",+ "it": "Importa automazione",+ "pt": "Importar automação",+ "es": "Importar automatización",+ "ar": "استيراد أتمتة",+ "fr": "Importer une automatisation",+ "tr": "Otomasyonu içe aktar",+ "de": "Automatisierung importieren",+ "uk": "Імпортувати автоматизацію",+ "ca": "Importa l'automatització"+ },+ "AUTOMATIONS$EXPORT": {+ "en": "Export",+ "ja": "エクスポート",+ "zh-CN": "导出",+ "zh-TW": "匯出",+ "ko-KR": "내보내기",+ "no": "Eksporter",+ "it": "Esporta",+ "pt": "Exportar",+ "es": "Exportar",+ "ar": "تصدير",+ "fr": "Exporter",+ "tr": "Dışa aktar",+ "de": "Exportieren",+ "uk": "Експортувати",+ "ca": "Exporta"+ },+ "AUTOMATIONS$IMPORT_PREVIEW_DESCRIPTION": {+ "en": "Review the automation details before importing.",+ "ja": "インポートする前にオートメーションの詳細を確認してください。",+ "zh-CN": "请在导入前检查自动化详情。",+ "zh-TW": "請在匯入前檢查自動化詳細資料。",+ "ko-KR": "가져오기 전에 자동화 세부 정보를 검토하세요.",+ "no": "Se gjennom automatiseringsdetaljene før import.",+ "it": "Controlla i dettagli dell'automazione prima di importarla.",+ "pt": "Revise os detalhes da automação antes de importar.",+ "es": "Revise los detalles de la automatización antes de importarla.",+ "ar": "راجع تفاصيل الأتمتة قبل الاستيراد.",+ "fr": "Vérifiez les détails de l'automatisation avant de l'importer.",+ "tr": "İçe aktarmadan önce otomasyon ayrıntılarını inceleyin.",+ "de": "Prüfen Sie vor dem Import die Details der Automatisierung.",+ "uk": "Перевірте деталі автоматизації перед імпортом.",+ "ca": "Reviseu els detalls de l'automatització abans d'importar-la."+ },+ "AUTOMATIONS$IMPORT_DISABLED_NOTICE": {+ "en": "The imported automation will be disabled until you review and enable it.",+ "ja": "インポートしたオートメーションは、確認して有効にするまで無効になります。",+ "zh-CN": "导入的自动化将保持禁用,直到您检查并启用它。",+ "zh-TW": "匯入的自動化將保持停用,直到您檢查並啟用它。",+ "ko-KR": "가져온 자동화는 검토 후 활성화할 때까지 비활성화됩니다.",+ "no": "Den importerte automatiseringen er deaktivert til du har sett gjennom og aktivert den.",+ "it": "L'automazione importata resterà disattivata finché non la controllerai e attiverai.",+ "pt": "A automação importada ficará desativada até que você a revise e ative.",+ "es": "La automatización importada permanecerá desactivada hasta que la revise y active.",+ "ar": "ستظل الأتمتة المستوردة معطلة حتى تراجعها وتفعّلها.",+ "fr": "L'automatisation importée restera désactivée jusqu'à ce que vous la vérifiiez et l'activiez.",+ "tr": "İçe aktarılan otomasyon, inceleyip etkinleştirene kadar devre dışı kalır.",+ "de": "Die importierte Automatisierung bleibt deaktiviert, bis Sie sie geprüft und aktiviert haben.",+ "uk": "Імпортована автоматизація буде вимкнена, доки ви не перевірите та не ввімкнете її.",+ "ca": "L'automatització importada quedarà desactivada fins que la reviseu i l'activeu."+ },+ "AUTOMATIONS$IMPORTING": {+ "en": "Importing...",+ "ja": "インポート中...",+ "zh-CN": "正在导入...",+ "zh-TW": "正在匯入...",+ "ko-KR": "가져오는 중...",+ "no": "Importerer...",+ "it": "Importazione...",+ "pt": "Importando...",+ "es": "Importando...",+ "ar": "جارٍ الاستيراد...",+ "fr": "Importation...",+ "tr": "İçe aktarılıyor...",+ "de": "Wird importiert...",+ "uk": "Імпортування...",+ "ca": "S'està important..."+ },+ "AUTOMATIONS$IMPORT_SUCCESS": {+ "en": "Imported \"{{name}}\" as disabled.",+ "ja": "「{{name}}」を無効な状態でインポートしました。",+ "zh-CN": "已导入“{{name}}”,当前为禁用状态。",+ "zh-TW": "已匯入「{{name}}」,目前為停用狀態。",+ "ko-KR": "\"{{name}}\"을(를) 비활성화 상태로 가져왔습니다.",+ "no": "Importerte «{{name}}» som deaktivert.",+ "it": "\"{{name}}\" è stata importata come disattivata.",+ "pt": "\"{{name}}\" foi importada como desativada.",+ "es": "Se importó \"{{name}}\" como desactivada.",+ "ar": "تم استيراد «{{name}}» بحالة معطلة.",+ "fr": "« {{name}} » a été importée comme désactivée.",+ "tr": "\"{{name}}\" devre dışı olarak içe aktarıldı.",+ "de": "„{{name}}“ wurde deaktiviert importiert.",+ "uk": "«{{name}}» імпортовано у вимкненому стані.",+ "ca": "S'ha importat «{{name}}» com a desactivada."+ },+ "AUTOMATIONS$IMPORT_VIEW": {+ "en": "View automation",+ "ja": "オートメーションを表示",+ "zh-CN": "查看自动化",+ "zh-TW": "檢視自動化",+ "ko-KR": "자동화 보기",+ "no": "Vis automatisering",+ "it": "Visualizza automazione",+ "pt": "Ver automação",+ "es": "Ver automatización",+ "ar": "عرض الأتمتة",+ "fr": "Voir l'automatisation",+ "tr": "Otomasyonu görüntüle",+ "de": "Automatisierung anzeigen",+ "uk": "Переглянути автоматизацію",+ "ca": "Mostra l'automatització"+ },+ "AUTOMATIONS$IMPORT_INVALID_JSON": {+ "en": "The selected file is not valid JSON.",+ "ja": "選択したファイルは有効な JSON ではありません。",+ "zh-CN": "所选文件不是有效的 JSON。",+ "zh-TW": "所選檔案不是有效的 JSON。",+ "ko-KR": "선택한 파일이 유효한 JSON이 아닙니다.",+ "no": "Den valgte filen er ikke gyldig JSON.",+ "it": "Il file selezionato non è un JSON valido.",+ "pt": "O arquivo selecionado não é um JSON válido.",+ "es": "El archivo seleccionado no es un JSON válido.",+ "ar": "الملف المحدد ليس بتنسيق JSON صالح.",+ "fr": "Le fichier sélectionné n'est pas un JSON valide.",+ "tr": "Seçilen dosya geçerli bir JSON değil.",+ "de": "Die ausgewählte Datei enthält kein gültiges JSON.",+ "uk": "Вибраний файл не є коректним JSON.",+ "ca": "El fitxer seleccionat no és un JSON vàlid."+ },"AUTOMATIONS$EMPTY": {"en": "No automations configured","ja": "オートメーションが設定されていません",diff --git a/src/mocks/automation-handlers.ts b/src/mocks/automation-handlers.tsindex 63120f272a..07f98ca726 100644--- a/src/mocks/automation-handlers.ts+++ b/src/mocks/automation-handlers.ts@@ -47,6 +47,52 @@ export const AUTOMATION_HANDLERS = [return HttpResponse.json(response);}),+ // POST /api/automation/v1/preset/:kind — Create a prompt/plugin automation+ http.post("*/api/automation/v1/preset/:kind", async ({ params, request }) => {+ await delay(200);++ const body = (await request.clone().json()) as {+ name: string;+ prompt: string;+ model?: string;+ trigger: Automation["trigger"];+ repos?: { url: string; ref?: string }[];+ plugins?: { source: string }[];+ };+ const now = new Date().toISOString();+ const automation: Automation = {+ id: crypto.randomUUID(),+ name: body.name,+ prompt: body.prompt,+ model: body.model ?? null,+ trigger: body.trigger,+ enabled: true,+ created_at: now,+ updated_at: now,+ last_triggered_at: null,+ ...(body.repos?.[0] && {+ repository: body.repos[0].url,+ branch: body.repos[0].ref,+ }),+ ...(body.plugins && {+ plugins: body.plugins.map((plugin) => plugin.source),+ }),+ ...(typeof body.trigger.timezone === "string" && {+ timezone: body.trigger.timezone,+ }),+ };++ if (params.kind !== "prompt" && params.kind !== "plugin") {+ return HttpResponse.json(+ { detail: "Unknown preset kind" },+ { status: 404 },+ );+ }++ automations.set(automation.id, automation);+ return HttpResponse.json(automation, { status: 201 });+ }),+// GET /api/automation/v1/:id/runs — List automation runshttp.get("*/api/automation/v1/:id/runs", async ({ params, request }) => {await delay(200);diff --git a/src/routes/automation-detail.tsx b/src/routes/automation-detail.tsxindex 76c6d57810..3c04af1622 100644--- a/src/routes/automation-detail.tsx+++ b/src/routes/automation-detail.tsx@@ -30,6 +30,12 @@ import { BackendNotConfigured } from "#/components/features/automations/backend-import { DeleteConfirmationModal } from "#/components/features/automations/delete-confirmation-modal";import { EditAutomationModal } from "#/components/features/automations/detail/edit-automation-modal";import { useTracking } from "#/hooks/use-tracking";+import AutomationService from "#/api/automation-service/automation-service.api";+import {+ getAutomationExportFilename,+ serializeAutomation,+} from "#/utils/automation-export";+import { downloadBlob } from "#/utils/utils";export default function AutomationDetail() {const { t } = useTranslation("openhands");@@ -67,7 +73,8 @@ export default function AutomationDetail() {enabled: isBackendHealthy && !backendChanged,});- const { trackPrebuiltAutomationEnabled } = useTracking();+ const { trackPrebuiltAutomationEnabled, trackAutomationExported } =+ useTracking();const toggleMutation = useToggleAutomation();const deleteMutation = useDeleteAutomation();const dispatchMutation = useDispatchAutomation();@@ -163,6 +170,15 @@ export default function AutomationDetail() {});};+ const handleExport = () => {+ const contents = `${JSON.stringify(serializeAutomation(automation), null, 2)}\n`;+ downloadBlob(+ new Blob([contents], { type: "application/json" }),+ getAutomationExportFilename(automation),+ );+ trackAutomationExported({ backendKind: active.backend.kind });+ };+// Edit is a local-backend-only feature in MVP — cloud automations// are managed elsewhere and we don't yet surface them here.const canEdit = active.backend.kind === "local";@@ -177,6 +193,10 @@ export default function AutomationDetail() {onToggle={handleToggle}onEdit={canEdit ? () => setShowEditModal(true) : undefined}onDelete={() => setShowDeleteModal(true)}+ onExport={handleExport}+ onDownloadTarball={() =>+ AutomationService.downloadTarball(automation.id, automation.name)+ }onRunNow={handleRunNow}isRunningNow={dispatchMutation.isPending}/>diff --git a/src/routes/automations-list.tsx b/src/routes/automations-list.tsxindex 864a6f80df..7e4f01ab58 100644--- a/src/routes/automations-list.tsx+++ b/src/routes/automations-list.tsx@@ -1,9 +1,17 @@-import { useState, useMemo, useCallback } from "react";+import {+ useState,+ useMemo,+ useCallback,+ useRef,+ type ChangeEvent,+} from "react";+import { FileUp } from "lucide-react";import { useTranslation } from "react-i18next";import { isAxiosError } from "axios";import { I18nKey } from "#/i18n/declaration";import {displaySuccessToast,+ displaySuccessToastWithLink,displayErrorToast,} from "#/utils/custom-toast-handlers";import {@@ -11,6 +19,7 @@ import {useToggleAutomation,useDeleteAutomation,useDispatchAutomation,+ useImportAutomation,} from "#/hooks/query/use-automations";import { useAutomationHealth } from "#/hooks/query/use-automation-health";import { useActiveBackend } from "#/contexts/active-backend-context";@@ -29,10 +38,17 @@ import { BackendNotConfigured } from "#/components/features/automations/backend-import { DeleteConfirmationModal } from "#/components/features/automations/delete-confirmation-modal";import { EditAutomationModal } from "#/components/features/automations/detail/edit-automation-modal";import { AddAutomationModal } from "#/components/features/automations/add-automation-modal";+import { ImportAutomationModal } from "#/components/features/automations/import-automation-modal";import { RecommendedAutomationsLauncher } from "#/components/features/automations/recommended-automations-launcher";import { BrandButton } from "#/components/features/settings/brand-button";import { useTracking } from "#/hooks/use-tracking";-import type { Automation } from "#/types/automation";+import type { Automation, AutomationSpec } from "#/types/automation";+import {+ getAutomationExportFilename,+ parseAutomationFile,+ serializeAutomation,+} from "#/utils/automation-export";+import { downloadBlob } from "#/utils/utils";const PAGE_SIZE = 50;@@ -49,6 +65,8 @@ export default function AutomationsList() {} | null>(null);const [editTarget, setEditTarget] = useState<Automation | null>(null);const [isAddAutomationOpen, setIsAddAutomationOpen] = useState(false);+ const [importSpec, setImportSpec] = useState<AutomationSpec | null>(null);+ const importInputRef = useRef<HTMLInputElement>(null);const active = useActiveBackend();// Edit is a local-backend-only feature in MVP — cloud automations@@ -69,10 +87,12 @@ export default function AutomationsList() {offset: 0,enabled: isBackendHealthy,});- const { trackPrebuiltAutomationEnabled } = useTracking();+ const { trackPrebuiltAutomationEnabled, trackAutomationExported } =+ useTracking();const toggleMutation = useToggleAutomation();const deleteMutation = useDeleteAutomation();const dispatchMutation = useDispatchAutomation();+ const importMutation = useImportAutomation();const filtered = useMemo(() => {if (!data?.automations) return [];@@ -139,6 +159,67 @@ export default function AutomationsList() {}};+ const handleExport = (automation: Automation) => {+ const contents = `${JSON.stringify(serializeAutomation(automation), null, 2)}\n`;+ downloadBlob(+ new Blob([contents], { type: "application/json" }),+ getAutomationExportFilename(automation),+ );+ trackAutomationExported({ backendKind: active.backend.kind });+ };++ const handleImportFile = async (event: ChangeEvent<HTMLInputElement>) => {+ const input = event.currentTarget;+ const file = input.files?.[0];+ input.value = "";+ if (!file) return;++ try {+ let parsed: unknown;+ try {+ parsed = JSON.parse(await file.text()) as unknown;+ } catch {+ displayErrorToast(t(I18nKey.AUTOMATIONS$IMPORT_INVALID_JSON));+ return;+ }+ setImportSpec(parseAutomationFile(parsed));+ } catch (error) {+ displayErrorToast(+ error instanceof Error ? error.message : t(I18nKey.ERROR$GENERIC),+ );+ }+ };++ const handleImportConfirm = () => {+ if (!importSpec) return;++ importMutation.mutate(+ { ...importSpec, enabled: false },+ {+ onSuccess: (created) => {+ setImportSpec(null);+ displaySuccessToastWithLink(+ t(I18nKey.AUTOMATIONS$IMPORT_SUCCESS, { name: created.name }),+ t(I18nKey.AUTOMATIONS$IMPORT_VIEW),+ `/automations/${encodeURIComponent(created.id)}`,+ );+ },+ onError: (error) => {+ const detail = isAxiosError(error)+ ? (error.response?.data as { detail?: unknown } | undefined)?.detail+ : undefined;+ const message =+ typeof detail === "string"+ ? detail+ : isAxiosError(error)+ ? error.message+ : t(I18nKey.ERROR$GENERIC);+ displayErrorToast(message);+ },+ },+ );+ };+const handleDeleteConfirm = () => {if (deleteTarget) {deleteMutation.mutate(deleteTarget.id);@@ -206,15 +287,35 @@ export default function AutomationsList() {{t(I18nKey.AUTOMATIONS$SUBTITLE)}</p></div>- <BrandButton- type="button"- variant="secondary"- testId="automations-add-automation"- className="shrink-0 whitespace-nowrap"- onClick={() => setIsAddAutomationOpen(true)}- >- {t(I18nKey.AUTOMATIONS$ADD_AUTOMATION)}- </BrandButton>+ <div className="flex shrink-0 flex-wrap justify-end gap-2">+ <BrandButton+ type="button"+ variant="secondary"+ testId="automations-import-automation"+ className="whitespace-nowrap"+ onClick={() => importInputRef.current?.click()}+ startContent={<FileUp className="size-4" aria-hidden />}+ >+ {t(I18nKey.AUTOMATIONS$IMPORT)}+ </BrandButton>+ <input+ ref={importInputRef}+ type="file"+ accept="application/json,.json"+ className="hidden"+ data-testid="automations-import-file"+ onChange={handleImportFile}+ />+ <BrandButton+ type="button"+ variant="secondary"+ testId="automations-add-automation"+ className="whitespace-nowrap"+ onClick={() => setIsAddAutomationOpen(true)}+ >+ {t(I18nKey.AUTOMATIONS$ADD_AUTOMATION)}+ </BrandButton>+ </div></div>{/* Search */}@@ -256,6 +357,7 @@ export default function AutomationsList() {: null}onDelete={handleDeleteRequest}+ onExport={handleExport}onEdit={canEdit ? handleEditRequest : undefined}/><AutomationGroup@@ -271,6 +373,7 @@ export default function AutomationsList() {: null}onDelete={handleDeleteRequest}+ onExport={handleExport}onEdit={canEdit ? handleEditRequest : undefined}/>@@ -312,6 +415,14 @@ export default function AutomationsList() {isOpen={isAddAutomationOpen}onClose={() => setIsAddAutomationOpen(false)}/>++ <ImportAutomationModal+ isOpen={importSpec !== null}+ spec={importSpec}+ isImporting={importMutation.isPending}+ onClose={() => setImportSpec(null)}+ onImport={handleImportConfirm}+ /></div></div>);diff --git a/src/types/automation.ts b/src/types/automation.tsindex 908bd1f2a7..cd6753d400 100644--- a/src/types/automation.ts+++ b/src/types/automation.ts@@ -11,6 +11,8 @@ export interface AutomationTrigger {schedule?: string;/** Human-readable schedule description (schedule triggers only). */schedule_human?: string;+ /** IANA timezone name (schedule triggers only). */+ timezone?: string;/** Event source, e.g. "github" (event triggers only). */source?: string;/** Event key pattern(s) to match, e.g. "pull_request.opened" or ["push", "release.*"]. */@@ -38,6 +40,17 @@ export interface Automation {last_triggered_at?: string | null;}+export type AutomationSpec = Omit<+ Automation,+ "id" | "created_at" | "updated_at" | "last_triggered_at"+>;++export interface AutomationExportFile {+ version: 1;+ kind: "automation";+ spec: AutomationSpec;+}+export interface AutomationsResponse {automations: Automation[];total: number;diff --git a/src/utils/automation-export.test.ts b/src/utils/automation-export.test.tsnew file mode 100644index 0000000000..1923b6be76--- /dev/null+++ b/src/utils/automation-export.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from "vitest";+import type { Automation } from "#/types/automation";+import {+ AutomationFileValidationError,+ parseAutomationFile,+ serializeAutomation,+} from "./automation-export";++const cronAutomation: Automation = {+ id: "automation-1",+ name: "Daily review",+ trigger: {+ type: "cron",+ schedule: "0 9 * * *",+ schedule_human: "Daily at 09:00",+ },+ enabled: true,+ repository: "openhands/agent-canvas",+ branch: "main",+ model: "fast",+ prompt: "Review open pull requests.",+ plugins: ["github:openhands/extensions"],+ notification: "Post a summary",+ timezone: "America/Los_Angeles",+ created_at: "2026-07-01T00:00:00Z",+ updated_at: "2026-07-02T00:00:00Z",+ last_triggered_at: "2026-07-03T00:00:00Z",+};++describe("automation export files", () => {+ it("round-trips a cron automation without server-assigned fields", () => {+ const exported = serializeAutomation(cronAutomation);++ expect(exported).toEqual({+ version: 1,+ kind: "automation",+ spec: {+ name: cronAutomation.name,+ trigger: cronAutomation.trigger,+ enabled: true,+ repository: cronAutomation.repository,+ model: cronAutomation.model,+ prompt: cronAutomation.prompt,+ branch: cronAutomation.branch,+ plugins: cronAutomation.plugins,+ notification: cronAutomation.notification,+ timezone: cronAutomation.timezone,+ },+ });+ expect(parseAutomationFile(exported)).toEqual(exported.spec);+ expect(exported.spec).not.toHaveProperty("id");+ expect(exported.spec).not.toHaveProperty("created_at");+ expect(exported.spec).not.toHaveProperty("updated_at");+ expect(exported.spec).not.toHaveProperty("last_triggered_at");+ });++ it("round-trips event trigger fields", () => {+ const exported = serializeAutomation({+ ...cronAutomation,+ trigger: {+ type: "event",+ source: "github",+ on: ["pull_request.opened", "pull_request.synchronize"],+ filter: "repository.full_name == 'openhands/agent-canvas'",+ },+ timezone: undefined,+ });++ expect(parseAutomationFile(exported).trigger).toEqual(+ exported.spec.trigger,+ );+ });++ it("reports every malformed field with its path", () => {+ const malformed = {+ version: 2,+ kind: "workflow",+ spec: {+ name: "",+ prompt: null,+ enabled: "yes",+ trigger: { type: "event", source: 42, on: [] },+ plugins: ["github:openhands/extensions", 42],+ model: false,+ },+ };++ expect(() => parseAutomationFile(malformed)).toThrow(+ AutomationFileValidationError,+ );++ try {+ parseAutomationFile(malformed);+ } catch (error) {+ expect(error).toBeInstanceOf(AutomationFileValidationError);+ expect((error as AutomationFileValidationError).issues).toEqual(+ expect.arrayContaining([+ "version: expected 1",+ 'kind: expected "automation"',+ "spec.name: expected a non-empty string",+ "spec.prompt: expected a non-empty string",+ "spec.enabled: expected a boolean",+ "spec.trigger.source: expected a string",+ "spec.trigger.source: required for an event trigger",+ "spec.trigger.on: expected a string or a non-empty array of strings",+ "spec.trigger.on: required for an event trigger",+ "spec.plugins: expected an array of non-empty strings",+ "spec.model: expected a non-empty string or null",+ ]),+ );+ }+ });++ it("rejects non-object files and missing specs", () => {+ expect(() => parseAutomationFile(null)).toThrow(+ "file: expected a JSON object",+ );+ expect(() =>+ parseAutomationFile({ version: 1, kind: "automation" }),+ ).toThrow("spec: expected an object");+ });+});diff --git a/src/utils/automation-export.ts b/src/utils/automation-export.tsnew file mode 100644index 0000000000..a8a15a5634--- /dev/null+++ b/src/utils/automation-export.ts@@ -0,0 +1,280 @@+import type {+ Automation,+ AutomationExportFile,+ AutomationSpec,+ AutomationTrigger,+} from "#/types/automation";++const SUPPORTED_TRIGGER_TYPES = new Set(["cron", "schedule", "event"]);++type UnknownRecord = Record<string, unknown>;++export class AutomationFileValidationError extends Error {+ readonly issues: string[];++ constructor(issues: string[]) {+ super(issues.join("\n"));+ this.name = "AutomationFileValidationError";+ this.issues = issues;+ }+}++function isRecord(value: unknown): value is UnknownRecord {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function validateRequiredString(+ record: UnknownRecord,+ field: string,+ path: string,+ issues: string[],+): string | undefined {+ const value = record[field];+ if (typeof value !== "string" || value.trim().length === 0) {+ issues.push(`${path}: expected a non-empty string`);+ return undefined;+ }+ return value;+}++function validateOptionalString(+ record: UnknownRecord,+ field: string,+ path: string,+ issues: string[],+): string | undefined {+ const value = record[field];+ if (value === undefined) return undefined;+ if (typeof value !== "string") {+ issues.push(`${path}: expected a string`);+ return undefined;+ }+ return value;+}++function validateTrigger(+ value: unknown,+ issues: string[],+): AutomationTrigger | undefined {+ if (!isRecord(value)) {+ issues.push("spec.trigger: expected an object");+ return undefined;+ }++ const type = validateRequiredString(+ value,+ "type",+ "spec.trigger.type",+ issues,+ );+ if (type && !SUPPORTED_TRIGGER_TYPES.has(type)) {+ issues.push(+ 'spec.trigger.type: expected one of "cron", "schedule", or "event"',+ );+ }++ const schedule = validateOptionalString(+ value,+ "schedule",+ "spec.trigger.schedule",+ issues,+ );+ const scheduleHuman = validateOptionalString(+ value,+ "schedule_human",+ "spec.trigger.schedule_human",+ issues,+ );+ const timezone = validateOptionalString(+ value,+ "timezone",+ "spec.trigger.timezone",+ issues,+ );+ const source = validateOptionalString(+ value,+ "source",+ "spec.trigger.source",+ issues,+ );+ const filter = validateOptionalString(+ value,+ "filter",+ "spec.trigger.filter",+ issues,+ );++ let on: string | string[] | undefined;+ if (value.on !== undefined) {+ if (+ typeof value.on === "string" ||+ (Array.isArray(value.on) &&+ value.on.length > 0 &&+ value.on.every(+ (entry) => typeof entry === "string" && entry.trim().length > 0,+ ))+ ) {+ on = value.on as string | string[];+ } else {+ issues.push(+ "spec.trigger.on: expected a string or a non-empty array of strings",+ );+ }+ }++ if ((type === "cron" || type === "schedule") && !schedule?.trim()) {+ issues.push("spec.trigger.schedule: required for a scheduled trigger");+ }+ if (type === "event") {+ if (!source?.trim()) {+ issues.push("spec.trigger.source: required for an event trigger");+ }+ if (+ on === undefined ||+ (typeof on === "string" && on.trim().length === 0)+ ) {+ issues.push("spec.trigger.on: required for an event trigger");+ }+ }++ if (!type || !SUPPORTED_TRIGGER_TYPES.has(type)) return undefined;++ return {+ type,+ ...(schedule !== undefined && { schedule }),+ ...(scheduleHuman !== undefined && { schedule_human: scheduleHuman }),+ ...(timezone !== undefined && { timezone }),+ ...(source !== undefined && { source }),+ ...(on !== undefined && { on }),+ ...(filter !== undefined && { filter }),+ };+}++export function serializeAutomation(a: Automation): AutomationExportFile {+ const timezone = a.timezone ?? a.trigger.timezone;+ const spec: AutomationSpec = {+ name: a.name,+ trigger: { ...a.trigger },+ enabled: a.enabled,+ prompt: a.prompt,+ ...(a.repository !== undefined && { repository: a.repository }),+ ...(a.model !== undefined && { model: a.model }),+ ...(a.branch !== undefined && { branch: a.branch }),+ ...(a.plugins !== undefined && { plugins: [...a.plugins] }),+ ...(a.notification !== undefined && { notification: a.notification }),+ ...(timezone !== undefined && { timezone }),+ };++ return { version: 1, kind: "automation", spec };+}++export function getAutomationExportFilename(+ automation: Pick<Automation, "id" | "name">,+): string {+ const slug = automation.name+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "");+ return `${slug || automation.id}.automation.json`;+}++export function parseAutomationFile(json: unknown): AutomationSpec {+ const issues: string[] = [];+ if (!isRecord(json)) {+ throw new AutomationFileValidationError(["file: expected a JSON object"]);+ }++ if (json.version !== 1) {+ issues.push("version: expected 1");+ }+ if (json.kind !== "automation") {+ issues.push('kind: expected "automation"');+ }+ if (!isRecord(json.spec)) {+ issues.push("spec: expected an object");+ throw new AutomationFileValidationError(issues);+ }++ const name = validateRequiredString(json.spec, "name", "spec.name", issues);+ const prompt = validateRequiredString(+ json.spec,+ "prompt",+ "spec.prompt",+ issues,+ );+ const trigger = validateTrigger(json.spec.trigger, issues);++ const enabled = json.spec.enabled;+ if (typeof enabled !== "boolean") {+ issues.push("spec.enabled: expected a boolean");+ }++ const repository = validateOptionalString(+ json.spec,+ "repository",+ "spec.repository",+ issues,+ );+ const branch = validateOptionalString(+ json.spec,+ "branch",+ "spec.branch",+ issues,+ );+ const notification = validateOptionalString(+ json.spec,+ "notification",+ "spec.notification",+ issues,+ );+ const timezone = validateOptionalString(+ json.spec,+ "timezone",+ "spec.timezone",+ issues,+ );++ let model: string | null | undefined;+ if (json.spec.model === null || json.spec.model === undefined) {+ model = json.spec.model;+ } else if (+ typeof json.spec.model === "string" &&+ json.spec.model.trim().length > 0+ ) {+ model = json.spec.model;+ } else {+ issues.push("spec.model: expected a non-empty string or null");+ }++ let plugins: string[] | undefined;+ if (json.spec.plugins !== undefined) {+ if (+ Array.isArray(json.spec.plugins) &&+ json.spec.plugins.every(+ (plugin) => typeof plugin === "string" && plugin.trim().length > 0,+ )+ ) {+ plugins = [...json.spec.plugins] as string[];+ } else {+ issues.push("spec.plugins: expected an array of non-empty strings");+ }+ }++ if (issues.length > 0 || !name || !prompt || !trigger) {+ throw new AutomationFileValidationError(issues);+ }++ return {+ name,+ prompt,+ trigger,+ enabled: enabled as boolean,+ ...(repository !== undefined && { repository }),+ ...(model !== undefined && { model }),+ ...(branch !== undefined && { branch }),+ ...(plugins !== undefined && { plugins }),+ ...(notification !== undefined && { notification }),+ ...(timezone !== undefined && { timezone }),+ };+}diff --git a/src/utils/custom-toast-handlers.tsx b/src/utils/custom-toast-handlers.tsxindex 25e401bb32..6ffc37f824 100644--- a/src/utils/custom-toast-handlers.tsx+++ b/src/utils/custom-toast-handlers.tsx@@ -117,6 +117,23 @@ export const displaySuccessToast = (message: string) => {);};+export const displaySuccessToastWithLink = (+ message: string,+ linkLabel: string,+ href: string,+) => {+ const duration = calculateToastDuration(`${message} ${linkLabel}`, 5000);+ toast.success(+ <span className="[word-break:break-word] [overflow-wrap:anywhere]">+ {message}{" "}+ <a className="underline hover:no-underline" href={href}>+ {linkLabel}+ </a>+ </span>,+ { ...TOAST_OPTIONS, duration },+ );+};+/*** Neutral, non-success notice — used when an action completed but the outcome* is qualified (e.g. a secret was saved but the active backend can't consume it