π OpenHands: AI-Driven Development
feat(automations): list every cloneable provider's repositories in the automation picker (#18821)
Alonaee80223e7650
diff --git a/__tests__/api/automation-handlers.test.ts b/__tests__/api/automation-handlers.test.tsindex f4d8ad3e9c..4114e2cc52 100644--- a/__tests__/api/automation-handlers.test.ts+++ b/__tests__/api/automation-handlers.test.ts@@ -88,6 +88,9 @@ describe("Automation MSW Handlers", () => {"automationDrafts","repoUpdate",],+ // Newer than the pinned fixture as well: the providers whose+ // repositories a run clones.+ repoProviders: ["bitbucket", "github", "gitlab"],},});});diff --git a/__tests__/components/automations/automation-setup-panel.test.tsx b/__tests__/components/automations/automation-setup-panel.test.tsxindex 76655db020..50f3397c43 100644--- a/__tests__/components/automations/automation-setup-panel.test.tsx+++ b/__tests__/components/automations/automation-setup-panel.test.tsx@@ -42,6 +42,7 @@ 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";+import type { Provider } from "#/types/settings";const mockNavigate = vi.fn();const mockToastSuccess = vi.fn();@@ -75,11 +76,40 @@ const createGitRepositoriesQueryResult = () => ({fetchNextPage: vi.fn(),onLoadMore: vi.fn(),});-const mockUseGitRepositories = vi.fn(createGitRepositoriesQueryResult);+/** One private repository listed by another provider than GitHub. */+const createProviderRepositoriesQueryResult = (+ provider: Provider,+ fullName: string,+) => ({+ ...createGitRepositoriesQueryResult(),+ data: {+ pages: [+ {+ items: [+ {+ id: `${provider}-1`,+ full_name: fullName,+ git_provider: provider,+ is_public: false,+ },+ ],+ missing_token: false,+ next_page_id: null,+ },+ ],+ },+});+const mockUseGitRepositories = vi.fn(+ (_options?: { provider?: Provider | null }) =>+ createGitRepositoriesQueryResult(),+);const mockUseSearchRepositories = vi.fn((..._args: unknown[]) => ({data: undefined as { full_name: string }[] | undefined,isFetching: false,}));+const mockUseSettings = vi.fn(() => ({+ data: { provider_tokens_set: {} as Record<string, string | null> },+}));const { mockSendMessage } = vi.hoisted(() => ({mockSendMessage: vi.fn().mockResolvedValue({ queued: false }),@@ -178,7 +208,12 @@ vi.mock("#/hooks/use-user-providers", () => ({}));vi.mock("#/hooks/query/use-git-repositories", () => ({- useGitRepositories: () => mockUseGitRepositories(),+ useGitRepositories: (options: { provider?: Provider | null }) =>+ mockUseGitRepositories(options),+}));++vi.mock("#/hooks/query/use-settings", () => ({+ useSettings: () => mockUseSettings(),}));vi.mock("#/hooks/query/use-search-repositories", () => ({@@ -322,6 +357,7 @@ describe("AutomationSetupPanel", () => {providers: ["github"],isLoadingSettings: false,});+ mockUseSettings.mockReturnValue({ data: { provider_tokens_set: {} } });});afterEach(() => {@@ -863,6 +899,320 @@ describe("AutomationSetupPanel", () => {).not.toBeInTheDocument();});+ it("adds a GitLab repository by its URL and sends it without a provider", async () => {+ vi.mocked(AutomationService.createServerDraft).mockRejectedValue({+ response: { status: 404 },+ });+ vi.mocked(AutomationService.validateDraft).mockResolvedValue({+ valid: true,+ errors: [],+ });+ mockUseUserProviders.mockReturnValue({+ providers: ["gitlab"],+ isLoadingSettings: false,+ });+ // The server names the connection's host; gitlab.com is the hosted service.+ mockUseSettings.mockReturnValue({+ data: { provider_tokens_set: { gitlab: "gitlab.com" } },+ });+ mockUseGitRepositories.mockReturnValue(+ createProviderRepositoriesQueryResult("gitlab", "acme/tools"),+ );++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-repository-add"));+ // One cloneable provider needs no provider choice.+ expect(+ screen.queryByTestId("automation-setup-repository-provider"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("automation-setup-repository-unsupported"),+ ).not.toBeInTheDocument();+ await user.click(+ screen.getByTestId("automation-setup-repository-option-acme/tools"),+ );++ expect(+ screen.getByTestId("automation-setup-repository-value"),+ ).toHaveTextContent("https://gitlab.com/acme/tools");++ await user.click(screen.getByTestId("automation-setup-test"));++ // gitlab.com is a hosted service the run recognizes on its own.+ await waitFor(() =>+ expect(AutomationService.validateDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ draft: expect.objectContaining({+ repos: [{ url: "https://gitlab.com/acme/tools" }],+ }),+ }),+ ),+ );+ });++ it("keeps GitLab repositories disabled when the server reports no host", async () => {+ // The same name covers gitlab.com and a self-managed instance, so without+ // the host the form cannot address the repository and must not guess.+ mockUseUserProviders.mockReturnValue({+ providers: ["gitlab"],+ isLoadingSettings: false,+ });+ mockUseSettings.mockReturnValue({+ data: { provider_tokens_set: { gitlab: null } },+ });+ mockUseGitRepositories.mockReturnValue(+ createProviderRepositoriesQueryResult("gitlab", "acme/tools"),+ );++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-repository-add"));++ expect(+ screen.queryByTestId("automation-setup-repository-provider"),+ ).not.toBeInTheDocument();+ expect(+ screen.getByTestId("automation-setup-repository-unsupported"),+ ).toHaveTextContent("AUTOMATION_SETUP$REPOSITORY_PROVIDER_UNSUPPORTED");+ const option = screen.getByTestId(+ "automation-setup-repository-option-acme/tools",+ );+ expect(option).toBeDisabled();+ await user.click(option);+ expect(+ screen.queryByTestId("automation-setup-repository-value"),+ ).not.toBeInTheDocument();+ });++ it("names the provider of a repository on a connected self-hosted host", async () => {+ vi.mocked(AutomationService.createServerDraft).mockRejectedValue({+ response: { status: 404 },+ });+ vi.mocked(AutomationService.validateDraft).mockResolvedValue({+ valid: true,+ errors: [],+ });+ mockUseUserProviders.mockReturnValue({+ providers: ["gitlab"],+ isLoadingSettings: false,+ });+ mockUseSettings.mockReturnValue({+ data: { provider_tokens_set: { gitlab: "https://gitlab.example.com" } },+ });+ mockUseGitRepositories.mockReturnValue(+ createProviderRepositoriesQueryResult("gitlab", "acme/tools"),+ );++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-repository-add"));+ await user.click(+ screen.getByTestId("automation-setup-repository-option-acme/tools"),+ );++ expect(+ screen.getByTestId("automation-setup-repository-value"),+ ).toHaveTextContent("https://gitlab.example.com/acme/tools");++ await user.click(screen.getByTestId("automation-setup-test"));++ // The run cannot tell whose host this is, so the provider goes along.+ await waitFor(() =>+ expect(AutomationService.validateDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ draft: expect.objectContaining({+ repos: [+ {+ url: "https://gitlab.example.com/acme/tools",+ provider: "gitlab",+ },+ ],+ }),+ }),+ ),+ );+ });++ it("sends no provider for a pasted URL on a host the run cannot clone from", async () => {+ vi.mocked(AutomationService.createServerDraft).mockRejectedValue({+ response: { status: 404 },+ });+ vi.mocked(AutomationService.validateDraft).mockResolvedValue({+ valid: true,+ errors: [],+ });+ mockUseUserProviders.mockReturnValue({+ providers: ["github", "bitbucket_data_center"],+ isLoadingSettings: false,+ });+ mockUseSettings.mockReturnValue({+ data: {+ provider_tokens_set: {+ github: "",+ bitbucket_data_center: "https://bb.example.com",+ },+ },+ });++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-repository-add"));+ // Only GitHub is cloneable here, so there is no provider choice to make.+ expect(+ screen.queryByTestId("automation-setup-repository-provider"),+ ).not.toBeInTheDocument();+ await user.click(screen.getByTestId("automation-setup-repository-custom"));+ await user.type(+ screen.getByTestId("automation-setup-repository-address"),+ "https://bb.example.com/PROJ/repo",+ );+ await user.click(screen.getByTestId("automation-setup-repository-submit"));+ await user.click(screen.getByTestId("automation-setup-test"));++ // The service's schema does not know bitbucket_data_center, so the URL+ // goes alone rather than failing the whole request.+ await waitFor(() =>+ expect(AutomationService.validateDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ draft: expect.objectContaining({+ repos: [{ url: "https://bb.example.com/PROJ/repo" }],+ }),+ }),+ ),+ );+ });++ it("lets a user with several providers choose whose repositories to list", async () => {+ mockUseUserProviders.mockReturnValue({+ providers: ["github", "gitlab"],+ isLoadingSettings: false,+ });+ mockUseSettings.mockReturnValue({+ data: { provider_tokens_set: { github: null, gitlab: "gitlab.com" } },+ });+ mockUseGitRepositories.mockImplementation((options) =>+ options?.provider === "gitlab"+ ? createProviderRepositoriesQueryResult("gitlab", "acme/tools")+ : createGitRepositoriesQueryResult(),+ );++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-repository-add"));+ const providerSelect = screen.getByTestId(+ "automation-setup-repository-provider",+ );+ expect(providerSelect).toHaveValue("github");+ expect(+ within(providerSelect)+ .getAllByRole("option")+ .map((option) => option.textContent),+ ).toEqual(["GitHub", "GitLab"]);+ expect(+ screen.getByTestId(+ "automation-setup-repository-option-OpenHands/OpenHands",+ ),+ ).toBeInTheDocument();++ await user.selectOptions(providerSelect, "gitlab");++ expect(+ await screen.findByTestId(+ "automation-setup-repository-option-acme/tools",+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByTestId(+ "automation-setup-repository-option-OpenHands/OpenHands",+ ),+ ).not.toBeInTheDocument();+ expect(mockUseSearchRepositories).toHaveBeenLastCalledWith(+ "",+ "gitlab",+ false,+ );++ await user.click(+ screen.getByTestId("automation-setup-repository-option-acme/tools"),+ );+ expect(+ screen.getByTestId("automation-setup-repository-value"),+ ).toHaveTextContent("https://gitlab.com/acme/tools");+ });++ it("offers Azure DevOps repositories when the service clones them", async () => {+ vi.mocked(useDeploymentCapabilities).mockReturnValue({+ data: {+ ready: true,+ features: [],+ triggerKinds: ["cron"],+ eventSources: [],+ eventTypes: [],+ triggers: {},+ repoProviders: ["azure_devops", "github"],+ },+ isLoading: false,+ } as never);+ vi.mocked(AutomationService.createServerDraft).mockRejectedValue({+ response: { status: 404 },+ });+ vi.mocked(AutomationService.validateDraft).mockResolvedValue({+ valid: true,+ errors: [],+ });+ mockUseUserProviders.mockReturnValue({+ providers: ["azure_devops"],+ isLoadingSettings: false,+ });+ mockUseGitRepositories.mockReturnValue(+ createProviderRepositoriesQueryResult(+ "azure_devops",+ "fabrikam/Fabrikam Fiber/fabrikam-web",+ ),+ );++ const user = userEvent.setup();+ renderPanel();++ await user.click(screen.getByTestId("automation-setup-repository-add"));+ expect(+ screen.queryByTestId("automation-setup-repository-unsupported"),+ ).not.toBeInTheDocument();+ const option = screen.getByTestId(+ "automation-setup-repository-option-fabrikam/Fabrikam Fiber/fabrikam-web",+ );+ expect(option).not.toBeDisabled();+ await user.click(option);++ expect(+ screen.getByTestId("automation-setup-repository-value"),+ ).toHaveTextContent(+ "https://dev.azure.com/fabrikam/Fabrikam%20Fiber/_git/fabrikam-web",+ );++ await user.click(screen.getByTestId("automation-setup-test"));++ await waitFor(() =>+ expect(AutomationService.validateDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ draft: expect.objectContaining({+ repos: [+ {+ url: "https://dev.azure.com/fabrikam/Fabrikam%20Fiber/_git/fabrikam-web",+ },+ ],+ }),+ }),+ ),+ );+ });+it("streams agent form updates field by field without overwriting user edits", async () => {vi.useFakeTimers();const conversationId = "conv-agent-updates";diff --git a/__tests__/utils/automation-repo-sources.test.ts b/__tests__/utils/automation-repo-sources.test.tsnew file mode 100644index 0000000000..f30163a09d--- /dev/null+++ b/__tests__/utils/automation-repo-sources.test.ts@@ -0,0 +1,312 @@+import { describe, expect, it } from "vitest";+import {+ automationRepositoryAddress,+ buildAutomationRepoSources,+ providerBaseUrl,+ providerForAddress,+ providerHostKnown,+} from "#/utils/automation-repo-sources";++describe("automationRepositoryAddress", () => {+ it("keeps GitHub's owner/repo shorthand", () => {+ expect(automationRepositoryAddress("github", "OpenHands/OpenHands")).toBe(+ "OpenHands/OpenHands",+ );+ expect(+ automationRepositoryAddress("github", "OpenHands/OpenHands", null),+ ).toBe("OpenHands/OpenHands");+ });++ it("uses the hosted service for a connection the server reports on it", () => {+ expect(+ automationRepositoryAddress("gitlab", "acme/tools", "gitlab.com"),+ ).toBe("https://gitlab.com/acme/tools");+ expect(automationRepositoryAddress("bitbucket", "acme/tools")).toBe(+ "https://bitbucket.org/acme/tools",+ );+ });++ it("builds no address for a GitLab or Forgejo connection without a host", () => {+ // The same name covers gitlab.com and a self-managed instance, so an+ // unreported host must not become the public service.+ expect(automationRepositoryAddress("gitlab", "acme/tools")).toBeNull();+ expect(automationRepositoryAddress("gitlab", "acme/tools", "")).toBeNull();+ expect(automationRepositoryAddress("forgejo", "acme/tools")).toBeNull();+ });++ it("uses a connected self-hosted host, with or without a scheme", () => {+ expect(+ automationRepositoryAddress(+ "gitlab",+ "acme/tools",+ "https://gitlab.example.com/",+ ),+ ).toBe("https://gitlab.example.com/acme/tools");+ expect(+ automationRepositoryAddress("github", "acme/tools", "GitHub.Example.com"),+ ).toBe("https://github.example.com/acme/tools");+ });++ it("keeps a self-hosted instance's port and path prefix", () => {+ expect(+ automationRepositoryAddress(+ "gitlab",+ "acme/tools",+ "https://git.example.com:8443",+ ),+ ).toBe("https://git.example.com:8443/acme/tools");+ expect(+ automationRepositoryAddress(+ "bitbucket_data_center",+ "PROJ/repo",+ "https://example.com/bitbucket/",+ ),+ ).toBe("https://example.com/bitbucket/PROJ/repo");+ });++ it("keeps Azure DevOps on dev.azure.com whatever the connection's host says", () => {+ // The server keeps an Azure DevOps connection's organization in `host`,+ // not an instance, and OpenHands serves dev.azure.com only.+ for (const host of ["fabrikam", "https://dev.azure.com/fabrikam", null]) {+ expect(+ automationRepositoryAddress(+ "azure_devops",+ "fabrikam/Fabrikam Fiber/fabrikam-web",+ host,+ ),+ ).toBe(+ "https://dev.azure.com/fabrikam/Fabrikam%20Fiber/_git/fabrikam-web",+ );+ }+ });++ it("builds an Azure DevOps _git URL from organization/project/repository", () => {+ expect(+ automationRepositoryAddress(+ "azure_devops",+ "fabrikam/Fabrikam Fiber/fabrikam-web",+ ),+ ).toBe("https://dev.azure.com/fabrikam/Fabrikam%20Fiber/_git/fabrikam-web");+ // A name that is not organization/project/repository is kept as it is.+ expect(automationRepositoryAddress("azure_devops", "fabrikam/web")).toBe(+ "fabrikam/web",+ );+ });++ it("keeps the name for a provider without a hosted service", () => {+ expect(+ automationRepositoryAddress("bitbucket_data_center", "PROJ/repo"),+ ).toBe("PROJ/repo");+ });+});++describe("providerHostKnown", () => {+ it("needs a reported host only where one name covers self-managed instances", () => {+ expect(providerHostKnown("github")).toBe(true);+ expect(providerHostKnown("bitbucket")).toBe(true);+ // Azure DevOps is served on dev.azure.com only.+ expect(providerHostKnown("azure_devops", null)).toBe(true);+ expect(providerHostKnown("gitlab")).toBe(false);+ expect(providerHostKnown("gitlab", "")).toBe(false);+ expect(providerHostKnown("gitlab", "gitlab.com")).toBe(true);+ expect(providerHostKnown("gitlab", "https://gitlab.example.com")).toBe(+ true,+ );+ expect(providerHostKnown("forgejo")).toBe(false);+ expect(providerHostKnown("forgejo", "codeberg.org")).toBe(true);+ });+});++describe("providerBaseUrl", () => {+ it("normalizes a configured host to its base URL", () => {+ expect(providerBaseUrl("https://gitlab.example.com/")).toBe(+ "https://gitlab.example.com",+ );+ expect(providerBaseUrl("Gitlab.Example.com")).toBe(+ "https://gitlab.example.com",+ );+ expect(providerBaseUrl("https://git.example.com:8443")).toBe(+ "https://git.example.com:8443",+ );+ expect(providerBaseUrl("http://example.com/gitlab/")).toBe(+ "http://example.com/gitlab",+ );+ expect(providerBaseUrl("")).toBeNull();+ expect(providerBaseUrl(null)).toBeNull();+ expect(providerBaseUrl("not a host")).toBeNull();+ });+});++describe("providerForAddress", () => {+ const hosts = {+ gitlab: "https://git.example.com:8443",+ bitbucket_data_center: "https://example.com/bitbucket/",+ github: null,+ azure_devops: "https://devops.example.com",+ };++ it("names the provider of a connected self-hosted instance", () => {+ expect(+ providerForAddress("https://git.example.com:8443/acme/tools", hosts),+ ).toBe("gitlab");+ // An Azure DevOps connection's host is its organization, never an instance.+ expect(+ providerForAddress("https://devops.example.com/o/p/_git/r", hosts, [+ "github",+ "azure_devops",+ ]),+ ).toBe(undefined);+ });++ it("names only providers the run can clone", () => {+ // The service's schema accepts the names it advertises and no others, so+ // a connected Bitbucket Data Center or Forgejo host gets no provider.+ expect(+ providerForAddress("https://example.com/bitbucket/PROJ/repo", hosts),+ ).toBe(undefined);+ expect(+ providerForAddress("https://devops.example.com/o/p/_git/r", hosts),+ ).toBe(undefined);+ expect(+ providerForAddress("https://forge.example.com/acme/tools", {+ forgejo: "https://forge.example.com",+ }),+ ).toBe(undefined);+ expect(+ providerForAddress("https://example.com/bitbucket/PROJ/repo", hosts, [+ "github",+ "bitbucket_data_center",+ ]),+ ).toBe("bitbucket_data_center");+ });++ it("leaves hosted services and unknown hosts without a provider", () => {+ expect(providerForAddress("https://gitlab.com/acme/tools", hosts)).toBe(+ undefined,+ );+ expect(providerForAddress("https://github.com/acme/tools", hosts)).toBe(+ undefined,+ );+ // Same hostname on another port, or outside the prefix, is not the instance.+ expect(+ providerForAddress("https://git.example.com/acme/tools", hosts),+ ).toBe(undefined);+ expect(providerForAddress("https://example.com/other/x", hosts)).toBe(+ undefined,+ );+ expect(providerForAddress("not a url", hosts)).toBe(undefined);+ });++ it("prefers the longest matching base when instances share an origin", () => {+ const nested = {+ github: "https://example.com",+ gitlab: "https://example.com/gitlab",+ };+ const reversed = {+ gitlab: "https://example.com/gitlab",+ github: "https://example.com",+ };+ for (const connected of [nested, reversed]) {+ expect(+ providerForAddress("https://example.com/gitlab/acme/tools", connected),+ ).toBe("gitlab");+ expect(+ providerForAddress("https://example.com/acme/tools", connected),+ ).toBe("github");+ // The prefix must end at a path boundary.+ expect(+ providerForAddress("https://example.com/gitlabber/x", connected),+ ).toBe("github");+ }+ });+});++describe("buildAutomationRepoSources", () => {+ it("sends shorthands as GitHub and hosted URLs without a provider", () => {+ expect(+ buildAutomationRepoSources([+ "OpenHands/OpenHands",+ "https://gitlab.com/acme/tools",+ ]),+ ).toEqual([+ { url: "OpenHands/OpenHands", provider: "github" },+ { url: "https://gitlab.com/acme/tools" },+ ]);+ });++ it("sends the provider for a URL on a connected self-hosted host", () => {+ expect(+ buildAutomationRepoSources(+ ["https://gitlab.example.com/acme/tools"],+ [],+ {+ gitlab: "https://gitlab.example.com",+ },+ ),+ ).toEqual([+ { url: "https://gitlab.example.com/acme/tools", provider: "gitlab" },+ ]);+ expect(+ buildAutomationRepoSources(+ ["https://git.example.com:8443/acme/tools"],+ [],+ { gitlab: "https://git.example.com:8443" },+ ),+ ).toEqual([+ { url: "https://git.example.com:8443/acme/tools", provider: "gitlab" },+ ]);+ });++ it("sends no provider for a host the run cannot clone from", () => {+ const hosts = {+ bitbucket_data_center: "https://bb.example.com",+ forgejo: "https://forge.example.com",+ };+ expect(+ buildAutomationRepoSources(+ ["https://bb.example.com/PROJ/repo", "https://forge.example.com/a/b"],+ [],+ hosts,+ ),+ ).toEqual([+ { url: "https://bb.example.com/PROJ/repo" },+ { url: "https://forge.example.com/a/b" },+ ]);+ // Once the service advertises the provider, the name goes along.+ expect(+ buildAutomationRepoSources(+ ["https://bb.example.com/PROJ/repo"],+ [],+ hosts,+ ["github", "bitbucket_data_center"],+ ),+ ).toEqual([+ {+ url: "https://bb.example.com/PROJ/repo",+ provider: "bitbucket_data_center",+ },+ ]);+ });++ it("keeps a saved repository's branch and provider", () => {+ expect(+ buildAutomationRepoSources(+ ["https://gitlab.example.com/acme/tools"],+ [+ {+ url: "https://gitlab.example.com/acme/tools",+ ref: "main",+ provider: "gitlab",+ },+ ],+ {},+ ),+ ).toEqual([+ {+ url: "https://gitlab.example.com/acme/tools",+ ref: "main",+ provider: "gitlab",+ },+ ]);+ });+});diff --git a/src/components/features/automations/setup/automation-setup-panel.tsx b/src/components/features/automations/setup/automation-setup-panel.tsxindex 892dd434f5..09650b49d4 100644--- a/src/components/features/automations/setup/automation-setup-panel.tsx+++ b/src/components/features/automations/setup/automation-setup-panel.tsx@@ -63,6 +63,7 @@ import { AutomationSetupPromptStack } from "#/components/features/automations/seimport { ContextMenuListItem } from "#/components/features/context-menu/context-menu-list-item";import { formatTriggerSourceLabel } from "#/components/features/home/featured-automations/automation-run-health";import { useClickOutsideElement } from "#/hooks/use-click-outside-element";+import { useSettings } from "#/hooks/query/use-settings";import { usePromptTextareaResize } from "#/hooks/use-prompt-textarea-resize";import { useSendMessage } from "#/hooks/use-send-message";import {@@ -117,6 +118,7 @@ import {import { setupDraftFromAutomation } from "#/utils/automation-edit-draft";import { withPresetSources } from "#/utils/automation-preset-sources";import {+ automationCloneProviders,automationRepositoriesChanged,buildAutomationRepoSources,} from "#/utils/automation-repo-sources";@@ -658,6 +660,13 @@ export function AutomationSetupPanel({const { t } = useTranslation("openhands");const { navigate } = useNavigation();const deploymentCapabilities = useDeploymentCapabilities();+ // Connected self-hosted providers name their hosts here; a repository on+ // one of them is sent with its provider so the run can authenticate, as+ // long as the service can clone from that provider at all.+ const providerHosts = useSettings().data?.provider_tokens_set;+ const cloneProviders = automationCloneProviders(+ deploymentCapabilities.data?.repoProviders,+ );const eventSourceOptions = deploymentCapabilities.data?.eventSources ?? [];const eventTypeOptions = deploymentCapabilities.data?.eventTypes ?? [];const initialDraft = conversationId@@ -1247,7 +1256,12 @@ export function AutomationSetupPanel({} as SetupRequestBody;const repositories = parseAutomationSetupRepositories(repository);if (repositories.length > 0) {- body.repos = buildAutomationRepoSources(repositories);+ body.repos = buildAutomationRepoSources(+ repositories,+ [],+ providerHosts,+ cloneProviders,+ );}if (showTimeout && timeoutSeconds.trim())body.timeout = Number(timeoutSeconds);@@ -1746,6 +1760,8 @@ export function AutomationSetupPanel({body.repos = buildAutomationRepoSources(repositories,existingRepositories,+ providerHosts,+ cloneProviders,);}return body as Partial<Automation>;diff --git a/src/components/features/automations/setup/automation-setup-prompt-stack.tsx b/src/components/features/automations/setup/automation-setup-prompt-stack.tsxindex 7eca775bee..c30883c477 100644--- a/src/components/features/automations/setup/automation-setup-prompt-stack.tsx+++ b/src/components/features/automations/setup/automation-setup-prompt-stack.tsx@@ -15,6 +15,8 @@ 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 { useDeploymentCapabilities } from "#/hooks/query/use-manifest-capabilities";+import { useSettings } from "#/hooks/query/use-settings";import { usePromptTextareaResize } from "#/hooks/use-prompt-textarea-resize";import { I18nKey } from "#/i18n/declaration";import CheckIcon from "#/icons/checkmark.svg?react";@@ -27,11 +29,14 @@ import { chatInputPillButtonClassName } from "#/utils/form-control-classes";import { modalTitleLgClassName } from "#/utils/modal-classes";import { cn, getProviderName } from "#/utils/utils";import { formatModelNameForDisplay } from "#/utils/format-model-name";+import {+ automationCloneProviders,+ automationRepositoryAddress,+ providerHostKnown,+} from "#/utils/automation-repo-sources";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 {@@ -286,9 +291,45 @@ export function AutomationSetupPromptStack({);const isLocalBackend = getActiveBackend().backend.kind === "local";const { providers } = useUserProviders();- const repositoryProvider: Provider | null = providers.includes("github")+ const { data: settings } = useSettings();+ const providerHosts = settings?.provider_tokens_set ?? {};+ const deploymentCapabilities = useDeploymentCapabilities();+ // The service says whose repositories its runs clone; older services predate+ // the field and clone from the three hosted providers.+ const cloneProviders = automationCloneProviders(+ deploymentCapabilities.data?.repoProviders,+ );+ // Whose repositories the picker can offer: a connected provider the runs+ // clone from, whose host is known (a GitLab connection needs the server to+ // report its host, or the form could not tell gitlab.com from an instance).+ const canListProvider = (provider: Provider) =>+ cloneProviders.includes(provider) &&+ providerHostKnown(provider, providerHosts[provider]);+ const connectedCloneProviders = providers.filter(canListProvider);+ const [selectedProvider, setSelectedProvider] = useState<Provider | null>(+ null,+ );+ const defaultProvider: Provider | null = connectedCloneProviders.includes(+ "github",+ )? "github"- : (providers[0] ?? (isLocalBackend ? "github" : null));+ : (connectedCloneProviders[0] ??+ providers[0] ??+ (isLocalBackend ? "github" : null));+ const repositoryProvider: Provider | null =+ selectedProvider && connectedCloneProviders.includes(selectedProvider)+ ? selectedProvider+ : defaultProvider;+ // What the form stores for a listed repository: GitHub's shorthand, or the+ // full URL on the provider's host for anything else.+ const addressFor = (name: string): string | null =>+ repositoryProvider+ ? automationRepositoryAddress(+ repositoryProvider,+ name,+ providerHosts[repositoryProvider],+ )+ : name;const repositoryQuery = useGitRepositories({provider: repositoryProvider,enabled: isRepositoryMenuOpen && repositoryProvider !== null,@@ -325,10 +366,13 @@ export function AutomationSetupPromptStack({const listedRepositoryNames = [...repositoryNames,...searchedRepositoryNames,- ].filter(- (name, index, names) =>- !repositories.includes(name) && names.indexOf(name) === index,- );+ ].filter((name, index, names) => {+ const address = addressFor(name);+ return (+ (address === null || !repositories.includes(address)) &&+ names.indexOf(name) === index+ );+ });const visibleRepositoryNames = repositorySearchText? listedRepositoryNames.filter((name) =>name.toLowerCase().includes(repositorySearchText),@@ -336,8 +380,7 @@ export function AutomationSetupPromptStack({: listedRepositoryNames;const addLabel = `${t(I18nKey.BUTTON$ADD)} ${t(I18nKey.AUTOMATIONS$DETAIL$REPOSITORIES)}`;const isRepositoryProviderUnsupported =- repositoryProvider !== null &&- repositoryProvider !== AUTOMATION_CLONE_PROVIDER;+ repositoryProvider !== null && !canListProvider(repositoryProvider);const writeRepositories = (next: string[]) => {onRepositoryChange(next.join(", "));@@ -502,6 +545,27 @@ export function AutomationSetupPromptStack({/></div></div>+ {connectedCloneProviders.length > 1 ? (+ <div className="shrink-0 px-2 pb-1">+ <select+ data-testid="automation-setup-repository-provider"+ aria-label={t(I18nKey.CONVERSATION$GIT_PROVIDER)}+ value={repositoryProvider ?? ""}+ onChange={(event) => {+ setSelectedProvider(event.target.value as Provider);+ setRepositorySearch("");+ }}+ onKeyDown={(event) => event.stopPropagation()}+ className="w-full rounded-md border border-border-subtle bg-tertiary px-2 py-1 text-sm text-content outline-none"+ >+ {connectedCloneProviders.map((provider) => (+ <option key={provider} value={provider}>+ {getProviderName(provider)}+ </option>+ ))}+ </select>+ </div>+ ) : null}<Divider inset="menu" /><divclassName="min-h-0 flex-1 overflow-y-auto px-1"@@ -550,7 +614,10 @@ export function AutomationSetupPromptStack({onClick={(event) => {event.preventDefault();event.stopPropagation();- writeRepositories([...repositories, name]);+ const address = addressFor(name);+ if (address && !repositories.includes(address)) {+ writeRepositories([...repositories, address]);+ }setIsRepositoryMenuOpen(false);}}isDisabled={isRepositoryProviderUnsupported}diff --git a/src/manifests/types.ts b/src/manifests/types.tsindex e15919fb03..561b8603e8 100644--- a/src/manifests/types.ts+++ b/src/manifests/types.ts@@ -245,6 +245,8 @@ export interface DeploymentCapabilities {event?: { filterLanguage: string; filterFunctions: string[] };};features: string[];+ /** Providers whose repositories a run clones with the user's token; older services omit it. */+ repoProviders?: string[];}/** A single problem with a draft, addressed to the field that caused it. */diff --git a/src/mocks/automation-handlers.ts b/src/mocks/automation-handlers.tsindex 998b3a1887..d536a69210 100644--- a/src/mocks/automation-handlers.ts+++ b/src/mocks/automation-handlers.ts@@ -33,6 +33,7 @@ const CAPABILITIES: DeploymentCapabilities = {// Changing a preset's repositories with PATCH is newer than the fixture too."repoUpdate",],+ repoProviders: ["bitbucket", "github", "gitlab"],};interface DraftTrigger {diff --git a/src/utils/automation-repo-sources.ts b/src/utils/automation-repo-sources.tsindex 033f5d50c8..f2a9c2cd11 100644--- a/src/utils/automation-repo-sources.ts+++ b/src/utils/automation-repo-sources.ts@@ -1,4 +1,6 @@import type { AutomationRepository } from "#/types/automation";+import type { Provider } from "#/types/settings";+import { getGitProviderBaseUrl } from "#/utils/utils";/** A `repos` entry in a preset create or update request. */export type AutomationRepoSource = {@@ -12,17 +14,165 @@ export type AutomationRepoSource = {const SHORTHAND_PROVIDER = "github";const FULL_GIT_URL_PATTERN = /^(?:https?:\/\/|git@)/i;+/** Providers whose repositories a run clones when the service does not say. */+export const DEFAULT_CLONE_PROVIDERS: Provider[] = [+ "github",+ "gitlab",+ "bitbucket",+];++/**+ * The providers whose repositories the automation service's runs clone, from+ * its `repoProviders` capability. An older service without the field clones+ * from the three hosted providers. Only these names are valid as a `repos`+ * entry's `provider`; the service rejects any other.+ */+export function automationCloneProviders(+ repoProviders?: string[] | null,+): Provider[] {+ return repoProviders+ ? (repoProviders as Provider[])+ : DEFAULT_CLONE_PROVIDERS;+}++/**+ * The base URL a connected provider is served on: scheme, host, port and any+ * path prefix, without a trailing slash. A self-managed instance keeps its+ * port (`https://git.example.com:8443`) and prefix (`https://example.com/gitlab`).+ */+export function providerBaseUrl(+ host: string | null | undefined,+): string | null {+ const trimmed = host?.trim();+ if (!trimmed) return null;+ try {+ const url = new URL(+ trimmed.includes("://") ? trimmed : `https://${trimmed}`,+ );+ if (!url.hostname) return null;+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;+ } catch {+ return null;+ }+}++/** The base URL of the provider's hosted service, or null when it has none. */+function hostedBaseUrl(provider: Provider): string | null {+ return providerBaseUrl(getGitProviderBaseUrl(provider));+}++// One provider name covers the hosted service and self-managed instances alike+// for these, so a connection whose host the server does not report cannot be+// addressed: the hosted URL would silently point a self-managed repository at+// the public service. Bitbucket names its self-managed product separately+// (`bitbucket_data_center`), and OpenHands' Azure DevOps integration serves+// dev.azure.com only, so a missing host there is the hosted service.+const HOST_REQUIRED_PROVIDERS: Provider[] = ["gitlab", "forgejo"];++/**+ * Whether a connected provider's listed repositories can be addressed: GitHub+ * by its shorthand, the others on the reported host or on their hosted+ * service, unless the name also covers self-managed instances and no host was+ * reported.+ */+export function providerHostKnown(+ provider: Provider,+ host?: string | null,+): boolean {+ if (providerBaseUrl(host)) return true;+ return provider === "github" || !HOST_REQUIRED_PROVIDERS.includes(provider);+}++/**+ * The repository field entry for a repository picked from a provider, or null+ * when the connection's host is unknown (see `providerHostKnown`).+ *+ * GitHub keeps its `owner/repo` shorthand. Other providers, and a GitHub+ * Enterprise host, get the full URL on the connected host or on the provider's+ * hosted service, which the service recognizes and clones with its token.+ */+export function automationRepositoryAddress(+ provider: Provider,+ fullName: string,+ host?: string | null,+): string | null {+ const configured = providerBaseUrl(host);+ if (provider === "github" && !configured) return fullName;+ if (!providerHostKnown(provider, host)) return null;+ if (provider === "azure_devops") {+ // Azure DevOps names a repository organization/project/repository, always+ // on dev.azure.com: the server stores an Azure DevOps connection's+ // organization (sometimes as a URL with a path) in its `host`, not an+ // instance, so that value is never a base URL.+ const [organization, project, ...rest] = fullName.split("/");+ const repository = rest.join("/");+ if (!organization || !project || !repository) return fullName;+ const path = [organization, project].map(encodeURIComponent).join("/");+ return `${hostedBaseUrl(provider)}/${path}/_git/${encodeURIComponent(repository)}`;+ }+ const base = configured ?? hostedBaseUrl(provider);+ if (!base) return fullName;+ return `${base}/${fullName}`;+}++/**+ * The provider a full URL belongs to when it points at a connected+ * self-hosted instance, matched on the same base URL the address was built+ * from. A hosted service's URL needs no provider: the service recognizes+ * those hosts itself. Only a provider the run can clone is named; a host of+ * any other connected provider gets none, since the service rejects the name.+ */+export function providerForAddress(+ url: string,+ hosts: Partial<Record<Provider, string | null>> = {},+ cloneProviders: Provider[] = DEFAULT_CLONE_PROVIDERS,+): Provider | undefined {+ let address: string;+ try {+ const parsed = new URL(url);+ address = `${parsed.origin}${parsed.pathname}`;+ } catch {+ return undefined;+ }+ // Two connected instances can share an origin with one base nested under+ // the other (`https://example.com` and `https://example.com/gitlab`), so the+ // longest matching base wins rather than whichever key comes first.+ let match: { provider: Provider; base: string } | undefined;+ for (const [provider, host] of Object.entries(hosts) as [+ Provider,+ string | null,+ ][]) {+ // An Azure DevOps connection's `host` is its organization, not a base URL.+ if (!cloneProviders.includes(provider) || provider === "azure_devops") {+ continue;+ }+ const base = providerBaseUrl(host);+ if (+ base &&+ base !== hostedBaseUrl(provider) &&+ (address === base || address.startsWith(`${base}/`)) &&+ (!match || base.length > match.base.length)+ ) {+ match = { provider, base };+ }+ }+ if (match) return match.provider;+ return undefined;+}+/*** 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.+ * provider. A new shorthand is a GitHub repository. A full URL is sent with a+ * provider only when it points at a connected self-hosted host, so the+ * service authenticates its clone for that host and for no other.*/export function buildAutomationRepoSources(repositories: string[],saved: AutomationRepository[] = [],+ hosts: Partial<Record<Provider, string | null>> = {},+ cloneProviders: Provider[] = DEFAULT_CLONE_PROVIDERS,): AutomationRepoSource[] {return repositories.map((url) => {const existing = saved.find((repo) => repo.url === url);@@ -33,9 +183,11 @@ export function buildAutomationRepoSources(...(existing.provider && { provider: existing.provider }),};}- return FULL_GIT_URL_PATTERN.test(url)- ? { url }- : { url, provider: SHORTHAND_PROVIDER };+ if (!FULL_GIT_URL_PATTERN.test(url)) {+ return { url, provider: SHORTHAND_PROVIDER };+ }+ const provider = providerForAddress(url, hosts, cloneProviders);+ return provider ? { url, provider } : { url };});}