Skip to content

🙌 OpenHands: AI-Driven Development

feat: open Git Sync to org admins on cloud backends (#17216)

Hiep Lee5a733c4215c
diff --git a/__tests__/hooks/query/use-git-sync.test.tsx b/__tests__/hooks/query/use-git-sync.test.tsx
index d4404c1347..ceb507de31 100644
--- a/__tests__/hooks/query/use-git-sync.test.tsx
+++ b/__tests__/hooks/query/use-git-sync.test.tsx
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, renderHook, waitFor } from "@testing-library/react";
import { QueryClientProvider, QueryClient } from "@tanstack/react-query";
import {
@@ -8,6 +8,13 @@ import {
useUpdateGitSyncConfig,
} from "#/hooks/query/use-git-sync";
import AutomationService from "#/api/automation-service/automation-service.api";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import type { Backend } from "#/api/backend-registry/types";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
import type { GitSyncStatus } from "#/types/git-sync";
vi.mock("#/api/automation-service/automation-service.api", () => ({
@@ -18,12 +25,21 @@ vi.mock("#/api/automation-service/automation-service.api", () => ({
},
}));
-vi.mock("#/contexts/active-backend-context", () => ({
- useActiveBackend: () => ({
- backend: { id: "test-backend", kind: "local" },
- orgId: null,
- }),
-}));
+const localBackend: Backend = {
+ id: "test-backend",
+ name: "Local",
+ host: "http://localhost:8000",
+ apiKey: "session-key",
+ kind: "local",
+};
+
+const cloudBackend: Backend = {
+ id: "cloud-1",
+ name: "Production",
+ host: "https://app.all-hands.dev",
+ apiKey: "bearer-key",
+ kind: "cloud",
+};
vi.mock("#/hooks/use-tracking", () => ({
useTracking: () => ({
@@ -56,13 +72,24 @@ function createHarness() {
defaultOptions: { queries: { retry: false, retryDelay: 0 } },
});
const wrapper = ({ children }: { children: React.ReactNode }) => (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>{children}</ActiveBackendProvider>
+ </QueryClientProvider>
);
return { queryClient, wrapper };
}
beforeEach(() => {
vi.clearAllMocks();
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ setRegisteredBackends([localBackend, cloudBackend]);
+ setActiveSelection({ backendId: localBackend.id });
+});
+
+afterEach(() => {
+ __resetActiveStoreForTests();
+ window.localStorage.clear();
});
describe("useUpdateGitSyncConfig", () => {
@@ -141,6 +168,43 @@ describe("useTriggerGitSync", () => {
});
});
+describe("useGitSyncStatus on a cloud backend", () => {
+ beforeEach(() => {
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });
+ });
+
+ it("scopes the status to the backend and org, and refreshes it after a trigger", async () => {
+ // Two orgs on the same backend must never read each other's cached
+ // status, and a trigger must invalidate the key it was cached under.
+ vi.mocked(AutomationService.getGitSyncStatus).mockResolvedValue(baseStatus);
+ vi.mocked(AutomationService.triggerGitSync).mockResolvedValue({
+ triggered: true,
+ });
+ const { queryClient, wrapper } = createHarness();
+ const { result } = renderHook(
+ () => ({ status: useGitSyncStatus(), trigger: useTriggerGitSync() }),
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.status.isSuccess).toBe(true));
+ expect(
+ queryClient.getQueryData([
+ ...GIT_SYNC_STATUS_QUERY_KEY,
+ "cloud-1",
+ "org-1",
+ ]),
+ ).toEqual(baseStatus);
+ expect(queryClient.getQueryData(STATUS_KEY)).toBeUndefined();
+
+ await act(async () => {
+ await result.current.trigger.mutateAsync(undefined);
+ });
+
+ await waitFor(() =>
+ expect(AutomationService.getGitSyncStatus).toHaveBeenCalledTimes(2),
+ );
+ });
+});
+
describe("useGitSyncStatus", () => {
it("does not retry a backend that has no git-sync API", async () => {
vi.mocked(AutomationService.getGitSyncStatus).mockRejectedValue({
diff --git a/__tests__/routes/automation-git-sync.test.tsx b/__tests__/routes/automation-git-sync.test.tsx
index 7438c3f1fb..564c71e540 100644
--- a/__tests__/routes/automation-git-sync.test.tsx
+++ b/__tests__/routes/automation-git-sync.test.tsx
@@ -6,6 +6,7 @@ import { HttpError } from "@openhands/typescript-client";
import { I18nKey } from "#/i18n/declaration";
import AutomationService from "#/api/automation-service/automation-service.api";
+import { getCloudOrganizationMe } from "#/api/cloud/organization-service.api";
import {
__resetActiveStoreForTests,
setActiveSelection,
@@ -33,6 +34,27 @@ vi.mock("#/utils/custom-toast-handlers", () => ({
displaySuccessToast: (message: string) => displaySuccessToast(message),
}));
+// Permissions come from the org's /me endpoint on cloud backends; local
+// backends never call it.
+vi.mock("#/api/cloud/organization-service.api", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/api/cloud/organization-service.api")
+ >()),
+ getCloudOrganizationMe: vi.fn(),
+}));
+
+const orgAdmin = {
+ orgId: "org-1",
+ userId: "user-1",
+ role: "admin",
+ permissions: ["view_automations", "manage_automations"],
+};
+const orgMember = {
+ ...orgAdmin,
+ role: "member",
+ permissions: ["view_automations"],
+};
+
const localBackend: Backend = {
id: "local-1",
name: "Local 1",
@@ -41,6 +63,14 @@ const localBackend: Backend = {
kind: "local",
};
+const cloudBackend: Backend = {
+ id: "cloud-1",
+ name: "Production",
+ host: "https://app.all-hands.dev",
+ apiKey: "bearer-key",
+ kind: "cloud",
+};
+
const status: GitSyncStatus = {
enabled: true,
repo_url: "https://example.com/org/repo.git",
@@ -89,7 +119,9 @@ beforeEach(() => {
});
displayErrorToast.mockReset();
displaySuccessToast.mockReset();
- setRegisteredBackends([localBackend]);
+ vi.mocked(getCloudOrganizationMe).mockReset();
+ vi.mocked(getCloudOrganizationMe).mockResolvedValue(orgAdmin);
+ setRegisteredBackends([localBackend, cloudBackend]);
setActiveSelection({ backendId: localBackend.id });
});
@@ -99,6 +131,32 @@ afterEach(() => {
__resetActiveStoreForTests();
});
+describe("AutomationGitSync — cloud backend", () => {
+ beforeEach(() => {
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });
+ });
+
+ it("loads the org's status for an admin", async () => {
+ renderGitSync();
+
+ expect(
+ await screen.findByTestId("git-sync-repo-url-input"),
+ ).toBeInTheDocument();
+ expect(AutomationService.getGitSyncStatus).toHaveBeenCalled();
+ });
+
+ it("shows the no-access state to a member and never asks for the status", async () => {
+ vi.mocked(getCloudOrganizationMe).mockResolvedValue(orgMember);
+
+ renderGitSync();
+
+ expect(
+ await screen.findByText(I18nKey.AUTOMATIONS$GIT_SYNC$NO_ACCESS_TITLE),
+ ).toBeInTheDocument();
+ expect(AutomationService.getGitSyncStatus).not.toHaveBeenCalled();
+ });
+});
+
describe("AutomationGitSync — backend without the git-sync API", () => {
it("names the missing API instead of showing the generic error panel", async () => {
// Every released automation version below the one that ships the router
diff --git a/__tests__/routes/automations-list.test.tsx b/__tests__/routes/automations-list.test.tsx
index 521be86c85..e7fcc34ad0 100644
--- a/__tests__/routes/automations-list.test.tsx
+++ b/__tests__/routes/automations-list.test.tsx
@@ -9,6 +9,7 @@ import { HttpError } from "@openhands/typescript-client";
import { I18nKey } from "#/i18n/declaration";
import AutomationService from "#/api/automation-service/automation-service.api";
+import { getCloudOrganizationMe } from "#/api/cloud/organization-service.api";
import ProfilesService from "#/api/profiles-service/profiles-service.api";
import {
__resetActiveStoreForTests,
@@ -47,16 +48,27 @@ vi.mock("#/utils/custom-toast-handlers", () => ({
displayErrorToast: vi.fn(),
}));
-// Mock permission hooks so cloud-backend tests don't need a real /me endpoint.
-vi.mock("#/hooks/use-automation-permissions", () => ({
- useAutomationPermissions: () => ({
- canView: true,
- canManage: true,
- isLoading: false,
- }),
- useIsAutomationOwner: () => true,
+// Permissions come from the org's /me endpoint on cloud backends, so mock that
+// service rather than the hooks that read it; local backends never call it.
+vi.mock("#/api/cloud/organization-service.api", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("#/api/cloud/organization-service.api")
+ >()),
+ getCloudOrganizationMe: vi.fn(),
}));
+const orgAdmin = {
+ orgId: "org-1",
+ userId: "user-1",
+ role: "admin",
+ permissions: ["view_automations", "manage_automations"],
+};
+const orgMember = {
+ ...orgAdmin,
+ role: "member",
+ permissions: ["view_automations"],
+};
+
const localBackend: Backend = {
id: "local-1",
name: "Local 1",
@@ -94,7 +106,10 @@ function renderList(queryClient?: QueryClient) {
const client =
queryClient ??
new QueryClient({
- defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
});
return render(
<QueryClientProvider client={client}>
@@ -121,6 +136,8 @@ beforeEach(() => {
profiles: [],
active_profile: null,
});
+ vi.mocked(getCloudOrganizationMe).mockReset();
+ vi.mocked(getCloudOrganizationMe).mockResolvedValue(orgAdmin);
setRegisteredBackends([localBackend, cloudBackend]);
setActiveSelection({ backendId: localBackend.id });
});
@@ -158,9 +175,10 @@ describe("AutomationsList — Edit from the row kebab", () => {
});
it("opens the Edit modal pre-filled from the row kebab when the active backend is cloud", async () => {
- // Arrange — switch to the cloud backend before mounting so the page sees
- // it as the active backend on first render.
- setActiveSelection({ backendId: cloudBackend.id });
+ // Arrange — switch to the cloud backend (with its org, which is what the
+ // permissions come from) before mounting so the page sees it as the
+ // active backend on first render.
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });
const user = userEvent.setup();
renderList();
await waitFor(() => {
@@ -176,7 +194,7 @@ describe("AutomationsList — Edit from the row kebab", () => {
);
// Assert — the same Edit modal mounts on cloud, wired to this row; the
- // permission model (mocked to canManage above) decides, not the backend.
+ // permission model decides, not the backend kind.
const nameInput = (await screen.findByTestId(
"edit-automation-name",
)) as HTMLInputElement;
@@ -184,15 +202,23 @@ describe("AutomationsList — Edit from the row kebab", () => {
});
});
-describe("AutomationsList — Git Sync entry point", () => {
- it("hides the Git Sync button when the active backend is cloud", async () => {
- // Arrange — Git Sync is a local-only operator feature that used to share
- // Edit's backend gate; it must not follow Edit onto cloud.
- setActiveSelection({ backendId: cloudBackend.id });
+describe("AutomationsList — Git Sync entry point follows manage_automations", () => {
+ it("shows the Git Sync button to an org admin on a cloud backend", async () => {
+ // Git sync is org-level config, not a local-only feature: an admin of the
+ // active org reaches it on any backend kind.
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });
+ renderList();
+ await screen.findByText(automation.name);
+
+ expect(screen.getByTestId("automations-git-sync")).toBeInTheDocument();
+ });
+
+ it("hides the Git Sync button from a member", async () => {
+ vi.mocked(getCloudOrganizationMe).mockResolvedValue(orgMember);
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });
renderList();
await screen.findByText(automation.name);
- // Assert
expect(
screen.queryByTestId("automations-git-sync"),
).not.toBeInTheDocument();
@@ -338,9 +364,7 @@ describe("AutomationsList — Run now toasts", () => {
});
const user = userEvent.setup();
renderList();
- await screen.findByTestId(
- `automation-list-row-${disabledAutomation.id}`,
- );
+ await screen.findByTestId(`automation-list-row-${disabledAutomation.id}`);
const button = screen.getByTestId(
`automation-run-now-${disabledAutomation.id}`,
);
@@ -410,9 +434,9 @@ describe("AutomationsList — add automation menu", () => {
).not.toBeInTheDocument();
await user.click(addTrigger);
- expect(screen.getByTestId("automations-add-automation-menu")).not.toHaveClass(
- "mt-2",
- );
+ expect(
+ screen.getByTestId("automations-add-automation-menu"),
+ ).not.toHaveClass("mt-2");
expect(
screen.getByTestId("automations-import-automation"),
).toBeInTheDocument();
@@ -461,7 +485,10 @@ describe("AutomationsList — list freshness on remount", () => {
total: 2,
});
const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
});
// Act — first mount lands on the original list, then unmount and remount
diff --git a/src/api/automation-service/automation-service.api.test.ts b/src/api/automation-service/automation-service.api.test.ts
index 894d0386d2..793af7a138 100644
--- a/src/api/automation-service/automation-service.api.test.ts
+++ b/src/api/automation-service/automation-service.api.test.ts
@@ -410,6 +410,9 @@ describe("AutomationService git sync", () => {
backend: cloudBackend,
method: "GET",
path: "/api/automation/v1/git-sync/status",
+ headers: expect.objectContaining({
+ "X-OpenHands-Client": "agent_canvas",
+ }),
}),
);
});
@@ -440,6 +443,32 @@ describe("AutomationService git sync", () => {
method: "PUT",
path: "/api/automation/v1/git-sync/config",
body: { token: null },
+ headers: expect.objectContaining({
+ "X-OpenHands-Client": "agent_canvas",
+ }),
+ }),
+ );
+ });
+
+ it("checks a candidate configuration through the cloud proxy", async () => {
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });
+ const check = { ok: true, branch_exists: true, detail: null };
+ callCloudProxy.mockResolvedValueOnce(check);
+
+ await expect(
+ AutomationService.checkGitSyncConfig({ branch: "develop" }),
+ ).resolves.toEqual(check);
+
+ expect(callCloudProxy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ backend: cloudBackend,
+ method: "POST",
+ path: "/api/automation/v1/git-sync/check",
+ body: { branch: "develop" },
+ headers: expect.objectContaining({
+ "X-OpenHands-Client": "agent_canvas",
+ }),
}),
);
});
diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.ts
index 3f86940809..e7b796d2a8 100644
--- a/src/api/automation-service/automation-service.api.ts
+++ b/src/api/automation-service/automation-service.api.ts
@@ -682,8 +682,8 @@ class AutomationService {
// Git sync paths are literal rather than routed through
// `getAutomationEndpoint`. That manifest describes the automation surface a
// host may remap, and `InterfaceEndpoints` requires every key it declares --
- // adding these would break existing manifests. Git sync is a local-mode
- // operator feature outside that surface.
+ // adding these would break existing manifests. Git sync is an org-admin
+ // feature outside that surface.
static async getGitSyncStatus(): Promise<GitSyncStatus> {
const active = getActiveBackend().backend;
const path = `${AUTOMATION_BASE_PATH}/v1/git-sync/status`;
@@ -693,6 +693,7 @@ class AutomationService {
backend: active,
method: "GET",
path,
+ headers: await buildAutomationRequestHeaders(),
});
}
@@ -712,6 +713,7 @@ class AutomationService {
method: "PUT",
path,
body: body as Record<string, unknown>,
+ headers: await buildAutomationRequestHeaders(),
});
}
@@ -736,6 +738,7 @@ class AutomationService {
method: "POST",
path,
body: body as Record<string, unknown>,
+ headers: await buildAutomationRequestHeaders(),
});
}
@@ -755,6 +758,7 @@ class AutomationService {
backend: active,
method: "POST",
path,
+ headers: await buildAutomationRequestHeaders(),
});
}
diff --git a/src/components/features/automations/git-sync/git-sync-config-form.test.tsx b/src/components/features/automations/git-sync/git-sync-config-form.test.tsx
index a6dfab022f..f679227ff2 100644
--- a/src/components/features/automations/git-sync/git-sync-config-form.test.tsx
+++ b/src/components/features/automations/git-sync/git-sync-config-form.test.tsx
@@ -334,11 +334,17 @@ describe("GitSyncConfigForm", () => {
expect(mutate.mock.calls[0][0]).toEqual({ branch: "develop" });
});
- it("explains the restart requirement when the backend refuses to enable sync", async () => {
- // The backend answers 409 when it booted without git sync turned on --
- // the raw detail is a wall of text, and the generic error message would
- // read as a transient failure worth retrying.
- respondWith({ error: { status: 409 } });
+ it("shows the backend's reason when it refuses the configuration", async () => {
+ // A 409 means another organization already syncs this repository, branch
+ // and path. The detail says so in words the operator can act on; the
+ // generic message would read as a transient failure worth retrying.
+ const detail = "Another organization already syncs this repository.";
+ respondWith({
+ error: Object.assign(new Error("Conflict"), {
+ status: 409,
+ response: { detail },
+ }),
+ });
render(
<GitSyncConfigForm
status={{ ...baseStatus, enabled: false }}
@@ -350,9 +356,7 @@ describe("GitSyncConfigForm", () => {
fireEvent.click(screen.getByTestId("git-sync-enabled-switch"));
await clickSave();
- expect(displayErrorToast).toHaveBeenCalledWith(
- I18nKey.AUTOMATIONS$GIT_SYNC$ENABLE_BLOCKED_ERROR,
- );
+ expect(displayErrorToast).toHaveBeenCalledWith(detail);
});
describe("reachability check", () => {
diff --git a/src/components/features/automations/git-sync/git-sync-config-form.tsx b/src/components/features/automations/git-sync/git-sync-config-form.tsx
index beae3614db..ca8c0612d0 100644
--- a/src/components/features/automations/git-sync/git-sync-config-form.tsx
+++ b/src/components/features/automations/git-sync/git-sync-config-form.tsx
@@ -11,7 +11,6 @@ import {
displaySuccessToast,
} from "#/utils/custom-toast-handlers";
import { getApiErrorMessage } from "#/utils/api-error-message";
-import { getErrorStatus } from "#/hooks/query/use-settings";
import {
useCheckGitSyncConfig,
useUpdateGitSyncConfig,
@@ -146,14 +145,10 @@ export function GitSyncConfigForm({
if (thenSync) onSyncNow();
},
onError: (error) => {
- displayErrorToast(
- // 409 is the backend refusing to enable sync in a deployment that
- // booted with it off -- a restart with the env var set, not a
- // transient failure the operator should retry.
- getErrorStatus(error) === 409
- ? t(I18nKey.AUTOMATIONS$GIT_SYNC$ENABLE_BLOCKED_ERROR)
- : getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)),
- );
+ // The backend's detail is the message: a 409 means another
+ // organization already syncs this repository, branch and path, and
+ // it says so in words the operator can act on.
+ displayErrorToast(getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)));
},
});
};
diff --git a/src/components/features/automations/git-sync/git-sync-not-local-state.tsx b/src/components/features/automations/git-sync/git-sync-no-access-state.tsx
similarity index 80%
rename from src/components/features/automations/git-sync/git-sync-not-local-state.tsx
rename to src/components/features/automations/git-sync/git-sync-no-access-state.tsx
index 8de914ef49..6a4b1bcf43 100644
--- a/src/components/features/automations/git-sync/git-sync-not-local-state.tsx
+++ b/src/components/features/automations/git-sync/git-sync-no-access-state.tsx
@@ -3,17 +3,17 @@ import { I18nKey } from "#/i18n/declaration";
import ExclamationCircleIcon from "#/icons/exclamation-circle.svg?react";
import { BackLink } from "#/components/features/automations/detail/back-link";
-export function GitSyncNotLocalState() {
+export function GitSyncNoAccessState() {
const { t } = useTranslation("openhands");
return (
<div className="flex flex-col items-center justify-center py-20">
<ExclamationCircleIcon className="size-12 text-muted" />
<p className="mt-4 text-sm font-medium text-content">
- {t(I18nKey.AUTOMATIONS$GIT_SYNC$NOT_LOCAL_TITLE)}
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$NO_ACCESS_TITLE)}
</p>
<p className="mt-2 text-sm text-muted">
- {t(I18nKey.AUTOMATIONS$GIT_SYNC$NOT_LOCAL_MESSAGE)}
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$NO_ACCESS_MESSAGE)}
</p>
<div className="mt-6">
<BackLink />
diff --git a/src/hooks/query/use-git-sync.ts b/src/hooks/query/use-git-sync.ts
index 3238a7d6bb..a28bee5636 100644
--- a/src/hooks/query/use-git-sync.ts
+++ b/src/hooks/query/use-git-sync.ts
@@ -56,9 +56,8 @@ export function useUpdateGitSyncConfig() {
queryClient.setQueryData(queryKey, data);
trackGitSyncConfigUpdated({ backendKind: active.backend.kind });
},
- // The form maps failures to its own message (the 409 "restart with the env
- // var set" case in particular), so the global mutation toast would stack a
- // raw one on top.
+ // The form reports failures itself, so the global mutation toast would
+ // stack a raw one on top.
meta: { disableToast: true },
});
}
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 90627f4f58..6934d4524c 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -41430,56 +41430,39 @@
"tr": "Yukarıdaki ayarları düzeltin veya yine de kaydetmek için Kaydet'e tekrar basın.",
"uk": "Виправте налаштування вище або натисніть «Зберегти» ще раз, щоб зберегти їх попри це."
},
- "AUTOMATIONS$GIT_SYNC$ENABLE_BLOCKED_ERROR": {
- "en": "Git Sync must be enabled in the automation backend's environment, and the service restarted, before it can be turned on here.",
- "ja": "Git 同期を有効にするには、オートメーションバックエンドの環境で有効化し、サービスを再起動する必要があります。",
- "zh-CN": "必须先在自动化后端的环境中启用 Git 同步并重启服务,才能在此处开启。",
- "zh-TW": "必須先在自動化後端的環境中啟用 Git 同步並重新啟動服務,才能在此處開啟。",
- "ko-KR": "여기서 켜려면 먼저 자동화 백엔드 환경에서 Git 동기화를 활성화하고 서비스를 다시 시작해야 합니다.",
- "no": "Git-synkronisering må aktiveres i automatiserings-backendens miljø, og tjenesten må startes på nytt, før den kan slås på her.",
- "ar": "يجب تفعيل مزامنة Git في بيئة الخدمة الخلفية للأتمتة وإعادة تشغيل الخدمة قبل تفعيلها هنا.",
- "de": "Die Git-Synchronisierung muss in der Umgebung des Automatisierungs-Backends aktiviert und der Dienst neu gestartet werden, bevor sie hier eingeschaltet werden kann.",
- "fr": "La synchronisation Git doit être activée dans l'environnement du backend d'automatisation et le service redémarré avant de pouvoir l'activer ici.",
- "it": "La sincronizzazione Git deve essere abilitata nell'ambiente del backend di automazione e il servizio riavviato prima di poterla attivare qui.",
- "pt": "A sincronização do Git precisa ser ativada no ambiente do backend de automação, e o serviço reiniciado, antes de poder ser ligada aqui.",
- "es": "La sincronización de Git debe habilitarse en el entorno del backend de automatización y reiniciar el servicio antes de poder activarla aquí.",
- "ca": "La sincronització de Git s'ha d'habilitar a l'entorn del backend d'automatització i cal reiniciar el servei abans de poder activar-la aquí.",
- "tr": "Git eşitlemesi burada açılabilmesi için önce otomasyon arka ucunun ortamında etkinleştirilmeli ve hizmet yeniden başlatılmalıdır.",
- "uk": "Щоб увімкнути синхронізацію Git тут, її потрібно спершу активувати в середовищі бекенда автоматизації та перезапустити службу."
- },
- "AUTOMATIONS$GIT_SYNC$NOT_LOCAL_TITLE": {
- "en": "Git Sync isn't available",
- "ja": "Git同期は利用できません",
- "zh-CN": "Git 同步不可用",
- "zh-TW": "Git 同步無法使用",
- "ko-KR": "Git 동기화를 사용할 수 없습니다",
- "no": "Git-synkronisering er ikke tilgjengelig",
- "ar": "مزامنة Git غير متاحة",
- "de": "Git-Synchronisierung ist nicht verfügbar",
- "fr": "La synchronisation Git n'est pas disponible",
- "it": "La sincronizzazione Git non è disponibile",
- "pt": "A sincronização Git não está disponível",
- "es": "La sincronización de Git no está disponible",
- "ca": "La sincronització de Git no està disponible",
- "tr": "Git Senkronizasyonu kullanılamıyor",
- "uk": "Git-синхронізація недоступна"
- },
- "AUTOMATIONS$GIT_SYNC$NOT_LOCAL_MESSAGE": {
- "en": "Git Sync is only available when connected to a local OpenHands backend.",
- "ja": "Git同期はローカルのOpenHandsバックエンドに接続している場合のみ利用できます。",
- "zh-CN": "只有连接到本地 OpenHands 后端时才能使用 Git 同步。",
- "zh-TW": "只有連線到本機 OpenHands 後端時才能使用 Git 同步。",
- "ko-KR": "Git 동기화는 로컬 OpenHands 백엔드에 연결된 경우에만 사용할 수 있습니다.",
- "no": "Git-synkronisering er kun tilgjengelig når du er koblet til en lokal OpenHands-backend.",
- "ar": "تتوفر مزامنة Git فقط عند الاتصال بخلفية OpenHands محلية.",
- "de": "Git-Synchronisierung ist nur verfügbar, wenn eine Verbindung zu einem lokalen OpenHands-Backend besteht.",
- "fr": "La synchronisation Git n'est disponible que lorsque vous êtes connecté à un backend OpenHands local.",
- "it": "La sincronizzazione Git è disponibile solo quando sei connesso a un backend OpenHands locale.",
- "pt": "A sincronização Git só está disponível quando conectado a um backend OpenHands local.",
- "es": "La sincronización de Git solo está disponible al conectarse a un backend local de OpenHands.",
- "ca": "La sincronització de Git només està disponible en connectar-se a un backend local d'OpenHands.",
- "tr": "Git Senkronizasyonu yalnızca yerel bir OpenHands arka ucuna bağlıyken kullanılabilir.",
- "uk": "Git-синхронізація доступна лише при підключенні до локального бекенду OpenHands."
+ "AUTOMATIONS$GIT_SYNC$NO_ACCESS_TITLE": {
+ "en": "Git Sync is managed by organization admins",
+ "ja": "Git同期は組織の管理者が管理します",
+ "zh-CN": "Git 同步由组织管理员管理",
+ "zh-TW": "Git 同步由組織管理員管理",
+ "ko-KR": "Git 동기화는 조직 관리자가 관리합니다",
+ "no": "Git-synkronisering administreres av organisasjonsadministratorer",
+ "ar": "تتم إدارة مزامنة Git بواسطة مسؤولي المؤسسة",
+ "de": "Git-Synchronisierung wird von Organisationsadministratoren verwaltet",
+ "fr": "La synchronisation Git est gérée par les administrateurs de l'organisation",
+ "it": "La sincronizzazione Git è gestita dagli amministratori dell'organizzazione",
+ "pt": "A sincronização Git é gerida pelos administradores da organização",
+ "es": "La sincronización de Git la gestionan los administradores de la organización",
+ "ca": "La sincronització de Git la gestionen els administradors de l'organització",
+ "tr": "Git Senkronizasyonu kuruluş yöneticileri tarafından yönetilir",
+ "uk": "Git-синхронізацією керують адміністратори організації"
+ },
+ "AUTOMATIONS$GIT_SYNC$NO_ACCESS_MESSAGE": {
+ "en": "Only organization admins and owners can view and configure Git Sync.",
+ "ja": "組織の管理者とオーナーのみがGit同期を表示・設定できます。",
+ "zh-CN": "只有组织管理员和所有者可以查看和配置 Git 同步。",
+ "zh-TW": "只有組織管理員和擁有者可以檢視和設定 Git 同步。",
+ "ko-KR": "조직 관리자와 소유자만 Git 동기화를 보고 구성할 수 있습니다.",
+ "no": "Bare organisasjonsadministratorer og eiere kan se og konfigurere Git-synkronisering.",
+ "ar": "يمكن فقط لمسؤولي المؤسسة ومالكيها عرض مزامنة Git وتكوينها.",
+ "de": "Nur Organisationsadministratoren und -inhaber können die Git-Synchronisierung anzeigen und konfigurieren.",
+ "fr": "Seuls les administrateurs et propriétaires de l'organisation peuvent consulter et configurer la synchronisation Git.",
+ "it": "Solo gli amministratori e i proprietari dell'organizzazione possono visualizzare e configurare la sincronizzazione Git.",
+ "pt": "Apenas administradores e proprietários da organização podem ver e configurar a sincronização Git.",
+ "es": "Solo los administradores y propietarios de la organización pueden ver y configurar la sincronización de Git.",
+ "ca": "Només els administradors i propietaris de l'organització poden veure i configurar la sincronització de Git.",
+ "tr": "Yalnızca kuruluş yöneticileri ve sahipleri Git Senkronizasyonunu görüntüleyebilir ve yapılandırabilir.",
+ "uk": "Лише адміністратори та власники організації можуть переглядати й налаштовувати Git-синхронізацію."
},
"AUTOMATIONS$GIT_SYNC$UNSUPPORTED_TITLE": {
"en": "Git Sync is not available on this backend",
diff --git a/src/routes/automation-git-sync.tsx b/src/routes/automation-git-sync.tsx
index df24eea3f3..2f0d857661 100644
--- a/src/routes/automation-git-sync.tsx
+++ b/src/routes/automation-git-sync.tsx
@@ -9,13 +9,12 @@ import {
useTriggerGitSync,
} from "#/hooks/query/use-git-sync";
import { useAutomationHealth } from "#/hooks/query/use-automation-health";
-import { useActiveBackend } from "#/contexts/active-backend-context";
import { useAutomationPermissions } from "#/hooks/use-automation-permissions";
import { BackLink } from "#/components/features/automations/detail/back-link";
import { ErrorState } from "#/components/features/automations/error-state";
import { BackendNotConfigured } from "#/components/features/automations/backend-not-configured";
import { GitSyncSkeleton } from "#/components/features/automations/git-sync/git-sync-skeleton";
-import { GitSyncNotLocalState } from "#/components/features/automations/git-sync/git-sync-not-local-state";
+import { GitSyncNoAccessState } from "#/components/features/automations/git-sync/git-sync-no-access-state";
import { GitSyncUnsupportedState } from "#/components/features/automations/git-sync/git-sync-unsupported-state";
import { GitSyncErrorBanner } from "#/components/features/automations/git-sync/git-sync-error-banner";
import { GitSyncOverviewSection } from "#/components/features/automations/git-sync/git-sync-overview-section";
@@ -52,13 +51,12 @@ const runningSince = (status: GitSyncStatus): SyncActivity => ({
export default function AutomationGitSync() {
const { t } = useTranslation("openhands");
- const active = useActiveBackend();
// Git sync is an org-level operation (not per-automation), so there is no
- // creator escape hatch — only users with manage_automations may configure,
- // check, or trigger a sync. The status read requires view_automations, but
- // since the page is local-only and local users always have manage, the
- // distinction only matters for cloud deployments that don't reach this page.
- const { canManage } = useAutomationPermissions();
+ // creator escape hatch: only users with manage_automations (org admins and
+ // owners) may see, configure, check, or trigger a sync. Local backends
+ // always grant it; on cloud it comes from the org's /me permissions.
+ const { canManage, isLoading: isPermissionsLoading } =
+ useAutomationPermissions();
const [activity, setActivity] = useState<SyncActivity>({ state: "idle" });
const isRunning = activity.state === "running";
@@ -69,15 +67,13 @@ export default function AutomationGitSync() {
} = useAutomationHealth();
const isBackendHealthy = healthData?.status === "ok";
- const isLocalBackend = active.backend.kind === "local";
-
const {
data: status,
isLoading,
error,
refetch,
} = useGitSyncStatus({
- enabled: isBackendHealthy && isLocalBackend,
+ enabled: isBackendHealthy && canManage,
refetchInterval: isRunning ? POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS,
});
@@ -119,21 +115,21 @@ export default function AutomationGitSync() {
const triggerMutation = useTriggerGitSync();
- if (!isLocalBackend) {
+ if (isHealthLoading || isPermissionsLoading) {
return (
<div className="min-h-full">
<div className="p-6 max-w-4xl mx-auto">
- <GitSyncNotLocalState />
+ <GitSyncSkeleton />
</div>
</div>
);
}
- if (isHealthLoading) {
+ if (!canManage) {
return (
<div className="min-h-full">
<div className="p-6 max-w-4xl mx-auto">
- <GitSyncSkeleton />
+ <GitSyncNoAccessState />
</div>
</div>
);
diff --git a/src/routes/automations-list.tsx b/src/routes/automations-list.tsx
index 8c462946f3..1245b30ced 100644
--- a/src/routes/automations-list.tsx
+++ b/src/routes/automations-list.tsx
@@ -38,6 +38,7 @@ import { ImportAutomationModal } from "#/components/features/automations/import-
import { RecommendedAutomationsLauncher } from "#/components/features/automations/recommended-automations-launcher";
import { BrandButton } from "#/components/features/settings/brand-button";
import { useTracking } from "#/hooks/use-tracking";
+import { useAutomationPermissions } from "#/hooks/use-automation-permissions";
import type { Automation, AutomationSpec } from "#/types/automation";
import {
getAutomationExportFilename,
@@ -118,8 +119,9 @@ export default function AutomationsList() {
const active = useActiveBackend();
const { navigate } = useNavigation();
- // Git Sync is only available on local backends.
- const isLocalBackend = active.backend.kind === "local";
+ // Git Sync is org-level config, so its entry point requires
+ // manage_automations (admins/owners) on every backend kind.
+ const { canManage } = useAutomationPermissions();
const {
data: healthData,
@@ -372,7 +374,10 @@ export default function AutomationsList() {
</p>
</div>
<div className="flex shrink-0 flex-wrap justify-end gap-2">
- {isLocalBackend && (
+ {/* Git sync is org-level config, so it follows manage_automations
+ (admins/owners) on every backend kind, not the local-only edit
+ gate. */}
+ {canManage && (
<BrandButton
type="button"
variant="secondary"