Skip to content

🙌 OpenHands: AI-Driven Development

fix: keep automation repositories when editing (#18776)

Alonac8a20662d5dd
diff --git a/__tests__/api/automation-form-session.test.ts b/__tests__/api/automation-form-session.test.ts
index 6a273534a2..d1338ee2c5 100644
--- a/__tests__/api/automation-form-session.test.ts
+++ b/__tests__/api/automation-form-session.test.ts
@@ -46,4 +46,28 @@ describe("automation form session", () => {
BUNDLE_PATH,
);
});
+
+ it("keeps the saved repositories and whether they can change after a field is edited", () => {
+ const repositories = [
+ { url: "acme/api", ref: "release", provider: "github" },
+ { url: "https://gitlab.com/acme/tools" },
+ ];
+ initializeAutomationFormSession("conv-1", {
+ prompt: "Review new pull requests.",
+ kind: "prompt",
+ editingAutomationId: "automation-1",
+ existingRepositories: repositories,
+ canUpdateRepositories: true,
+ });
+
+ patchAutomationFormSession(
+ "conv-1",
+ { name: "Reviewer" },
+ { source: "user" },
+ );
+
+ const session = getAutomationFormSession("conv-1");
+ expect(session?.existingRepositories).toEqual(repositories);
+ expect(session?.canUpdateRepositories).toBe(true);
+ });
});
diff --git a/__tests__/api/automation-handlers.test.ts b/__tests__/api/automation-handlers.test.ts
index 8c640702f9..f4d8ad3e9c 100644
--- a/__tests__/api/automation-handlers.test.ts
+++ b/__tests__/api/automation-handlers.test.ts
@@ -86,6 +86,7 @@ describe("Automation MSW Handlers", () => {
features: [
...(capabilitiesFixture.responses.supported.body.features ?? []),
"automationDrafts",
+ "repoUpdate",
],
},
});
diff --git a/__tests__/api/automation-service.test.ts b/__tests__/api/automation-service.test.ts
index 1111720ad9..64bd2be466 100644
--- a/__tests__/api/automation-service.test.ts
+++ b/__tests__/api/automation-service.test.ts
@@ -301,7 +301,7 @@ describe("AutomationService", () => {
expect(result.repositories).toEqual([
{ url: "https://github.com/qa-example/qa-repo", ref: "main" },
- { url: "qa-example/docs" },
+ { url: "qa-example/docs", provider: "github" },
]);
expect(result.plugins).toEqual([
"github:qa-example/qa-plugin",
diff --git a/__tests__/components/automations/automation-setup-panel.test.tsx b/__tests__/components/automations/automation-setup-panel.test.tsx
index 7854d25ee4..76655db020 100644
--- a/__tests__/components/automations/automation-setup-panel.test.tsx
+++ b/__tests__/components/automations/automation-setup-panel.test.tsx
@@ -21,10 +21,13 @@ import {
AutomationSetupPanel,
} from "#/components/features/automations/setup/automation-setup-panel";
import AutomationService from "#/api/automation-service/automation-service.api";
+import { useEffect, useState } from "react";
import {
PENDING_AUTOMATION_SETUP_ID,
+ clearAutomationFormSession,
getAutomationFormSession,
initializeAutomationFormSession,
+ subscribeAutomationFormSession,
} from "#/api/automation-form-session";
import type { AutomationSetupDraft } from "#/api/automation-setup-types";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
@@ -34,8 +37,11 @@ import { AUTOMATION_FORM_UPDATE_ACTION_KIND } from "#/constants/automation-form"
import { AUTOMATION_SETUP_SHOW_AGENT_EVENT } from "#/components/features/automations/setup/automation-setup-agent-request";
import { setupDraftFromAutomation } from "#/utils/automation-edit-draft";
import { useDeploymentCapabilities } from "#/hooks/query/use-manifest-capabilities";
+import { AUTOMATION_DETAIL_QUERY_KEY } from "#/hooks/query/use-automation-detail";
+import { AUTOMATIONS_QUERY_KEY } from "#/hooks/query/use-automations";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
import type { AutomationDraftApiResponse } from "#/manifests/types";
+import type { Automation } from "#/types/automation";
const mockNavigate = vi.fn();
const mockToastSuccess = vi.fn();
@@ -70,6 +76,10 @@ const createGitRepositoriesQueryResult = () => ({
onLoadMore: vi.fn(),
});
const mockUseGitRepositories = vi.fn(createGitRepositoriesQueryResult);
+const mockUseSearchRepositories = vi.fn((..._args: unknown[]) => ({
+ data: undefined as { full_name: string }[] | undefined,
+ isFetching: false,
+}));
const { mockSendMessage } = vi.hoisted(() => ({
mockSendMessage: vi.fn().mockResolvedValue({ queued: false }),
@@ -158,17 +168,24 @@ vi.mock("#/hooks/query/use-agent-profiles", () => ({
}),
}));
+const mockUseUserProviders = vi.fn(() => ({
+ providers: ["github"],
+ isLoadingSettings: false,
+}));
+
vi.mock("#/hooks/use-user-providers", () => ({
- useUserProviders: () => ({
- providers: ["github"],
- isLoadingSettings: false,
- }),
+ useUserProviders: () => mockUseUserProviders(),
}));
vi.mock("#/hooks/query/use-git-repositories", () => ({
useGitRepositories: () => mockUseGitRepositories(),
}));
+vi.mock("#/hooks/query/use-search-repositories", () => ({
+ useSearchRepositories: (...args: unknown[]) =>
+ mockUseSearchRepositories(...args),
+}));
+
vi.mock("#/hooks/query/use-llm-profiles", () => ({
useLlmProfiles: () => ({
data: {
@@ -214,6 +231,9 @@ function renderPanel(
},
conversationId = "conv-1",
conversationTags: Record<string, string> | null | undefined = null,
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ }),
) {
const value: NavigationContextValue = {
currentPath: `/conversations/${conversationId}`,
@@ -221,9 +241,6 @@ function renderPanel(
isNavigating: false,
navigate: mockNavigate,
};
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
- });
return render(
<QueryClientProvider client={queryClient}>
@@ -238,6 +255,47 @@ function renderPanel(
);
}
+/** Feeds the panel from the form session on every change, as the setup route does. */
+function SessionBoundPanel({ conversationId }: { conversationId: string }) {
+ const [draft, setDraft] = useState(
+ () => getAutomationFormSession(conversationId) as AutomationSetupDraft,
+ );
+ useEffect(
+ () =>
+ subscribeAutomationFormSession(conversationId, (next) => {
+ if (next) setDraft(next);
+ }),
+ [conversationId],
+ );
+ return (
+ <AutomationSetupPanel
+ draft={draft}
+ conversationId={conversationId}
+ conversationTags={null}
+ />
+ );
+}
+
+function renderSessionBoundPanel(conversationId: string) {
+ const value: NavigationContextValue = {
+ currentPath: "/automations/setup",
+ conversationId: null,
+ isNavigating: false,
+ navigate: mockNavigate,
+ };
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <NavigationProvider value={value}>
+ <SessionBoundPanel conversationId={conversationId} />
+ </NavigationProvider>
+ </QueryClientProvider>,
+ );
+}
+
describe("AutomationSetupPanel", () => {
beforeEach(() => {
window.sessionStorage.clear();
@@ -256,6 +314,14 @@ describe("AutomationSetupPanel", () => {
AgentServerConversationService.updateConversationTags,
).mockImplementation(async (_conversationId, tags) => ({ tags }) as never);
mockUseGitRepositories.mockReturnValue(createGitRepositoriesQueryResult());
+ mockUseSearchRepositories.mockReturnValue({
+ data: undefined,
+ isFetching: false,
+ });
+ mockUseUserProviders.mockReturnValue({
+ providers: ["github"],
+ isLoadingSettings: false,
+ });
});
afterEach(() => {
@@ -599,8 +665,16 @@ describe("AutomationSetupPanel", () => {
"OpenHands/software-agent-sdk",
);
await user.click(screen.getByTestId("automation-setup-repository-submit"));
+ await user.click(screen.getByTestId("automation-setup-repository-add"));
+ await user.click(screen.getByTestId("automation-setup-repository-custom"));
+ await user.type(
+ screen.getByTestId("automation-setup-repository-address"),
+ "https://gitlab.com/acme/tools",
+ );
+ await user.click(screen.getByTestId("automation-setup-repository-submit"));
await user.click(screen.getByTestId("automation-setup-test"));
+ // A full URL names its own host, so it is cloned without a GitHub token.
await waitFor(() =>
expect(AutomationService.validateDraft).toHaveBeenCalledWith(
expect.objectContaining({
@@ -608,6 +682,7 @@ describe("AutomationSetupPanel", () => {
repos: [
{ url: "OpenHands/OpenHands", provider: "github" },
{ url: "OpenHands/software-agent-sdk", provider: "github" },
+ { url: "https://gitlab.com/acme/tools" },
],
}),
}),
@@ -628,14 +703,16 @@ describe("AutomationSetupPanel", () => {
screen.queryByTestId("automation-setup-add-repository-modal"),
).not.toBeInTheDocument();
- await user.click(
- await screen.findByTestId(
- "automation-setup-repository-option-OpenHands/OpenHands",
- ),
+ const option = await screen.findByTestId(
+ "automation-setup-repository-option-OpenHands/OpenHands",
);
- expect(
- screen.getByTestId("automation-setup-repository-value"),
- ).toHaveTextContent("OpenHands/OpenHands");
+ // Long organization/project/repository names are truncated, so the full
+ // name is available on hover.
+ expect(within(option).getByTitle("OpenHands/OpenHands")).toBeVisible();
+ await user.click(option);
+ const pill = screen.getByTestId("automation-setup-repository-value");
+ expect(pill).toHaveTextContent("OpenHands/OpenHands");
+ expect(within(pill).getByTitle("OpenHands/OpenHands")).toBeVisible();
await user.click(screen.getByTestId("automation-setup-repository-add"));
await user.click(screen.getByTestId("automation-setup-repository-custom"));
@@ -707,6 +784,85 @@ describe("AutomationSetupPanel", () => {
).toBeInTheDocument();
});
+ it("searches the provider for repositories that are not loaded yet", async () => {
+ mockUseSearchRepositories.mockImplementation((query) => ({
+ data:
+ query === "agent"
+ ? [{ full_name: "OpenHands/agent-canvas-extras" }]
+ : undefined,
+ isFetching: false,
+ }));
+
+ const user = userEvent.setup();
+ renderPanel();
+
+ await user.click(screen.getByTestId("automation-setup-repository-add"));
+ await user.type(
+ screen.getByTestId("automation-setup-repository-search"),
+ "agent",
+ );
+
+ expect(
+ await screen.findByTestId(
+ "automation-setup-repository-option-OpenHands/agent-canvas-extras",
+ ),
+ ).toBeInTheDocument();
+ // A loaded repository that matches stays listed.
+ expect(
+ screen.getByTestId(
+ "automation-setup-repository-option-OpenHands/software-agent-sdk",
+ ),
+ ).toBeInTheDocument();
+ expect(mockUseSearchRepositories).toHaveBeenLastCalledWith(
+ "agent",
+ "github",
+ false,
+ );
+ });
+
+ it("explains that automations cannot clone another provider's repositories", async () => {
+ mockUseUserProviders.mockReturnValue({
+ providers: ["azure_devops"],
+ isLoadingSettings: false,
+ });
+ mockUseGitRepositories.mockReturnValue({
+ ...createGitRepositoriesQueryResult(),
+ data: {
+ pages: [
+ {
+ items: [
+ {
+ id: "ado-1",
+ full_name: "fabrikam/Fabrikam Fiber/fabrikam-web",
+ git_provider: "azure_devops",
+ is_public: false,
+ },
+ ],
+ missing_token: false,
+ next_page_id: null,
+ },
+ ],
+ },
+ });
+
+ const user = userEvent.setup();
+ renderPanel();
+
+ await user.click(screen.getByTestId("automation-setup-repository-add"));
+
+ expect(
+ screen.getByTestId("automation-setup-repository-unsupported"),
+ ).toHaveTextContent("AUTOMATION_SETUP$REPOSITORY_PROVIDER_UNSUPPORTED");
+ const option = screen.getByTestId(
+ "automation-setup-repository-option-fabrikam/Fabrikam Fiber/fabrikam-web",
+ );
+ expect(option).toBeDisabled();
+ await user.click(option);
+ expect(
+ screen.queryByTestId("automation-setup-repository-value"),
+ ).not.toBeInTheDocument();
+ });
+
it("streams agent form updates field by field without overwriting user edits", async () => {
vi.useFakeTimers();
const conversationId = "conv-agent-updates";
@@ -2254,31 +2410,57 @@ describe("AutomationSetupPanel", () => {
expect(AutomationService.dispatchServerDraft).not.toHaveBeenCalled();
});
- it("does not send unsupported repository and plugin fields while editing", async () => {
- vi.mocked(AutomationService.updateAutomation).mockResolvedValue({
- id: "auto-1",
- } as never);
+ const savedReviewer = (overrides: Partial<Automation> = {}): Automation => ({
+ id: "auto-1",
+ name: "Reviewer",
+ prompt: "Review PRs",
+ enabled: true,
+ created_at: "2026-01-01T00:00:00.000Z",
+ updated_at: "2026-01-01T00:00:00.000Z",
+ // The service keeps repositories in preset metadata; the client reads
+ // them as `repositories`.
+ repositories: [
+ { url: "OpenHands/OpenHands", ref: "main", provider: "github" },
+ ],
+ preset_metadata: {
+ preset_type: "prompt",
+ repos: [{ url: "OpenHands/OpenHands", ref: "main", provider: "github" }],
+ },
+ trigger: {
+ type: "cron",
+ schedule: "0 9 * * *",
+ timezone: "UTC",
+ },
+ ...overrides,
+ });
+
+ it("shows saved repositories read-only when the service cannot change them", async () => {
+ vi.mocked(AutomationService.updateAutomation).mockResolvedValue(
+ savedReviewer(),
+ );
const user = userEvent.setup();
renderPanel(
- setupDraftFromAutomation({
- id: "auto-1",
- name: "Reviewer",
- prompt: "Review PRs",
- enabled: true,
- created_at: "2026-01-01T00:00:00.000Z",
- updated_at: "2026-01-01T00:00:00.000Z",
- repository: "OpenHands/OpenHands",
- plugins: ["github:OpenHands/extensions/plugins/pr-review"],
- trigger: {
- type: "cron",
- schedule: "0 9 * * *",
- timezone: "UTC",
- },
- }),
+ setupDraftFromAutomation(
+ savedReviewer({
+ plugins: ["github:OpenHands/extensions/plugins/pr-review"],
+ }),
+ ),
);
- await user.click(screen.getByTestId("automation-setup-repository-remove"));
+ expect(
+ screen.getByTestId("automation-setup-repository-value"),
+ ).toHaveTextContent("OpenHands/OpenHands");
+ expect(
+ screen.getByTestId("automation-setup-repository-read-only"),
+ ).toHaveTextContent("AUTOMATION_SETUP$REPOSITORIES_READ_ONLY");
+ expect(
+ screen.queryByTestId("automation-setup-repository-add"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("automation-setup-repository-remove"),
+ ).not.toBeInTheDocument();
+
await user.click(screen.getByTestId("automation-setup-plugin-remove"));
await user.click(screen.getByTestId("automation-setup-save"));
@@ -2302,6 +2484,189 @@ describe("AutomationSetupPanel", () => {
);
});
+ it("saves changed repositories when the service can change them", async () => {
+ vi.mocked(useDeploymentCapabilities).mockReturnValue({
+ data: {
+ ready: true,
+ features: ["repoUpdate"],
+ triggerKinds: ["cron"],
+ eventSources: [],
+ eventTypes: [],
+ triggers: {},
+ },
+ isLoading: false,
+ } as never);
+ vi.mocked(AutomationService.updateAutomation).mockImplementation(
+ async (_id, body) =>
+ savedReviewer({
+ preset_metadata: {
+ preset_type: "prompt",
+ ...((body as { repos?: unknown }).repos
+ ? { repos: (body as { repos: unknown }).repos }
+ : {}),
+ },
+ }),
+ );
+
+ const user = userEvent.setup();
+ renderPanel(setupDraftFromAutomation(savedReviewer()));
+
+ // An unchanged list is not sent.
+ await user.click(screen.getByTestId("automation-setup-save"));
+ await waitFor(() =>
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(1),
+ );
+ expect(
+ vi.mocked(AutomationService.updateAutomation).mock.calls[0][1],
+ ).not.toHaveProperty("repos");
+
+ await user.click(screen.getByTestId("automation-setup-repository-add"));
+ await user.click(
+ await screen.findByTestId(
+ "automation-setup-repository-option-OpenHands/software-agent-sdk",
+ ),
+ );
+ await user.click(screen.getByTestId("automation-setup-save"));
+
+ // The saved repository keeps its branch and provider.
+ await waitFor(() =>
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(2),
+ );
+ expect(
+ vi.mocked(AutomationService.updateAutomation).mock.calls[1][1],
+ ).toMatchObject({
+ repos: [
+ { url: "OpenHands/OpenHands", ref: "main", provider: "github" },
+ { url: "OpenHands/software-agent-sdk", provider: "github" },
+ ],
+ });
+ });
+
+ it("saves a repository removal made after an earlier save", async () => {
+ vi.mocked(useDeploymentCapabilities).mockReturnValue({
+ data: {
+ ready: true,
+ features: ["repoUpdate"],
+ triggerKinds: ["cron"],
+ eventSources: [],
+ eventTypes: [],
+ triggers: {},
+ },
+ isLoading: false,
+ } as never);
+ vi.mocked(AutomationService.updateAutomation).mockImplementation(
+ async (_id, body) =>
+ savedReviewer({
+ preset_metadata: {
+ preset_type: "prompt",
+ repos: (body as { repos: unknown }).repos,
+ },
+ }),
+ );
+ initializeAutomationFormSession(
+ PENDING_AUTOMATION_SETUP_ID,
+ setupDraftFromAutomation(savedReviewer()),
+ );
+
+ const user = userEvent.setup();
+ renderSessionBoundPanel(PENDING_AUTOMATION_SETUP_ID);
+
+ await user.click(screen.getByTestId("automation-setup-repository-add"));
+ await user.click(
+ await screen.findByTestId(
+ "automation-setup-repository-option-OpenHands/software-agent-sdk",
+ ),
+ );
+ await user.click(screen.getByTestId("automation-setup-save"));
+ await waitFor(() =>
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(1),
+ );
+
+ await user.click(
+ screen.getByRole("button", {
+ name: "COMMON$REMOVE OpenHands/software-agent-sdk",
+ }),
+ );
+ await user.click(screen.getByTestId("automation-setup-save"));
+
+ await waitFor(() =>
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(2),
+ );
+ expect(
+ vi.mocked(AutomationService.updateAutomation).mock.calls[1][1],
+ ).toMatchObject({
+ repos: [{ url: "OpenHands/OpenHands", ref: "main", provider: "github" }],
+ });
+ clearAutomationFormSession(PENDING_AUTOMATION_SETUP_ID);
+ });
+
+ it("refreshes the cached automation after a save, so Edit from its page starts from the saved repositories", async () => {
+ vi.mocked(useDeploymentCapabilities).mockReturnValue({
+ data: {
+ ready: true,
+ features: ["repoUpdate"],
+ triggerKinds: ["cron"],
+ eventSources: [],
+ eventTypes: [],
+ triggers: {},
+ },
+ isLoading: false,
+ } as never);
+ vi.mocked(AutomationService.updateAutomation).mockImplementation(
+ async (_id, body) =>
+ savedReviewer({
+ preset_metadata: {
+ preset_type: "prompt",
+ repos: (body as { repos: unknown }).repos,
+ },
+ }),
+ );
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ // The automation's page keeps its copy for five minutes and opens Edit from it.
+ const detailKey = [
+ ...AUTOMATION_DETAIL_QUERY_KEY,
+ "auto-1",
+ "cloud",
+ "org-1",
+ ];
+ const listKey = [...AUTOMATIONS_QUERY_KEY, "cloud", "org-1"];
+ queryClient.setQueryData(detailKey, savedReviewer());
+ queryClient.setQueryData(listKey, { automations: [savedReviewer()] });
+
+ const user = userEvent.setup();
+ renderPanel(
+ setupDraftFromAutomation(savedReviewer()),
+ "conv-1",
+ null,
+ queryClient,
+ );
+ await user.click(screen.getByTestId("automation-setup-repository-add"));
+ await user.click(
+ await screen.findByTestId(
+ "automation-setup-repository-option-OpenHands/software-agent-sdk",
+ ),
+ );
+ await user.click(screen.getByTestId("automation-setup-save"));
+ await waitFor(() =>
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(1),
+ );
+
+ await waitFor(() =>
+ expect(
+ setupDraftFromAutomation(
+ queryClient.getQueryData<Automation>(detailKey)!,
+ ).form?.repository,
+ ).toBe("OpenHands/OpenHands, OpenHands/software-agent-sdk"),
+ );
+ expect(queryClient.getQueryState(detailKey)?.isInvalidated).toBe(true);
+ expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(true);
+ });
+
it("shows existing custom bundle metadata without replacing it on save", async () => {
vi.mocked(AutomationService.updateAutomation).mockResolvedValue({
id: "auto-1",
diff --git a/__tests__/components/automations/build-automation-pills.test.tsx b/__tests__/components/automations/build-automation-pills.test.tsx
index 91a06dbe9d..abad10175b 100644
--- a/__tests__/components/automations/build-automation-pills.test.tsx
+++ b/__tests__/components/automations/build-automation-pills.test.tsx
@@ -69,6 +69,31 @@ describe("buildAutomationMetadataPills", () => {
expect(screen.getByTestId("automation-source-logo")).toBeInTheDocument();
});
+ it("shows each repository the automation clones, with its full address on hover", () => {
+ const pills = buildAutomationMetadataPills(
+ buildAutomation({
+ trigger: { type: "cron", schedule: "0 9 * * *" },
+ repositories: [
+ { url: "acme/widgets", provider: "github" },
+ { url: "https://github.com/acme/docs" },
+ ],
+ }),
+ "unused",
+ );
+
+ renderPills(pills);
+
+ expect(screen.getByTestId("pill-repository")).toHaveTextContent(
+ "acme/widgets",
+ );
+ expect(screen.getByTestId("pill-repository-1")).toHaveTextContent(
+ "acme/docs",
+ );
+ expect(
+ screen.getByTitle("https://github.com/acme/docs"),
+ ).toBeInTheDocument();
+ });
+
it("omits the source pill when the event has no source", () => {
const pills = buildAutomationMetadataPills(
buildAutomation({
diff --git a/__tests__/manifests/automation-insights.test.ts b/__tests__/manifests/automation-insights.test.ts
index 79db494afe..c56524c0a0 100644
--- a/__tests__/manifests/automation-insights.test.ts
+++ b/__tests__/manifests/automation-insights.test.ts
@@ -281,6 +281,15 @@ describe("matchesAutomationSearch", () => {
it("rejects an automation matching no field", () => {
expect(matchesAutomationSearch(createAutomation(), "gadget")).toBe(false);
});
+
+ it("matches the repositories the service returns", () => {
+ const automation = createAutomation({
+ repository: undefined,
+ repositories: [{ url: "fabrikam/Fabrikam Fiber/fabrikam-web" }],
+ });
+
+ expect(matchesAutomationSearch(automation, "fabrikam-web")).toBe(true);
+ });
});
describe("applyDashboardView", () => {
diff --git a/__tests__/utils/automation-edit-draft.test.ts b/__tests__/utils/automation-edit-draft.test.ts
index 9a25885848..f411ccc7bf 100644
--- a/__tests__/utils/automation-edit-draft.test.ts
+++ b/__tests__/utils/automation-edit-draft.test.ts
@@ -13,7 +13,13 @@ function automation(overrides: Partial<Automation> = {}): Automation {
timezone: "America/New_York",
},
enabled: true,
- repository: "acme/repo",
+ // What the client reads: repositories lifted from the service's preset
+ // metadata, which has no top-level `repository`.
+ repositories: [{ url: "acme/repo", provider: "github" }],
+ preset_metadata: {
+ preset_type: "prompt",
+ repos: [{ url: "acme/repo", provider: "github" }],
+ },
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
...overrides,
@@ -79,4 +85,42 @@ describe("setupDraftFromAutomation", () => {
expected,
);
});
+
+ it("keeps the saved repositories so an edit can tell what changed", () => {
+ const draft = setupDraftFromAutomation(
+ automation({
+ repositories: [
+ { url: "acme/repo", ref: "main", provider: "github" },
+ { url: "https://github.com/acme/docs" },
+ ],
+ }),
+ );
+
+ expect(draft.form?.repository).toBe(
+ "acme/repo, https://github.com/acme/docs",
+ );
+ expect(draft.existingRepositories).toEqual([
+ { url: "acme/repo", ref: "main", provider: "github" },
+ { url: "https://github.com/acme/docs" },
+ ]);
+ expect(draft.canUpdateRepositories).toBe(true);
+ });
+
+ it("falls back to the single repository of an imported file", () => {
+ const draft = setupDraftFromAutomation(
+ automation({ repositories: undefined, repository: "acme/legacy" }),
+ );
+
+ expect(draft.form?.repository).toBe("acme/legacy");
+ });
+
+ it.each([
+ { name: "a plugin spec", preset_metadata: { preset_type: "plugin_spec" } },
+ { name: "a custom bundle", preset_metadata: null },
+ ])("does not offer repository changes for $name", ({ preset_metadata }) => {
+ expect(
+ setupDraftFromAutomation(automation({ preset_metadata }))
+ .canUpdateRepositories,
+ ).toBe(false);
+ });
});
diff --git a/src/api/automation-form-session.ts b/src/api/automation-form-session.ts
index 3f992c79d2..19854b83a5 100644
--- a/src/api/automation-form-session.ts
+++ b/src/api/automation-form-session.ts
@@ -13,6 +13,8 @@ import type {
AutomationSetupTriggerKind,
AutomationSetupFrequency,
} from "#/api/automation-setup-types";
+import type { AutomationRepository } from "#/types/automation";
+import { readAutomationRepositories } from "#/utils/automation-preset-sources";
const AUTOMATION_FORM_SESSION_CHANGED_EVENT =
"openhands:automation-form-session-changed";
@@ -173,6 +175,9 @@ function normalizeDraft(value: AutomationSetupDraft): AutomationSetupDraft {
typeof value.existingCustomTarballPath === "string"
? value.existingCustomTarballPath.trim()
: "";
+ const existingRepositories = readAutomationRepositories(
+ value.existingRepositories,
+ );
const serverDraftId =
typeof value.serverDraftId === "string" ? value.serverDraftId.trim() : "";
const materializedAutomationId =
@@ -194,6 +199,10 @@ function normalizeDraft(value: AutomationSetupDraft): AutomationSetupDraft {
form: normalizedForm,
...(editingAutomationId ? { editingAutomationId } : {}),
...(existingCustomTarballPath ? { existingCustomTarballPath } : {}),
+ ...(existingRepositories.length > 0 ? { existingRepositories } : {}),
+ ...(value.canUpdateRepositories === true
+ ? { canUpdateRepositories: true }
+ : {}),
...(serverDraftId ? { serverDraftId } : {}),
...(materializedAutomationId ? { materializedAutomationId } : {}),
...(fieldMetadata ? { fieldMetadata } : {}),
@@ -236,6 +245,19 @@ export function initializeAutomationFormSession(
sessions.set(conversationId, normalizeDraft(draft));
}
+/** Record the repositories an edited automation clones after a save. */
+export function setAutomationFormSessionRepositories(
+ conversationId: string,
+ repositories: AutomationRepository[],
+) {
+ const existing = sessions.get(conversationId);
+ if (!existing) return;
+ sessions.set(
+ conversationId,
+ normalizeDraft({ ...existing, existingRepositories: repositories }),
+ );
+}
+
export function getAutomationFormSession(
conversationId: string | null | undefined,
): AutomationSetupDraft | null {
diff --git a/src/api/automation-setup-types.ts b/src/api/automation-setup-types.ts
index ba45a6fa97..a594339321 100644
--- a/src/api/automation-setup-types.ts
+++ b/src/api/automation-setup-types.ts
@@ -1,3 +1,5 @@
+import type { AutomationRepository } from "#/types/automation";
+
export type AutomationSetupKind = "prompt" | "plugin" | "custom";
export type AutomationSetupTriggerKind = "cron" | "event";
export type AutomationSetupFrequency =
@@ -60,6 +62,10 @@ export interface AutomationSetupDraft {
serverDraftId?: string;
materializedAutomationId?: string | null;
existingCustomTarballPath?: string;
+ /** Repositories the edited automation clones, as the service stores them. */
+ existingRepositories?: AutomationRepository[];
+ /** Whether the edited automation's repositories can be changed in place. */
+ canUpdateRepositories?: boolean;
form?: AutomationSetupFormPatch;
fieldMetadata?: Partial<
Record<AutomationSetupField, AutomationSetupFieldMetadata>
diff --git a/src/components/features/automations/build-automation-pills.tsx b/src/components/features/automations/build-automation-pills.tsx
index 15e1f9cbae..7a699c561b 100644
--- a/src/components/features/automations/build-automation-pills.tsx
+++ b/src/components/features/automations/build-automation-pills.tsx
@@ -9,6 +9,7 @@ import type { Automation } from "#/types/automation";
import { cn } from "#/utils/utils";
import { extensionModuleCardPillClassName } from "#/utils/extension-module-card-classes";
import { getMarketplaceEntryById } from "#/utils/mcp-marketplace-utils";
+import { parseGitRemoteUrl } from "#/utils/parse-git-remote-url";
import {
formatTriggerSourceLabel,
getTriggerEventLabel,
@@ -21,17 +22,27 @@ export function buildAutomationMetadataPills(
): SkillCardPill[] {
const pills: SkillCardPill[] = [];
- if (automation.repository) {
+ // The service returns repositories, lifted from preset metadata; only an
+ // imported file shape carries the single `repository`.
+ const repositoryUrls = automation.repositories?.map(({ url }) => url) ?? [];
+ if (repositoryUrls.length === 0 && automation.repository) {
+ repositoryUrls.push(automation.repository);
+ }
+ repositoryUrls.forEach((url, index) => {
+ const name = parseGitRemoteUrl(url)?.repository ?? url;
pills.push({
- id: "repository",
+ id: index === 0 ? "repository" : `repository-${index}`,
node: (
- <span className={cn(extensionModuleCardPillClassName, "gap-1")}>
+ <span
+ className={cn(extensionModuleCardPillClassName, "gap-1")}
+ title={url}
+ >
<FolderIcon className="size-3 shrink-0" />
- {automation.repository}
+ {name}
</span>
),
});
- }
+ });
if (automation.trigger.type === "event") {
const eventLabel = getTriggerEventLabel(automation);
diff --git a/src/components/features/automations/setup/automation-setup-panel.tsx b/src/components/features/automations/setup/automation-setup-panel.tsx
index d6dbc7143a..892dd434f5 100644
--- a/src/components/features/automations/setup/automation-setup-panel.tsx
+++ b/src/components/features/automations/setup/automation-setup-panel.tsx
@@ -32,6 +32,7 @@ import {
initializeAutomationFormSession,
isPendingAutomationSetupId,
patchAutomationFormSession,
+ setAutomationFormSessionRepositories,
subscribeAutomationFormSession,
} from "#/api/automation-form-session";
import type {
@@ -77,6 +78,8 @@ import {
import { Divider } from "#/ui/divider";
import { cn } from "#/utils/utils";
import { useDeploymentCapabilities } from "#/hooks/query/use-manifest-capabilities";
+import { AUTOMATION_DETAIL_QUERY_KEY } from "#/hooks/query/use-automation-detail";
+import { AUTOMATIONS_QUERY_KEY } from "#/hooks/query/use-automations";
import {
invalidateConversationQueries,
patchConversationInCache,
@@ -112,11 +115,18 @@ import {
removeAutomationDraftTags,
} from "#/utils/automation-draft-tags";
import { setupDraftFromAutomation } from "#/utils/automation-edit-draft";
+import { withPresetSources } from "#/utils/automation-preset-sources";
+import {
+ automationRepositoriesChanged,
+ buildAutomationRepoSources,
+} from "#/utils/automation-repo-sources";
const DEFAULT_TIMEZONE = "America/New_York";
const DEFAULT_TIME = "09:00";
const DEFAULT_CUSTOM_SCHEDULE = "0 9 * * *";
const DEFAULT_EVENT_SOURCE = "github";
+// Capability feature: preset repositories can be changed with PATCH.
+const REPO_UPDATE_FEATURE = "repoUpdate";
/** Used when the deployment has not advertised its event sources yet. */
const FALLBACK_EVENT_SOURCES = ["github", "gitlab", "slack", "linear", "jira"];
const DEFAULT_EVENT_KEY = "issue_comment.created";
@@ -727,6 +737,20 @@ export function AutomationSetupPanel({
const [existingCustomTarballPath, setExistingCustomTarballPath] = useState(
draft.existingCustomTarballPath ?? "",
);
+ const [existingRepositories, setExistingRepositories] = useState(
+ draft.existingRepositories ?? [],
+ );
+ const [canUpdateRepositories, setCanUpdateRepositories] = useState(
+ draft.canUpdateRepositories ?? false,
+ );
+ // A new automation sends its repositories on create. An existing one can
+ // change them only when the service can rebuild it with them.
+ const repositoriesEditable =
+ !isEditingExisting ||
+ (canUpdateRepositories &&
+ (deploymentCapabilities.data?.features ?? []).includes(
+ REPO_UPDATE_FEATURE,
+ ));
const streamQueueRef = useRef<
{
field: AutomationSetupField;
@@ -753,6 +777,11 @@ export function AutomationSetupPanel({
setExistingCustomTarballPath(draft.existingCustomTarballPath ?? "");
}, [draft.existingCustomTarballPath]);
+ useEffect(() => {
+ setExistingRepositories(draft.existingRepositories ?? []);
+ setCanUpdateRepositories(draft.canUpdateRepositories ?? false);
+ }, [draft.existingRepositories, draft.canUpdateRepositories]);
+
const updateConversationTags = useCallback(
async (
buildNextTags: (
@@ -848,6 +877,8 @@ export function AutomationSetupPanel({
const nextForm = buildInitialForm(next);
initializeAutomationFormSession(conversationId, next);
setExistingCustomTarballPath(next.existingCustomTarballPath ?? "");
+ setExistingRepositories(next.existingRepositories ?? []);
+ setCanUpdateRepositories(next.canUpdateRepositories ?? false);
setForm(nextForm);
})
.catch((error: unknown) => {
@@ -1216,7 +1247,7 @@ export function AutomationSetupPanel({
} as SetupRequestBody;
const repositories = parseAutomationSetupRepositories(repository);
if (repositories.length > 0) {
- body.repos = repositories.map((url) => ({ url, provider: "github" }));
+ body.repos = buildAutomationRepoSources(repositories);
}
if (showTimeout && timeoutSeconds.trim())
body.timeout = Number(timeoutSeconds);
@@ -1692,8 +1723,9 @@ export function AutomationSetupPanel({
/**
* Only fields accepted by the backend PATCH contract are sent when editing an
- * existing automation. Repositories, plugins and uploaded code are create-time
- * configuration today, so the edit form must not include them in PATCH.
+ * existing automation. Plugins and uploaded code are create-time
+ * configuration, and repositories are sent only when they changed and the
+ * service can rebuild this automation with them.
*/
const buildExistingAutomationBody = () => {
const body: Record<string, unknown> = {
@@ -1706,6 +1738,16 @@ export function AutomationSetupPanel({
if (kind === "custom")
body.agent_profile_id = agentProfileId.trim() || null;
else body.prompt = prompt.trim();
+ const repositories = parseAutomationSetupRepositories(repository);
+ if (
+ repositoriesEditable &&
+ automationRepositoriesChanged(repositories, existingRepositories)
+ ) {
+ body.repos = buildAutomationRepoSources(
+ repositories,
+ existingRepositories,
+ );
+ }
return body as Partial<Automation>;
};
@@ -1715,10 +1757,24 @@ export function AutomationSetupPanel({
setSaveState("saving");
try {
if (!(await ensureCustomWebhookSource())) return;
- await AutomationService.updateAutomation(
+ const updated = await AutomationService.updateAutomation(
editingAutomationId,
buildExistingAutomationBody(),
);
+ const saved = withPresetSources(updated);
+ const savedRepositories = saved.repositories ?? [];
+ // The session re-supplies this draft on every edit, so it must hold the
+ // saved list too, or the next change is compared with the old one.
+ if (conversationId) {
+ setAutomationFormSessionRepositories(conversationId, savedRepositories);
+ }
+ setExistingRepositories(savedRepositories);
+ // The automation's page opens Edit from its cached copy, so replace that
+ // copy with the saved automation before anything can reopen it.
+ const detailKey = [...AUTOMATION_DETAIL_QUERY_KEY, editingAutomationId];
+ queryClient.setQueriesData({ queryKey: detailKey }, saved);
+ queryClient.invalidateQueries({ queryKey: detailKey });
+ queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });
setSaveState("saved");
toast.success(t(I18nKey.AUTOMATIONS$EDIT_SUCCESS));
} catch (error) {
@@ -2017,6 +2073,7 @@ export function AutomationSetupPanel({
onRepositoryChange={(value) =>
updateField("repository", value)
}
+ repositoryReadOnly={!repositoriesEditable}
model={model}
onModelChange={(value) => updateField("model", value)}
/>
diff --git a/src/components/features/automations/setup/automation-setup-prompt-stack.tsx b/src/components/features/automations/setup/automation-setup-prompt-stack.tsx
index a8abe26d8e..7eca775bee 100644
--- a/src/components/features/automations/setup/automation-setup-prompt-stack.tsx
+++ b/src/components/features/automations/setup/automation-setup-prompt-stack.tsx
@@ -10,8 +10,10 @@ import { ModalCloseButton } from "#/components/shared/modals/modal-close-button"
import { ContextMenuListItem } from "#/components/features/context-menu/context-menu-list-item";
import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";
import { useGitRepositories } from "#/hooks/query/use-git-repositories";
+import { useSearchRepositories } from "#/hooks/query/use-search-repositories";
import { useLlmProfiles } from "#/hooks/query/use-llm-profiles";
import { useClickOutsideElement } from "#/hooks/use-click-outside-element";
+import { useDebounce } from "#/hooks/use-debounce";
import { useUserProviders } from "#/hooks/use-user-providers";
import { usePromptTextareaResize } from "#/hooks/use-prompt-textarea-resize";
import { I18nKey } from "#/i18n/declaration";
@@ -23,11 +25,14 @@ import { ContextMenu } from "#/ui/context-menu";
import { extensionModuleCardPillClassName } from "#/utils/extension-module-card-classes";
import { chatInputPillButtonClassName } from "#/utils/form-control-classes";
import { modalTitleLgClassName } from "#/utils/modal-classes";
-import { cn } from "#/utils/utils";
+import { cn, getProviderName } from "#/utils/utils";
import { formatModelNameForDisplay } from "#/utils/format-model-name";
import type { Provider } from "#/types/settings";
const PROFILE_LABEL_MAX_CHARS = 18;
+// Automations clone the picker's `owner/repo` names as GitHub repositories.
+const AUTOMATION_CLONE_PROVIDER: Provider = "github";
+const REPOSITORY_SEARCH_DEBOUNCE_MS = 300;
function truncateLabel(label: string): string {
return label.length <= PROFILE_LABEL_MAX_CHARS
@@ -245,6 +250,7 @@ export function AutomationSetupPromptStack({
titleAction,
showTitle = true,
model,
+ repositoryReadOnly = false,
onPromptChange,
onRepositoryChange,
onModelChange,
@@ -260,6 +266,8 @@ export function AutomationSetupPromptStack({
/** The setup form owns the title when the kind toggle stays outside the crossfade. */
showTitle?: boolean;
model: string;
+ /** Show the repositories without letting them be added or removed. */
+ repositoryReadOnly?: boolean;
onPromptChange: (value: string) => void;
onRepositoryChange: (value: string) => void;
onModelChange: (profileName: string) => void;
@@ -296,7 +304,28 @@ export function AutomationSetupPromptStack({
.flatMap((page) => page.items)
.map((repo) => repo.full_name);
const repositorySearchText = repositorySearch.trim().toLowerCase();
- const listedRepositoryNames = repositoryNames.filter(
+ // The loaded pages may not hold every match, so a search also asks the
+ // provider.
+ const debouncedRepositorySearch = useDebounce(
+ repositorySearch.trim(),
+ REPOSITORY_SEARCH_DEBOUNCE_MS,
+ );
+ const repositorySearchQuery = useSearchRepositories(
+ debouncedRepositorySearch,
+ repositoryProvider,
+ !isRepositoryMenuOpen,
+ );
+ const isRepositorySearchLoading =
+ repositorySearchText !== "" &&
+ (repositorySearchQuery.isFetching ||
+ debouncedRepositorySearch !== repositorySearch.trim());
+ const searchedRepositoryNames = repositorySearchText
+ ? (repositorySearchQuery.data ?? []).map((repo) => repo.full_name)
+ : [];
+ const listedRepositoryNames = [
+ ...repositoryNames,
+ ...searchedRepositoryNames,
+ ].filter(
(name, index, names) =>
!repositories.includes(name) && names.indexOf(name) === index,
);
@@ -306,6 +335,9 @@ export function AutomationSetupPromptStack({
)
: listedRepositoryNames;
const addLabel = `${t(I18nKey.BUTTON$ADD)} ${t(I18nKey.AUTOMATIONS$DETAIL$REPOSITORIES)}`;
+ const isRepositoryProviderUnsupported =
+ repositoryProvider !== null &&
+ repositoryProvider !== AUTOMATION_CLONE_PROVIDER;
const writeRepositories = (next: string[]) => {
onRepositoryChange(next.join(", "));
@@ -396,23 +428,32 @@ export function AutomationSetupPromptStack({
{repositorySuffix}
</span>
) : null}
- <button
- ref={repositoryAddRef}
- type="button"
- data-testid="automation-setup-repository-add"
- aria-label={addLabel}
- aria-haspopup="menu"
- aria-expanded={isRepositoryMenuOpen}
- className="inline-flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--oh-muted)] hover:bg-white/10 hover:text-white"
- onMouseDown={(event) => event.preventDefault()}
- onClick={() => {
- setRepositorySearch("");
- setIsRepositoryMenuOpen((open) => !open);
- }}
- >
- <Plus className="size-4" aria-hidden />
- </button>
- {isLocalGithubTokenMissing ? (
+ {repositoryReadOnly ? (
+ <span
+ data-testid="automation-setup-repository-read-only"
+ className="text-xs text-muted"
+ >
+ {t(I18nKey.AUTOMATION_SETUP$REPOSITORIES_READ_ONLY)}
+ </span>
+ ) : (
+ <button
+ ref={repositoryAddRef}
+ type="button"
+ data-testid="automation-setup-repository-add"
+ aria-label={addLabel}
+ aria-haspopup="menu"
+ aria-expanded={isRepositoryMenuOpen}
+ className="inline-flex size-6 shrink-0 items-center justify-center rounded-md text-[var(--oh-muted)] hover:bg-white/10 hover:text-white"
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => {
+ setRepositorySearch("");
+ setIsRepositoryMenuOpen((open) => !open);
+ }}
+ >
+ <Plus className="size-4" aria-hidden />
+ </button>
+ )}
+ {isLocalGithubTokenMissing && !repositoryReadOnly ? (
<StyledTooltip
content={t(
I18nKey.AUTOMATION_SETUP$GITHUB_TOKEN_REQUIRED_TOOLTIP,
@@ -437,7 +478,7 @@ export function AutomationSetupPromptStack({
ref={repositoryMenuRef}
role="menu"
data-testid="automation-setup-repository-menu"
- className="absolute top-full left-0 z-[60] mt-1 flex max-h-72 w-[260px] flex-col overflow-hidden rounded-md border border-border-subtle bg-tertiary py-1 shadow-lg"
+ className="absolute top-full left-0 z-[60] mt-1 flex max-h-72 w-[min(28rem,calc(100vw-3rem))] flex-col overflow-hidden rounded-md border border-border-subtle bg-tertiary py-1 shadow-lg"
>
<div className="shrink-0 px-2">
<div className="relative">
@@ -474,6 +515,17 @@ export function AutomationSetupPromptStack({
}
}}
>
+ {isRepositoryProviderUnsupported && repositoryProvider ? (
+ <p
+ data-testid="automation-setup-repository-unsupported"
+ className="px-2 py-2 text-sm text-muted"
+ >
+ {t(
+ I18nKey.AUTOMATION_SETUP$REPOSITORY_PROVIDER_UNSUPPORTED,
+ { provider: getProviderName(repositoryProvider) },
+ )}
+ </p>
+ ) : null}
{isRepositoryListError ? (
<p
data-testid="automation-setup-repository-error"
@@ -481,7 +533,8 @@ export function AutomationSetupPromptStack({
>
{t(I18nKey.HOME$FAILED_TO_LOAD_REPOSITORIES)}
</p>
- ) : isRepositoryListLoading &&
+ ) : (isRepositoryListLoading ||
+ isRepositorySearchLoading) &&
visibleRepositoryNames.length === 0 ? (
<div
data-testid="automation-setup-repository-loading"
@@ -500,14 +553,20 @@ export function AutomationSetupPromptStack({
writeRepositories([...repositories, name]);
setIsRepositoryMenuOpen(false);
}}
- className="flex w-full items-center"
+ isDisabled={isRepositoryProviderUnsupported}
+ className="flex w-full items-center text-wrap"
>
- <span className="truncate">{name}</span>
+ {/* Organization/project/repository names can be
+ long; wrap them so every option reads in full. */}
+ <span className="min-w-0 break-all" title={name}>
+ {name}
+ </span>
</ContextMenuListItem>
))
)}
{repositorySearchText &&
!isRepositoryListLoading &&
+ !isRepositorySearchLoading &&
!isRepositoryListError &&
visibleRepositoryNames.length === 0 ? (
<p className="px-2 py-2 text-sm text-muted italic">
@@ -551,21 +610,25 @@ export function AutomationSetupPromptStack({
"gap-1 pr-1",
)}
>
- <span className="truncate">{item}</span>
- <button
- type="button"
- data-testid="automation-setup-repository-remove"
- aria-label={`${t(I18nKey.COMMON$REMOVE)} ${item}`}
- className="inline-flex size-4 items-center justify-center rounded-full text-tertiary-light hover:bg-white/10 hover:text-white"
- onMouseDown={(event) => event.preventDefault()}
- onClick={() =>
- writeRepositories(
- repositories.filter((entry) => entry !== item),
- )
- }
- >
- <X className="size-3" aria-hidden />
- </button>
+ <span className="truncate" title={item}>
+ {item}
+ </span>
+ {repositoryReadOnly ? null : (
+ <button
+ type="button"
+ data-testid="automation-setup-repository-remove"
+ aria-label={`${t(I18nKey.COMMON$REMOVE)} ${item}`}
+ className="inline-flex size-4 items-center justify-center rounded-full text-tertiary-light hover:bg-white/10 hover:text-white"
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() =>
+ writeRepositories(
+ repositories.filter((entry) => entry !== item),
+ )
+ }
+ >
+ <X className="size-3" aria-hidden />
+ </button>
+ )}
</span>
))}
</div>
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index ff61525c99..9f5f289d5e 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -51245,6 +51245,42 @@
"zh-TW": "在設定頁面設定「GITHUB_TOKEN」密鑰即可查看儲存庫選項。",
"id": "Konfigurasikan rahasia token penyedia, mis. \"GITHUB_TOKEN\", di halaman Pengaturan untuk melihat opsi repositori."
},
+ "AUTOMATION_SETUP$REPOSITORIES_READ_ONLY": {
+ "en": "Can't be changed for this automation",
+ "ja": "このオートメーションでは変更できません",
+ "zh-CN": "此自动化的仓库无法更改",
+ "zh-TW": "此自動化的儲存庫無法變更",
+ "ko-KR": "이 자동화에서는 변경할 수 없습니다",
+ "no": "Kan ikke endres for denne automatiseringen",
+ "ar": "لا يمكن تغييرها لهذه الأتمتة",
+ "de": "Für diese Automatisierung nicht änderbar",
+ "fr": "Non modifiables pour cette automatisation",
+ "it": "Non modificabili per questa automazione",
+ "pt": "Não podem ser alterados nesta automação",
+ "es": "No se pueden cambiar en esta automatización",
+ "tr": "Bu otomasyon için değiştirilemez",
+ "uk": "Не можна змінити для цієї автоматизації",
+ "ca": "No es poden canviar en aquesta automatització",
+ "id": "Tidak dapat diubah untuk otomatisasi ini"
+ },
+ "AUTOMATION_SETUP$REPOSITORY_PROVIDER_UNSUPPORTED": {
+ "en": "Automations can't clone {{provider}} repositories yet.",
+ "ja": "オートメーションはまだ {{provider}} のリポジトリをクローンできません。",
+ "zh-CN": "自动化暂时无法克隆 {{provider}} 仓库。",
+ "zh-TW": "自動化暫時無法複製 {{provider}} 儲存庫。",
+ "ko-KR": "자동화는 아직 {{provider}} 저장소를 복제할 수 없습니다.",
+ "no": "Automatiseringer kan ikke klone {{provider}}-repositorier ennå.",
+ "ar": "لا يمكن للأتمتة استنساخ مستودعات {{provider}} بعد.",
+ "de": "Automatisierungen können {{provider}}-Repositorys noch nicht klonen.",
+ "fr": "Les automatisations ne peuvent pas encore cloner les dépôts {{provider}}.",
+ "it": "Le automazioni non possono ancora clonare i repository {{provider}}.",
+ "pt": "As automações ainda não podem clonar repositórios do {{provider}}.",
+ "es": "Las automatizaciones aún no pueden clonar repositorios de {{provider}}.",
+ "tr": "Otomasyonlar henüz {{provider}} depolarını klonlayamaz.",
+ "uk": "Автоматизації поки що не можуть клонувати репозиторії {{provider}}.",
+ "ca": "Les automatitzacions encara no poden clonar repositoris de {{provider}}.",
+ "id": "Otomatisasi belum dapat mengkloning repositori {{provider}}."
+ },
"AUTOMATION_SETUP$CUSTOM_PYTHON": {
"ar": "Custom Python",
"ca": "Custom Python",
diff --git a/src/manifests/automation-insights.ts b/src/manifests/automation-insights.ts
index 8733d0ccea..2a55260892 100644
--- a/src/manifests/automation-insights.ts
+++ b/src/manifests/automation-insights.ts
@@ -166,6 +166,9 @@ export function matchesAutomationSearch(
return (
automation.name.toLowerCase().includes(q) ||
(automation.prompt ?? "").toLowerCase().includes(q) ||
+ (automation.repositories ?? []).some(({ url }) =>
+ url.toLowerCase().includes(q),
+ ) ||
automation.repository?.toLowerCase().includes(q) === true ||
automation.model?.toLowerCase().includes(q) === true
);
diff --git a/src/mocks/automation-handlers.ts b/src/mocks/automation-handlers.ts
index 03577ffacc..998b3a1887 100644
--- a/src/mocks/automation-handlers.ts
+++ b/src/mocks/automation-handlers.ts
@@ -10,6 +10,7 @@ import type {
} from "#/manifests/types";
import type {
Automation,
+ AutomationRepository,
AutomationsResponse,
AutomationRun,
AutomationRunsResponse,
@@ -29,6 +30,8 @@ const CAPABILITIES: DeploymentCapabilities = {
features: [
...(capabilitiesFixture.responses.supported.body.features ?? []),
"automationDrafts",
+ // Changing a preset's repositories with PATCH is newer than the fixture too.
+ "repoUpdate",
],
};
@@ -418,11 +421,13 @@ export const AUTOMATION_HANDLERS = [
prompt: string;
model?: string;
trigger: Automation["trigger"];
- repos?: { url: string; ref?: string }[];
+ repos?: AutomationRepository[];
plugins?: { source: string }[];
timeout?: number;
};
const now = new Date().toISOString();
+ // Like the service: repositories live only in preset metadata, which the
+ // client lifts onto `repositories` when it reads the automation.
const automation: Automation = {
id: crypto.randomUUID(),
name: body.name,
@@ -433,10 +438,11 @@ export const AUTOMATION_HANDLERS = [
created_at: now,
updated_at: now,
last_triggered_at: null,
- ...(body.repos?.[0] && {
- repository: body.repos[0].url,
- branch: body.repos[0].ref,
- }),
+ preset_metadata: {
+ preset_type: params.kind,
+ prompt: body.prompt,
+ ...(body.repos?.length && { repos: body.repos }),
+ },
...(body.plugins && {
plugins: body.plugins.map((plugin) => plugin.source),
}),
@@ -510,7 +516,9 @@ export const AUTOMATION_HANDLERS = [
const id = params.id as string;
// Clone the request before reading the body to avoid "Body has already been read" errors
// when MSW internally consumes the body during handler resolution.
- const body = (await request.clone().json()) as Partial<Automation>;
+ const { repos, ...body } = (await request.clone().json()) as Partial<
+ Automation & { repos: AutomationRepository[] | null }
+ >;
const automation = automations.get(id);
if (!automation) {
return HttpResponse.json(
@@ -519,9 +527,16 @@ export const AUTOMATION_HANDLERS = [
);
}
+ // Repositories replace the preset's whole list, as the service applies them.
+ let presetMetadata = automation.preset_metadata;
+ if (repos !== undefined) {
+ const { repos: _previous, ...rest } = presetMetadata ?? {};
+ presetMetadata = { ...rest, ...(repos?.length && { repos }) };
+ }
const updated: Automation = {
...automation,
...body,
+ preset_metadata: presetMetadata,
updated_at: new Date().toISOString(),
};
automations.set(id, updated);
diff --git a/src/types/automation.ts b/src/types/automation.ts
index 4aec50e19a..ca04ecf69c 100644
--- a/src/types/automation.ts
+++ b/src/types/automation.ts
@@ -30,6 +30,8 @@ export interface AutomationRepository {
url: string;
/** Branch, tag or commit to check out; absent uses the default branch. */
ref?: string;
+ /** Git provider that authenticates the clone; required for the shorthand. */
+ provider?: string;
}
export type AutomationState = "ACTIVE" | "INACTIVE" | "DRAFT";
diff --git a/src/utils/automation-edit-draft.ts b/src/utils/automation-edit-draft.ts
index 76e816c0f2..eb0ffabc84 100644
--- a/src/utils/automation-edit-draft.ts
+++ b/src/utils/automation-edit-draft.ts
@@ -12,12 +12,16 @@ import {
type AutomationSetupKind,
} from "#/api/automation-setup-types";
import type { Automation } from "#/types/automation";
+import { formatAutomationRepositories } from "#/utils/automation-repo-sources";
import {
formatTimeOfDay,
parseCronSchedule,
} from "#/utils/automation-schedule";
const HOURLY_CRON = "0 * * * *";
+// Prompt and plugin presets bake their repositories into a package the
+// service can rebuild; other automations keep them fixed.
+const REPOSITORY_UPDATABLE_PRESET_TYPES = new Set(["prompt", "plugin"]);
function setupKind(automation: Automation): AutomationSetupKind {
if ((automation.plugins?.length ?? 0) > 0) return "plugin";
@@ -25,6 +29,14 @@ function setupKind(automation: Automation): AutomationSetupKind {
return "prompt";
}
+function canUpdateRepositories(automation: Automation): boolean {
+ const presetType = automation.preset_metadata?.preset_type;
+ return (
+ typeof presetType === "string" &&
+ REPOSITORY_UPDATABLE_PRESET_TYPES.has(presetType)
+ );
+}
+
function eventKey(on: Automation["trigger"]["on"]): string {
if (Array.isArray(on)) return on.join(",");
return on ?? "";
@@ -86,7 +98,9 @@ export function setupDraftFromAutomation(
kind,
name: automation.name,
prompt,
- repository: automation.repository ?? "",
+ repository:
+ formatAutomationRepositories(automation.repositories) ||
+ (automation.repository ?? ""),
model: automation.model ?? "",
agentProfileId: automation.agent_profile_id ?? "",
entrypoint: automation.entrypoint ?? "",
@@ -113,6 +127,8 @@ export function setupDraftFromAutomation(
prompt,
kind,
editingAutomationId: automation.id,
+ existingRepositories: automation.repositories ?? [],
+ canUpdateRepositories: canUpdateRepositories(automation),
...(kind === "custom" && automation.tarball_path
? { existingCustomTarballPath: automation.tarball_path }
: {}),
diff --git a/src/utils/automation-preset-sources.ts b/src/utils/automation-preset-sources.ts
index 00095330ec..71b37ea822 100644
--- a/src/utils/automation-preset-sources.ts
+++ b/src/utils/automation-preset-sources.ts
@@ -16,14 +16,16 @@ function readNonEmptyString(value: unknown): string | undefined {
: undefined;
}
-function readPresetRepositories(
- metadata: UnknownRecord,
+/** The repository entries in `value` that name a URL. */
+export function readAutomationRepositories(
+ value: unknown,
): AutomationRepository[] {
- return readRecords(metadata.repos).flatMap((repo) => {
+ return readRecords(value).flatMap((repo) => {
const url = readNonEmptyString(repo.url);
if (!url) return [];
const ref = readNonEmptyString(repo.ref);
- return [{ url, ...(ref && { ref }) }];
+ const provider = readNonEmptyString(repo.provider);
+ return [{ url, ...(ref && { ref }), ...(provider && { provider }) }];
});
}
@@ -48,7 +50,7 @@ export function withPresetSources(automation: Automation): Automation {
? automation.preset_metadata
: {};
- const presetRepositories = readPresetRepositories(metadata);
+ const presetRepositories = readAutomationRepositories(metadata.repos);
const legacyRepositories: AutomationRepository[] = automation.repository
? [
{
diff --git a/src/utils/automation-repo-sources.ts b/src/utils/automation-repo-sources.ts
new file mode 100644
index 0000000000..033f5d50c8
--- /dev/null
+++ b/src/utils/automation-repo-sources.ts
@@ -0,0 +1,61 @@
+import type { AutomationRepository } from "#/types/automation";
+
+/** A `repos` entry in a preset create or update request. */
+export type AutomationRepoSource = {
+ url: string;
+ ref?: string;
+ provider?: string;
+};
+
+// The setup picker lists GitHub repositories by their `owner/repo` shorthand,
+// and the service needs a provider to clone a shorthand.
+const SHORTHAND_PROVIDER = "github";
+const FULL_GIT_URL_PATTERN = /^(?:https?:\/\/|git@)/i;
+
+/**
+ * The `repos` a request sends for the setup form's repositories.
+ *
+ * A repository the automation already clones keeps its saved branch and
+ * provider. A new shorthand is a GitHub repository. A full URL is sent without
+ * a provider, so the service authenticates its clone only for that URL's own
+ * host.
+ */
+export function buildAutomationRepoSources(
+ repositories: string[],
+ saved: AutomationRepository[] = [],
+): AutomationRepoSource[] {
+ return repositories.map((url) => {
+ const existing = saved.find((repo) => repo.url === url);
+ if (existing) {
+ return {
+ url: existing.url,
+ ...(existing.ref && { ref: existing.ref }),
+ ...(existing.provider && { provider: existing.provider }),
+ };
+ }
+ return FULL_GIT_URL_PATTERN.test(url)
+ ? { url }
+ : { url, provider: SHORTHAND_PROVIDER };
+ });
+}
+
+/** Whether the form lists other repositories than the automation clones. */
+export function automationRepositoriesChanged(
+ repositories: string[],
+ saved: AutomationRepository[] = [],
+): boolean {
+ return (
+ repositories.length !== saved.length ||
+ repositories.some((url, index) => url !== saved[index]?.url)
+ );
+}
+
+/** Repositories in the setup form's comma-separated shape. */
+export function formatAutomationRepositories(
+ repositories: AutomationRepository[] = [],
+): string {
+ return repositories
+ .map((repo) => repo.url.trim())
+ .filter(Boolean)
+ .join(", ");
+}