🙌 OpenHands: AI-Driven Development
feat: support generic custom automation manifests in Canvas (#17129)
Rohit Malhotrafbf9d6188f7a
diff --git a/__tests__/components/automations/recommended-automations-rail.test.tsx b/__tests__/components/automations/recommended-automations-rail.test.tsxindex ffdebdf9bf..cf220431dc 100644--- a/__tests__/components/automations/recommended-automations-rail.test.tsx+++ b/__tests__/components/automations/recommended-automations-rail.test.tsx@@ -51,7 +51,7 @@ describe("RecommendedAutomationsRail", () => {it("renders remaining proven workflows before conversation-only extras", () => {render(<RecommendedAutomationsRail- installedAutomations={[{ name: "GitHub Code Review Agent" }]}+ installedAutomations={[{ name: "GitHub code review" }]}onSelect={vi.fn()}/>,);@@ -65,6 +65,7 @@ describe("RecommendedAutomationsRail", () => {);expect(cardIds).toEqual([+ "custom-automation","github-issue-to-pr","slack-channel-monitor","github-agents-md-maintainer",@@ -109,7 +110,9 @@ describe("RecommendedAutomationsRail", () => {);await user.click(- screen.getByTestId("recommended-automation-rail-card-slack-standup-digest"),+ screen.getByTestId(+ "recommended-automation-rail-card-slack-standup-digest",+ ),);expect(onSelect).toHaveBeenCalledWith(@@ -121,8 +124,9 @@ describe("RecommendedAutomationsRail", () => {const { container } = render(<RecommendedAutomationsRailinstalledAutomations={[- { name: "GitHub Code Review Agent" },- { name: "GitHub Issue to PR Agent" },+ { name: "GitHub code review" },+ { name: "GitHub issue to PR" },+ { name: "Custom automation" },{ name: "Slack channel monitor" },{ name: "AGENTS.md Maintainer" },{ name: "Daily news digest" },@@ -175,7 +179,9 @@ describe("RecommendedAutomationsRail", () => {/>,);- const scroller = screen.getByTestId("recommended-automations-rail-scroll");+ const scroller = screen.getByTestId(+ "recommended-automations-rail-scroll",+ );const leftFade = screen.getByTestId("recommended-automations-rail-fade-left",);diff --git a/__tests__/components/automations/recommended-automations.test.tsx b/__tests__/components/automations/recommended-automations.test.tsxindex 929a519436..5a40b24af2 100644--- a/__tests__/components/automations/recommended-automations.test.tsx+++ b/__tests__/components/automations/recommended-automations.test.tsx@@ -206,6 +206,7 @@ describe("recommended automations", () => {expect(cardIds).toEqual(["github-pr-reviewer",+ "custom-automation","github-issue-to-pr","slack-channel-monitor","github-agents-md-maintainer",@@ -238,7 +239,7 @@ describe("recommended automations", () => {const provenHeading = screen.getByText(I18nKey.RECOMMENDED_AUTOMATIONS$SECTION_TITLE,).parentElement!;- expect(within(provenHeading).getByText("5")).toBeInTheDocument();+ expect(within(provenHeading).getByText("6")).toBeInTheDocument();const betaHeading = screen.getByTestId("recommended-automations-beta-heading",@@ -918,7 +919,7 @@ describe("recommended automations", () => {automations: [{id: "installed-1",- name: "GitHub Code Review Agent",+ name: "GitHub code review",trigger: { type: "cron", schedule: "0 9 * * *" },enabled: true,prompt: "Review PRs",diff --git a/__tests__/components/manifest/manifest-form-field.test.tsx b/__tests__/components/manifest/manifest-form-field.test.tsxindex 72e7b217c7..01bb5061b1 100644--- a/__tests__/components/manifest/manifest-form-field.test.tsx+++ b/__tests__/components/manifest/manifest-form-field.test.tsx@@ -112,6 +112,30 @@ afterEach(() => {__resetActiveStoreForTests();});+const LLM_PROFILE_FIELD: SetupFormFieldDefinition = {+ type: "llm-profile",+ label: "LLM profile",+ help: "Which profile should run the automation.",+ required: false,+};++describe("SetupFormField llm-profile", () => {+ it("shows an empty disabled dropdown instead of a text input", () => {+ // Arrange / Act+ renderRepositoryField(LOCAL_BACKEND, { field: LLM_PROFILE_FIELD });++ // Assert — profile names must come from the backend; when none are loaded,+ // the form should not invite users to type an unchecked profile name.+ const profileInput = screen.getByTestId("setup-field-repository");+ expect(profileInput).toHaveAttribute("role", "combobox");+ expect(profileInput).toBeDisabled();+ expect(profileInput).toHaveAttribute(+ "placeholder",+ "MODEL$NO_SAVED_PROFILES",+ );+ });+});+describe("SetupFormField repo-picker", () => {it("lets a repository be typed on a backend that cannot list them", async () => {// Arrange — a local backend, where GitService answers every repositorydiff --git a/__tests__/components/manifest/manifest-setup-dialog.test.tsx b/__tests__/components/manifest/manifest-setup-dialog.test.tsxindex fd1c0d7a04..4cba8318e6 100644--- a/__tests__/components/manifest/manifest-setup-dialog.test.tsx+++ b/__tests__/components/manifest/manifest-setup-dialog.test.tsx@@ -5,7 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import AutomationService from "#/api/automation-service/automation-service.api";import { SetupDialog } from "#/components/features/manifest/manifest-setup-dialog";import type { SetupPrerequisitesResult } from "#/hooks/query/use-manifest-prerequisites";-import type { SetupEntry } from "#/manifests/types";+import type { DeploymentCapabilities, SetupEntry } from "#/manifests/types";import {createSetup,createSetupEntry,@@ -22,6 +22,7 @@ const mocks = vi.hoisted(() => ({runAction: vi.fn(),prerequisites: vi.fn(),capabilities: vi.fn(),+ llmProfiles: vi.fn(),missingCreateEndpoints: vi.fn<(entry: SetupEntry) => string[]>(() => []),tracking: {trackAutomationSetupOpened: vi.fn(),@@ -53,6 +54,11 @@ vi.mock("#/hooks/query/use-manifest-prerequisites", () => ({useSetupPrerequisites: () => mocks.prerequisites(),}));+vi.mock("#/hooks/query/use-llm-profiles", () => ({+ useLlmProfiles: (options: { enabled?: boolean } = {}) =>+ mocks.llmProfiles(options),+}));+// Which endpoints an entry cannot be created without is read off the published// interface manifest, so a real one that declares them leaves the refusal path// unreachable. Stubbed so the case states the manifest it is about, rather than@@ -118,6 +124,10 @@ beforeEach(() => {unmet: [],isLoading: false,});+ mocks.llmProfiles.mockReturnValue({+ data: { profiles: [] },+ isLoading: false,+ });vi.mocked(AutomationService.validateDraft).mockResolvedValue({valid: true,errors: [],@@ -161,6 +171,77 @@ const UNSUPPORTED = {isLoading: false,};+const CRON_ONLY_CAPABILITIES: DeploymentCapabilities = {+ ready: true,+ maxAutomationTimeoutSeconds: 900,+ triggerKinds: ["cron"],+ eventSources: ["github"],+ eventTypes: ["issue_comment.created"],+ triggers: {+ cron: { minIntervalSeconds: 60, timezones: ["UTC"] },+ event: { filterLanguage: "jmespath", filterFunctions: ["icontains"] },+ },+ features: [],+};++const EVENT_FIRST_MIXED_TRIGGER_ENTRY: SetupEntry = (() => {+ const { form } = createSetup();+ return createSetupEntry({+ setup: createSetup({+ form: {+ ...form,+ triggers: {+ event: {+ source: {+ type: "event-source",+ label: "Event source",+ help: "Where events come from.",+ default: "github",+ required: true,+ },+ on: {+ type: "event-type",+ label: "Event type",+ help: "Which event to watch.",+ default: "issue_comment.created",+ required: true,+ },+ mention: {+ type: "text",+ label: "Mention",+ help: "Text that must appear in the comment.",+ default: "@openhands",+ required: true,+ },+ },+ cron: form.triggers!.cron,+ },+ },+ filter: "icontains(comment.body, '{{form.mention}}')",+ }),+ });+})();++const LLM_PROFILE_ENTRY: SetupEntry = (() => {+ const { form } = createSetup();+ return createSetupEntry({+ setup: createSetup({+ form: {+ ...form,+ args: {+ ...form.args,+ model: {+ type: "llm-profile",+ label: "LLM profile",+ help: "Which saved profile should run this automation.",+ required: false,+ },+ },+ },+ }),+ });+})();+describe("SetupDialog", () => {it("asks about an unconnected integration before it asks anything else", async () => {// Arrange — an advisory integration, which is shown but does not block.@@ -185,6 +266,39 @@ describe("SetupDialog", () => {expect(screen.queryByTestId("setup-prerequisites")).toBeNull();});+ it("hides trigger variants unsupported by the deployment", async () => {+ mocks.capabilities.mockReturnValue({+ capabilities: CRON_ONLY_CAPABILITIES,+ supported: true,+ unmet: [],+ isLoading: false,+ });+ mocks.runAction.mockResolvedValue({ response: { id: "automation-1" } });+ const { user } = renderDialog(EVENT_FIRST_MIXED_TRIGGER_ENTRY);++ await waitFor(() =>+ expect(screen.getByTestId("setup-field-schedule")).toBeInTheDocument(),+ );+ expect(screen.queryByTestId("setup-trigger-kind")).toBeNull();+ expect(screen.queryByTestId("setup-field-source")).toBeNull();+ await fillForm(user);++ await user.click(screen.getByTestId("setup-continue-button"));+ await waitFor(() =>+ expect(screen.getByTestId("setup-review")).toBeInTheDocument(),+ );+ await user.click(screen.getByTestId("setup-continue-button"));++ await waitFor(() => expect(mocks.runAction).toHaveBeenCalled());+ expect(mocks.runAction.mock.calls[0][2]).toEqual({+ name: "Widget monitor - OpenHands/agent-server-gui",+ prompt: "Report on Widgets in OpenHands/agent-server-gui.",+ repos: [{ url: "OpenHands/agent-server-gui", provider: "github" }],+ trigger: { type: "cron", schedule: "*/15 * * * *" },+ });+ expect(mocks.runAction.mock.calls[0][3]).toBe("cron");+ });+it("holds an unanswered required field back from the service", async () => {// Arrange — nothing typed, so two required fields are still empty.const { user } = renderDialog();@@ -229,6 +343,56 @@ describe("SetupDialog", () => {});});+ it("waits for LLM profiles before continuing", () => {+ // Arrange — profile names come from the backend, not the manifest, so the+ // form should not validate while that closed set is still unknown.+ mocks.llmProfiles.mockReturnValue({ data: undefined, isLoading: true });++ // Act+ renderDialog(LLM_PROFILE_ENTRY);++ // Assert+ expect(mocks.llmProfiles).toHaveBeenCalledWith({ enabled: true });+ expect(screen.getByTestId("setup-continue-button")).toBeDisabled();+ expect(screen.getByTestId("setup-field-model")).toHaveAttribute(+ "role",+ "combobox",+ );+ expect(screen.getByTestId("setup-field-model")).toBeDisabled();+ });++ it("submits a selected backend LLM profile name", async () => {+ // Arrange+ mocks.llmProfiles.mockReturnValue({+ data: { profiles: [{ name: "Fast" }, { name: "Smart" }] },+ isLoading: false,+ });+ mocks.runAction.mockResolvedValue({ response: { id: "automation-1" } });+ const { user } = renderDialog(LLM_PROFILE_ENTRY);++ // Act+ const modelInput = screen.getByTestId("setup-field-model");+ expect(modelInput).toHaveAttribute("role", "combobox");+ await user.click(modelInput);+ await user.click(await screen.findByText("Smart"));+ await fillForm(user);+ await user.click(screen.getByTestId("setup-continue-button"));+ await waitFor(() =>+ expect(screen.getByTestId("setup-review")).toBeInTheDocument(),+ );+ await user.click(screen.getByTestId("setup-continue-button"));++ // Assert+ await waitFor(() => expect(mocks.runAction).toHaveBeenCalled());+ expect(mocks.runAction.mock.calls[0][2]).toEqual({+ name: "Widget monitor - OpenHands/agent-server-gui",+ model: "Smart",+ prompt: "Report on Widgets in OpenHands/agent-server-gui.",+ repos: [{ url: "OpenHands/agent-server-gui", provider: "github" }],+ trigger: { type: "cron", schedule: "*/15 * * * *" },+ });+ });+it("offers the conversation fallback when the deployment cannot run a direct entry", async () => {// Arrange — capabilities answered and came up short, and the entry ships// a fallback-conversation seed.@@ -257,6 +421,8 @@ describe("SetupDialog", () => {entry,expect.anything(),null,+ "cron",+ null,);});diff --git a/__tests__/components/onboarding/onboarding-modal.test.tsx b/__tests__/components/onboarding/onboarding-modal.test.tsxindex be09c02be6..a08bb10559 100644--- a/__tests__/components/onboarding/onboarding-modal.test.tsx+++ b/__tests__/components/onboarding/onboarding-modal.test.tsx@@ -24,6 +24,11 @@ import * as telemetry from "#/services/telemetry";const llmSettingsScreenMock = vi.hoisted(() => vi.fn());const getServerInfoMock = vi.hoisted(() => vi.fn());const getSettingsMock = vi.hoisted(() => vi.fn().mockResolvedValue({}));+const saveAgentProfileMock = vi.hoisted(() => vi.fn().mockResolvedValue({}));+const getAgentProfileMock = vi.hoisted(() =>+ vi.fn().mockResolvedValue({ profile: { id: "default-profile-id" } }),+);+const activateAgentProfileMock = vi.hoisted(() => vi.fn().mockResolvedValue({}));let captureMock: MockInstance<typeof telemetry.trackEvent>;// Both the backend status badge in the embedded edit form and the@@ -42,6 +47,13 @@ vi.mock("@openhands/typescript-client/clients", () => ({getSettings: vi.fn(() => getSettingsMock()),};}),+ AgentProfilesClient: vi.fn(function AgentProfilesClientMock() {+ return {+ saveAgentProfile: vi.fn((...args) => saveAgentProfileMock(...args)),+ getAgentProfile: vi.fn((...args) => getAgentProfileMock(...args)),+ activateAgentProfile: vi.fn((...args) => activateAgentProfileMock(...args)),+ };+ }),}));vi.mock("#/api/cloud/organization-service.api", () => ({diff --git a/__tests__/constants/extensions-catalogs.test.ts b/__tests__/constants/extensions-catalogs.test.tsindex fd11c6eedd..edc6b76a05 100644--- a/__tests__/constants/extensions-catalogs.test.ts+++ b/__tests__/constants/extensions-catalogs.test.ts@@ -50,16 +50,18 @@ describe("OpenHands extensions catalogs", () => {expect(linear.docsUrl).toBe("https://linear.app/docs/mcp");expect(mcpOption.auth.strategy).toBe("bearer");expect(- linear.connectionOptions.some((option) => option.transport?.kind === "sse"),+ linear.connectionOptions.some(+ (option) => option.transport?.kind === "sse",+ ),).toBe(false);});- it("drops deprecated MCP entries that no longer have maintained replacements", () => {+ it("keeps maintained MCP entries and drops deprecated ones", () => {const catalogIds = new Set(getMcpMarketplaceCatalog(INTEGRATION_CATALOG).map((entry) => entry.id),);- expect(catalogIds.has("gitlab")).toBe(false);+ expect(catalogIds.has("gitlab")).toBe(true);expect(catalogIds.has("google-maps")).toBe(false);expect(catalogIds.has("postgres")).toBe(false);expect(catalogIds.has("puppeteer")).toBe(false);diff --git a/__tests__/manifests/manifest-validation.test.ts b/__tests__/manifests/manifest-validation.test.tsindex 70a731c549..367fcefd64 100644--- a/__tests__/manifests/manifest-validation.test.ts+++ b/__tests__/manifests/manifest-validation.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from "vitest";import { validateSetupEntry } from "#/manifests/manifest-validation";-import type { SetupForm } from "#/manifests/types";+import type {+ SetupForm,+ SetupFormField,+ SetupFormFields,+} from "#/manifests/types";import {createSetup,createSetupEntry,@@ -65,6 +69,47 @@ describe("validateSetupEntry", () => {},);+ it("admits a direct entry with selectable cron and event trigger kinds", () => {+ // Arrange+ const entry = createSetupEntry({+ setup: createSetup({+ form: {+ triggers: {+ cron: {+ schedule: {+ type: "cron",+ label: "Frequency",+ help: "How often.",+ required: true,+ },+ },+ event: {+ on: {+ type: "event-type",+ label: "Respond to",+ help: "Which event.",+ required: true,+ },+ source: {+ type: "event-source",+ label: "Source",+ help: "Where events come from.",+ required: true,+ },+ },+ },+ args: createSetup().form.args,+ },+ }),+ });++ // Act+ const result = validateSetupEntry(entry);++ // Assert+ expect(result).toEqual({ valid: true, errors: [] });+ });+// Each case is a separate invariant the host enforces on data authored in// another repository. A manifest that trips any of them must not render.it.each([@@ -98,45 +143,6 @@ describe("validateSetupEntry", () => {"a template version that is not semver",{ version: "v1" },],- [- // The host reads one trigger kind to build the request, so a second one- // would be silently dropped rather than refused.- "more trigger kinds than the host can send",- {- setup: createSetup({- form: {- triggers: {- cron: {- schedule: {- type: "cron",- label: "Frequency",- help: "How often.",- required: true,- },- },- event: {- on: {- type: "select",- label: "Respond to",- help: "Which event.",- required: true,- options: [{ value: "push", label: "Push" }],- },- },- },- args: {- repository: {- type: "repo-picker",- label: "Repository",- help: "Which repository.",- provider: "github",- required: true,- },- },- },- }),- },- ],[// An event trigger's source is read off the repository field's provider."an event trigger with no repository field to take its source from",@@ -419,4 +425,196 @@ describe("validateSetupEntry", () => {// Assertexpect(errors).toHaveLength(2);});++ // An event trigger's `source` is derived either from a field named `source`+ // in the event trigger, or from the selected action's repo-picker provider.+ // A repo-picker that the derivation cannot reach for the event trigger — in+ // another trigger group, or in only some actions — must not satisfy the+ // check, or the user is left with an empty source no field can fix.+ describe("event trigger source", () => {+ const repoPicker: SetupFormField = {+ type: "repo-picker",+ label: "Repository",+ help: "Which repository to watch.",+ provider: "github",+ required: true,+ };+ // `event-type` cannot carry options, and `args` must be non-empty, so the+ // event trigger carries a select for its `on` field and a placeholder arg.+ const eventFields: SetupFormFields = {+ on: {+ type: "select",+ label: "Respond to",+ help: "Which event.",+ required: true,+ options: [{ value: "push", label: "Push" }],+ },+ };+ const args: SetupFormFields = {+ widgetName: {+ type: "text",+ label: "Widget name",+ help: "What to call it.",+ required: true,+ },+ };++ it("admits an event trigger whose repo-picker lives in the shared args", () => {+ // Arrange — `form.args` is collected for every trigger and action, so a+ // picker here is reachable no matter which action is selected.+ const entry = createSetupEntry({+ setup: createSetup({+ form: {+ triggers: { event: eventFields },+ args: { ...args, repository: repoPicker },+ },+ prompt: "Report on {{form.repository}}.",+ }),+ });++ // Act+ const result = validateSetupEntry(entry);++ // Assert+ expect(result).toEqual({ valid: true, errors: [] });+ });++ it("admits an event trigger with a repo-picker in its own fields when it is the only trigger", () => {+ // Arrange+ const entry = createSetupEntry({+ setup: createSetup({+ form: {+ triggers: { event: { ...eventFields, repository: repoPicker } },+ args,+ },+ prompt: "Report on {{form.repository}}.",+ }),+ });++ // Act+ const result = validateSetupEntry(entry);++ // Assert+ expect(result).toEqual({ valid: true, errors: [] });+ });++ it("admits selectable actions where every action carries its own repo-picker", () => {+ // Arrange — no shared picker, but each action supplies one.+ const entry = createSetupEntry({+ setup: createSetup({+ prompt: undefined,+ form: { triggers: { event: eventFields }, args },+ actions: {+ prompt: {+ label: "Prompt",+ help: "Run a prompt.",+ features: ["presetPrompt"],+ args: { repository: repoPicker },+ prompt: "{{form.repository}}",+ },+ plugin: {+ label: "Plugin",+ help: "Run a plugin.",+ features: ["presetPlugin"],+ args: { repository: repoPicker },+ prompt: "{{form.repository}}",+ plugins: "{{form.repository}}",+ },+ },+ }),+ });++ // Act+ const result = validateSetupEntry(entry);++ // Assert+ expect(result).toEqual({ valid: true, errors: [] });+ });++ it("refuses a repo-picker in the cron trigger group as the event source (cross-trigger leakage)", () => {+ // Arrange — `buildTrigger` reads the picker only from the event trigger+ // (or shared args), so a picker that lives under `cron` is invisible to+ // the event trigger and leaves `source` empty.+ const entry = createSetupEntry({+ setup: createSetup({+ form: {+ triggers: {+ cron: {+ schedule: {+ type: "cron",+ label: "Frequency",+ help: "How often.",+ required: true,+ },+ repository: repoPicker,+ },+ event: eventFields,+ },+ args,+ },+ prompt: "Report on {{form.repository}}.",+ }),+ });++ // Act+ const result = validateSetupEntry(entry);++ // Assert+ expect(result.valid).toBe(false);+ expect(result.errors).toEqual([+ "setup.form.triggers.event: must declare an event source field or repository picker",+ ]);+ });++ it("refuses a repo-picker on only one of several selectable actions (cross-action leakage)", () => {+ // Arrange — the `prompt` action has a repo-picker, but `upload` does not;+ // selecting `upload` derives `source: ""`, and no field can fix it.+ const entry = createSetupEntry({+ setup: createSetup({+ prompt: undefined,+ form: { triggers: { event: eventFields }, args },+ actions: {+ prompt: {+ label: "Prompt",+ help: "Run a prompt.",+ features: ["presetPrompt"],+ args: { repository: repoPicker },+ prompt: "{{form.repository}}",+ },+ upload: {+ label: "Upload tarball",+ help: "Upload a tarball.",+ features: ["customTarball"],+ args: {+ tarball: {+ type: "tarball-upload",+ label: "Tarball",+ help: "Archive to upload.",+ required: true,+ },+ entrypoint: {+ type: "text",+ label: "Entrypoint",+ help: "Command to run.",+ default: "python3 main.py",+ required: true,+ },+ },+ tarballPath: "tarball.tar",+ entrypoint: "python3 main.py",+ },+ },+ }),+ });++ // Act+ const result = validateSetupEntry(entry);++ // Assert+ expect(result.valid).toBe(false);+ expect(result.errors).toEqual([+ "setup.form.triggers.event: must declare an event source field or repository picker",+ ]);+ });+ });});diff --git a/__tests__/utils/recommended-automation-rail.test.ts b/__tests__/utils/recommended-automation-rail.test.tsindex 800fa7f224..d93b56811f 100644--- a/__tests__/utils/recommended-automation-rail.test.ts+++ b/__tests__/utils/recommended-automation-rail.test.ts@@ -49,6 +49,7 @@ describe("recommended automation rail", () => {]);expect(groups.proven.map((entry) => entry.id)).toEqual([+ "custom-automation","github-issue-to-pr","slack-channel-monitor","github-agents-md-maintainer",@@ -62,6 +63,7 @@ describe("recommended automation rail", () => {expect(groups.proven.map((entry) => entry.id)).toEqual(["github-pr-reviewer",+ "custom-automation","github-issue-to-pr","slack-channel-monitor","github-agents-md-maintainer",@@ -94,6 +96,7 @@ describe("recommended automation rail", () => {const groups = getRecommendedRailGroups([{ name: "GitHub Code Review Agent" },{ name: "GitHub Issue to PR Agent" },+ { name: "Custom automation" },{ name: "Slack channel monitor" },{ name: "AGENTS.md Maintainer" },{ name: "Daily news digest" },diff --git a/package-lock.json b/package-lock.jsonindex c8e1aa75a2..b58a2cd7d5 100644--- a/package-lock.json+++ b/package-lock.json@@ -13,7 +13,7 @@"@heroui/react": "2.8.10","@microlink/react-json-view": "1.31.25","@monaco-editor/react": "4.7.0",- "@openhands/extensions": "0.19.0",+ "@openhands/extensions": "0.20.0","@openhands/typescript-client": "1.39.0","@react-router/node": "7.18.2","@react-router/serve": "7.18.2",@@ -4164,9 +4164,9 @@"license": "MIT"},"node_modules/@openhands/extensions": {- "version": "0.19.0",- "resolved": "https://registry.npmjs.org/@openhands/extensions/-/extensions-0.19.0.tgz",- "integrity": "sha512-nT0jTxvVUmiCcKjg2lLYAUUAYFFFbMivZuCjj8qxOIXs6yePVANEpt8HkLe5ViCEweRsbIokfDwcnjQDzVhQ6w==",+ "version": "0.20.0",+ "resolved": "https://registry.npmjs.org/@openhands/extensions/-/extensions-0.20.0.tgz",+ "integrity": "sha512-1FdkXr4GOUgJ/Pvh3X0obIDghquHYOAK0iJqfsBydEnjdiYUytQ1bLcY30DuuZqggEpKN0jeUVKhHwFMLMSVZQ==","license": "MIT","engines": {"node": ">=18.20.0"diff --git a/package.json b/package.jsonindex 1969a3303c..ab2286bba9 100644--- a/package.json+++ b/package.json@@ -23,7 +23,7 @@"@heroui/react": "2.8.10","@microlink/react-json-view": "1.31.25","@monaco-editor/react": "4.7.0",- "@openhands/extensions": "0.19.0",+ "@openhands/extensions": "0.20.0","@openhands/typescript-client": "1.39.0","@react-router/node": "7.18.2","@react-router/serve": "7.18.2",diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.tsindex f3584595f8..3f86940809 100644--- a/src/api/automation-service/automation-service.api.ts+++ b/src/api/automation-service/automation-service.api.ts@@ -589,11 +589,15 @@ class AutomationService {*/static async createAutomationDraft(body: SetupRequestBody,- /** The entry the draft came from, which decides the create endpoint. */+ /** The entry and selected action decide the create endpoint. */entry?: SetupEntry,+ selectedAction?: string | null,): Promise<Record<string, unknown>> {const active = getActiveBackend().backend;- const path = `${AUTOMATION_BASE_PATH}${automationCreateEndpoint(entry)}`;+ const path = `${AUTOMATION_BASE_PATH}${automationCreateEndpoint(+ entry,+ selectedAction,+ )}`;if (active.kind === "cloud") {return callCloudProxy<Record<string, unknown>>({diff --git a/src/components/features/manifest/manifest-form-field.tsx b/src/components/features/manifest/manifest-form-field.tsxindex 16ee5f1158..94f344da54 100644--- a/src/components/features/manifest/manifest-form-field.tsx+++ b/src/components/features/manifest/manifest-form-field.tsx@@ -4,7 +4,10 @@ import { SettingsDropdownInput } from "#/components/features/settings/settings-dimport { GitRepoDropdown } from "#/components/features/home/git-repo-dropdown";import { useActiveBackend } from "#/contexts/active-backend-context";import { I18nKey } from "#/i18n/declaration";-import { formControlMultilineFieldClassName } from "#/utils/form-control-classes";+import {+ formControlMultilineFieldClassName,+ formControlSettingsFieldClassName,+} from "#/utils/form-control-classes";import { cn } from "#/utils/utils";import type { GitRepository } from "#/types/git";import { fieldText, fieldValues } from "#/manifests/manifest-local-validation";@@ -25,6 +28,8 @@ export interface SetupFormFieldProps {error?: string;/** Declared options, or the ones the deployment supplied. */options: SetupFieldOption[];+ /** Whether dynamic options for this field are still loading. */+ isOptionsLoading?: boolean;/** The picked repository, kept so the picker can show what is selected. */repository: GitRepository | null;disabled: boolean;@@ -47,6 +52,7 @@ export function SetupFormField({value,error,options,+ isOptionsLoading = false,repository,disabled,onChange,@@ -111,13 +117,20 @@ export function SetupFormField({);}- // A timezone field declares no options of its own: the accepted zones are the- // deployment's, so it renders as a list once they are known and as a plain- // input when they are not.- if (+ // A timezone or event field declares no options of its own: the accepted+ // values are the deployment's, so it renders as a list once they are known and+ // as a plain input when they are not. LLM profiles are different: they are a+ // semantic closed set owned by the current backend, so an unavailable list is+ // still shown as a disabled dropdown rather than an unrestricted text input.+ const shouldRenderDropdown =field.type === "select" ||- (field.type === "timezone" && options.length > 0)- ) {+ field.type === "llm-profile" ||+ (["timezone", "event-source", "event-type"].includes(field.type) &&+ options.length > 0);+ if (shouldRenderDropdown) {+ const hasOptions = options.length > 0;+ const profileOptionsUnavailable =+ field.type === "llm-profile" && !isOptionsLoading && !hasOptions;return (<div className="flex w-full flex-col gap-2.5"><SettingsDropdownInput@@ -129,8 +142,13 @@ export function SetupFormField({label: option.label,}))}selectedKey={fieldText(value) || undefined}- placeholder={field.placeholder}- isDisabled={disabled}+ placeholder={+ profileOptionsUnavailable+ ? t(I18nKey.MODEL$NO_SAVED_PROFILES)+ : field.placeholder+ }+ isDisabled={disabled || profileOptionsUnavailable}+ isLoading={isOptionsLoading}required={field.required}onSelectionChange={(key) => {onChange(key === null ? "" : String(key));@@ -143,6 +161,61 @@ export function SetupFormField({);}+ if (field.type === "plugin-sources") {+ return (+ <label className="flex w-full flex-col gap-2.5">+ <FieldLabelText field={field} />+ <textarea+ data-testid={testId}+ name={name}+ rows={4}+ value={fieldText(value)}+ placeholder={field.placeholder}+ disabled={disabled}+ aria-invalid={!!error}+ onChange={(event) => onChange(event.target.value)}+ onBlur={onBlur}+ className={cn(+ formControlMultilineFieldClassName,+ error && "border-red-500",+ )}+ />+ <FieldError testId={testId} error={error} />+ {help}+ </label>+ );+ }++ if (field.type === "tarball-upload") {+ return (+ <div className="flex w-full flex-col gap-2.5">+ <FieldLabel field={field} />+ <input+ data-testid={testId}+ name={name}+ type="file"+ accept=".tar,.tar.gz,.tgz,application/gzip,application/x-tar"+ disabled={disabled}+ aria-invalid={!!error}+ onChange={(event) => {+ onChange(event.target.files?.[0] ?? "");+ onBlur();+ }}+ className={cn(+ formControlSettingsFieldClassName,+ "file:mr-3 file:rounded-md file:border-0 file:bg-neutral-700 file:px-3 file:py-1.5 file:text-sm file:text-white",+ error && "border-red-500",+ )}+ />+ {fieldText(value) && (+ <p className="text-xs text-[var(--oh-muted)]">{fieldText(value)}</p>+ )}+ <FieldError testId={testId} error={error} />+ {help}+ </div>+ );+ }+if (field.type === "textarea") {return (<label className="flex w-full flex-col gap-2.5">@@ -181,11 +254,13 @@ export function SetupFormField({<SettingsInputtestId={testId}name={name}- type="text"+ type={field.type === "number" ? "number" : "text"}label={field.label}value={fieldText(value)}placeholder={placeholder}isDisabled={disabled}+ min={field.constraints?.min}+ max={field.constraints?.max}showRequiredTag={field.required}error={error}onChange={onChange}diff --git a/src/components/features/manifest/manifest-review-step.tsx b/src/components/features/manifest/manifest-review-step.tsxindex 8b8f42dc03..be6e71588b 100644--- a/src/components/features/manifest/manifest-review-step.tsx+++ b/src/components/features/manifest/manifest-review-step.tsx@@ -9,6 +9,8 @@ import type { SetupBlock, SetupFormValues } from "#/manifests/types";export interface SetupReviewStepProps {setup: SetupBlock;values: SetupFormValues;+ selectedTrigger?: string | null;+ selectedAction?: string | null;}/**@@ -19,13 +21,34 @@ export interface SetupReviewStepProps {* row per declared field, labelled the way the field was labelled, says the* same thing without asking every entry to restate it.*/-export function SetupReviewStep({ setup, values }: SetupReviewStepProps) {+export function SetupReviewStep({+ setup,+ values,+ selectedTrigger,+ selectedAction,+}: SetupReviewStepProps) {const { t } = useTranslation("openhands");return (<div className="flex flex-col gap-4" data-testid="setup-review"><dl className="flex flex-col gap-3">- {Object.entries(collectFields(setup)).map(([name, field]) => (+ {selectedAction &&+ setup.actions?.[selectedAction as keyof typeof setup.actions] && (+ <div className="flex flex-col gap-0.5">+ <dt className="text-xs text-[var(--oh-muted)]">+ {t(I18nKey.SETUP$ACTION_LABEL)}+ </dt>+ <dd className="text-sm break-words">+ {+ setup.actions[selectedAction as keyof typeof setup.actions]+ ?.label+ }+ </dd>+ </div>+ )}+ {Object.entries(+ collectFields(setup, selectedTrigger, selectedAction),+ ).map(([name, field]) => (<div key={name} className="flex flex-col gap-0.5"><dt className="text-xs text-[var(--oh-muted)]">{field.label}</dt><dd className="text-sm break-words">diff --git a/src/components/features/manifest/manifest-setup-dialog.tsx b/src/components/features/manifest/manifest-setup-dialog.tsxindex e326911ee7..d340a00aae 100644--- a/src/components/features/manifest/manifest-setup-dialog.tsx+++ b/src/components/features/manifest/manifest-setup-dialog.tsx@@ -4,6 +4,7 @@ import { useNavigate } from "react-router";import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";import { ModalCloseButton } from "#/components/shared/modals/modal-close-button";import { BrandButton } from "#/components/features/settings/brand-button";+import { SettingsDropdownInput } from "#/components/features/settings/settings-dropdown-input";import { LoadingSpinner } from "#/components/shared/loading-spinner";import { I18nKey } from "#/i18n/declaration";import { cn } from "#/utils/utils";@@ -12,18 +13,27 @@ import { getApiErrorBody } from "#/utils/api-error-message";import { useTracking } from "#/hooks/use-tracking";import { useSetupCapabilities } from "#/hooks/query/use-manifest-capabilities";import { useSetupPrerequisites } from "#/hooks/query/use-manifest-prerequisites";+import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";import { useSetupPreflight } from "#/hooks/use-manifest-preflight";import { useSetupAction } from "#/manifests/manifest-actions";+import {+ supportedActionKinds,+ supportedTriggerKinds,+} from "#/manifests/manifest-capabilities";import {buildCreatePayload,deriveErrorMap,missingCreateEndpoints,} from "#/manifests/automation-setup";import {+ actionKinds,collectFields,getFieldOptions,getInitialFormValues,+ initialActionKind,+ initialTriggerKind,resolveFieldOverrides,+ triggerKinds,validateFormValues,type SetupFieldError,type SetupFieldErrors,@@ -101,8 +111,26 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {} = useTracking();const [step, setStep] = useState<SetupStep>("prerequisites");+ const allTriggerOptions = useMemo(() => triggerKinds(entry.setup), [entry]);+ const triggerOptions = useMemo(() => {+ if (allTriggerOptions.length === 0) return [];+ return capabilities.capabilities+ ? supportedTriggerKinds(entry, capabilities.capabilities)+ : allTriggerOptions;+ }, [allTriggerOptions, capabilities.capabilities, entry]);+ const allActionOptions = useMemo(() => actionKinds(entry.setup), [entry]);+ const [selectedTrigger, setSelectedTrigger] = useState<string | null>(() =>+ initialTriggerKind(entry.setup),+ );+ const [selectedAction, setSelectedAction] = useState<string | null>(() =>+ initialActionKind(entry.setup),+ );const [values, setValues] = useState<SetupFormValues>(() =>- getInitialFormValues(entry.setup),+ getInitialFormValues(+ entry.setup,+ initialTriggerKind(entry.setup),+ initialActionKind(entry.setup),+ ),);const [repositories, setRepositories] = useState<Record<string, GitRepository | null>@@ -123,16 +151,76 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {[],);- const fields = useMemo(() => collectFields(entry.setup), [entry]);- const overrides = useMemo(- () => resolveFieldOverrides(entry.setup, capabilities.capabilities),- [entry, capabilities.capabilities],+ const actionOptions = useMemo(() => {+ if (allActionOptions.length === 0) return [];+ const supported = capabilities.capabilities+ ? supportedActionKinds(entry, capabilities.capabilities)+ : allActionOptions;+ return supported.filter(+ (kind) => missingCreateEndpoints(entry, kind).length === 0,+ );+ }, [allActionOptions, capabilities.capabilities, entry]);++ const fields = useMemo(+ () => collectFields(entry.setup, selectedTrigger, selectedAction),+ [entry, selectedTrigger, selectedAction],+ );+ const hasLlmProfileField = useMemo(+ () => Object.values(fields).some((field) => field.type === "llm-profile"),+ [fields],);+ const { data: profilesData, isLoading: isLoadingProfiles } = useLlmProfiles({+ enabled: hasLlmProfileField,+ });+ const llmProfileOptions = useMemo(+ () =>+ (profilesData?.profiles ?? []).map((profile) => ({+ value: profile.name,+ label: profile.name,+ })),+ [profilesData?.profiles],+ );+ const overrides = useMemo(() => {+ const base = resolveFieldOverrides(+ entry.setup,+ capabilities.capabilities,+ selectedTrigger,+ selectedAction,+ );+ if (!hasLlmProfileField || isLoadingProfiles) return base;++ return Object.entries(fields).reduce(+ (next, [fieldName, field]) =>+ field.type === "llm-profile"+ ? { ...next, [fieldName]: { options: llmProfileOptions } }+ : next,+ base,+ );+ }, [+ entry.setup,+ capabilities.capabilities,+ selectedTrigger,+ selectedAction,+ hasLlmProfileField,+ isLoadingProfiles,+ fields,+ llmProfileOptions,+ ]);const payload = useMemo(- () => buildCreatePayload(entry, values),- [entry, values],+ () =>+ buildCreatePayload(+ entry,+ values,+ undefined,+ selectedTrigger,+ selectedAction,+ ),+ [entry, values, selectedTrigger, selectedAction],+ );+ const errorMap = useMemo(+ () => deriveErrorMap(entry, selectedTrigger, selectedAction),+ [entry, selectedTrigger, selectedAction],);- const errorMap = useMemo(() => deriveErrorMap(entry), [entry]);const emittedOpenRef = useRef(false);useEffect(() => {@@ -147,8 +235,8 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {// them. Named alongside the deployment's own unmet requirements, because// "which one" is the only thing that makes either diagnosable.const missingEndpoints = useMemo(- () => missingCreateEndpoints(entry),- [entry],+ () => missingCreateEndpoints(entry, selectedAction),+ [entry, selectedAction],);const isUnsupported =capabilities.supported === false || missingEndpoints.length > 0;@@ -161,6 +249,51 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {const currentStep: SetupStep =step === "prerequisites" && !showPrerequisites ? "form" : step;+ const setTriggerValue = (kind: string) => {+ setSelectedTrigger(kind);+ const defaults = getInitialFormValues(entry.setup, kind, selectedAction);+ valuesRef.current = { ...defaults, ...valuesRef.current };+ setValues(valuesRef.current);+ setLocalErrors({});+ setServiceErrors(NO_SERVICE_ERRORS);+ };++ const setActionValue = (kind: string) => {+ setSelectedAction(kind);+ const defaults = getInitialFormValues(entry.setup, selectedTrigger, kind);+ valuesRef.current = { ...defaults, ...valuesRef.current };+ setValues(valuesRef.current);+ setLocalErrors({});+ setServiceErrors(NO_SERVICE_ERRORS);+ };++ useEffect(() => {+ if (allTriggerOptions.length === 0 || capabilities.isLoading) return;+ if (selectedTrigger && triggerOptions.includes(selectedTrigger)) return;+ if (triggerOptions.length > 0) setTriggerValue(triggerOptions[0]);+ }, [+ triggerOptions,+ allTriggerOptions.length,+ capabilities.isLoading,+ selectedTrigger,+ ]);++ useEffect(() => {+ if (allActionOptions.length === 0 || capabilities.isLoading) return;+ if (+ selectedAction &&+ actionOptions.includes(selectedAction as (typeof actionOptions)[number])+ ) {+ return;+ }+ if (actionOptions.length > 0) setActionValue(actionOptions[0]);+ }, [+ actionOptions,+ allActionOptions.length,+ capabilities.isLoading,+ selectedAction,+ ]);+const setFieldValue = (name: string, value: SetupFormValue) => {valuesRef.current = { ...valuesRef.current, [name]: value };setValues(valuesRef.current);@@ -175,7 +308,11 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {const handleFieldBlur = () => {if (blurTimerRef.current) window.clearTimeout(blurTimerRef.current);blurTimerRef.current = window.setTimeout(() => {- void runPreflight(valuesRef.current).then((result) => {+ void runPreflight(+ valuesRef.current,+ selectedTrigger,+ selectedAction,+ ).then((result) => {if (result) setServiceErrors(result);});}, PREFLIGHT_DEBOUNCE_MS);@@ -187,14 +324,20 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {return;}- const failures = validateFormValues(entry.setup, values, overrides);+ const failures = validateFormValues(+ entry.setup,+ values,+ overrides,+ selectedTrigger,+ selectedAction,+ );if (Object.keys(failures).length > 0) {setLocalErrors(failures);return;}setLocalErrors({});- const result = await runPreflight(values);+ const result = await runPreflight(values, selectedTrigger, selectedAction);if (result && hasAnyError(result)) {setServiceErrors(result);return;@@ -211,7 +354,13 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {) => {setIsSubmitting(true);try {- const { response } = await runAction(entry, values, actionPayload);+ const { response } = await runAction(+ entry,+ values,+ actionPayload,+ selectedTrigger,+ selectedAction,+ );trackAutomationSetupCreated({automationId: entry.id,setupMode,@@ -259,6 +408,7 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {};const isLoading = capabilities.isLoading || prerequisites.isLoading;+ const isLoadingLlmProfileOptions = hasLlmProfileField && isLoadingProfiles;const title = (() => {if (isUnsupported) return t(I18nKey.SETUP$UNAVAILABLE_TITLE);@@ -325,6 +475,62 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {{entry.setup.form.note}</p>)}+ {allActionOptions.length > 1 && actionOptions.length > 1 && (+ <div className="flex w-full flex-col gap-2.5">+ <SettingsDropdownInput+ testId="setup-action-kind"+ name="actionKind"+ label={t(I18nKey.SETUP$ACTION_LABEL)}+ items={actionOptions.map((kind) => {+ const action = entry.setup.actions?.[kind];+ return {+ key: kind,+ label: action?.label ?? kind,+ };+ })}+ selectedKey={selectedAction ?? undefined}+ isDisabled={isSubmitting}+ required+ onSelectionChange={(key) => {+ if (key !== null) setActionValue(String(key));+ }}+ />+ {selectedAction &&+ entry.setup.actions?.[+ selectedAction as keyof typeof entry.setup.actions+ ] && (+ <p className="text-xs text-[var(--oh-muted)]">+ {+ entry.setup.actions[+ selectedAction as keyof typeof entry.setup.actions+ ]?.help+ }+ </p>+ )}+ </div>+ )}+ {triggerOptions.length > 1 && (+ <div className="flex w-full flex-col gap-2.5">+ <SettingsDropdownInput+ testId="setup-trigger-kind"+ name="triggerKind"+ label={t(I18nKey.SETUP$TRIGGER_LABEL)}+ items={triggerOptions.map((kind) => ({+ key: kind,+ label: kind === "cron" ? "Scheduled" : "Event",+ }))}+ selectedKey={selectedTrigger ?? undefined}+ isDisabled={isSubmitting}+ required+ onSelectionChange={(key) => {+ if (key !== null) setTriggerValue(String(key));+ }}+ />+ <p className="text-xs text-[var(--oh-muted)]">+ {t(I18nKey.SETUP$TRIGGER_HELP)}+ </p>+ </div>+ )}{Object.entries(fields).map(([name, field]) => (<SetupFormFieldkey={name}@@ -335,6 +541,9 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {options={getFieldOptions(name, field, overrides)}repository={repositories[name] ?? null}disabled={isSubmitting}+ isOptionsLoading={+ field.type === "llm-profile" && isLoadingLlmProfileOptions+ }onChange={(value) => setFieldValue(name, value)}onRepositoryChange={(repository) =>setRepositories((current) => ({@@ -349,7 +558,12 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {)}{!isLoading && !isUnsupported && currentStep === "review" && (- <SetupReviewStep setup={entry.setup} values={values} />+ <SetupReviewStep+ setup={entry.setup}+ values={values}+ selectedTrigger={selectedTrigger}+ selectedAction={selectedAction}+ />)}{serviceErrors.formErrors.map((message) => (@@ -406,6 +620,7 @@ export function SetupDialog({ entry, onClose }: SetupDialogProps) {variant="primary"isDisabled={isLoading ||+ isLoadingLlmProfileOptions ||isSubmitting ||(currentStep === "prerequisites" && prerequisites.isBlocked)}@@ -435,6 +650,10 @@ function formatFieldError(return t(I18nKey.SETUP$VALIDATION_MIN_LENGTH, { length: error.length });case "maxLength":return t(I18nKey.SETUP$VALIDATION_MAX_LENGTH, { length: error.length });+ case "min":+ return `Must be at least ${error.value}.`;+ case "max":+ return `Must be at most ${error.value}.`;case "invalidOption":return t(I18nKey.SETUP$VALIDATION_INVALID_OPTION);case "unsafeExpressionLiteral":diff --git a/src/hooks/use-manifest-preflight.ts b/src/hooks/use-manifest-preflight.tsindex 7139477024..8971998f7f 100644--- a/src/hooks/use-manifest-preflight.ts+++ b/src/hooks/use-manifest-preflight.ts@@ -1,4 +1,4 @@-import { useCallback, useMemo, useRef } from "react";+import { useCallback, useRef } from "react";import axios from "axios";import AutomationService from "#/api/automation-service/automation-service.api";import { isSdkHttpStatusError } from "#/api/agent-server-compatibility";@@ -52,11 +52,12 @@ function isPreflightUnimplemented(error: unknown): boolean {*/export function useSetupPreflight(entry: SetupEntry) {const latestRequestRef = useRef(0);- const errorMap = useMemo(() => deriveErrorMap(entry), [entry]);return useCallback(async (formValues: SetupFormValues,+ selectedTrigger?: string | null,+ selectedAction?: string | null,): Promise<MappedManifestErrors | null> => {try {// Deriving the body is inside the guard too: a bundle entry resolves@@ -65,7 +66,12 @@ export function useSetupPreflight(entry: SetupEntry) {// validator that will not answer, and left outside it rejected a// promise no caller handles - which reads as a Continue button that// does nothing at all.- const body = buildPreflightBody(entry, formValues);+ const body = buildPreflightBody(+ entry,+ formValues,+ selectedTrigger,+ selectedAction,+ );if (!body) return null;latestRequestRef.current += 1;@@ -77,7 +83,7 @@ export function useSetupPreflight(entry: SetupEntry) {return mapServiceErrors(normalizeServiceErrors(result, body.draft as SetupRequestBody),- errorMap,+ deriveErrorMap(entry, selectedTrigger, selectedAction),);} catch (error) {// A broken validator and an unimplemented one degrade to the same@@ -89,6 +95,6 @@ export function useSetupPreflight(entry: SetupEntry) {return null;}},- [entry, errorMap],+ [entry],);}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex d131b02dcc..728c4e75a2 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -37435,6 +37435,57 @@"uk": "Перевірка","ca": "Revisa"},+ "SETUP$ACTION_LABEL": {+ "en": "Action",+ "ja": "アクション",+ "zh-CN": "操作",+ "zh-TW": "動作",+ "ko-KR": "작업",+ "no": "Handling",+ "it": "Azione",+ "pt": "Ação",+ "es": "Acción",+ "ar": "الإجراء",+ "fr": "Action",+ "tr": "Eylem",+ "de": "Aktion",+ "uk": "Дія",+ "ca": "Acció"+ },+ "SETUP$TRIGGER_LABEL": {+ "en": "Trigger",+ "ja": "トリガー",+ "zh-CN": "触发器",+ "zh-TW": "觸發條件",+ "ko-KR": "트리거",+ "no": "Utløser",+ "it": "Attivatore",+ "pt": "Acionador",+ "es": "Activador",+ "ar": "المشغّل",+ "fr": "Déclencheur",+ "tr": "Tetikleyici",+ "de": "Auslöser",+ "uk": "Тригер",+ "ca": "Activador"+ },+ "SETUP$TRIGGER_HELP": {+ "en": "Choose whether the automation runs on a schedule or when an event arrives.",+ "ja": "自動化をスケジュールで実行するか、イベント到着時に実行するかを選択します。",+ "zh-CN": "选择自动化是按计划运行还是在事件到达时运行。",+ "zh-TW": "選擇自動化要依排程執行,還是在事件到達時執行。",+ "ko-KR": "자동화가 일정에 따라 실행될지 이벤트가 도착할 때 실행될지 선택하세요.",+ "no": "Velg om automatiseringen skal kjøre etter en tidsplan eller når en hendelse kommer.",+ "it": "Scegli se l'automazione viene eseguita in base a una pianificazione o quando arriva un evento.",+ "pt": "Escolha se a automatização é executada em uma agenda ou quando um evento chega.",+ "es": "Elige si la automatización se ejecuta con una programación o cuando llega un evento.",+ "ar": "اختر ما إذا كانت الأتمتة تعمل وفق جدول زمني أو عند وصول حدث.",+ "fr": "Choisissez si l'automatisation s'exécute selon un planning ou lorsqu'un événement arrive.",+ "tr": "Otomasyonun bir zamanlamaya göre mi yoksa bir olay geldiğinde mi çalışacağını seçin.",+ "de": "Wählen Sie, ob die Automatisierung nach Zeitplan oder beim Eintreffen eines Ereignisses ausgeführt wird.",+ "uk": "Виберіть, чи автоматизація запускатиметься за розкладом, чи коли надходить подія.",+ "ca": "Trieu si l'automatització s'executa segons una planificació o quan arriba un esdeveniment."+ },"SETUP$CONFIRM": {"en": "Confirm and create","ja": "確認して作成",diff --git a/src/manifests/automation-setup.test.ts b/src/manifests/automation-setup.test.tsnew file mode 100644index 0000000000..138095c85a--- /dev/null+++ b/src/manifests/automation-setup.test.ts@@ -0,0 +1,111 @@+import { AUTOMATION_CATALOG } from "@openhands/extensions/automations";+import customAutomationFixture from "@openhands/extensions/testing/automations/custom-automation.json";+import { describe, expect, it } from "vitest";+import { buildCreatePayload, buildPreflightBody } from "./automation-setup";+import type { SetupEntry, SetupFormValues, SetupRequestBody } from "./types";+import { validateSetupEntry } from "./manifest-validation";++const customAutomation = AUTOMATION_CATALOG.find(+ (entry) => entry.id === "custom-automation",+) as SetupEntry | undefined;++describe("custom automation setup actions", () => {+ it("admits the custom automation action manifest", () => {+ expect(customAutomation).toBeDefined();+ expect(validateSetupEntry(customAutomation).errors).toEqual([]);+ });++ it.each(customAutomationFixture.scenarios)(+ "derives the $id preflight and create payloads",+ (scenario) => {+ expect(customAutomation).toBeDefined();+ const formValues = scenario.formValues as unknown as SetupFormValues;+ const createBody = scenario.create.request+ .body as unknown as SetupRequestBody;+ const tarballPath =+ typeof createBody.tarball_path === "string"+ ? createBody.tarball_path+ : undefined;++ expect(+ buildPreflightBody(+ customAutomation!,+ formValues,+ scenario.selectedTrigger,+ scenario.selectedAction,+ ),+ ).toEqual(scenario.preflight.request.body);+ expect(+ buildCreatePayload(+ customAutomation!,+ formValues,+ tarballPath,+ scenario.selectedTrigger,+ scenario.selectedAction,+ ),+ ).toEqual(createBody);+ },+ );++ it("keeps event filters rendered from non-filter form fields", () => {+ const entry: SetupEntry = {+ id: "mention-responder",+ name: "Mention responder",+ description: "Respond to matching comments.",+ requires: { integrations: {} },+ setup: {+ version: "1.0",+ mode: "direct",+ form: {+ triggers: {+ event: {+ source: {+ type: "event-source",+ label: "Source",+ help: "Where events come from.",+ required: true,+ },+ on: {+ type: "event-type",+ label: "Event",+ help: "Which event to watch.",+ required: true,+ },+ mention: {+ type: "text",+ label: "Mention",+ help: "Text that must appear in the comment.",+ required: true,+ },+ },+ },+ args: {},+ },+ prompt: "Handle {{form.mention}}.",+ filter: "icontains(comment.body, '{{form.mention}}')",+ },+ };++ expect(+ buildCreatePayload(+ entry,+ {+ source: "github",+ on: "issue_comment.created",+ mention: "@openhands",+ },+ undefined,+ "event",+ ),+ ).toEqual({+ name: "Mention responder",+ prompt: "Handle @openhands.",+ trigger: {+ type: "event",+ source: "github",+ on: "issue_comment.created",+ filter: "icontains(comment.body, '@openhands')",+ },+ });+ });+});diff --git a/src/manifests/automation-setup.ts b/src/manifests/automation-setup.tsindex ed4ca331ac..5864acedc4 100644--- a/src/manifests/automation-setup.ts+++ b/src/manifests/automation-setup.ts@@ -18,12 +18,14 @@ import { I18nKey } from "#/i18n/declaration";import { findAutomationCommand } from "#/utils/automation-catalog";import { getAutomationEndpoint } from "./automation-interface";import {+ actionKinds,collectFields,fieldText,fieldValues,} from "./manifest-local-validation";import { interpolateText, interpolateValue } from "./manifest-template";import type {+ SetupActionKind,SetupBlock,SetupBundleConfigValue,SetupEntry,@@ -41,8 +43,13 @@ import type {* a tarball it uploaded rather than arguments to a preset. Called without an* entry - as the import path does - it answers for a prompt.*/-export function automationCreateEndpoint(entry?: SetupEntry): string {- if (entry && isBundleEntry(entry)) {+export function automationCreateEndpoint(+ entry?: SetupEntry,+ selectedAction?: string | null,+): string {+ const kind = selectedActionKind(entry, selectedAction);+ if (kind === "plugin") return getAutomationEndpoint("createPlugin");+ if (kind === "upload" || kind === "bundle") {return requireBundleEndpoint("createBundle");}return getAutomationEndpoint("createPrompt");@@ -83,9 +90,28 @@ function requireBundleEndpoint(* entry that is not a bundle, which needs nothing beyond what the block has* always declared.*/-export function missingCreateEndpoints(entry: SetupEntry): string[] {- if (!isBundleEntry(entry)) return [];- return BUNDLE_ENDPOINTS.filter((name) => !getAutomationEndpoint(name));+function missingEndpointsForAction(kind: SetupActionKind | "bundle"): string[] {+ return kind === "upload" || kind === "bundle"+ ? BUNDLE_ENDPOINTS.filter((name) => !getAutomationEndpoint(name))+ : [];+}++export function missingCreateEndpoints(+ entry: SetupEntry,+ selectedAction?: string | null,+): string[] {+ if (isBundleEntry(entry)) return missingEndpointsForAction("bundle");+ if (!entry.setup.actions) return [];++ if (selectedAction && selectedAction in entry.setup.actions) {+ return missingEndpointsForAction(selectedAction as SetupActionKind);+ }++ const missingByAction = actionKinds(entry.setup).map(+ missingEndpointsForAction,+ );+ if (missingByAction.some((missing) => missing.length === 0)) return [];+ return Array.from(new Set(missingByAction.flat()));}/** Whether this entry ships a script tarball instead of a prompt. */@@ -93,6 +119,28 @@ export function isBundleEntry(entry: SetupEntry): boolean {return entry.setup.mode === "direct" && entry.setup.bundle !== undefined;}+export function isUploadAction(+ entry: SetupEntry,+ selectedAction?: string | null,+): boolean {+ return selectedActionKind(entry, selectedAction) === "upload";+}++export function selectedActionKind(+ entry: SetupEntry | undefined,+ selectedAction?: string | null,+): SetupActionKind | "bundle" | "prompt" {+ if (!entry) return "prompt";+ if (isBundleEntry(entry)) return "bundle";+ const actions = entry.setup.actions ?? {};+ if (selectedAction && selectedAction in actions) {+ return selectedAction as SetupActionKind;+ }+ const keys = actionKinds(entry.setup);+ if (keys.length === 1) return keys[0];+ return "prompt";+}+/*** The `tarball_path` a preflight draft carries.*@@ -112,9 +160,11 @@ export const PREFLIGHT_TARBALL_PATH =*/const TRIGGER_PROPERTIES: Record<SetupTriggerKind, readonly string[]> = {cron: ["schedule", "timezone"],- event: ["on"],+ event: ["source", "on"],};+const OPTIONAL_CREATE_PROPERTIES = ["model", "timeout"] as const;+/*** Repository properties a form field may fill, read the same way* {@link TRIGGER_PROPERTIES} is: a field whose name is listed here fills the@@ -131,16 +181,23 @@ const REPO_PROPERTIES: readonly string[] = ["ref"];const FORM_PLACEHOLDER_PATTERN = /\{\{form\.([A-Za-z0-9_.]+)\}\}/g;/** The repository input, which supplies `repos` and an event trigger's source. */-function findRepoPickerField(setup: SetupBlock) {- const match = Object.entries(collectFields(setup)).find(+function findRepoPickerField(+ setup: SetupBlock,+ selectedAction?: string | null,+) {+ const match = Object.entries(collectFields(setup, null, selectedAction)).find(([, field]) => field.type === "repo-picker",);return match ? { name: match[0], field: match[1] } : null;}/** Every repository the form collected, whether the picker takes one or many. */-function repositories(setup: SetupBlock, values: SetupFormValues): string[] {- const picker = findRepoPickerField(setup);+function repositories(+ setup: SetupBlock,+ values: SetupFormValues,+ selectedAction?: string | null,+): string[] {+ const picker = findRepoPickerField(setup, selectedAction);return picker ? fieldValues(values[picker.name]) : [];}@@ -150,8 +207,19 @@ function repositories(setup: SetupBlock, values: SetupFormValues): string[] {* One repository is worth naming; several are not, so the count stands in* rather than a list of names that would not fit.*/-function deriveName(entry: SetupEntry, values: SetupFormValues): string {- const repos = repositories(entry.setup, values);+function deriveName(+ entry: SetupEntry,+ values: SetupFormValues,+ selectedAction?: string | null,+): string {+ if (+ "name" in collectFields(entry.setup, null, selectedAction) &&+ "name" in values+ ) {+ return fieldText(values.name);+ }++ const repos = repositories(entry.setup, values, selectedAction);if (repos.length === 0) return entry.name;if (repos.length === 1) return `${entry.name} - ${repos[0]}`;// The count is the one word here the host writes rather than reads off the@@ -163,14 +231,107 @@ function deriveName(entry: SetupEntry, values: SetupFormValues): string {return `${entry.name} - ${count}`;}-/** The single trigger kind a direct entry declares, with its fields. */-function getTrigger(setup: SetupBlock) {- const entries = Object.entries(setup.form.triggers ?? {});+/** The active trigger kind for a direct entry, with its fields. */+function getTrigger(setup: SetupBlock, selectedTrigger?: string | null) {+ const triggers = setup.form.triggers ?? {};+ const entries = Object.entries(triggers);if (entries.length === 0) return null;- const [kind, fields] = entries[0];+ const match =+ selectedTrigger && selectedTrigger in triggers+ ? [selectedTrigger, triggers[selectedTrigger as SetupTriggerKind]]+ : entries.length === 1+ ? entries[0]+ : null;+ if (!match) return null;+ const [kind, fields] = match;return { kind: kind as SetupTriggerKind, fields: fields ?? {} };}+function hasPayloadValue(+ value: SetupRequestBody[string] | undefined,+): value is SetupRequestBody[string] {+ return value !== undefined && value !== null && value !== "";+}++function fieldPayloadValue(+ fieldType: string | undefined,+ value: SetupFormValues[string],+) {+ if (fieldType === "number") {+ const text = fieldText(value);+ return text === "" ? undefined : Number(text);+ }+ return fieldText(value);+}++function optionalCreateProperties(+ setup: SetupBlock,+ values: SetupFormValues,+ selectedAction?: string | null,+): SetupRequestBody {+ return Object.fromEntries(+ OPTIONAL_CREATE_PROPERTIES.flatMap((name) => {+ const field = collectFields(setup, null, selectedAction)[name];+ const value = fieldPayloadValue(field?.type, values[name]);+ return hasPayloadValue(value) ? [[name, value]] : [];+ }),+ ) as SetupRequestBody;+}++function repositoryProperty(+ setup: SetupBlock,+ values: SetupFormValues,+ selectedAction?: string | null,+): SetupRequestBody {+ const repoPicker = findRepoPickerField(setup, selectedAction);+ const repos = repositories(setup, values, selectedAction);+ if (repos.length === 0 || !repoPicker?.field.provider) return {};++ const declared = REPO_PROPERTIES.filter((name) =>+ hasPayloadValue(fieldText(values[name])),+ );+ return {+ repos: repos.map((url) => ({+ url,+ ...Object.fromEntries(+ declared.map((name) => [name, fieldText(values[name])]),+ ),+ provider: repoPicker.field.provider as string,+ })),+ };+}++function parsePluginSources(+ value: SetupRequestBody[string],+): SetupRequestBody[string] {+ if (!hasPayloadValue(value) || typeof value !== "string") return value;+ const trimmed = value.trim();+ if (!trimmed) return [];+ if (trimmed.startsWith("[")) {+ try {+ return JSON.parse(trimmed) as SetupRequestBody[string];+ } catch {+ return [{ source: trimmed }];+ }+ }+ return trimmed+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean)+ .map((line) => {+ const [source, ...parts] = line.split(/\s+/);+ const plugin: Record<string, string> = { source };+ parts.forEach((part) => {+ const [key, ...raw] = part.split("=");+ const valuePart = raw.join("=");+ if ((key === "ref" || key === "repo_path") && valuePart) {+ plugin[key] = valuePart;+ }+ });+ return plugin;+ });+}+/*** The create request body these form values produce.*@@ -185,39 +346,101 @@ function getTrigger(setup: SetupBlock) {export function buildCreatePayload(entry: SetupEntry,values: SetupFormValues,- /** Bundle entries only: what the upload returned. */+ /** Bundle/upload entries only: what the upload returned. */tarballPath: string = PREFLIGHT_TARBALL_PATH,+ selectedTrigger?: string | null,+ selectedActionKey?: string | null,): SetupRequestBody | null {const { setup } = entry;if (setup.mode !== "direct") return null;- if (setup.bundle) return buildBundlePayload(entry, values, tarballPath);+ if (setup.bundle) {+ return buildBundlePayload(entry, values, tarballPath, selectedTrigger);+ }+ if (setup.actions) {+ return buildActionPayload(+ entry,+ values,+ tarballPath,+ selectedTrigger,+ selectedActionKey,+ );+ }if (!setup.prompt) return null;const scope = { form: values, automation: entry };- const repoPicker = findRepoPickerField(setup);- const repos = repositories(setup, values);const payload: SetupRequestBody = {name: deriveName(entry, values),prompt: interpolateText(setup.prompt, scope),+ ...optionalCreateProperties(setup, values),+ ...repositoryProperty(setup, values),};- if (repos.length > 0 && repoPicker?.field.provider) {- const declared = REPO_PROPERTIES.filter((name) => name in values);- payload.repos = repos.map((url) => ({- url,- ...Object.fromEntries(- declared.map((name) => [name, fieldText(values[name])]),- ),- provider: repoPicker.field.provider as string,- }));- }+ const trigger = buildTrigger(entry, values, selectedTrigger);+ if (trigger) payload.trigger = trigger;++ const template = buildTemplate(entry, values);+ if (template) payload.template = template;++ return payload;+}++function buildActionPayload(+ entry: SetupEntry,+ values: SetupFormValues,+ tarballPath: string,+ selectedTrigger?: string | null,+ selectedActionKey?: string | null,+): SetupRequestBody | null {+ const kind = selectedActionKind(entry, selectedActionKey);+ if (kind === "bundle") return null;- // A filter is optional: an entry that declares none accepts every delivered- // event, so the key is left off rather than sent empty.- const trigger = buildTrigger(entry, values);+ const setup = entry.setup;+ const scope = { form: values, automation: entry };+ const payload: SetupRequestBody = {+ name: deriveName(entry, values, selectedActionKey),+ };++ const trigger = buildTrigger(+ entry,+ values,+ selectedTrigger,+ selectedActionKey,+ );if (trigger) payload.trigger = trigger;+ Object.assign(+ payload,+ optionalCreateProperties(setup, values, selectedActionKey),+ );++ if (kind === "upload") {+ const action = setup.actions?.upload;+ if (!action) return null;+ payload.tarball_path =+ tarballPath || interpolateText(action.tarballPath, scope);+ payload.entrypoint = interpolateText(action.entrypoint, scope);+ if (action.setupScript) {+ const setupScript = interpolateText(action.setupScript, scope);+ if (hasPayloadValue(setupScript)) payload.setup_script_path = setupScript;+ }+ return payload;+ }++ const action =+ kind === "plugin" ? setup.actions?.plugin : setup.actions?.prompt;+ if (!action) return null;+ payload.prompt = interpolateText(action.prompt, scope);+ Object.assign(payload, repositoryProperty(setup, values, selectedActionKey));++ if (kind === "plugin") {+ const pluginAction = setup.actions?.plugin;+ if (!pluginAction) return null;+ payload.plugins = parsePluginSources(+ interpolateValue(pluginAction.plugins, scope),+ );+ }+const template = buildTemplate(entry, values);if (template) payload.template = template;@@ -241,7 +464,7 @@ function buildTemplate(return {id: entry.id,version: entry.version,- config: { ...values },+ config: { ...values } as SetupRequestBody,};}@@ -254,29 +477,38 @@ function buildTemplate(function buildTrigger(entry: SetupEntry,values: SetupFormValues,+ selectedTrigger?: string | null,+ selectedAction?: string | null,): SetupRequestBody | undefined {- const trigger = getTrigger(entry.setup);+ const trigger = getTrigger(entry.setup, selectedTrigger);if (!trigger) return undefined;const properties = TRIGGER_PROPERTIES[trigger.kind];const declared = Object.keys(trigger.fields).filter((name) =>properties.includes(name),);- const repoPicker = findRepoPickerField(entry.setup);+ const repoPicker = findRepoPickerField(entry.setup, selectedAction);+ const derived = Object.fromEntries(+ declared+ .map((name) => [name, fieldText(values[name])])+ .filter(([, value]) => hasPayloadValue(value)),+ );++ const filter = entry.setup.filter+ ? interpolateText(entry.setup.filter, {+ form: values,+ automation: entry,+ })+ : undefined;return {type: trigger.kind,- ...Object.fromEntries(- declared.map((name) => [name, fieldText(values[name])]),- ),+ ...derived,...(trigger.kind === "event" && {- source: repoPicker?.field.provider ?? "",- ...(entry.setup.filter && {- filter: interpolateText(entry.setup.filter, {- form: values,- automation: entry,- }),+ ...(!("source" in derived) && {+ source: repoPicker?.field.provider ?? "",}),+ ...(hasPayloadValue(filter) && { filter }),}),};}@@ -296,6 +528,7 @@ function buildBundlePayload(entry: SetupEntry,values: SetupFormValues,tarballPath: string,+ selectedTrigger?: string | null,): SetupRequestBody {const bundle = entry.setup.bundle!;const scope = { form: values, automation: entry };@@ -304,7 +537,7 @@ function buildBundlePayload(name: deriveName(entry, values),};- const trigger = buildTrigger(entry, values);+ const trigger = buildTrigger(entry, values, selectedTrigger);if (trigger) payload.trigger = trigger;payload.tarball_path = tarballPath;@@ -353,13 +586,21 @@ function interpolateConfig(export function buildPreflightBody(entry: SetupEntry,values: SetupFormValues,+ selectedTrigger?: string | null,+ selectedAction?: string | null,): SetupRequestBody | null {- const draft = buildCreatePayload(entry, values);+ const draft = buildCreatePayload(+ entry,+ values,+ PREFLIGHT_TARBALL_PATH,+ selectedTrigger,+ selectedAction,+ );if (!draft) return null;return {automationId: entry.id,- endpoint: automationCreateEndpoint(entry),+ endpoint: automationCreateEndpoint(entry, selectedAction),draft,};}@@ -400,17 +641,26 @@ function collectPlaceholderFields(value: string): string[] {* each field standing in for its own value recovers the mapping exactly, so an* entry does not declare it.*/-export function deriveErrorMap(entry: SetupEntry): Record<string, string[]> {+export function deriveErrorMap(+ entry: SetupEntry,+ selectedTrigger?: string | null,+ selectedAction?: string | null,+): Record<string, string[]> {const mapping: Record<string, string[]> = {};- const standIns = Object.fromEntries(- Object.keys(collectFields(entry.setup)).map((name) => [- name,- `{{form.${name}}}`,- ]),- );- const template = buildCreatePayload(entry, standIns);- if (!template) return mapping;+ const triggerEntries = Object.keys(entry.setup.form.triggers ?? {});+ const triggerVariants = selectedTrigger+ ? [selectedTrigger]+ : triggerEntries.length > 1+ ? triggerEntries+ : [null];++ const actionEntries = actionKinds(entry.setup);+ const actionVariants = selectedAction+ ? [selectedAction]+ : actionEntries.length > 1+ ? actionEntries+ : [null];const walk = (node: unknown, path: string): void => {if (Array.isArray(node)) {@@ -425,10 +675,31 @@ export function deriveErrorMap(entry: SetupEntry): Record<string, string[]> {}if (typeof node === "string") {const names = collectPlaceholderFields(node);- if (names.length > 0) mapping[path] = names;+ if (names.length > 0) {+ mapping[path] = Array.from(+ new Set([...(mapping[path] ?? []), ...names]),+ );+ }}};- walk(template, "");+ actionVariants.forEach((actionVariant) => {+ triggerVariants.forEach((triggerVariant) => {+ const names = Object.keys(+ collectFields(entry.setup, triggerVariant, actionVariant),+ );+ const variantStandIns = Object.fromEntries(+ names.map((name) => [name, `{{form.${name}}}`]),+ );+ const template = buildCreatePayload(+ entry,+ variantStandIns,+ actionVariant === "upload" ? "" : PREFLIGHT_TARBALL_PATH,+ triggerVariant,+ actionVariant,+ );+ if (template) walk(template, "");+ });+ });return mapping;}diff --git a/src/manifests/manifest-actions.ts b/src/manifests/manifest-actions.tsindex 444f45685d..04dabec85d 100644--- a/src/manifests/manifest-actions.ts+++ b/src/manifests/manifest-actions.ts@@ -25,15 +25,53 @@ import {buildAssistedMessage,buildCreatePayload,isBundleEntry,+ isUploadAction,} from "./automation-setup";import { packBundle } from "./manifest-bundle";-import type { SetupEntry, SetupFormValues, SetupRequestBody } from "./types";+import type {+ SetupEntry,+ SetupFormValue,+ SetupFormValues,+ SetupRequestBody,+} from "./types";export interface SetupActionResult {/** The created resource, or the conversation that will finish setup. */response: Record<string, unknown>;}+function isFileValue(value: SetupFormValue | undefined): value is File {+ return typeof File !== "undefined" && value instanceof File;+}++function uploadCacheKey(+ entry: SetupEntry,+ values: SetupFormValues,+ selectedAction?: string | null,+): string {+ const upload = values.tarball;+ const uploadIdentity = isFileValue(upload)+ ? {+ name: upload.name,+ size: upload.size,+ lastModified: upload.lastModified,+ }+ : upload;+ return `${entry.id}+${selectedAction ?? ""}+${JSON.stringify({ ...values, tarball: uploadIdentity })}`;+}++async function uploadedTarballBytes(+ values: SetupFormValues,+): Promise<Uint8Array> {+ const upload = values.tarball;+ if (!isFileValue(upload)) {+ throw new Error("Choose a tarball before creating this automation.");+ }+ return new Uint8Array(await upload.arrayBuffer());+}+export function useSetupAction() {const createConversation = useCreateConversation();const setMessageToSend = useConversationStore(@@ -77,6 +115,8 @@ export function useSetupAction() {values: SetupFormValues,/** Present for a direct entry, and absent for an assisted one. */payload: SetupRequestBody | null,+ selectedTrigger?: string | null,+ selectedAction?: string | null,): Promise<SetupActionResult> => {if (!payload) {return startConversation(buildAssistedMessage(entry, values));@@ -86,27 +126,40 @@ export function useSetupAction() {// from is an archive: pack it with the rendered config, upload it, and// create against the path that came back. The payload built for the form// carries a stand-in path, which is replaced here with the real one.- if (isBundleEntry(entry)) {- const key = `${entry.id}\n${JSON.stringify(values)}`;+ if (isBundleEntry(entry) || isUploadAction(entry, selectedAction)) {+ const key = uploadCacheKey(entry, values, selectedAction);let tarballPath = uploadedRef.current?.path ?? null;if (uploadedRef.current?.key !== key || tarballPath === null) {- const archive = await packBundle(entry, values);+ const archive = isBundleEntry(entry)+ ? await packBundle(entry, values)+ : await uploadedTarballBytes(values);tarballPath = await AutomationService.uploadAutomationTarball(entry.id,archive,);uploadedRef.current = { key, path: tarballPath };}- const body = buildCreatePayload(entry, values, tarballPath);+ const body = buildCreatePayload(+ entry,+ values,+ tarballPath,+ selectedTrigger,+ selectedAction,+ );if (!body) throw new Error(`'${entry.id}' produced no create request.`);return {- response: await AutomationService.createAutomationDraft(body, entry),+ response: await AutomationService.createAutomationDraft(+ body,+ entry,+ selectedAction,+ ),};}const response = await AutomationService.createAutomationDraft(payload,entry,+ selectedAction,);return { response };},diff --git a/src/manifests/manifest-capabilities.ts b/src/manifests/manifest-capabilities.tsindex b10c174ab2..bbb8feae05 100644--- a/src/manifests/manifest-capabilities.ts+++ b/src/manifests/manifest-capabilities.ts@@ -7,7 +7,12 @@* this stays neutral about what any particular capability means.*/-import type { DeploymentCapabilities, SetupEntry } from "./types";+import type {+ DeploymentCapabilities,+ SetupActionKind,+ SetupEntry,+ SetupTriggerKind,+} from "./types";/*** "unknown" is a real outcome, not an error: a deployment that cannot be asked@@ -33,6 +38,35 @@ function findUnreported(return required.filter((entry) => !reported.includes(entry));}+function actionSupportsCapabilities(+ features: readonly string[],+ reported: DeploymentCapabilities,+): boolean {+ return findUnreported(reported.features ?? [], features).length === 0;+}++export function supportedActionKinds(+ entry: SetupEntry,+ reported: DeploymentCapabilities,+): SetupActionKind[] {+ const actions = entry.setup.actions ?? {};+ return (Object.keys(actions) as SetupActionKind[]).filter((kind) =>+ actionSupportsCapabilities(actions[kind]?.features ?? [], reported),+ );+}++export function supportedTriggerKinds(+ entry: SetupEntry,+ reported: DeploymentCapabilities,+): SetupTriggerKind[] {+ const triggers = Object.keys(+ entry.setup.form.triggers ?? {},+ ) as SetupTriggerKind[];+ return triggers.filter((kind) =>+ (reported.triggerKinds ?? []).includes(kind),+ );+}+export function assessCapabilityRequirements(entry: SetupEntry,reported: DeploymentCapabilities,@@ -41,12 +75,34 @@ export function assessCapabilityRequirements(// that requires nothing of it.if (!reported.ready) return { supported: false, unmet: [] };+ const unmetFeatures = findUnreported(+ reported.features ?? [],+ entry.requires.features ?? [],+ );+ const triggerKinds = Object.keys(entry.setup.form.triggers ?? {});+ const supportsAnyTrigger =+ triggerKinds.length === 0 ||+ triggerKinds.some((kind) => (reported.triggerKinds ?? []).includes(kind));++ const actions = entry.setup.actions ?? {};+ const actionFeatureSets = Object.values(actions).map(+ (action) => action?.features ?? [],+ );+ const supportsAnyAction =+ actionFeatureSets.length === 0 ||+ actionFeatureSets.some((features) =>+ actionSupportsCapabilities(features, reported),+ );+ const unmetActionFeatures = supportsAnyAction+ ? []+ : Array.from(new Set(actionFeatureSets.flat())).filter(+ (feature) => !(reported.features ?? []).includes(feature),+ );+const unmet = [- ...findUnreported(reported.features ?? [], entry.requires.features ?? []),- ...findUnreported(- reported.triggerKinds ?? [],- Object.keys(entry.setup.form.triggers ?? {}),- ),+ ...unmetFeatures,+ ...unmetActionFeatures,+ ...(supportsAnyTrigger ? [] : triggerKinds),];return { supported: unmet.length === 0, unmet };diff --git a/src/manifests/manifest-local-validation.ts b/src/manifests/manifest-local-validation.tsindex 2fa1555b8d..4505f64af8 100644--- a/src/manifests/manifest-local-validation.ts+++ b/src/manifests/manifest-local-validation.ts@@ -12,6 +12,7 @@import type {DeploymentCapabilities,+ SetupActionKind,SetupBlock,SetupFieldOption,SetupFormField,@@ -27,6 +28,8 @@ export type SetupFieldError =| { code: "required" }| { code: "minLength"; length: number }| { code: "maxLength"; length: number }+ | { code: "min"; value: number }+ | { code: "max"; value: number }| { code: "invalidOption" }| { code: "unsafeExpressionLiteral" };@@ -37,6 +40,22 @@ export interface SetupFieldOverride {options?: SetupFieldOption[];}+export function triggerKinds(setup: SetupBlock): string[] {+ return Object.keys(setup.form.triggers ?? {});+}++export function initialTriggerKind(setup: SetupBlock): string | null {+ return triggerKinds(setup)[0] ?? null;+}++export function actionKinds(setup: SetupBlock): SetupActionKind[] {+ return Object.keys(setup.actions ?? {}) as SetupActionKind[];+}++export function initialActionKind(setup: SetupBlock): SetupActionKind | null {+ return actionKinds(setup)[0] ?? null;+}+export type SetupFieldOverrides = Record<string, SetupFieldOverride>;/**@@ -46,9 +65,33 @@ export type SetupFieldOverrides = Record<string, SetupFieldOverride>;* runs on, and so every derived view of the form keeps that order. Admission* rejects a name declared in both halves, so the merge cannot lose a field.*/-export function collectFields(setup: SetupBlock): SetupFormFields {- const triggers = Object.values(setup.form.triggers ?? {});- return Object.assign({}, ...triggers, setup.form.args) as SetupFormFields;+export function collectFields(+ setup: SetupBlock,+ selectedTrigger?: string | null,+ selectedAction?: string | null,+): SetupFormFields {+ const triggers = setup.form.triggers ?? {};+ const triggerEntries = Object.entries(triggers);+ const activeTrigger =+ selectedTrigger && selectedTrigger in triggers+ ? triggers[selectedTrigger as keyof typeof triggers]+ : triggerEntries.length === 1+ ? triggerEntries[0][1]+ : {};+ const actions = setup.actions ?? {};+ const actionEntries = Object.entries(actions);+ const activeAction =+ selectedAction && selectedAction in actions+ ? actions[selectedAction as SetupActionKind]?.args+ : actionEntries.length === 1+ ? actionEntries[0][1]?.args+ : {};+ return Object.assign(+ {},+ activeTrigger,+ setup.form.args,+ activeAction,+ ) as SetupFormFields;}/**@@ -64,16 +107,46 @@ export function collectFields(setup: SetupBlock): SetupFormFields {export function resolveFieldOverrides(setup: SetupBlock,capabilities: DeploymentCapabilities | null,+ selectedTrigger?: string | null,+ selectedAction?: string | null,): SetupFieldOverrides {+ const overrides: SetupFieldOverrides = {};+ const fields = collectFields(setup, selectedTrigger, selectedAction);const timezones = capabilities?.triggers?.cron?.timezones;- if (!timezones?.length) return {};-- const options = timezones.map((zone) => ({ value: zone, label: zone }));- return Object.fromEntries(- Object.entries(collectFields(setup))+ if (timezones?.length) {+ const options = timezones.map((zone) => ({ value: zone, label: zone }));+ Object.entries(fields).filter(([, field]) => field.type === "timezone")- .map(([name]) => [name, { options }]),- );+ .forEach(([name]) => {+ overrides[name] = { options };+ });+ }++ if (capabilities?.eventSources?.length) {+ const options = capabilities.eventSources.map((source) => ({+ value: source,+ label: source,+ }));+ Object.entries(fields)+ .filter(([, field]) => field.type === "event-source")+ .forEach(([name]) => {+ overrides[name] = { options };+ });+ }++ if (capabilities?.eventTypes?.length) {+ const options = capabilities.eventTypes.map((type) => ({+ value: type,+ label: type,+ }));+ Object.entries(fields)+ .filter(([, field]) => field.type === "event-type")+ .forEach(([name]) => {+ overrides[name] = { options };+ });+ }++ return overrides;}/** The options a field offers, after deployment constraints are applied. */@@ -91,25 +164,40 @@ export function getFieldOptions(* Reading both shapes as a list is what keeps validation, interpolation and* the payload mapping from branching on `multiple` at every use.*/+function isFileValue(value: SetupFormValue | undefined): value is File {+ return typeof File !== "undefined" && value instanceof File;+}+export function fieldValues(value: SetupFormValue | undefined): string[] {if (Array.isArray(value)) return value.filter((item) => item.trim() !== "");- return value && value.trim() !== "" ? [value] : [];+ if (isFileValue(value)) return value.name ? [value.name] : [];+ if (typeof value === "string" && value.trim() === "") return [];+ if (value === undefined || value === null) return [];+ return [String(value)];}/** The single value a field holds, or "" for a field collecting several. */export function fieldText(value: SetupFormValue | undefined): string {- return typeof value === "string" ? value : "";+ if (Array.isArray(value) || value === undefined || value === null) return "";+ if (isFileValue(value)) return value.name;+ return String(value);}/** Initial form state: every declared field, seeded with its declared default. */-export function getInitialFormValues(setup: SetupBlock): SetupFormValues {+export function getInitialFormValues(+ setup: SetupBlock,+ selectedTrigger?: string | null,+ selectedAction?: string | null,+): SetupFormValues {return Object.fromEntries(- Object.entries(collectFields(setup)).map(([name, field]) => [- name,- // A field collecting several values starts empty rather than holding one- // blank entry, so "required" means "add one" rather than "fill this in".- field.multiple ? [] : (field.default ?? ""),- ]),+ Object.entries(collectFields(setup, selectedTrigger, selectedAction)).map(+ ([name, field]) => [+ name,+ // A field collecting several values starts empty rather than holding one+ // blank entry, so "required" means "add one" rather than "fill this in".+ field.multiple ? [] : (field.default ?? ""),+ ],+ ),);}@@ -139,13 +227,19 @@ function validateValue(value: string,overrides: SetupFieldOverrides,): SetupFieldError | null {- const { minLength, maxLength, format } = field.constraints ?? {};+ const { minLength, maxLength, min, max, format } = field.constraints ?? {};if (minLength !== undefined && value.length < minLength) {return { code: "minLength", length: minLength };}if (maxLength !== undefined && value.length > maxLength) {return { code: "maxLength", length: maxLength };}+ if (field.type === "number") {+ const numeric = Number(value);+ if (Number.isNaN(numeric)) return { code: "invalidOption" };+ if (min !== undefined && numeric < min) return { code: "min", value: min };+ if (max !== undefined && numeric > max) return { code: "max", value: max };+ }if (format === "safeExpressionLiteral" &&UNSAFE_EXPRESSION_LITERAL_PATTERN.test(value)@@ -168,12 +262,13 @@ export function validateFormValues(setup: SetupBlock,values: SetupFormValues,overrides: SetupFieldOverrides = {},+ selectedTrigger?: string | null,+ selectedAction?: string | null,): SetupFieldErrors {- return Object.entries(collectFields(setup)).reduce<SetupFieldErrors>(- (errors, [name, field]) => {- const error = validateField(name, field, values[name], overrides);- return error ? { ...errors, [name]: error } : errors;- },- {},- );+ return Object.entries(+ collectFields(setup, selectedTrigger, selectedAction),+ ).reduce<SetupFieldErrors>((errors, [name, field]) => {+ const error = validateField(name, field, values[name], overrides);+ return error ? { ...errors, [name]: error } : errors;+ }, {});}diff --git a/src/manifests/manifest-template.ts b/src/manifests/manifest-template.tsindex 2ddce64579..2e09715cbd 100644--- a/src/manifests/manifest-template.ts+++ b/src/manifests/manifest-template.ts@@ -7,7 +7,7 @@* cannot express behavior here.*/-import type { SetupEntry, SetupFormValues } from "./types";+import type { SetupEntry, SetupFormValues, SetupPayloadValue } from "./types";const PLACEHOLDER_PATTERN = /\{\{([A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*)\}\}/g;@@ -42,11 +42,19 @@ function wholePlaceholderPath(template: string): string | null {return match ? match[1] : null;}-/** A list of strings, which is the one non-string shape a form value takes. */-function isStringList(value: unknown): value is string[] {- return (- Array.isArray(value) && value.every((item) => typeof item === "string")- );+function isPlainPayloadValue(value: unknown): value is SetupPayloadValue {+ if (+ value === null ||+ typeof value === "string" ||+ typeof value === "number" ||+ typeof value === "boolean"+ ) {+ return true;+ }+ if (Array.isArray(value)) return value.every(isPlainPayloadValue);+ if (typeof value !== "object") return false;+ if (Object.getPrototypeOf(value) !== Object.prototype) return false;+ return Object.values(value).every(isPlainPayloadValue);}/**@@ -57,19 +65,19 @@ function isStringList(value: unknown): value is string[] {* get an array. Inside a sentence the same placeholder still reads as text,* because there is nowhere for a list to go in a string.*- * Only the shapes a form value has are kept whole. A placeholder naming- * anything else - `{{automation.setup}}` resolves to the setup block itself -+ * Plain JSON form values are kept whole. A placeholder naming anything else -+ * for example `{{automation.setup}}`, or a browser `File` selected by the user -* reads as text like it does inside a sentence, so a manifest cannot state one* value and put its own object graph into the request body.*/export function interpolateValue(template: string,scope: SetupScope,-): string | string[] {+): SetupPayloadValue {const path = wholePlaceholderPath(template);if (path === null) return interpolateText(template, scope);const resolved = getByPath(scope, path);- return isStringList(resolved) ? resolved : toText(resolved);+ return isPlainPayloadValue(resolved) ? resolved : toText(resolved);}/** Substitute placeholders inside a template string. */diff --git a/src/manifests/manifest-validation.ts b/src/manifests/manifest-validation.tsindex f926c4cc8a..b5c0aa722d 100644--- a/src/manifests/manifest-validation.ts+++ b/src/manifests/manifest-validation.ts@@ -53,9 +53,15 @@ const FIELD_TYPES = ["text","textarea","select",+ "number","cron","timezone","repo-picker",+ "llm-profile",+ "event-source",+ "event-type",+ "plugin-sources",+ "tarball-upload",] as const;const GIT_PROVIDERS = ["github", "gitlab", "bitbucket"] as const;const TRIGGER_KINDS = ["cron", "event"] as const;@@ -233,13 +239,19 @@ function checkConstraints(return;}- const { minLength, maxLength, format } = constraints;+ const { minLength, maxLength, min, max, format } = constraints;if (minLength !== undefined && !isInteger(minLength, 0)) {check.fail(`${path}.minLength`, "must be a non-negative integer");}if (maxLength !== undefined && !isInteger(maxLength, 1)) {check.fail(`${path}.maxLength`, "must be a positive integer");}+ if (min !== undefined && !isInteger(min, 0)) {+ check.fail(`${path}.min`, "must be a non-negative integer");+ }+ if (max !== undefined && !isInteger(max, 1)) {+ check.fail(`${path}.max`, "must be a positive integer");+ }if (format !== undefined && !isOneOf(format, CONSTRAINT_FORMATS)) {check.fail(`${path}.format`, "is not a supported format");}@@ -259,8 +271,14 @@ function checkField(check: SetupChecker, field: unknown, path: string): void {check.copy(label, `${path}.label`);check.copy(help, `${path}.help`);if (placeholder !== undefined) check.copy(placeholder, `${path}.placeholder`);- if (field.default !== undefined && typeof field.default !== "string") {- check.fail(`${path}.default`, "must be a string");+ if (+ field.default !== undefined &&+ typeof field.default !== "string" &&+ typeof field.default !== "number" &&+ typeof field.default !== "boolean" &&+ field.default !== null+ ) {+ check.fail(`${path}.default`, "must be a string, number, boolean or null");}if (typeof required !== "boolean") {check.fail(`${path}.required`, "must be a boolean");@@ -330,10 +348,13 @@ function checkFields(}/** Returns the trigger kinds declared, in order. */-function checkForm(check: SetupChecker, form: unknown): string[] {+function checkForm(+ check: SetupChecker,+ form: unknown,+): { kinds: string[]; fieldNames: string[] } {if (!isRecord(form)) {check.fail("setup.form", "must be an object");- return [];+ return { kinds: [], fieldNames: [] };}if (form.note !== undefined) check.copy(form.note, "setup.form.note");@@ -367,24 +388,147 @@ function checkForm(check: SetupChecker, form: unknown): string[] {check.fail(`setup.form.${name}`, "is declared more than once"),);- return kinds;+ return { kinds, fieldNames: names };+}++function checkActionFeatures(+ check: SetupChecker,+ features: unknown,+ path: string,+): void {+ if (!Array.isArray(features) || features.length === 0) {+ check.fail(path, "must be a non-empty array");+ return;+ }+ features.forEach((feature, index) => {+ if (typeof feature !== "string" || feature.length === 0) {+ check.fail(`${path}[${index}]`, "must be a non-empty string");+ }+ });+}++function checkAction(+ check: SetupChecker,+ kind: string,+ action: unknown,+ commonFieldNames: string[],+): void {+ const path = `setup.actions.${kind}`;+ if (!isRecord(action)) {+ check.fail(path, "must be an object");+ return;+ }++ check.copy(action.label, `${path}.label`);+ check.copy(action.help, `${path}.help`);+ checkActionFeatures(check, action.features, `${path}.features`);+ const actionFieldNames = checkFields(check, action.args, `${path}.args`);+ actionFieldNames+ .filter((name) => commonFieldNames.includes(name))+ .forEach((name) =>+ check.fail(`${path}.args.${name}`, "is already declared by the form"),+ );++ if (kind === "prompt") {+ check.templateValue(action.prompt, `${path}.prompt`);+ } else if (kind === "plugin") {+ check.templateValue(action.prompt, `${path}.prompt`);+ check.templateValue(action.plugins, `${path}.plugins`);+ } else if (kind === "upload") {+ check.templateValue(action.tarballPath, `${path}.tarballPath`);+ check.templateValue(action.entrypoint, `${path}.entrypoint`);+ if (action.setupScript !== undefined) {+ check.templateValue(action.setupScript, `${path}.setupScript`);+ }+ } else {+ check.fail(path, "is not a supported action kind");+ }++ const allowedByKind: Record<string, string[]> = {+ prompt: ["label", "help", "features", "args", "prompt"],+ plugin: ["label", "help", "features", "args", "prompt", "plugins"],+ upload: [+ "label",+ "help",+ "features",+ "args",+ "tarballPath",+ "entrypoint",+ "setupScript",+ ],+ };+ const allowed = allowedByKind[kind] ?? [];+ Object.keys(action)+ .filter((key) => !allowed.includes(key))+ .forEach((key) => check.fail(`${path}.${key}`, "is not allowed"));}-function hasRepoPicker(form: unknown): boolean {- if (!isRecord(form)) return false;- const groups = [- form.args,- ...Object.values(isRecord(form.triggers) ? form.triggers : {}),- ];- return groups.some(- (group) =>- isRecord(group) &&- Object.values(group).some(- (field) => isRecord(field) && field.type === "repo-picker",- ),+function checkActions(+ check: SetupChecker,+ actions: unknown,+ commonFieldNames: string[],+): void {+ if (!isRecord(actions) || Object.keys(actions).length === 0) {+ check.fail("setup.actions", "must be a non-empty object");+ return;+ }+ Object.entries(actions).forEach(([kind, action]) =>+ checkAction(check, kind, action, commonFieldNames),);}+function fieldsContainType(fields: unknown, type: string): boolean {+ if (!isRecord(fields)) return false;+ return Object.values(fields).some(+ (field) => isRecord(field) && field.type === type,+ );+}++function actionHasRepoPicker(action: unknown): boolean {+ return isRecord(action) && fieldsContainType(action.args, "repo-picker");+}++/**+ * Whether an event trigger's `source` is derivable for every selectable action.+ *+ * `buildTrigger` fills `source` from a field named `source` in the event+ * trigger, or failing that from the selected action's repo-picker provider. A+ * picker in another trigger group (such as `cron`) is never collected for the+ * event trigger, and a picker in only some actions is invisible when one of the+ * others is selected — so neither may satisfy this check, or the user can end+ * up with an empty `source` no form field can fix.+ */+function setupSuppliesEventSource(setup: Rec): boolean {+ const form = isRecord(setup.form) ? setup.form : {};+ const triggers = isRecord(form.triggers) ? form.triggers : {};+ const eventFields = triggers.event;++ // An explicit event-source field fills `source` directly, regardless of which+ // action is selected.+ if (fieldsContainType(eventFields, "event-source")) return true;++ // A repo-picker in the event trigger is only collected when `event` is the+ // sole trigger kind; with a sibling trigger the derivation reads no trigger+ // fields for the picker. `form.args` is shared across every selection, so a+ // picker there is always available.+ const singleEventTrigger =+ "event" in triggers && Object.keys(triggers).length === 1;+ if (+ (singleEventTrigger && fieldsContainType(eventFields, "repo-picker")) ||+ fieldsContainType(form.args, "repo-picker")+ ) {+ return true;+ }++ // Without a shared or event-trigger picker, every selectable action must+ // carry its own repo-picker; otherwise selecting an action without one+ // derives `source: ""`.+ if (!isRecord(setup.actions) || Object.keys(setup.actions).length === 0) {+ return false;+ }+ return Object.values(setup.actions).every(actionHasRepoPicker);+}+function checkMessage(check: SetupChecker, message: unknown): void {if (check.templateCopy(message, "setup.message")) {if ((message as string).length > MAX_MESSAGE_LENGTH) {@@ -505,25 +649,34 @@ function checkBundleConfig(}}-function checkMode(check: SetupChecker, setup: Rec, kinds: string[]): void {+function checkMode(+ check: SetupChecker,+ setup: Rec,+ kinds: string[],+ commonFieldNames: string[],+): void {if (!isOneOf(setup.mode, SETUP_MODES)) {check.fail("setup.mode", "is not a supported mode");return;}if (setup.mode === "direct") {- // A direct entry produces one of two things: a prompt, or a script bundle- // the host packs and uploads. Both would be ambiguous, neither is nothing- // to create.+ // A direct entry produces one of three things: a prompt, a script bundle+ // the host packs and uploads, or a selectable set of action variants.+ // More than one would be ambiguous, and none is nothing to create.const hasPrompt = setup.prompt !== undefined;const hasBundle = setup.bundle !== undefined;- if (hasPrompt === hasBundle) {+ const hasActions = setup.actions !== undefined;+ const variants = [hasPrompt, hasBundle, hasActions].filter(Boolean);+ if (variants.length !== 1) {check.fail("setup",- "must declare exactly one of prompt or bundle for direct setup",+ "must declare exactly one of prompt, bundle or actions for direct setup",);} else if (hasBundle) {checkBundle(check, setup.bundle);+ } else if (hasActions) {+ checkActions(check, setup.actions, commonFieldNames);} else {check.templateValue(setup.prompt, "setup.prompt");}@@ -532,18 +685,16 @@ function checkMode(check: SetupChecker, setup: Rec, kinds: string[]): void {// message.if (setup.message !== undefined) checkMessage(check, setup.message);- // The derivation reads a single trigger kind, and an event trigger takes- // its source from the repository field's provider.- if (kinds.length !== 1) {+ if (kinds.length === 0) {check.fail("setup.form.triggers",- "must declare exactly one trigger kind",+ "must declare at least one trigger kind",);}- if (kinds.includes("event") && !hasRepoPicker(setup.form)) {+ if (kinds.includes("event") && !setupSuppliesEventSource(setup)) {check.fail(- "setup.form",- "must declare a repository field for an event trigger",+ "setup.form.triggers.event",+ "must declare an event source field or repository picker",);}if (setup.filter !== undefined) {@@ -559,6 +710,7 @@ function checkMode(check: SetupChecker, setup: Rec, kinds: string[]): void {checkMessage(check, setup.message);check.absent(setup, "prompt", "setup", "is only allowed for direct setup");check.absent(setup, "bundle", "setup", "is only allowed for direct setup");+ check.absent(setup, "actions", "setup", "is only allowed for direct setup");check.absent(setup, "filter", "setup", "is only allowed for direct setup");}@@ -615,8 +767,8 @@ export function validateSetupEntry(candidate: unknown): SetupValidationResult {}checkRequires(check, candidate.requires);- const kinds = checkForm(check, setup.form);- checkMode(check, setup, kinds);+ const { kinds, fieldNames } = checkForm(check, setup.form);+ checkMode(check, setup, kinds, fieldNames);return { valid: check.errors.length === 0, errors: check.errors };}diff --git a/src/manifests/types.ts b/src/manifests/types.tsindex c1ba3e440c..03e9c798ca 100644--- a/src/manifests/types.ts+++ b/src/manifests/types.ts@@ -18,9 +18,15 @@ export type SetupFieldType =| "text"| "textarea"| "select"+ | "number"| "cron"| "timezone"- | "repo-picker";+ | "repo-picker"+ | "llm-profile"+ | "event-source"+ | "event-type"+ | "plugin-sources"+ | "tarball-upload";export type SetupGitProvider = "github" | "gitlab" | "bitbucket";@@ -37,6 +43,8 @@ export interface SetupFieldOption {export interface SetupFieldConstraints {minLength?: number;maxLength?: number;+ min?: number;+ max?: number;/*** A host-implemented check named from a closed set. Entries supply no regex* of their own, so they cannot hand the host a pathological pattern.@@ -49,7 +57,7 @@ export interface SetupFormField {label: string;help: string;placeholder?: string;- default?: string;+ default?: string | number | boolean | null;required: boolean;provider?: SetupGitProvider;/**@@ -67,7 +75,7 @@ export type SetupFormFields = Record<string, SetupFormField>;export interface SetupForm {note?: string;- /** Inputs that decide when the automation runs, keyed by trigger kind. */+ /** Inputs that decide when the automation runs, keyed by trigger kind. Multiple keys are selectable variants. */triggers?: Partial<Record<SetupTriggerKind, SetupFormFields>>;/** Every other input: the arguments to the automation itself. */args: SetupFormFields;@@ -112,6 +120,46 @@ export interface SetupBundle {config: Record<string, SetupBundleConfigValue>;}+export type SetupActionKind = "prompt" | "plugin" | "upload";++export interface SetupPromptAction {+ label: string;+ help: string;+ features: string[];+ args: SetupFormFields;+ prompt: string;+}++export interface SetupPluginAction {+ label: string;+ help: string;+ features: string[];+ args: SetupFormFields;+ prompt: string;+ plugins: string;+}++export interface SetupUploadAction {+ label: string;+ help: string;+ features: string[];+ args: SetupFormFields;+ tarballPath: string;+ entrypoint: string;+ setupScript?: string;+}++export interface SetupActions {+ prompt?: SetupPromptAction;+ plugin?: SetupPluginAction;+ upload?: SetupUploadAction;+}++export type SetupAction =+ | SetupPromptAction+ | SetupPluginAction+ | SetupUploadAction;+export interface SetupBlock {version: typeof SETUP_VERSION;mode: SetupMode;@@ -120,6 +168,8 @@ export interface SetupBlock {prompt?: string;/** direct only, and the alternative to `prompt`. Exactly one is present. */bundle?: SetupBundle;+ /** direct only, and the alternative to `prompt` or `bundle`. */+ actions?: SetupActions;/** direct only, event trigger only. Which delivered events belong to it. */filter?: string;/**@@ -184,7 +234,7 @@ export interface SetupRequestBody {* string, including fields whose value is a number to the service - the* payload mapping is where a value stops being what was typed.*/-export type SetupFormValue = string | string[];+export type SetupFormValue = string | number | boolean | null | string[] | File;export type SetupFormValues = Record<string, SetupFormValue>;/** `GET /v1/capabilities` — what this deployment supports. */diff --git a/src/mocks/automation-handlers.ts b/src/mocks/automation-handlers.tsindex d88f7b4674..f63d9f4dbe 100644--- a/src/mocks/automation-handlers.ts+++ b/src/mocks/automation-handlers.ts@@ -151,6 +151,50 @@ export const AUTOMATION_HANDLERS = [return HttpResponse.json(response);}),+ // POST /api/automation/v1/uploads — Upload custom automation tarball+ http.post("*/api/automation/v1/uploads", async ({ request }) => {+ await delay(200);+ const url = new URL(request.url);+ const name = url.searchParams.get("name") || "automation";+ return HttpResponse.json({+ tarball_path: `oh-internal://uploads/${encodeURIComponent(name)}-${crypto.randomUUID()}.tar.gz`,+ });+ }),++ // POST /api/automation/v1 — Create an automation from uploaded tarball+ http.post("*/api/automation/v1", async ({ request }) => {+ await delay(200);++ const body = (await request.clone().json()) as {+ name: string;+ model?: string;+ trigger: Automation["trigger"];+ timeout?: number;+ tarball_path?: string;+ entrypoint?: string;+ setup_script_path?: string;+ };+ const now = new Date().toISOString();+ const automation: Automation = {+ id: crypto.randomUUID(),+ name: body.name,+ prompt: null,+ model: body.model ?? null,+ trigger: body.trigger,+ enabled: true,+ created_at: now,+ updated_at: now,+ last_triggered_at: null,+ ...(typeof body.timeout === "number" && { timeout: body.timeout }),+ ...(typeof body.trigger.timezone === "string" && {+ timezone: body.trigger.timezone,+ }),+ };++ automations.set(automation.id, automation);+ return HttpResponse.json(automation, { 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/utils/recommended-automation-rail.ts b/src/utils/recommended-automation-rail.tsindex 1fe21fdc5e..ff343dfbd2 100644--- a/src/utils/recommended-automation-rail.ts+++ b/src/utils/recommended-automation-rail.ts@@ -33,7 +33,12 @@ export function normalizeAutomationKey(value: string): string {}function catalogMatchKeys(entry: RecommendedAutomation): string[] {- return [entry.id, entry.name, entry.skill]+ return [+ entry.id,+ entry.name,+ entry.name ? `${entry.name} Agent` : undefined,+ entry.skill,+ ].filter((value): value is string => Boolean(value)).map(normalizeAutomationKey);}