Skip to content

🙌 OpenHands: AI-Driven Development

feat(automations): add a Git Sync page (#16521)

Vasco Schiavo475a73162fe6
diff --git a/__tests__/hooks/query/use-git-sync.test.tsx b/__tests__/hooks/query/use-git-sync.test.tsx
new file mode 100644
index 0000000000..d4404c1347
--- /dev/null
+++ b/__tests__/hooks/query/use-git-sync.test.tsx
@@ -0,0 +1,187 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClientProvider, QueryClient } from "@tanstack/react-query";
+import {
+ GIT_SYNC_STATUS_QUERY_KEY,
+ useGitSyncStatus,
+ useTriggerGitSync,
+ useUpdateGitSyncConfig,
+} from "#/hooks/query/use-git-sync";
+import AutomationService from "#/api/automation-service/automation-service.api";
+import type { GitSyncStatus } from "#/types/git-sync";
+
+vi.mock("#/api/automation-service/automation-service.api", () => ({
+ default: {
+ getGitSyncStatus: vi.fn(),
+ updateGitSyncConfig: vi.fn(),
+ triggerGitSync: vi.fn(),
+ },
+}));
+
+vi.mock("#/contexts/active-backend-context", () => ({
+ useActiveBackend: () => ({
+ backend: { id: "test-backend", kind: "local" },
+ orgId: null,
+ }),
+}));
+
+vi.mock("#/hooks/use-tracking", () => ({
+ useTracking: () => ({
+ trackGitSyncConfigUpdated: vi.fn(),
+ trackGitSyncTriggered: vi.fn(),
+ }),
+}));
+
+const STATUS_KEY = [...GIT_SYNC_STATUS_QUERY_KEY, "test-backend", null];
+
+const baseStatus: GitSyncStatus = {
+ enabled: true,
+ repo_url: "https://example.com/org/repo.git",
+ branch: "main",
+ path: "automations",
+ encryption_enabled: false,
+ interval_seconds: 0,
+ last_synced_commit: null,
+ last_synced_at: null,
+ last_error: null,
+ last_error_at: null,
+ dirty_count: 0,
+};
+
+function createHarness() {
+ const queryClient = new QueryClient({
+ // `retry` is the default for queries that don't set their own; the hooks
+ // under test do, so `retryDelay` is what matters here -- without it the
+ // real exponential backoff would make a retry test wait a second.
+ defaultOptions: { queries: { retry: false, retryDelay: 0 } },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ return { queryClient, wrapper };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("useUpdateGitSyncConfig", () => {
+ it("does not let a status fetch started before the save overwrite it", async () => {
+ // React Query resolves fetches in completion order, not request order: a
+ // GET in flight when the save lands would otherwise replace the saved
+ // config with its own pre-save snapshot.
+ let resolveStaleFetch: (value: GitSyncStatus) => void = () => {};
+ vi.mocked(AutomationService.getGitSyncStatus).mockReturnValue(
+ new Promise<GitSyncStatus>((resolve) => {
+ resolveStaleFetch = resolve;
+ }),
+ );
+ const saved: GitSyncStatus = { ...baseStatus, branch: "develop" };
+ vi.mocked(AutomationService.updateGitSyncConfig).mockResolvedValue(saved);
+
+ const { queryClient, wrapper } = createHarness();
+ const { result } = renderHook(
+ () => ({
+ status: useGitSyncStatus(),
+ update: useUpdateGitSyncConfig(),
+ }),
+ { wrapper },
+ );
+
+ await act(async () => {
+ await result.current.update.mutateAsync({ branch: "develop" });
+ });
+ expect(queryClient.getQueryData(STATUS_KEY)).toEqual(saved);
+
+ // The pre-save GET now comes back with the old branch.
+ await act(async () => {
+ resolveStaleFetch(baseStatus);
+ await Promise.resolve();
+ });
+
+ expect(queryClient.getQueryData(STATUS_KEY)).toEqual(saved);
+ });
+
+ it("leaves error reporting to the caller", async () => {
+ // The page maps 409/503 to specific guidance; the global mutation toast
+ // would stack the raw axios message on top of it.
+ vi.mocked(AutomationService.updateGitSyncConfig).mockRejectedValue(
+ new Error("boom"),
+ );
+ const { queryClient, wrapper } = createHarness();
+ const { result } = renderHook(() => useUpdateGitSyncConfig(), { wrapper });
+
+ act(() => {
+ result.current.mutate({ branch: "develop" });
+ });
+ await waitFor(() => expect(result.current.isError).toBe(true));
+
+ expect(queryClient.getMutationCache().getAll()[0].options.meta).toEqual({
+ disableToast: true,
+ });
+ });
+});
+
+describe("useTriggerGitSync", () => {
+ it("leaves error reporting to the caller", async () => {
+ vi.mocked(AutomationService.triggerGitSync).mockRejectedValue(
+ new Error("boom"),
+ );
+ const { queryClient, wrapper } = createHarness();
+ const { result } = renderHook(() => useTriggerGitSync(), { wrapper });
+
+ act(() => {
+ result.current.mutate();
+ });
+ await waitFor(() => expect(result.current.isError).toBe(true));
+
+ expect(queryClient.getMutationCache().getAll()[0].options.meta).toEqual({
+ disableToast: true,
+ });
+ });
+});
+
+describe("useGitSyncStatus", () => {
+ it("does not retry a backend that has no git-sync API", async () => {
+ vi.mocked(AutomationService.getGitSyncStatus).mockRejectedValue({
+ status: 404,
+ });
+ const { wrapper } = createHarness();
+
+ const { result } = renderHook(() => useGitSyncStatus(), { wrapper });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(AutomationService.getGitSyncStatus).toHaveBeenCalledTimes(1);
+ });
+
+ // Regression: this retried anything that wasn't a 404. The automation
+ // service answers 500 only after its own 30s connection-pool timeout, so
+ // three retries plus backoff held the page's skeleton for about two minutes
+ // instead of showing the error panel with its Retry button straight away.
+ it("does not retry an answered failure", async () => {
+ vi.mocked(AutomationService.getGitSyncStatus).mockRejectedValue({
+ status: 500,
+ });
+ const { wrapper } = createHarness();
+
+ const { result } = renderHook(() => useGitSyncStatus(), { wrapper });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(AutomationService.getGitSyncStatus).toHaveBeenCalledTimes(1);
+ });
+
+ it("retries a request that never got an answer", async () => {
+ // No status: the request never reached the service, so repeating it is
+ // cheap and can actually succeed.
+ vi.mocked(AutomationService.getGitSyncStatus)
+ .mockRejectedValueOnce(new Error("network error"))
+ .mockResolvedValue(baseStatus);
+ const { wrapper } = createHarness();
+
+ const { result } = renderHook(() => useGitSyncStatus(), { wrapper });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(AutomationService.getGitSyncStatus).toHaveBeenCalledTimes(2);
+ expect(result.current.data).toEqual(baseStatus);
+ });
+});
diff --git a/__tests__/routes/automation-git-sync.test.tsx b/__tests__/routes/automation-git-sync.test.tsx
new file mode 100644
index 0000000000..45da6f69d4
--- /dev/null
+++ b/__tests__/routes/automation-git-sync.test.tsx
@@ -0,0 +1,278 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MemoryRouter, Route, Routes } from "react-router";
+import { HttpError } from "@openhands/typescript-client";
+
+import { I18nKey } from "#/i18n/declaration";
+import AutomationService from "#/api/automation-service/automation-service.api";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+import AutomationGitSync from "#/routes/automation-git-sync";
+import type { Backend } from "#/api/backend-registry/types";
+import type { GitSyncStatus } from "#/types/git-sync";
+
+vi.mock("#/api/automation-service/automation-service.api", () => ({
+ default: {
+ getGitSyncStatus: vi.fn(),
+ updateGitSyncConfig: vi.fn(),
+ triggerGitSync: vi.fn(),
+ checkHealth: vi.fn(),
+ },
+}));
+
+const displayErrorToast = vi.fn();
+const displaySuccessToast = vi.fn();
+
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displayErrorToast: (message: string) => displayErrorToast(message),
+ displaySuccessToast: (message: string) => displaySuccessToast(message),
+}));
+
+const localBackend: Backend = {
+ id: "local-1",
+ name: "Local 1",
+ host: "http://localhost:8000",
+ apiKey: "session-key",
+ kind: "local",
+};
+
+const status: GitSyncStatus = {
+ enabled: true,
+ repo_url: "https://example.com/org/repo.git",
+ branch: "main",
+ path: "automations",
+ encryption_enabled: false,
+ interval_seconds: 0,
+ last_synced_commit: "abc1234",
+ last_synced_at: "2026-08-10T00:00:00Z",
+ last_error: null,
+ last_error_at: null,
+ dirty_count: 0,
+};
+
+function renderGitSync() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const view = render(
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>
+ <MemoryRouter initialEntries={["/automations/git-sync"]}>
+ <Routes>
+ <Route
+ path="/automations/git-sync"
+ element={<AutomationGitSync />}
+ />
+ </Routes>
+ </MemoryRouter>
+ </ActiveBackendProvider>
+ </QueryClientProvider>,
+ );
+ return { ...view, queryClient };
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ vi.mocked(AutomationService.checkHealth).mockReset();
+ vi.mocked(AutomationService.checkHealth).mockResolvedValue({ status: "ok" });
+ vi.mocked(AutomationService.getGitSyncStatus).mockReset();
+ vi.mocked(AutomationService.getGitSyncStatus).mockResolvedValue(status);
+ vi.mocked(AutomationService.triggerGitSync).mockReset();
+ vi.mocked(AutomationService.triggerGitSync).mockResolvedValue({
+ triggered: true,
+ });
+ displayErrorToast.mockReset();
+ displaySuccessToast.mockReset();
+ setRegisteredBackends([localBackend]);
+ setActiveSelection({ backendId: localBackend.id });
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+});
+
+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
+ // answers 404 here, which used to settle on "something went wrong".
+ vi.mocked(AutomationService.getGitSyncStatus).mockRejectedValue(
+ new HttpError(404, "Not Found", { detail: "Not Found" }),
+ );
+
+ renderGitSync();
+
+ expect(
+ await screen.findByText(I18nKey.AUTOMATIONS$GIT_SYNC$UNSUPPORTED_TITLE),
+ ).toBeInTheDocument();
+ // A permanent 404 is not worth retrying.
+ expect(AutomationService.getGitSyncStatus).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("AutomationGitSync — failed background refetch", () => {
+ it("keeps the loaded page instead of replacing it with the error panel", async () => {
+ vi.useFakeTimers();
+ renderGitSync();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(screen.getByTestId("git-sync-repo-url-input")).toBeInTheDocument();
+
+ // Break the endpoint the way an automation backend restart would, then
+ // let the post-trigger poll run into it.
+ vi.mocked(AutomationService.getGitSyncStatus).mockRejectedValue(
+ new HttpError(502, "Bad Gateway", { detail: "upstream restarting" }),
+ );
+ await act(async () => {
+ fireEvent.click(screen.getByTestId("git-sync-now-button"));
+ // Several 3s polls plus their retries and backoff.
+ await vi.advanceTimersByTimeAsync(20_000);
+ });
+
+ // The config form is still mounted, so nothing half-typed in it is lost.
+ expect(screen.getByTestId("git-sync-repo-url-input")).toBeInTheDocument();
+ expect(screen.queryByText(I18nKey.ERROR$GENERIC)).not.toBeInTheDocument();
+ });
+});
+
+describe("AutomationGitSync — sync progress", () => {
+ /** Load the page with fake timers already running. */
+ async function loadPage() {
+ vi.useFakeTimers();
+ renderGitSync();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ return screen.getByTestId("git-sync-now-button");
+ }
+
+ const activityRow = () => screen.queryByTestId("git-sync-activity-row");
+
+ it("reports the running cycle in the page rather than with a toast", async () => {
+ // The trigger returns as soon as the cycle is scheduled, so a toast can
+ // only ever say "started" and never how it ended.
+ const syncNow = await loadPage();
+
+ await act(async () => {
+ fireEvent.click(syncNow);
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ expect(activityRow()).toHaveAttribute("data-state", "running");
+ expect(displaySuccessToast).not.toHaveBeenCalled();
+ expect(syncNow).toHaveTextContent(I18nKey.AUTOMATIONS$GIT_SYNC$SYNCING);
+ expect(syncNow).toBeDisabled();
+ });
+
+ it("resolves as soon as the cycle lands, without waiting out the window", async () => {
+ const syncNow = await loadPage();
+ await act(async () => {
+ fireEvent.click(syncNow);
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ // The backend finishes the cycle: a newer success than the one the page
+ // started from.
+ vi.mocked(AutomationService.getGitSyncStatus).mockResolvedValue({
+ ...status,
+ last_synced_at: "2026-08-11T00:00:00Z",
+ last_synced_commit: "def5678",
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(4_000);
+ });
+
+ expect(activityRow()).toHaveAttribute("data-state", "succeeded");
+ // Released well inside the 30s window the page used to sit out.
+ expect(syncNow).not.toBeDisabled();
+ });
+
+ it("reports a cycle that failed", async () => {
+ const syncNow = await loadPage();
+ await act(async () => {
+ fireEvent.click(syncNow);
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ vi.mocked(AutomationService.getGitSyncStatus).mockResolvedValue({
+ ...status,
+ last_error: "fatal: Authentication failed",
+ last_error_at: "2026-08-11T00:00:00Z",
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(4_000);
+ });
+
+ expect(activityRow()).toHaveAttribute("data-state", "failed");
+ expect(screen.getByTestId("git-sync-error-banner")).toHaveTextContent(
+ "fatal: Authentication failed",
+ );
+ });
+
+ it("follows a cycle the backend started on its own", async () => {
+ // An interval-driven sync, or one triggered from another tab: the page
+ // never asked for it, so only `sync_in_progress` reveals it.
+ vi.mocked(AutomationService.getGitSyncStatus).mockResolvedValue({
+ ...status,
+ sync_in_progress: true,
+ sync_started_at: "2026-08-10T00:00:05Z",
+ });
+
+ const syncNow = await loadPage();
+
+ expect(activityRow()).toHaveAttribute("data-state", "running");
+ expect(syncNow).toBeDisabled();
+ expect(AutomationService.triggerGitSync).not.toHaveBeenCalled();
+ });
+
+ it("gives up on a backend that never reports the cycle", async () => {
+ // Fallback for an automation backend without `sync_in_progress`: the page
+ // can only wait a bounded time for an outcome that may never come.
+ const syncNow = await loadPage();
+ await act(async () => {
+ fireEvent.click(syncNow);
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(activityRow()).toHaveAttribute("data-state", "running");
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(31_000);
+ });
+
+ expect(activityRow()).not.toBeInTheDocument();
+ expect(syncNow).not.toBeDisabled();
+ });
+
+ it("keeps reporting the trigger's own failure with a toast", async () => {
+ // A rejected request never becomes a cycle, so there is no progress to
+ // show for it -- 503 means sync is switched off.
+ vi.mocked(AutomationService.triggerGitSync).mockRejectedValue({
+ status: 503,
+ });
+ const syncNow = await loadPage();
+
+ await act(async () => {
+ fireEvent.click(syncNow);
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ expect(displayErrorToast).toHaveBeenCalledWith(
+ I18nKey.AUTOMATIONS$GIT_SYNC$SYNC_DISABLED_ERROR,
+ );
+ expect(activityRow()).not.toBeInTheDocument();
+ });
+});
diff --git a/__tests__/scripts/dev-with-automation.test.ts b/__tests__/scripts/dev-with-automation.test.ts
index 87b43890ec..f6e108c161 100644
--- a/__tests__/scripts/dev-with-automation.test.ts
+++ b/__tests__/scripts/dev-with-automation.test.ts
@@ -25,6 +25,7 @@ import {
getLocalServiceRoutes,
setServiceLogListener,
spawnService,
+ validateLocalAutomationPath,
DEFAULT_AUTOMATION_REPO,
DEFAULT_AUTOMATION_PACKAGE,
DEFAULT_AUTOMATION_VERSION,
@@ -121,6 +122,69 @@ describe("buildAutomationCommand", () => {
expect(cmd.args).not.toContain(`${DEFAULT_AUTOMATION_PACKAGE}==1.0.0`);
expect(cmd.source).toBe("git (main)");
});
+
+ it("runs a local checkout in place, ahead of the other env vars", () => {
+ const cmd = buildAutomationCommand({
+ OH_AUTOMATION_LOCAL_PATH: "/checkouts/automation",
+ OH_AUTOMATION_GIT_REF: "main",
+ OH_AUTOMATION_VERSION: "1.0.0",
+ });
+
+ expect(cmd.command).toBe("uv");
+ expect(cmd.args).toEqual([
+ "run",
+ "--project",
+ "/checkouts/automation",
+ "uvicorn",
+ "openhands.automation.app:app",
+ ]);
+ expect(cmd.source).toBe("local (/checkouts/automation)");
+ });
+});
+
+describe("validateLocalAutomationPath", () => {
+ const dirs: string[] = [];
+
+ afterEach(() => {
+ while (dirs.length > 0) {
+ const dir = dirs.pop();
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ function makeCheckout({ withProjectFile = true } = {}) {
+ const dir = mkdtempSync(path.join(tmpdir(), "automation-checkout-"));
+ dirs.push(dir);
+ if (withProjectFile) {
+ writeFileSync(path.join(dir, "pyproject.toml"), "[project]\n");
+ }
+ return dir;
+ }
+
+ it("accepts an absolute path to a Python project", () => {
+ expect(() => validateLocalAutomationPath(makeCheckout())).not.toThrow();
+ });
+
+ // Without these, `uv run --project <bad path>` just exits and the rest of
+ // the stack stays up, leaving the automations UI blaming the backend.
+ it("rejects a relative path", () => {
+ expect(() => validateLocalAutomationPath("../automation")).toThrow(
+ /absolute path/i,
+ );
+ });
+
+ it("rejects a path that does not exist", () => {
+ const dir = makeCheckout();
+ rmSync(dir, { recursive: true, force: true });
+
+ expect(() => validateLocalAutomationPath(dir)).toThrow(/does not exist/i);
+ });
+
+ it("rejects a directory that is not a Python project", () => {
+ expect(() =>
+ validateLocalAutomationPath(makeCheckout({ withProjectFile: false })),
+ ).toThrow(/pyproject\.toml/);
+ });
});
describe("buildAgentServerAutomationEnv", () => {
@@ -237,6 +301,31 @@ describe("buildConfig", () => {
expect(ports.size).toBe(4);
});
+ it("lets --automation-git-ref win over an exported OH_AUTOMATION_LOCAL_PATH", async () => {
+ // Otherwise someone with the checkout exported in their shell profile
+ // reproduces a bug against their own working tree while believing they
+ // are testing the ref they just passed.
+ const env = envWithIsolatedKeyPath({
+ OH_AUTOMATION_LOCAL_PATH: "/checkouts/automation",
+ });
+
+ await buildConfig({ automationGitRef: "abc123" }, env);
+
+ expect(env.OH_AUTOMATION_GIT_REF).toBe("abc123");
+ expect(env.OH_AUTOMATION_LOCAL_PATH).toBeUndefined();
+ expect(buildAutomationCommand(env).source).toBe("git (abc123)");
+ });
+
+ it("keeps a local checkout when no ref is passed", async () => {
+ const env = envWithIsolatedKeyPath({
+ OH_AUTOMATION_LOCAL_PATH: "/checkouts/automation",
+ });
+
+ await buildConfig({}, env);
+
+ expect(env.OH_AUTOMATION_LOCAL_PATH).toBe("/checkouts/automation");
+ });
+
it("respects preferred port from args when available", async () => {
// Use a high port unlikely to be busy
const preferredPort = 19500;
diff --git a/scripts/check-translation-completeness.cjs b/scripts/check-translation-completeness.cjs
index 010c6d9658..30df95d5b7 100755
--- a/scripts/check-translation-completeness.cjs
+++ b/scripts/check-translation-completeness.cjs
@@ -17,6 +17,9 @@ const IDENTICAL_VALUE_ALLOWLIST = new Set([
'API$TAVILY_KEY_EXAMPLE',
'API$TVLY_KEY_EXAMPLE',
'AUTOMATIONS$DOWNLOAD_TARBALL',
+ 'AUTOMATIONS$GIT_SYNC$BRANCH_PLACEHOLDER',
+ 'AUTOMATIONS$GIT_SYNC$PATH_PLACEHOLDER',
+ 'AUTOMATIONS$GIT_SYNC$REPO_URL_PLACEHOLDER',
'BACKEND$CLOUD_TITLE',
'BACKEND$VERSION_LABEL',
'BRANDING$OPENHANDS',
diff --git a/scripts/dev-with-automation.mjs b/scripts/dev-with-automation.mjs
index 0bf41bda26..a965c07634 100644
--- a/scripts/dev-with-automation.mjs
+++ b/scripts/dev-with-automation.mjs
@@ -46,7 +46,7 @@
import { spawn, spawnSync } from "node:child_process";
import { mkdirSync, existsSync, readFileSync } from "node:fs";
-import { join, resolve, dirname } from "node:path";
+import { join, resolve, dirname, isAbsolute } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { homedir } from "node:os";
import { setTimeout as delay } from "node:timers/promises";
@@ -252,6 +252,7 @@ ENVIRONMENT VARIABLES:
PORT Alternative to --port
OH_AUTOMATION_GIT_REF Git ref for automation (overrides default version)
OH_AUTOMATION_VERSION Specific PyPI version for automation (default: ${DEFAULT_AUTOMATION_VERSION})
+ OH_AUTOMATION_LOCAL_PATH Absolute path to a local automation checkout (overridden only by --automation-git-ref)
OH_AGENT_SERVER_LOCAL_PATH Absolute path to a local software-agent-sdk checkout (highest precedence)
OH_AGENT_SERVER_GIT_REF Git ref for agent-server SDK (overrides default version)
OH_AGENT_SERVER_VERSION Specific PyPI version for agent-server
@@ -270,10 +271,34 @@ ACCESS POINTS:
`);
}
+/**
+ * Fail fast on an unusable OH_AUTOMATION_LOCAL_PATH instead of letting
+ * `uv run --project <bad path>` exit on its own -- that leaves the rest of the
+ * stack up and the automations UI just reporting "backend unavailable", with
+ * nothing pointing at the env var. Mirrors validateLocalAgentServerPath.
+ */
+function validateLocalAutomationPath(localPath) {
+ if (!isAbsolute(localPath)) {
+ throw new Error(
+ `OH_AUTOMATION_LOCAL_PATH must be an absolute path, got: ${localPath}`,
+ );
+ }
+ if (!existsSync(localPath)) {
+ throw new Error(`OH_AUTOMATION_LOCAL_PATH does not exist: ${localPath}`);
+ }
+ const projectFile = join(localPath, "pyproject.toml");
+ if (!existsSync(projectFile)) {
+ throw new Error(
+ `OH_AUTOMATION_LOCAL_PATH is not a Python project (no pyproject.toml): ${projectFile}`,
+ );
+ }
+}
+
/**
* Build the uvx command for running automation backend.
*
* Environment variables (highest precedence first):
+ * - OH_AUTOMATION_LOCAL_PATH: Absolute path to a local checkout
* - OH_AUTOMATION_GIT_REF: Git commit SHA or branch name
* - OH_AUTOMATION_VERSION: Specific PyPI version (e.g., "1.0.0a1")
*
@@ -282,6 +307,7 @@ ACCESS POINTS:
* git branch or commit instead.
*/
function buildAutomationCommand(env = process.env) {
+ const localPath = env.OH_AUTOMATION_LOCAL_PATH;
const gitRef = env.OH_AUTOMATION_GIT_REF;
const version = env.OH_AUTOMATION_VERSION;
const repoUrl = env.OH_AUTOMATION_REPO || DEFAULT_AUTOMATION_REPO;
@@ -289,6 +315,25 @@ function buildAutomationCommand(env = process.env) {
const uvxArgs = [];
let source = "";
+ if (localPath) {
+ // Run straight from a local checkout via `uv run --project`, so
+ // uncommitted working-tree changes are picked up. Outranks the other
+ // automation env vars, mirroring OH_AGENT_SERVER_LOCAL_PATH for the
+ // agent-server SDK; buildConfig drops it when --automation-git-ref asks
+ // for a specific ref.
+ return {
+ command: "uv",
+ args: [
+ "run",
+ "--project",
+ localPath,
+ "uvicorn",
+ "openhands.automation.app:app",
+ ],
+ source: `local (${localPath})`,
+ };
+ }
+
if (gitRef) {
// Use git ref - refresh to ensure latest commit is fetched
const gitUrl = `git+${repoUrl}@${gitRef}`;
@@ -331,6 +376,17 @@ async function buildConfig(args, env = process.env) {
// Apply args to env for buildAutomationCommand
if (args.automationGitRef) {
env.OH_AUTOMATION_GIT_REF = args.automationGitRef;
+ // An explicit flag outranks an ambient env var. Otherwise someone with
+ // OH_AUTOMATION_LOCAL_PATH exported in their shell profile would run their
+ // own working tree while believing they were reproducing against the ref
+ // they just passed.
+ if (env.OH_AUTOMATION_LOCAL_PATH) {
+ logStep(
+ "automation",
+ `--automation-git-ref ${args.automationGitRef} overrides OH_AUTOMATION_LOCAL_PATH (${env.OH_AUTOMATION_LOCAL_PATH})`,
+ );
+ delete env.OH_AUTOMATION_LOCAL_PATH;
+ }
}
if (args.automationRepo) {
env.OH_AUTOMATION_REPO = args.automationRepo;
@@ -1347,6 +1403,21 @@ async function main(options = {}) {
}
}
+ // Same for the automation checkout -- skipped when --automation-git-ref was
+ // passed, since buildConfig drops the env var in favor of the explicit flag.
+ if (
+ !args.frontendOnly &&
+ !args.automationGitRef &&
+ process.env.OH_AUTOMATION_LOCAL_PATH
+ ) {
+ try {
+ validateLocalAutomationPath(process.env.OH_AUTOMATION_LOCAL_PATH);
+ } catch (error) {
+ logError(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+ }
+ }
+
// Build config with dynamic port allocation
const config = await buildConfig(args);
if (viteWorkingDir) config.viteWorkingDir = viteWorkingDir;
@@ -1521,6 +1592,7 @@ export {
registerShutdownHook,
spawnService,
commandExists,
+ validateLocalAutomationPath,
logService,
logStep,
logSuccess,
diff --git a/src/api/automation-service/automation-service.api.test.ts b/src/api/automation-service/automation-service.api.test.ts
index 6b8cb2f50c..894d0386d2 100644
--- a/src/api/automation-service/automation-service.api.test.ts
+++ b/src/api/automation-service/automation-service.api.test.ts
@@ -5,6 +5,7 @@ import {
} from "#/api/backend-registry/active-store";
import type { Backend } from "#/api/backend-registry/types";
import type { Automation, AutomationSpec } from "#/types/automation";
+import type { GitSyncStatus } from "#/types/git-sync";
import AutomationService from "./automation-service.api";
const {
@@ -19,6 +20,7 @@ const {
interceptors: { request: { use: vi.fn() } },
get: vi.fn(),
post: vi.fn(),
+ put: vi.fn(),
patch: vi.fn(),
delete: vi.fn(),
},
@@ -355,3 +357,102 @@ describe("AutomationService.createAutomation", () => {
);
});
});
+
+const gitSyncStatus: GitSyncStatus = {
+ enabled: true,
+ repo_url: "https://example.com/org/repo.git",
+ branch: "main",
+ path: "automations",
+ encryption_enabled: false,
+ interval_seconds: 0,
+ last_synced_commit: "abc123",
+ last_synced_at: "2026-07-10T00:00:00Z",
+ last_error: null,
+ last_error_at: null,
+ dirty_count: 0,
+};
+
+describe("AutomationService git sync", () => {
+ beforeEach(() => {
+ setRegisteredBackends([localBackend]);
+ setActiveSelection({ backendId: localBackend.id });
+ });
+
+ afterEach(() => {
+ setActiveSelection(null);
+ setRegisteredBackends([]);
+ vi.clearAllMocks();
+ });
+
+ it("fetches status from the local automation backend", async () => {
+ localAxios.get.mockResolvedValueOnce({ data: gitSyncStatus });
+
+ await expect(AutomationService.getGitSyncStatus()).resolves.toEqual(
+ gitSyncStatus,
+ );
+
+ expect(localAxios.get).toHaveBeenCalledWith(
+ "/api/automation/v1/git-sync/status",
+ );
+ });
+
+ it("fetches status through the cloud proxy", async () => {
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });
+ callCloudProxy.mockResolvedValueOnce(gitSyncStatus);
+
+ await expect(AutomationService.getGitSyncStatus()).resolves.toEqual(
+ gitSyncStatus,
+ );
+
+ expect(callCloudProxy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ backend: cloudBackend,
+ method: "GET",
+ path: "/api/automation/v1/git-sync/status",
+ }),
+ );
+ });
+
+ it("sends a partial config update", async () => {
+ localAxios.put.mockResolvedValueOnce({ data: gitSyncStatus });
+
+ await expect(
+ AutomationService.updateGitSyncConfig({ branch: "develop" }),
+ ).resolves.toEqual(gitSyncStatus);
+
+ expect(localAxios.put).toHaveBeenCalledWith(
+ "/api/automation/v1/git-sync/config",
+ { branch: "develop" },
+ );
+ });
+
+ it("sends a null override through the cloud proxy", async () => {
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id, orgId: "org-1" });
+ callCloudProxy.mockResolvedValueOnce(gitSyncStatus);
+
+ await AutomationService.updateGitSyncConfig({ token: null });
+
+ expect(callCloudProxy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ backend: cloudBackend,
+ method: "PUT",
+ path: "/api/automation/v1/git-sync/config",
+ body: { token: null },
+ }),
+ );
+ });
+
+ it("triggers a sync cycle", async () => {
+ localAxios.post.mockResolvedValueOnce({ data: { triggered: true } });
+
+ await expect(AutomationService.triggerGitSync()).resolves.toEqual({
+ triggered: true,
+ });
+
+ expect(localAxios.post).toHaveBeenCalledWith(
+ "/api/automation/v1/git-sync/sync",
+ );
+ });
+});
diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.ts
index 2b93e3cc42..bba5de9482 100644
--- a/src/api/automation-service/automation-service.api.ts
+++ b/src/api/automation-service/automation-service.api.ts
@@ -14,6 +14,12 @@ import type {
AutomationsResponse,
AutomationRunsResponse,
} from "#/types/automation";
+import type {
+ GitSyncCheckResponse,
+ GitSyncConfigUpdateRequest,
+ GitSyncStatus,
+ GitSyncTriggerResponse,
+} from "#/types/git-sync";
import { AUTOMATION_CREATE_ENDPOINT } from "#/manifests/automation-setup";
import {
getAutomationEndpoint,
@@ -600,6 +606,90 @@ class AutomationService {
return data;
}
+ // 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.
+ static async getGitSyncStatus(): Promise<GitSyncStatus> {
+ const active = getActiveBackend().backend;
+ const path = `${AUTOMATION_BASE_PATH}/v1/git-sync/status`;
+
+ if (active.kind === "cloud") {
+ return callCloudProxy<GitSyncStatus>({
+ backend: active,
+ method: "GET",
+ path,
+ });
+ }
+
+ const { data } = await localAutomationAxios.get<GitSyncStatus>(path);
+ return data;
+ }
+
+ static async updateGitSyncConfig(
+ body: GitSyncConfigUpdateRequest,
+ ): Promise<GitSyncStatus> {
+ const active = getActiveBackend().backend;
+ const path = `${AUTOMATION_BASE_PATH}/v1/git-sync/config`;
+
+ if (active.kind === "cloud") {
+ return callCloudProxy<GitSyncStatus>({
+ backend: active,
+ method: "PUT",
+ path,
+ body: body as Record<string, unknown>,
+ });
+ }
+
+ const { data } = await localAutomationAxios.put<GitSyncStatus>(path, body);
+ return data;
+ }
+
+ /**
+ * Ask whether a configuration can reach its repo, without saving it. Takes
+ * the same body as `updateGitSyncConfig` and answers for the settings that
+ * body would leave in place.
+ */
+ static async checkGitSyncConfig(
+ body: GitSyncConfigUpdateRequest,
+ ): Promise<GitSyncCheckResponse> {
+ const active = getActiveBackend().backend;
+ const path = `${AUTOMATION_BASE_PATH}/v1/git-sync/check`;
+
+ if (active.kind === "cloud") {
+ return callCloudProxy<GitSyncCheckResponse>({
+ backend: active,
+ method: "POST",
+ path,
+ body: body as Record<string, unknown>,
+ });
+ }
+
+ const { data } = await localAutomationAxios.post<GitSyncCheckResponse>(
+ path,
+ body,
+ );
+ return data;
+ }
+
+ static async triggerGitSync(): Promise<GitSyncTriggerResponse> {
+ const active = getActiveBackend().backend;
+ const path = `${AUTOMATION_BASE_PATH}/v1/git-sync/sync`;
+
+ if (active.kind === "cloud") {
+ return callCloudProxy<GitSyncTriggerResponse>({
+ backend: active,
+ method: "POST",
+ path,
+ });
+ }
+
+ const { data } =
+ await localAutomationAxios.post<GitSyncTriggerResponse>(path);
+ return data;
+ }
+
static async checkHealth(): Promise<AutomationHealthResponse> {
const active = getActiveBackend().backend;
const path = `${AUTOMATION_BASE_PATH}${getAutomationEndpoint("health")}`;
diff --git a/src/components/features/automations/git-sync/git-sync-activity-row.test.tsx b/src/components/features/automations/git-sync/git-sync-activity-row.test.tsx
new file mode 100644
index 0000000000..eede7201f8
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-activity-row.test.tsx
@@ -0,0 +1,69 @@
+import { render, screen, act } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { GitSyncActivityRow } from "./git-sync-activity-row";
+
+// The global test mock returns the key and drops interpolation values; these
+// tests are about the interpolated elapsed time, so keep it.
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) =>
+ options ? `${key}|${JSON.stringify(options)}` : key,
+ i18n: { language: "en", exists: () => false },
+ }),
+}));
+
+const STARTED_AT = "2026-08-12T12:00:00Z";
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("GitSyncActivityRow", () => {
+ it("counts the elapsed time up while the cycle runs", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(STARTED_AT));
+
+ render(
+ <GitSyncActivityRow
+ state="running"
+ startedAt={STARTED_AT}
+ pendingCount={0}
+ />,
+ );
+
+ const row = screen.getByTestId("git-sync-activity-row");
+ expect(row).toHaveTextContent('"time":"0s"');
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3_000);
+ });
+
+ expect(row).toHaveTextContent('"time":"3s"');
+ });
+
+ it("stops ticking once the cycle is no longer running", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(STARTED_AT));
+
+ const { rerender, unmount } = render(
+ <GitSyncActivityRow
+ state="running"
+ startedAt={STARTED_AT}
+ pendingCount={0}
+ />,
+ );
+ expect(vi.getTimerCount()).toBeGreaterThan(0);
+
+ rerender(
+ <GitSyncActivityRow
+ state="succeeded"
+ startedAt={null}
+ pendingCount={0}
+ />,
+ );
+ expect(vi.getTimerCount()).toBe(0);
+
+ unmount();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/src/components/features/automations/git-sync/git-sync-activity-row.tsx b/src/components/features/automations/git-sync/git-sync-activity-row.tsx
new file mode 100644
index 0000000000..1849933ad4
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-activity-row.tsx
@@ -0,0 +1,92 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { RefreshCw, Check, TriangleAlert } from "lucide-react";
+import { I18nKey } from "#/i18n/declaration";
+import { formatTimeDelta } from "#/utils/format-time-delta";
+import { cn } from "#/utils/utils";
+
+export type GitSyncActivityState = "idle" | "running" | "succeeded" | "failed";
+
+interface GitSyncActivityRowProps {
+ state: GitSyncActivityState;
+ /** When the running cycle started, for the elapsed-time hint. */
+ startedAt: string | null;
+ /** Automations still waiting to be pushed, shown while a cycle runs. */
+ pendingCount: number;
+}
+
+/**
+ * Re-render every second while a cycle runs. The elapsed hint is derived from
+ * the clock, not from props, and the status poll returns identical JSON for as
+ * long as the cycle is in flight -- react-query's structural sharing then
+ * hands back the same object, nothing re-renders, and the hint would sit at
+ * whatever it read when the cycle started.
+ */
+function useSecondsTick(active: boolean) {
+ const [, setTick] = useState(0);
+
+ useEffect(() => {
+ if (!active) return undefined;
+ const timer = setInterval(() => setTick((count) => count + 1), 1_000);
+ return () => clearInterval(timer);
+ }, [active]);
+}
+
+/**
+ * The page's own account of the sync cycle, in place of the fire-and-forget
+ * success toast: the trigger returns as soon as the cycle is scheduled, so a
+ * toast said "started" and then never came back with an outcome.
+ */
+export function GitSyncActivityRow({
+ state,
+ startedAt,
+ pendingCount,
+}: GitSyncActivityRowProps) {
+ const { t } = useTranslation("openhands");
+ const isRunning = state === "running";
+
+ useSecondsTick(isRunning && startedAt !== null);
+
+ if (state === "idle") return null;
+
+ const isFailed = state === "failed";
+
+ return (
+ <div
+ data-testid="git-sync-activity-row"
+ data-state={state}
+ className={cn(
+ "mt-4 flex flex-wrap items-center gap-x-2 gap-y-1 rounded-md px-3 py-2 text-sm",
+ isRunning && "bg-tertiary text-content",
+ state === "succeeded" && "bg-green-500/10 text-green-300",
+ isFailed && "bg-red-500/10 text-red-300",
+ )}
+ >
+ {isRunning && <RefreshCw className="size-4 animate-spin" aria-hidden />}
+ {state === "succeeded" && <Check className="size-4" aria-hidden />}
+ {isFailed && <TriangleAlert className="size-4" aria-hidden />}
+
+ <span className="font-medium">
+ {isRunning && t(I18nKey.AUTOMATIONS$GIT_SYNC$SYNCING)}
+ {state === "succeeded" &&
+ t(I18nKey.AUTOMATIONS$GIT_SYNC$SYNC_COMPLETED)}
+ {isFailed && t(I18nKey.AUTOMATIONS$GIT_SYNC$SYNC_FAILED)}
+ </span>
+
+ {isRunning && startedAt && (
+ <span className="text-xs text-muted">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$SYNC_STARTED_AGO, {
+ time: formatTimeDelta(startedAt),
+ })}
+ </span>
+ )}
+ {isRunning && pendingCount > 0 && (
+ <span className="text-xs text-muted">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$SYNC_PENDING_COUNT, {
+ count: pendingCount,
+ })}
+ </span>
+ )}
+ </div>
+ );
+}
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
new file mode 100644
index 0000000000..a6dfab022f
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-config-form.test.tsx
@@ -0,0 +1,608 @@
+import { render, screen, fireEvent, act } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { I18nKey } from "#/i18n/declaration";
+import type { GitSyncStatus } from "#/types/git-sync";
+import { GitSyncConfigForm } from "./git-sync-config-form";
+
+const mutate = vi.fn();
+const checkConfig = vi.fn();
+const syncNow = vi.fn();
+
+vi.mock("#/hooks/query/use-git-sync", () => ({
+ useUpdateGitSyncConfig: () => ({ mutate, isPending: false }),
+ useCheckGitSyncConfig: () => ({
+ mutateAsync: checkConfig,
+ isPending: false,
+ }),
+}));
+
+/** Submitting is async now: it awaits the reachability check before saving. */
+const clickSave = async () => {
+ await act(async () => {
+ fireEvent.click(screen.getByTestId("git-sync-save-button"));
+ });
+};
+
+beforeEach(() => {
+ // Reachable unless a test says otherwise, so the save path stays the
+ // default one under test.
+ checkConfig.mockResolvedValue({
+ ok: true,
+ branch_exists: true,
+ detail: null,
+ });
+});
+
+const displayErrorToast = vi.fn();
+const displaySuccessToast = vi.fn();
+
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displayErrorToast: (message: string) => displayErrorToast(message),
+ displaySuccessToast: (message: string) => displaySuccessToast(message),
+}));
+
+/** Make the next save resolve down the success or the failure path. */
+const respondWith = (outcome: "success" | { error: unknown }) => {
+ mutate.mockImplementation((_body, options) => {
+ if (outcome === "success") options.onSuccess?.();
+ else options.onError?.(outcome.error);
+ // react-query runs onSettled on both paths.
+ options.onSettled?.();
+ });
+};
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+const baseStatus: GitSyncStatus = {
+ enabled: true,
+ repo_url: "https://example.com/org/repo.git",
+ branch: "main",
+ path: "automations",
+ encryption_enabled: false,
+ interval_seconds: 0,
+ last_synced_commit: "abc1234",
+ last_synced_at: "2026-08-10T00:00:00Z",
+ last_error: null,
+ last_error_at: null,
+ dirty_count: 0,
+};
+
+describe("GitSyncConfigForm", () => {
+ it("always renders the token and encryption key fields empty", async () => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ expect(screen.getByTestId("git-sync-token-input")).toHaveValue("");
+ expect(screen.getByTestId("git-sync-encryption-key-input")).toHaveValue("");
+ });
+
+ it("shows the encryption key placeholder based on encryption_enabled", async () => {
+ const { rerender } = render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+ expect(screen.getByTestId("git-sync-encryption-key-input")).toHaveAttribute(
+ "placeholder",
+ I18nKey.AUTOMATIONS$GIT_SYNC$KEY_UNSET_PLACEHOLDER,
+ );
+
+ rerender(
+ <GitSyncConfigForm
+ status={{ ...baseStatus, encryption_enabled: true }}
+ canManage
+ onSyncNow={syncNow}
+ />,
+ );
+ expect(screen.getByTestId("git-sync-encryption-key-input")).toHaveAttribute(
+ "placeholder",
+ I18nKey.AUTOMATIONS$GIT_SYNC$KEY_SET_PLACEHOLDER,
+ );
+ });
+
+ it("enables submit once a field changes and sends only the changed field", async () => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ expect(screen.getByTestId("git-sync-save-button")).toBeDisabled();
+
+ fireEvent.change(screen.getByTestId("git-sync-branch-input"), {
+ target: { value: "develop" },
+ });
+ expect(screen.getByTestId("git-sync-save-button")).not.toBeDisabled();
+
+ await clickSave();
+
+ expect(mutate).toHaveBeenCalledTimes(1);
+ expect(mutate.mock.calls[0][0]).toEqual({ branch: "develop" });
+ });
+
+ it("sends a typed token as a plain string, omitting unrelated fields", async () => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-token-input"), {
+ target: { value: "ghp_new_token" },
+ });
+ await clickSave();
+
+ expect(mutate.mock.calls[0][0]).toEqual({ token: "ghp_new_token" });
+ });
+
+ it("shows the configured interval and sends a changed one", async () => {
+ render(
+ <GitSyncConfigForm
+ status={{ ...baseStatus, interval_seconds: 300 }}
+ canManage
+ onSyncNow={syncNow}
+ />,
+ );
+
+ expect(screen.getByTestId("git-sync-interval-input")).toHaveValue(300);
+
+ fireEvent.change(screen.getByTestId("git-sync-interval-input"), {
+ target: { value: "60" },
+ });
+ await clickSave();
+
+ expect(mutate.mock.calls[0][0]).toEqual({ interval_seconds: 60 });
+ });
+
+ it("treats a blank interval as manual-only rather than no change", async () => {
+ // Clearing the field must mean 0 (manual), never "leave the timer on".
+ render(
+ <GitSyncConfigForm
+ status={{ ...baseStatus, interval_seconds: 300 }}
+ canManage
+ onSyncNow={syncNow}
+ />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-interval-input"), {
+ target: { value: "" },
+ });
+ await clickSave();
+
+ expect(mutate.mock.calls[0][0]).toEqual({ interval_seconds: 0 });
+ });
+
+ it("clearing the token disables the text field and sends null", async () => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.click(screen.getByTestId("git-sync-clear-token-switch"));
+
+ expect(screen.getByTestId("git-sync-token-input")).toBeDisabled();
+ expect(screen.getByTestId("git-sync-save-button")).not.toBeDisabled();
+
+ await clickSave();
+
+ expect(mutate.mock.calls[0][0]).toEqual({ token: null });
+ });
+
+ // Regression: these posted "" rather than null, and the backend stored the
+ // empty string as a literal override. An empty branch or path then made the
+ // next git command fatal (`git checkout -B ""`, `git add -A -- ""`), wedging
+ // every subsequent sync cycle.
+ it.each([
+ ["git-sync-branch-input", "branch"],
+ ["git-sync-path-input", "path"],
+ ["git-sync-repo-url-input", "repo_url"],
+ ])("clearing %s sends null, not an empty string", async (testId, field) => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId(testId), { target: { value: "" } });
+ await clickSave();
+
+ expect(mutate.mock.calls[0][0]).toEqual({ [field]: null });
+ });
+
+ it("sends a whitespace-only field as null", async () => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-path-input"), {
+ target: { value: " " },
+ });
+ await clickSave();
+
+ expect(mutate.mock.calls[0][0]).toEqual({ path: null });
+ });
+
+ // Regression: the clear switch remounts the secret input, which emptied the
+ // DOM field but left the typed value in state -- so a change of mind sent
+ // `token: ""`, an override that fails every later push with
+ // `fatal: Authentication failed`.
+ it.each([
+ ["git-sync-token-input", "git-sync-clear-token-switch"],
+ ["git-sync-encryption-key-input", "git-sync-clear-encryption-key-switch"],
+ ])(
+ "forgets a typed %s when its clear switch is toggled on and back off",
+ async (inputTestId, switchTestId) => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId(inputTestId), {
+ target: { value: "s3cret" },
+ });
+ fireEvent.click(screen.getByTestId(switchTestId));
+ fireEvent.click(screen.getByTestId(switchTestId));
+
+ // Nothing left to save: the field is empty again and no secret is
+ // pending, so an empty override can't be submitted.
+ expect(screen.getByTestId(inputTestId)).toHaveValue("");
+ expect(screen.getByTestId("git-sync-save-button")).toBeDisabled();
+
+ fireEvent.change(screen.getByTestId("git-sync-branch-input"), {
+ target: { value: "develop" },
+ });
+ await clickSave();
+
+ expect(mutate.mock.calls[0][0]).toEqual({ branch: "develop" });
+ },
+ );
+
+ it("keeps the edits and the enabled Save button when the save fails", async () => {
+ // React resets an uncontrolled `<form action={...}>` as soon as the action
+ // returns, which used to wipe the edits mid-flight; clearing the change
+ // flags on `onSettled` then disabled Save, leaving nothing to retry with.
+ respondWith({ error: { status: 500 } });
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-branch-input"), {
+ target: { value: "develop" },
+ });
+ fireEvent.click(screen.getByTestId("git-sync-clear-token-switch"));
+ await clickSave();
+
+ expect(screen.getByTestId("git-sync-branch-input")).toHaveValue("develop");
+ expect(screen.getByTestId("git-sync-save-button")).not.toBeDisabled();
+ expect(screen.getByTestId("git-sync-clear-token-switch")).toBeChecked();
+ });
+
+ it("goes clean again after a successful save", async () => {
+ respondWith("success");
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.click(screen.getByTestId("git-sync-clear-token-switch"));
+ await clickSave();
+
+ expect(screen.getByTestId("git-sync-save-button")).toBeDisabled();
+ expect(screen.getByTestId("git-sync-clear-token-switch")).not.toBeChecked();
+ expect(displaySuccessToast).toHaveBeenCalledWith(
+ I18nKey.AUTOMATIONS$GIT_SYNC$CONFIG_SAVED,
+ );
+ });
+
+ // Regression: the author fields were dirty only while non-empty, so emptying
+ // one never posted `author_name: null` and a wrong override was permanent.
+ it.each([
+ ["git-sync-author-name-input", "author_name"],
+ ["git-sync-author-email-input", "author_email"],
+ ])(
+ "clearing %s resets the override to the default",
+ async (testId, field) => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId(testId), {
+ target: { value: "[email protected]" },
+ });
+ fireEvent.change(screen.getByTestId(testId), { target: { value: "" } });
+ await clickSave();
+
+ expect(mutate.mock.calls[0][0]).toEqual({ [field]: null });
+ },
+ );
+
+ it("sends the enabled flag when the sync switch is flipped", async () => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ expect(screen.getByTestId("git-sync-enabled-switch")).toBeChecked();
+
+ fireEvent.click(screen.getByTestId("git-sync-enabled-switch"));
+ await clickSave();
+
+ expect(mutate.mock.calls[0][0]).toEqual({ enabled: false });
+ });
+
+ it("leaves enabled out of the request when the switch is not touched", async () => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-branch-input"), {
+ target: { value: "develop" },
+ });
+ await clickSave();
+
+ 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 } });
+ render(
+ <GitSyncConfigForm
+ status={{ ...baseStatus, enabled: false }}
+ canManage
+ onSyncNow={syncNow}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("git-sync-enabled-switch"));
+ await clickSave();
+
+ expect(displayErrorToast).toHaveBeenCalledWith(
+ I18nKey.AUTOMATIONS$GIT_SYNC$ENABLE_BLOCKED_ERROR,
+ );
+ });
+
+ describe("reachability check", () => {
+ const unreachable = () =>
+ checkConfig.mockResolvedValue({
+ ok: false,
+ branch_exists: false,
+ detail: "fatal: repository not found",
+ });
+
+ it("tests the settings against the remote before saving them", async () => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-repo-url-input"), {
+ target: { value: "https://example.com/org/other.git" },
+ });
+ await clickSave();
+
+ // The same body that is about to be saved, so the check answers for
+ // the configuration that would actually take effect.
+ expect(checkConfig).toHaveBeenCalledWith({
+ repo_url: "https://example.com/org/other.git",
+ });
+ expect(mutate).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not save a configuration that cannot reach its repo", async () => {
+ unreachable();
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-repo-url-input"), {
+ target: { value: "https://example.com/typo.git" },
+ });
+ await clickSave();
+
+ expect(mutate).not.toHaveBeenCalled();
+ expect(screen.getByTestId("git-sync-check-failure")).toHaveTextContent(
+ "fatal: repository not found",
+ );
+ // Still dirty, so the operator can fix the field and try again.
+ expect(screen.getByTestId("git-sync-save-button")).not.toBeDisabled();
+ });
+
+ it("saves the same values anyway when Save is pressed a second time", async () => {
+ // A check is evidence, not an authority: a remote that refuses
+ // `ls-remote` but accepts a push must not lock its operator out.
+ unreachable();
+ respondWith("success");
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-repo-url-input"), {
+ target: { value: "https://example.com/typo.git" },
+ });
+ await clickSave();
+ await clickSave();
+
+ expect(checkConfig).toHaveBeenCalledTimes(1);
+ expect(mutate).toHaveBeenCalledTimes(1);
+ expect(mutate.mock.calls[0][0]).toEqual({
+ repo_url: "https://example.com/typo.git",
+ });
+ });
+
+ it("re-checks once the settings are edited after a failure", async () => {
+ unreachable();
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-repo-url-input"), {
+ target: { value: "https://example.com/typo.git" },
+ });
+ await clickSave();
+
+ checkConfig.mockResolvedValue({
+ ok: true,
+ branch_exists: false,
+ detail: null,
+ });
+ fireEvent.change(screen.getByTestId("git-sync-repo-url-input"), {
+ target: { value: "https://example.com/fixed.git" },
+ });
+ await clickSave();
+
+ expect(checkConfig).toHaveBeenCalledTimes(2);
+ expect(mutate.mock.calls[0][0]).toEqual({
+ repo_url: "https://example.com/fixed.git",
+ });
+ expect(screen.queryByTestId("git-sync-check-failure")).toBeNull();
+ });
+
+ it("skips the check when nothing the remote could reject changed", async () => {
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-interval-input"), {
+ target: { value: "60" },
+ });
+ await clickSave();
+
+ expect(checkConfig).not.toHaveBeenCalled();
+ expect(mutate).toHaveBeenCalledTimes(1);
+ });
+
+ it("saves anyway when the check itself cannot run", async () => {
+ // An automation backend that predates the endpoint answers 404. A check
+ // that says nothing must never be what blocks a save.
+ checkConfig.mockRejectedValue({ status: 404 });
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-branch-input"), {
+ target: { value: "develop" },
+ });
+ await clickSave();
+
+ expect(mutate).toHaveBeenCalledTimes(1);
+ expect(screen.queryByTestId("git-sync-check-failure")).toBeNull();
+ });
+ });
+
+ describe("save and sync", () => {
+ const clickSaveAndSync = async () => {
+ await act(async () => {
+ fireEvent.click(screen.getByTestId("git-sync-save-and-sync-button"));
+ });
+ };
+
+ it("runs a cycle once the settings are stored", async () => {
+ respondWith("success");
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-branch-input"), {
+ target: { value: "develop" },
+ });
+ await clickSaveAndSync();
+
+ expect(mutate.mock.calls[0][0]).toEqual({ branch: "develop" });
+ expect(syncNow).toHaveBeenCalledTimes(1);
+ });
+
+ // The cycle runs off the stored configuration, so syncing a rejected save
+ // would push the settings the operator was trying to replace.
+ it("does not sync when the save is rejected", async () => {
+ respondWith({ error: { status: 500 } });
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-branch-input"), {
+ target: { value: "develop" },
+ });
+ await clickSaveAndSync();
+
+ expect(syncNow).not.toHaveBeenCalled();
+ });
+
+ it("does not sync when the settings fail their check", async () => {
+ checkConfig.mockResolvedValue({
+ ok: false,
+ branch_exists: false,
+ detail: "repository not found",
+ });
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-repo-url-input"), {
+ target: { value: "https://example.com/typo.git" },
+ });
+ await clickSaveAndSync();
+
+ expect(mutate).not.toHaveBeenCalled();
+ expect(syncNow).not.toHaveBeenCalled();
+ });
+
+ it("does not sync a plain save", async () => {
+ respondWith("success");
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-branch-input"), {
+ target: { value: "develop" },
+ });
+ await clickSave();
+
+ expect(mutate).toHaveBeenCalledTimes(1);
+ expect(syncNow).not.toHaveBeenCalled();
+ });
+
+ // Regression: the button used to arm a flag on click, and native
+ // validation swallows the submit that click was meant to start -- so the
+ // flag was still set when Save was pressed next, syncing off a button
+ // that never asked for it.
+ it("does not carry a swallowed submit over to the next save", async () => {
+ respondWith("success");
+ render(
+ <GitSyncConfigForm status={baseStatus} canManage onSyncNow={syncNow} />,
+ );
+
+ // An invalid email fails the input's own constraint, so the click never
+ // reaches a submit.
+ fireEvent.change(screen.getByTestId("git-sync-author-email-input"), {
+ target: { value: "not-an-email" },
+ });
+ await clickSaveAndSync();
+ expect(mutate).not.toHaveBeenCalled();
+
+ fireEvent.change(screen.getByTestId("git-sync-author-email-input"), {
+ target: { value: "[email protected]" },
+ });
+ await clickSave();
+
+ expect(mutate).toHaveBeenCalledTimes(1);
+ expect(syncNow).not.toHaveBeenCalled();
+ });
+
+ // A trigger against disabled sync is a 503, so there is nothing to offer
+ // until the same save turns it on.
+ it("stays disabled while sync is off and arms when it is switched on", async () => {
+ render(
+ <GitSyncConfigForm
+ status={{ ...baseStatus, enabled: false }}
+ canManage
+ onSyncNow={syncNow}
+ />,
+ );
+
+ fireEvent.change(screen.getByTestId("git-sync-branch-input"), {
+ target: { value: "develop" },
+ });
+ expect(
+ screen.getByTestId("git-sync-save-and-sync-button"),
+ ).toBeDisabled();
+ expect(screen.getByTestId("git-sync-save-button")).toBeEnabled();
+
+ fireEvent.click(screen.getByTestId("git-sync-enabled-switch"));
+
+ expect(screen.getByTestId("git-sync-save-and-sync-button")).toBeEnabled();
+ });
+ });
+});
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
new file mode 100644
index 0000000000..beae3614db
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-config-form.tsx
@@ -0,0 +1,466 @@
+import { useState, type FormEvent } from "react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { SettingsInput } from "#/components/features/settings/settings-input";
+import { SettingsSwitch } from "#/components/features/settings/settings-switch";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { SectionCard } from "#/components/features/automations/detail/section-card";
+import CogIcon from "#/icons/cog.svg?react";
+import {
+ displayErrorToast,
+ displaySuccessToast,
+} from "#/utils/custom-toast-handlers";
+import { getApiErrorMessage } from "#/utils/api-error-message";
+import { getErrorStatus } from "#/hooks/query/use-settings";
+import {
+ useCheckGitSyncConfig,
+ useUpdateGitSyncConfig,
+} from "#/hooks/query/use-git-sync";
+import type {
+ GitSyncConfigUpdateRequest,
+ GitSyncStatus,
+} from "#/types/git-sync";
+
+/**
+ * Identifies the save-and-sync button in the submit event. Read from the
+ * event's `submitter` rather than tracked on click: native field validation
+ * (the author email, the interval) can swallow a submit after the click has
+ * already happened, and a flag set there would still be armed when Save is
+ * pressed next -- syncing off a button that never asked for it.
+ */
+const SAVE_AND_SYNC = "git-sync-save-and-sync";
+
+interface GitSyncConfigFormProps {
+ status: GitSyncStatus;
+ canManage: boolean;
+ /**
+ * Runs a sync cycle. The same handler the overview's Sync now button uses,
+ * so a save-and-sync is followed by the one activity row rather than
+ * starting a cycle nothing on the page is watching.
+ */
+ onSyncNow: () => void;
+}
+
+export function GitSyncConfigForm({
+ status,
+ canManage,
+ onSyncNow,
+}: GitSyncConfigFormProps) {
+ const { t } = useTranslation("openhands");
+ const { mutate: updateConfig, isPending } = useUpdateGitSyncConfig();
+ const { mutateAsync: checkConfig, isPending: isChecking } =
+ useCheckGitSyncConfig();
+
+ // The settings that failed their reachability check, so the same submit
+ // pressed a second time saves them anyway. Keyed by the values that were
+ // checked rather than a plain flag: editing any of them changes the key,
+ // which re-arms the check without the field handlers having to clear it.
+ const [failedCheck, setFailedCheck] = useState<{
+ key: string;
+ detail: string;
+ } | null>(null);
+
+ const [intervalHasChanged, setIntervalHasChanged] = useState(false);
+ const [repoUrlHasChanged, setRepoUrlHasChanged] = useState(false);
+ const [branchHasChanged, setBranchHasChanged] = useState(false);
+ const [pathHasChanged, setPathHasChanged] = useState(false);
+ const [authorNameHasChanged, setAuthorNameHasChanged] = useState(false);
+ const [authorEmailHasChanged, setAuthorEmailHasChanged] = useState(false);
+
+ // `null` means untouched, so the switch keeps following the server state
+ // (including a status refetch) until the operator actually flips it.
+ const [enabledOverride, setEnabledOverride] = useState<boolean | null>(null);
+ const enabled = enabledOverride ?? status.enabled;
+ const enabledHasChanged =
+ enabledOverride !== null && enabled !== status.enabled;
+
+ const [tokenText, setTokenText] = useState("");
+ const [clearToken, setClearToken] = useState(false);
+ const [encryptionKeyText, setEncryptionKeyText] = useState("");
+ const [clearEncryptionKey, setClearEncryptionKey] = useState(false);
+
+ const tokenHasChanged = tokenText.trim().length > 0 || clearToken;
+ const encryptionKeyHasChanged =
+ encryptionKeyText.trim().length > 0 || clearEncryptionKey;
+
+ const formIsClean =
+ !enabledHasChanged &&
+ !intervalHasChanged &&
+ !repoUrlHasChanged &&
+ !branchHasChanged &&
+ !pathHasChanged &&
+ !authorNameHasChanged &&
+ !authorEmailHasChanged &&
+ !tokenHasChanged &&
+ !encryptionKeyHasChanged;
+
+ const resetChangeFlags = () => {
+ setEnabledOverride(null);
+ setIntervalHasChanged(false);
+ setRepoUrlHasChanged(false);
+ setBranchHasChanged(false);
+ setPathHasChanged(false);
+ setAuthorNameHasChanged(false);
+ setAuthorEmailHasChanged(false);
+ setTokenText("");
+ setClearToken(false);
+ setEncryptionKeyText("");
+ setClearEncryptionKey(false);
+ setFailedCheck(null);
+ };
+
+ // The secret inputs are remounted -- and therefore emptied -- whenever the
+ // matching clear switch flips, so drop the typed value with them. Keeping it
+ // in state would leave the field marked dirty against an empty input and
+ // submit `token: ""`, an override that fails every later push with
+ // `fatal: Authentication failed`.
+ const toggleClearToken = (isToggled: boolean) => {
+ setClearToken(isToggled);
+ setTokenText("");
+ };
+
+ const toggleClearEncryptionKey = (isToggled: boolean) => {
+ setClearEncryptionKey(isToggled);
+ setEncryptionKeyText("");
+ };
+
+ // A cleared field posts `null` -- clear the override and fall back to the
+ // environment default -- rather than `""`, which the backend stored as a
+ // literal empty override. An empty branch or path then made the next git
+ // command fatal (`git checkout -B ""`, `git add -A -- ""`), wedging every
+ // subsequent sync cycle with that error in the status banner.
+ const clearedFieldAsNull = (formData: FormData, name: string) =>
+ formData.get(name)?.toString().trim() || null;
+
+ const save = (body: GitSyncConfigUpdateRequest, thenSync: boolean) => {
+ updateConfig(body, {
+ onSuccess: () => {
+ displaySuccessToast(t(I18nKey.AUTOMATIONS$GIT_SYNC$CONFIG_SAVED));
+ // Only on success: clearing the flags after a failure would disable
+ // Save and silently un-toggle the clear switches, leaving no way to
+ // retry the change that was just rejected.
+ resetChangeFlags();
+ // A cycle runs off the stored configuration, so it can only be
+ // triggered once the save has landed -- and a rejected save leaves
+ // nothing new to sync.
+ 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)),
+ );
+ },
+ });
+ };
+
+ // What the reachability check actually depends on. A save that touches only
+ // the interval or the author has nothing for the remote to reject, so it
+ // shouldn't cost a round trip to the repo.
+ const remoteFieldsOf = (body: GitSyncConfigUpdateRequest) =>
+ (["repo_url", "branch", "token"] as const)
+ .filter((field) => field in body)
+ .map((field) => `${field}=${body[field]}`)
+ .join("&");
+
+ /** The reason these settings can't reach their repo, or null to go ahead. */
+ const reachabilityFailure = async (body: GitSyncConfigUpdateRequest) => {
+ try {
+ const result = await checkConfig(body);
+ return result.ok
+ ? null
+ : (result.detail ?? t(I18nKey.AUTOMATIONS$GIT_SYNC$CHECK_FAILED_TITLE));
+ } catch {
+ // A check that couldn't run says nothing about the configuration --
+ // an automation backend that predates the endpoint answers 404 -- and
+ // must never be what stands between an operator and saving.
+ return null;
+ }
+ };
+
+ // A plain submit handler rather than `<form action={...}>`: React resets an
+ // uncontrolled form as soon as the action returns, which wiped every edit
+ // while the save was still in flight -- so a rejected save left the operator
+ // with the old values and nothing to retry.
+ const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ const thenSync =
+ (event.nativeEvent as SubmitEvent).submitter?.getAttribute("name") ===
+ SAVE_AND_SYNC;
+ const formData = new FormData(event.currentTarget);
+ const body: GitSyncConfigUpdateRequest = {};
+
+ if (enabledHasChanged) {
+ body.enabled = enabled;
+ }
+ if (intervalHasChanged) {
+ // Blank reads as manual-only rather than clearing the override, so an
+ // emptied field can never be mistaken for "keep syncing on a timer".
+ const raw = formData.get("git-sync-interval-input")?.toString().trim();
+ const parsed = Number(raw);
+ body.interval_seconds =
+ raw && Number.isFinite(parsed) ? Math.max(0, Math.trunc(parsed)) : 0;
+ }
+ if (repoUrlHasChanged) {
+ body.repo_url = clearedFieldAsNull(formData, "git-sync-repo-url-input");
+ }
+ if (branchHasChanged) {
+ body.branch = clearedFieldAsNull(formData, "git-sync-branch-input");
+ }
+ if (pathHasChanged) {
+ body.path = clearedFieldAsNull(formData, "git-sync-path-input");
+ }
+ if (authorNameHasChanged) {
+ body.author_name = clearedFieldAsNull(
+ formData,
+ "git-sync-author-name-input",
+ );
+ }
+ if (authorEmailHasChanged) {
+ body.author_email = clearedFieldAsNull(
+ formData,
+ "git-sync-author-email-input",
+ );
+ }
+ // The secrets come from state rather than FormData: the clear switch
+ // remounts (and empties) their inputs, so the two disagree for a render
+ // and only state knows what the operator actually typed.
+ const token = tokenText.trim();
+ const encryptionKey = encryptionKeyText.trim();
+ if (clearToken) {
+ body.token = null;
+ } else if (token) {
+ body.token = token;
+ }
+ if (clearEncryptionKey) {
+ body.encryption_key = null;
+ } else if (encryptionKey) {
+ body.encryption_key = encryptionKey;
+ }
+
+ // Test the settings before storing them, so a mistyped repo URL or a
+ // rejected token is caught here instead of by the next sync cycle. The
+ // same values submitted twice save anyway: an operator who disagrees with
+ // the check -- or whose remote refuses `ls-remote` but accepts a push --
+ // must not be locked out of their own configuration.
+ const remoteFields = remoteFieldsOf(body);
+ if (remoteFields && failedCheck?.key !== remoteFields) {
+ const detail = await reachabilityFailure(body);
+ if (detail) {
+ setFailedCheck({ key: remoteFields, detail });
+ return;
+ }
+ }
+ setFailedCheck(null);
+
+ save(body, thenSync);
+ };
+
+ return (
+ <SectionCard
+ icon={<CogIcon className="size-4" />}
+ title={t(I18nKey.AUTOMATIONS$GIT_SYNC$CONFIG_TITLE)}
+ >
+ <form onSubmit={handleSubmit} className="flex flex-col gap-6">
+ <div className="flex flex-col gap-2">
+ <SettingsSwitch
+ testId="git-sync-enabled-switch"
+ isToggled={enabled}
+ isDisabled={!canManage}
+ onToggle={setEnabledOverride}
+ >
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_ENABLED)}
+ </SettingsSwitch>
+ <p className="text-xs text-muted">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$ENABLED_HELP)}
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <SettingsInput
+ testId="git-sync-interval-input"
+ name="git-sync-interval-input"
+ type="number"
+ min={0}
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_INTERVAL)}
+ defaultValue={String(status.interval_seconds)}
+ isDisabled={!canManage}
+ onChange={(value) =>
+ setIntervalHasChanged(
+ value.trim() !== String(status.interval_seconds),
+ )
+ }
+ />
+ <p className="text-xs text-muted">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$INTERVAL_HELP)}
+ </p>
+ </div>
+
+ <SettingsInput
+ testId="git-sync-repo-url-input"
+ name="git-sync-repo-url-input"
+ type="text"
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_REPO_URL)}
+ defaultValue={status.repo_url}
+ placeholder={t(I18nKey.AUTOMATIONS$GIT_SYNC$REPO_URL_PLACEHOLDER)}
+ isDisabled={!canManage}
+ onChange={(value) =>
+ setRepoUrlHasChanged(value.trim() !== status.repo_url)
+ }
+ />
+
+ <SettingsInput
+ testId="git-sync-branch-input"
+ name="git-sync-branch-input"
+ type="text"
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_BRANCH)}
+ defaultValue={status.branch}
+ placeholder={t(I18nKey.AUTOMATIONS$GIT_SYNC$BRANCH_PLACEHOLDER)}
+ isDisabled={!canManage}
+ onChange={(value) =>
+ setBranchHasChanged(value.trim() !== status.branch)
+ }
+ />
+
+ <SettingsInput
+ testId="git-sync-path-input"
+ name="git-sync-path-input"
+ type="text"
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_PATH)}
+ defaultValue={status.path}
+ placeholder={t(I18nKey.AUTOMATIONS$GIT_SYNC$PATH_PLACEHOLDER)}
+ isDisabled={!canManage}
+ onChange={(value) => setPathHasChanged(value.trim() !== status.path)}
+ />
+
+ <div className="flex flex-col gap-2">
+ <SettingsInput
+ testId="git-sync-author-name-input"
+ name="git-sync-author-name-input"
+ type="text"
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_AUTHOR_NAME)}
+ showOptionalTag
+ defaultValue=""
+ isDisabled={!canManage}
+ // Dirty on any edit, not just a non-empty one: gating on the value
+ // meant emptying the field never posted `author_name: null`, so a
+ // wrong override could never be cleared back to the default.
+ onChange={() => setAuthorNameHasChanged(true)}
+ />
+
+ <SettingsInput
+ testId="git-sync-author-email-input"
+ name="git-sync-author-email-input"
+ type="email"
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_AUTHOR_EMAIL)}
+ showOptionalTag
+ defaultValue=""
+ isDisabled={!canManage}
+ onChange={() => setAuthorEmailHasChanged(true)}
+ />
+ <p className="text-xs text-muted">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$AUTHOR_HELP)}
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <SettingsInput
+ key={clearToken ? "token-cleared" : "token-editable"}
+ testId="git-sync-token-input"
+ name="git-sync-token-input"
+ type="password"
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_TOKEN)}
+ placeholder={t(I18nKey.AUTOMATIONS$GIT_SYNC$TOKEN_PLACEHOLDER)}
+ isDisabled={!canManage || clearToken}
+ onChange={setTokenText}
+ />
+ <p className="text-xs text-muted">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$TOKEN_HELP)}
+ </p>
+ <SettingsSwitch
+ testId="git-sync-clear-token-switch"
+ isToggled={clearToken}
+ isDisabled={!canManage}
+ onToggle={toggleClearToken}
+ >
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$CLEAR_TOKEN)}
+ </SettingsSwitch>
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <SettingsInput
+ key={clearEncryptionKey ? "key-cleared" : "key-editable"}
+ testId="git-sync-encryption-key-input"
+ name="git-sync-encryption-key-input"
+ type="password"
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_ENCRYPTION_KEY)}
+ placeholder={t(
+ status.encryption_enabled
+ ? I18nKey.AUTOMATIONS$GIT_SYNC$KEY_SET_PLACEHOLDER
+ : I18nKey.AUTOMATIONS$GIT_SYNC$KEY_UNSET_PLACEHOLDER,
+ )}
+ isDisabled={!canManage || clearEncryptionKey}
+ onChange={setEncryptionKeyText}
+ />
+ <p className="text-xs text-muted">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$ENCRYPTION_KEY_HELP)}
+ </p>
+ <SettingsSwitch
+ testId="git-sync-clear-encryption-key-switch"
+ isToggled={clearEncryptionKey}
+ isDisabled={!canManage}
+ onToggle={toggleClearEncryptionKey}
+ >
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$CLEAR_ENCRYPTION_KEY)}
+ </SettingsSwitch>
+ </div>
+
+ {failedCheck && (
+ <div
+ role="alert"
+ data-testid="git-sync-check-failure"
+ className="rounded-md border border-red-500/40 bg-red-500/10 p-3 text-sm text-red-300 whitespace-pre-wrap break-words"
+ >
+ <p className="font-medium">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$CHECK_FAILED_TITLE)}
+ </p>
+ <p className="mt-1">{failedCheck.detail}</p>
+ <p className="mt-1 text-xs text-red-300/70">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$CHECK_FAILED_HINT)}
+ </p>
+ </div>
+ )}
+
+ <div className="flex justify-start gap-3">
+ <BrandButton
+ testId="git-sync-save-button"
+ variant="primary"
+ type="submit"
+ isDisabled={!canManage || isPending || isChecking || formIsClean}
+ >
+ {!isPending && !isChecking && t(I18nKey.SETTINGS$SAVE_CHANGES)}
+ {isChecking && t(I18nKey.AUTOMATIONS$GIT_SYNC$CHECKING)}
+ {isPending && t(I18nKey.SETTINGS$SAVING)}
+ </BrandButton>
+ <BrandButton
+ testId="git-sync-save-and-sync-button"
+ name={SAVE_AND_SYNC}
+ variant="secondary"
+ type="submit"
+ // Sync left off is a 503 from the trigger, so there is nothing to
+ // offer -- but a save that turns it on can sync straight after.
+ isDisabled={
+ !canManage || isPending || isChecking || formIsClean || !enabled
+ }
+ >
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$SAVE_AND_SYNC)}
+ </BrandButton>
+ </div>
+ </form>
+ </SectionCard>
+ );
+}
diff --git a/src/components/features/automations/git-sync/git-sync-error-banner.tsx b/src/components/features/automations/git-sync/git-sync-error-banner.tsx
new file mode 100644
index 0000000000..a9627ef8c5
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-error-banner.tsx
@@ -0,0 +1,33 @@
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { formatTimeDelta } from "#/utils/format-time-delta";
+
+interface GitSyncErrorBannerProps {
+ error: string;
+ errorAt: string | null;
+}
+
+export function GitSyncErrorBanner({
+ error,
+ errorAt,
+}: GitSyncErrorBannerProps) {
+ const { t } = useTranslation("openhands");
+
+ return (
+ <div
+ role="alert"
+ data-testid="git-sync-error-banner"
+ className="rounded-md border border-red-500/40 bg-red-500/10 p-3 text-sm text-red-300 whitespace-pre-wrap break-words"
+ >
+ <p className="font-medium">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$LAST_ERROR_TITLE)}
+ </p>
+ <p className="mt-1">{error}</p>
+ {errorAt && (
+ <p className="mt-1 text-xs text-red-300/70">
+ {`${formatTimeDelta(errorAt)} ${t(I18nKey.CONVERSATION$AGO)}`}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/features/automations/git-sync/git-sync-not-local-state.tsx b/src/components/features/automations/git-sync/git-sync-not-local-state.tsx
new file mode 100644
index 0000000000..8de914ef49
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-not-local-state.tsx
@@ -0,0 +1,23 @@
+import { useTranslation } from "react-i18next";
+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() {
+ 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)}
+ </p>
+ <p className="mt-2 text-sm text-muted">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$NOT_LOCAL_MESSAGE)}
+ </p>
+ <div className="mt-6">
+ <BackLink />
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/features/automations/git-sync/git-sync-overview-section.test.tsx b/src/components/features/automations/git-sync/git-sync-overview-section.test.tsx
new file mode 100644
index 0000000000..8418f5c97d
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-overview-section.test.tsx
@@ -0,0 +1,84 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import type { GitSyncStatus } from "#/types/git-sync";
+import { GitSyncOverviewSection } from "./git-sync-overview-section";
+
+const baseStatus: GitSyncStatus = {
+ enabled: true,
+ repo_url: "https://github.com/org/repo.git",
+ branch: "main",
+ path: "automations",
+ encryption_enabled: false,
+ interval_seconds: 0,
+ last_synced_commit: null,
+ last_synced_at: null,
+ last_error: null,
+ last_error_at: null,
+ dirty_count: 0,
+};
+
+function renderWith(repoUrl: string) {
+ render(
+ <GitSyncOverviewSection
+ status={{ ...baseStatus, repo_url: repoUrl }}
+ onSyncNow={() => {}}
+ isSyncing={false}
+ syncActivity="idle"
+ syncStartedAt={null}
+ canManage
+ />,
+ );
+}
+
+describe("GitSyncOverviewSection", () => {
+ it("links an https remote, dropping the .git suffix", () => {
+ renderWith("https://github.com/org/repo.git");
+
+ const link = screen.getByTestId("git-sync-repo-link");
+ expect(link).toHaveAttribute("href", "https://github.com/org/repo");
+ expect(link).toHaveAttribute("target", "_blank");
+ expect(link).toHaveAttribute("rel", "noopener noreferrer");
+ // The configured value stays visible, so what is shown is still what is set.
+ expect(link).toHaveTextContent("https://github.com/org/repo.git");
+ });
+
+ it("links an ssh remote over https", () => {
+ renderWith("[email protected]:org/repo.git");
+
+ expect(screen.getByTestId("git-sync-repo-link")).toHaveAttribute(
+ "href",
+ "https://github.com/org/repo",
+ );
+ });
+
+ it("keeps a self-hosted forge's port and forge-specific path", () => {
+ renderWith("https://git.example.com:8443/org/team/_git/repo.git");
+
+ expect(screen.getByTestId("git-sync-repo-link")).toHaveAttribute(
+ "href",
+ "https://git.example.com:8443/org/team/_git/repo",
+ );
+ });
+
+ // A remote configured with credentials in it must not put them in an href,
+ // where they would ride along in the outgoing navigation.
+ it("strips credentials from the link", () => {
+ renderWith("https://user:[email protected]/org/repo.git");
+
+ const link = screen.getByTestId("git-sync-repo-link");
+ expect(link).toHaveAttribute("href", "https://github.com/org/repo");
+ expect(link.getAttribute("href")).not.toContain("ghp_token");
+ });
+
+ // A bare repo on disk is a valid sync target but has nothing to open.
+ it.each(["/tmp/git-sync-remote.git", "not a url", ""])(
+ "renders %s as plain text",
+ (repoUrl) => {
+ renderWith(repoUrl);
+
+ expect(
+ screen.queryByTestId("git-sync-repo-link"),
+ ).not.toBeInTheDocument();
+ },
+ );
+});
diff --git a/src/components/features/automations/git-sync/git-sync-overview-section.tsx b/src/components/features/automations/git-sync/git-sync-overview-section.tsx
new file mode 100644
index 0000000000..d2d25475af
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-overview-section.tsx
@@ -0,0 +1,203 @@
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { RefreshCw } from "lucide-react";
+import type { GitSyncStatus } from "#/types/git-sync";
+import { formatTimeDelta } from "#/utils/format-time-delta";
+import { parseGitRemoteUrl } from "#/utils/parse-git-remote-url";
+import { cn } from "#/utils/utils";
+import GitBranchIcon from "#/icons/git-branch.svg?react";
+import GlobeIcon from "#/icons/globe.svg?react";
+import FolderIcon from "#/icons/folder.svg?react";
+import ClockIcon from "#/icons/clock.svg?react";
+import { SectionCard } from "#/components/features/automations/detail/section-card";
+import { ConfigField } from "#/components/features/automations/detail/config-field";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { GitSyncStatusPill } from "./git-sync-status-pill";
+import {
+ GitSyncActivityRow,
+ type GitSyncActivityState,
+} from "./git-sync-activity-row";
+
+/**
+ * A browsable URL for the configured remote, or `null` when there isn't one.
+ * A bare repo on disk is a valid sync target, so a local path -- and anything
+ * else that doesn't parse -- stays plain text rather than becoming a dead link.
+ *
+ * An http(s) remote is already browsable, so it is reused as-is apart from the
+ * `.git` suffix and any embedded credentials, which keeps forge-specific paths
+ * (Azure's `org/project/_git/repo`) and non-default ports intact. Other schemes
+ * -- `ssh://`, `git://`, `git@host:owner/repo` -- carry no browsable form, so
+ * they are rebuilt over https from the parsed host and repository.
+ */
+function browseUrlFor(repoUrl: string): string | null {
+ const parsed = parseGitRemoteUrl(repoUrl);
+ if (!parsed?.host || !parsed.repository) return null;
+
+ if (/^https?:\/\//i.test(parsed.url)) {
+ const url = new URL(parsed.url);
+ url.username = "";
+ url.password = "";
+ url.pathname = url.pathname.replace(/\.git$/, "");
+ return url.toString();
+ }
+
+ return `https://${parsed.host}/${parsed.repository}`;
+}
+
+interface GitSyncOverviewSectionProps {
+ status: GitSyncStatus;
+ onSyncNow: () => void;
+ isSyncing: boolean;
+ syncActivity: GitSyncActivityState;
+ syncStartedAt: string | null;
+ canManage: boolean;
+}
+
+export function GitSyncOverviewSection({
+ status,
+ onSyncNow,
+ isSyncing,
+ syncActivity,
+ syncStartedAt,
+ canManage,
+}: GitSyncOverviewSectionProps) {
+ const { t } = useTranslation("openhands");
+ const repoHref = browseUrlFor(status.repo_url);
+
+ return (
+ <SectionCard
+ icon={<GitBranchIcon className="size-4" />}
+ title={t(I18nKey.AUTOMATIONS$GIT_SYNC$STATUS_TITLE)}
+ >
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <GitSyncStatusPill
+ testId="git-sync-enabled-pill"
+ tone={status.enabled ? "success" : "neutral"}
+ label={t(
+ status.enabled
+ ? I18nKey.AUTOMATIONS$GIT_SYNC$ENABLED
+ : I18nKey.AUTOMATIONS$GIT_SYNC$DISABLED,
+ )}
+ />
+ <GitSyncStatusPill
+ testId="git-sync-encryption-pill"
+ tone={status.encryption_enabled ? "success" : "neutral"}
+ label={t(
+ status.encryption_enabled
+ ? I18nKey.AUTOMATIONS$GIT_SYNC$ENCRYPTED
+ : I18nKey.AUTOMATIONS$GIT_SYNC$NOT_ENCRYPTED,
+ )}
+ />
+ </div>
+ <BrandButton
+ testId="git-sync-now-button"
+ type="button"
+ variant="secondary"
+ isDisabled={!canManage || !status.enabled || isSyncing}
+ onClick={onSyncNow}
+ startContent={
+ <RefreshCw
+ className={cn("size-4", isSyncing && "animate-spin")}
+ aria-hidden
+ />
+ }
+ >
+ {t(
+ isSyncing
+ ? I18nKey.AUTOMATIONS$GIT_SYNC$SYNCING
+ : I18nKey.AUTOMATIONS$GIT_SYNC$SYNC_NOW,
+ )}
+ </BrandButton>
+ </div>
+
+ <GitSyncActivityRow
+ state={syncActivity}
+ startedAt={syncStartedAt}
+ pendingCount={status.dirty_count}
+ />
+
+ <div className="mt-5 grid grid-cols-2 gap-x-4 gap-y-5">
+ <ConfigField
+ icon={<GlobeIcon className="size-3.5" />}
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$REPOSITORY)}
+ >
+ {repoHref ? (
+ <a
+ data-testid="git-sync-repo-link"
+ href={repoHref}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="break-all underline transition-colors hover:text-foreground"
+ >
+ {status.repo_url}
+ </a>
+ ) : (
+ <span className="break-all">
+ {status.repo_url ||
+ t(I18nKey.AUTOMATIONS$GIT_SYNC$NOT_CONFIGURED)}
+ </span>
+ )}
+ </ConfigField>
+
+ <ConfigField
+ icon={<GitBranchIcon className="size-3.5" />}
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_BRANCH)}
+ >
+ {status.branch}
+ </ConfigField>
+
+ <ConfigField
+ icon={<FolderIcon className="size-3.5" />}
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_PATH)}
+ >
+ {status.path}
+ </ConfigField>
+
+ <ConfigField
+ icon={<GitBranchIcon className="size-3.5" />}
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$LAST_SYNCED_COMMIT)}
+ >
+ {status.last_synced_commit ? (
+ <span className="font-mono">
+ {status.last_synced_commit.slice(0, 7)}
+ </span>
+ ) : (
+ t(I18nKey.AUTOMATIONS$GIT_SYNC$NEVER_SYNCED)
+ )}
+ </ConfigField>
+
+ <ConfigField
+ icon={<ClockIcon className="size-3.5" />}
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$LAST_SYNCED_AT)}
+ >
+ {status.last_synced_at
+ ? `${formatTimeDelta(status.last_synced_at)} ${t(I18nKey.CONVERSATION$AGO)}`
+ : t(I18nKey.AUTOMATIONS$GIT_SYNC$NEVER_SYNCED)}
+ </ConfigField>
+
+ <ConfigField
+ icon={<ClockIcon className="size-3.5" />}
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$FIELD_INTERVAL)}
+ >
+ {status.interval_seconds > 0
+ ? t(I18nKey.AUTOMATIONS$GIT_SYNC$EVERY_N_SECONDS, {
+ count: status.interval_seconds,
+ })
+ : t(I18nKey.AUTOMATIONS$GIT_SYNC$MANUAL_ONLY)}
+ </ConfigField>
+
+ <ConfigField
+ icon={<ClockIcon className="size-3.5" />}
+ label={t(I18nKey.AUTOMATIONS$GIT_SYNC$PENDING_CHANGES)}
+ >
+ <span
+ className={cn(status.dirty_count > 0 && "text-[var(--oh-warning)]")}
+ >
+ {status.dirty_count}
+ </span>
+ </ConfigField>
+ </div>
+ </SectionCard>
+ );
+}
diff --git a/src/components/features/automations/git-sync/git-sync-skeleton.tsx b/src/components/features/automations/git-sync/git-sync-skeleton.tsx
new file mode 100644
index 0000000000..81847a679a
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-skeleton.tsx
@@ -0,0 +1,19 @@
+import { cn } from "#/utils/utils";
+
+function SkeletonBlock({ className }: { className: string }) {
+ return (
+ <div className={cn("animate-pulse rounded bg-surface-raised", className)} />
+ );
+}
+
+export function GitSyncSkeleton() {
+ return (
+ <div className="flex flex-col gap-4" data-testid="git-sync-skeleton">
+ <SkeletonBlock className="h-5 w-40" />
+ <SkeletonBlock className="h-6 w-48" />
+ <SkeletonBlock className="h-5 w-96" />
+ <SkeletonBlock className="h-48 w-full rounded-2xl" />
+ <SkeletonBlock className="h-96 w-full rounded-2xl" />
+ </div>
+ );
+}
diff --git a/src/components/features/automations/git-sync/git-sync-status-pill.tsx b/src/components/features/automations/git-sync/git-sync-status-pill.tsx
new file mode 100644
index 0000000000..f58dcfbcb1
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-status-pill.tsx
@@ -0,0 +1,29 @@
+import { cn } from "#/utils/utils";
+
+interface GitSyncStatusPillProps {
+ tone: "success" | "neutral" | "warning";
+ label: string;
+ testId?: string;
+}
+
+export function GitSyncStatusPill({
+ tone,
+ label,
+ testId,
+}: GitSyncStatusPillProps) {
+ return (
+ <span
+ data-testid={testId}
+ className={cn(
+ "inline-flex items-center rounded-full px-3 py-1 text-xs font-medium",
+ tone === "success" &&
+ "bg-[var(--oh-success)]/15 text-[var(--oh-success)]",
+ tone === "warning" &&
+ "bg-[var(--oh-warning)]/15 text-[var(--oh-warning)]",
+ tone === "neutral" && "bg-surface-raised text-muted",
+ )}
+ >
+ {label}
+ </span>
+ );
+}
diff --git a/src/components/features/automations/git-sync/git-sync-unsupported-state.tsx b/src/components/features/automations/git-sync/git-sync-unsupported-state.tsx
new file mode 100644
index 0000000000..3e9f617f2a
--- /dev/null
+++ b/src/components/features/automations/git-sync/git-sync-unsupported-state.tsx
@@ -0,0 +1,29 @@
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import ExclamationCircleIcon from "#/icons/exclamation-circle.svg?react";
+import { BackLink } from "#/components/features/automations/detail/back-link";
+
+/**
+ * Shown when the automation backend answers the git-sync endpoints with 404:
+ * it predates the API. Without this the page settles on the generic "something
+ * went wrong" panel, which reads as a broken install rather than an old
+ * backend.
+ */
+export function GitSyncUnsupportedState() {
+ 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$UNSUPPORTED_TITLE)}
+ </p>
+ <p className="mt-2 text-sm text-muted">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$UNSUPPORTED_MESSAGE)}
+ </p>
+ <div className="mt-6">
+ <BackLink />
+ </div>
+ </div>
+ );
+}
diff --git a/src/hooks/query/use-git-sync.ts b/src/hooks/query/use-git-sync.ts
new file mode 100644
index 0000000000..3238a7d6bb
--- /dev/null
+++ b/src/hooks/query/use-git-sync.ts
@@ -0,0 +1,98 @@
+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import AutomationService from "#/api/automation-service/automation-service.api";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { getErrorStatus } from "#/hooks/query/use-settings";
+import { useTracking } from "#/hooks/use-tracking";
+import type { GitSyncConfigUpdateRequest } from "#/types/git-sync";
+
+export const GIT_SYNC_STATUS_QUERY_KEY = ["git-sync-status"] as const;
+
+interface UseGitSyncStatusOptions {
+ enabled?: boolean;
+ refetchInterval?: number | false;
+}
+
+export function useGitSyncStatus(options: UseGitSyncStatusOptions = {}) {
+ const { enabled = true, refetchInterval = false } = options;
+ const active = useActiveBackend();
+ return useQuery({
+ queryKey: [...GIT_SYNC_STATUS_QUERY_KEY, active.backend.id, active.orgId],
+ queryFn: () => AutomationService.getGitSyncStatus(),
+ staleTime: 10 * 1000, // 10 seconds
+ enabled,
+ refetchInterval,
+ // Only a request that never got an answer is worth repeating. A 404 means
+ // the backend has no git-sync API and will answer the same forever, and an
+ // answered failure has already cost the service's own timeout: a saturated
+ // automation service replies 500 after a 30s connection-pool timeout, so
+ // three retries plus backoff sat the page in its skeleton for about two
+ // minutes before showing the error panel it could have shown at once.
+ retry: (failureCount, error) =>
+ getErrorStatus(error) === undefined && failureCount < 2,
+ // The page turns every failure into a state of its own (unsupported
+ // backend, or the error panel with Retry), so the global query toast
+ // would only add raw axios text on top of it.
+ meta: { disableToast: true },
+ });
+}
+
+export function useUpdateGitSyncConfig() {
+ const queryClient = useQueryClient();
+ const active = useActiveBackend();
+ const { trackGitSyncConfigUpdated } = useTracking();
+ return useMutation({
+ mutationFn: (body: GitSyncConfigUpdateRequest) =>
+ AutomationService.updateGitSyncConfig(body),
+ onSuccess: async (data) => {
+ const queryKey = [
+ ...GIT_SYNC_STATUS_QUERY_KEY,
+ active.backend.id,
+ active.orgId,
+ ];
+ // Cancel first: a status GET that started before this save resolves
+ // after it and would overwrite the response we just seeded with its own
+ // pre-save snapshot.
+ await queryClient.cancelQueries({ queryKey });
+ 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.
+ meta: { disableToast: true },
+ });
+}
+
+/**
+ * Test a configuration against its remote before saving it.
+ *
+ * Deliberately not retried and never surfaced as a toast: the form treats a
+ * check it cannot complete -- an older automation backend answering 404,
+ * a network failure -- as "no opinion" and saves anyway, so a check that is
+ * itself broken can never become the thing that blocks a save.
+ */
+export function useCheckGitSyncConfig() {
+ return useMutation({
+ mutationFn: (body: GitSyncConfigUpdateRequest) =>
+ AutomationService.checkGitSyncConfig(body),
+ retry: false,
+ meta: { disableToast: true },
+ });
+}
+
+export function useTriggerGitSync() {
+ const queryClient = useQueryClient();
+ const active = useActiveBackend();
+ const { trackGitSyncTriggered } = useTracking();
+ return useMutation({
+ mutationFn: () => AutomationService.triggerGitSync(),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: GIT_SYNC_STATUS_QUERY_KEY });
+ trackGitSyncTriggered({ backendKind: active.backend.kind });
+ },
+ // The page maps a failed trigger to its own message (503 means sync is
+ // off, not that the request broke), so the global mutation toast would
+ // stack a raw one on top.
+ meta: { disableToast: true },
+ });
+}
diff --git a/src/hooks/use-tracking.ts b/src/hooks/use-tracking.ts
index fb17522104..fa89acc8ab 100644
--- a/src/hooks/use-tracking.ts
+++ b/src/hooks/use-tracking.ts
@@ -322,6 +322,22 @@ export const useTracking = () => {
track("automation_imported", { backend_kind: backendKind });
};
+ const trackGitSyncConfigUpdated = ({
+ backendKind,
+ }: {
+ backendKind: BackendKind;
+ }) => {
+ track("git_sync_config_updated", { backend_kind: backendKind });
+ };
+
+ const trackGitSyncTriggered = ({
+ backendKind,
+ }: {
+ backendKind: BackendKind;
+ }) => {
+ track("git_sync_triggered", { backend_kind: backendKind });
+ };
+
const trackBackendAdded = ({
backendKind,
connectionMethod,
@@ -422,6 +438,8 @@ export const useTracking = () => {
trackAutomationExported,
trackAutomationActivityLogExported,
trackAutomationImported,
+ trackGitSyncConfigUpdated,
+ trackGitSyncTriggered,
trackBackendAdded,
trackOnboardingStarted,
trackOnboardingStepViewed,
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index c194ae2aeb..b404bc0151 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -38180,5 +38180,974 @@
"tr": "Alt sohbet istendi",
"uk": "Запитано дочірню розмову",
"ca": "S'ha sol·licitat una conversa filla"
+ },
+ "AUTOMATIONS$GIT_SYNC$NAV_BUTTON": {
+ "en": "Git Sync",
+ "ja": "Git同期",
+ "zh-CN": "Git 同步",
+ "zh-TW": "Git 同步",
+ "ko-KR": "Git 동기화",
+ "no": "Git-synkronisering",
+ "ar": "مزامنة Git",
+ "de": "Git-Synchronisierung",
+ "fr": "Synchronisation Git",
+ "it": "Sincronizzazione Git",
+ "pt": "Sincronização Git",
+ "es": "Sincronización de Git",
+ "ca": "Sincronització de Git",
+ "tr": "Git Senkronizasyonu",
+ "uk": "Git-синхронізація"
+ },
+ "AUTOMATIONS$GIT_SYNC$TITLE": {
+ "en": "Git Sync",
+ "ja": "Git同期",
+ "zh-CN": "Git 同步",
+ "zh-TW": "Git 同步",
+ "ko-KR": "Git 동기화",
+ "no": "Git-synkronisering",
+ "ar": "مزامنة Git",
+ "de": "Git-Synchronisierung",
+ "fr": "Synchronisation Git",
+ "it": "Sincronizzazione Git",
+ "pt": "Sincronização Git",
+ "es": "Sincronización de Git",
+ "ca": "Sincronització de Git",
+ "tr": "Git Senkronizasyonu",
+ "uk": "Git-синхронізація"
+ },
+ "AUTOMATIONS$GIT_SYNC$SUBTITLE": {
+ "en": "Sync automations to a git repository so they persist across restarts and can be shared.",
+ "ja": "自動化をGitリポジトリと同期し、再起動後も保持され共有できるようにします。",
+ "zh-CN": "将自动化同步到 Git 仓库,以便在重启后保留并可以共享。",
+ "zh-TW": "將自動化同步到 Git 儲存庫,以便在重新啟動後保留並可以共用。",
+ "ko-KR": "자동화를 Git 저장소와 동기화하여 재시작 후에도 유지되고 공유할 수 있도록 합니다.",
+ "no": "Synkroniser automatiseringer til et Git-lager slik at de bevares etter omstart og kan deles.",
+ "ar": "مزامنة الأتمتة مع مستودع Git بحيث تظل موجودة بعد إعادة التشغيل ويمكن مشاركتها.",
+ "de": "Automatisierungen mit einem Git-Repository synchronisieren, damit sie Neustarts überdauern und geteilt werden können.",
+ "fr": "Synchronisez les automatisations avec un dépôt Git afin qu'elles persistent après un redémarrage et puissent être partagées.",
+ "it": "Sincronizza le automazioni con un repository Git in modo che persistano dopo un riavvio e possano essere condivise.",
+ "pt": "Sincronize automações com um repositório Git para que persistam após reinicializações e possam ser compartilhadas.",
+ "es": "Sincroniza las automatizaciones con un repositorio de Git para que persistan tras un reinicio y puedan compartirse.",
+ "ca": "Sincronitza les automatitzacions amb un repositori de Git perquè persisteixin després de reiniciar i es puguin compartir.",
+ "tr": "Otomasyonları bir Git deposuyla senkronize edin, böylece yeniden başlatmalardan sonra da kalıcı olur ve paylaşılabilir.",
+ "uk": "Синхронізуйте автоматизації з репозиторієм Git, щоб вони зберігалися після перезапуску та могли надаватися в спільний доступ."
+ },
+ "AUTOMATIONS$GIT_SYNC$STATUS_TITLE": {
+ "en": "Sync Status",
+ "ja": "同期ステータス",
+ "zh-CN": "同步状态",
+ "zh-TW": "同步狀態",
+ "ko-KR": "동기화 상태",
+ "no": "Synkroniseringsstatus",
+ "ar": "حالة المزامنة",
+ "de": "Synchronisierungsstatus",
+ "fr": "État de la synchronisation",
+ "it": "Stato sincronizzazione",
+ "pt": "Status da sincronização",
+ "es": "Estado de la sincronización",
+ "ca": "Estat de la sincronització",
+ "tr": "Senkronizasyon Durumu",
+ "uk": "Стан синхронізації"
+ },
+ "AUTOMATIONS$GIT_SYNC$CONFIG_TITLE": {
+ "en": "Configuration",
+ "ja": "設定",
+ "zh-CN": "配置",
+ "zh-TW": "設定",
+ "ko-KR": "구성",
+ "no": "Konfigurasjon",
+ "ar": "الإعدادات",
+ "de": "Konfiguration",
+ "fr": "Configuration",
+ "it": "Configurazione",
+ "pt": "Configuração",
+ "es": "Configuración",
+ "ca": "Configuració",
+ "tr": "Yapılandırma",
+ "uk": "Конфігурація"
+ },
+ "AUTOMATIONS$GIT_SYNC$FIELD_ENABLED": {
+ "en": "Enable Git Sync",
+ "ja": "Git 同期を有効にする",
+ "zh-CN": "启用 Git 同步",
+ "zh-TW": "啟用 Git 同步",
+ "ko-KR": "Git 동기화 활성화",
+ "no": "Aktiver Git-synkronisering",
+ "ar": "تفعيل مزامنة Git",
+ "de": "Git-Synchronisierung aktivieren",
+ "fr": "Activer la synchronisation Git",
+ "it": "Abilita la sincronizzazione Git",
+ "pt": "Ativar sincronização do Git",
+ "es": "Activar la sincronización de Git",
+ "ca": "Activa la sincronització de Git",
+ "tr": "Git eşitlemeyi etkinleştir",
+ "uk": "Увімкнути синхронізацію Git"
+ },
+ "AUTOMATIONS$GIT_SYNC$ENABLED_HELP": {
+ "en": "Turn this off to pause syncing without losing the configuration. Turning it on requires a backend that was started with git sync enabled.",
+ "ja": "オフにすると、設定を保持したまま同期を一時停止します。オンにするには、Git 同期を有効にして起動したバックエンドが必要です。",
+ "zh-CN": "关闭后可暂停同步而不丢失配置。要开启,后端必须在启动时已启用 Git 同步。",
+ "zh-TW": "關閉後可暫停同步而不遺失設定。要開啟,後端必須在啟動時已啟用 Git 同步。",
+ "ko-KR": "끄면 설정을 유지한 채 동기화를 일시 중지합니다. 켜려면 Git 동기화가 활성화된 상태로 시작된 백엔드가 필요합니다.",
+ "no": "Slå av for å sette synkroniseringen på pause uten å miste oppsettet. For å slå den på må backend være startet med Git-synkronisering aktivert.",
+ "ar": "أوقف هذا الخيار لإيقاف المزامنة مؤقتًا دون فقدان الإعدادات. لتفعيله، يجب أن تكون الخدمة الخلفية قد بدأت مع تفعيل مزامنة Git.",
+ "de": "Deaktivieren pausiert die Synchronisierung, ohne die Konfiguration zu verlieren. Zum Aktivieren muss das Backend mit aktivierter Git-Synchronisierung gestartet worden sein.",
+ "fr": "Désactivez cette option pour mettre la synchronisation en pause sans perdre la configuration. Pour l'activer, le backend doit avoir démarré avec la synchronisation Git activée.",
+ "it": "Disattiva per mettere in pausa la sincronizzazione senza perdere la configurazione. Per attivarla, il backend deve essere stato avviato con la sincronizzazione Git abilitata.",
+ "pt": "Desative para pausar a sincronização sem perder a configuração. Para ativá-la, o backend precisa ter sido iniciado com a sincronização do Git ativada.",
+ "es": "Desactívalo para pausar la sincronización sin perder la configuración. Para activarlo, el backend debe haberse iniciado con la sincronización de Git habilitada.",
+ "ca": "Desactiva-ho per posar en pausa la sincronització sense perdre la configuració. Per activar-ho, el backend s'ha d'haver iniciat amb la sincronització de Git habilitada.",
+ "tr": "Yapılandırmayı kaybetmeden eşitlemeyi duraklatmak için bunu kapatın. Açmak için arka ucun Git eşitlemesi etkin olarak başlatılmış olması gerekir.",
+ "uk": "Вимкніть, щоб призупинити синхронізацію, не втрачаючи налаштування. Щоб увімкнути, бекенд має бути запущений з увімкненою синхронізацією Git."
+ },
+ "AUTOMATIONS$GIT_SYNC$ENABLED": {
+ "en": "Enabled",
+ "ja": "有効",
+ "zh-CN": "已启用",
+ "zh-TW": "已啟用",
+ "ko-KR": "활성화됨",
+ "no": "Aktivert",
+ "ar": "مُفعّل",
+ "de": "Aktiviert",
+ "fr": "Activée",
+ "it": "Abilitata",
+ "pt": "Ativado",
+ "es": "Activada",
+ "ca": "Activada",
+ "tr": "Etkin",
+ "uk": "Увімкнено"
+ },
+ "AUTOMATIONS$GIT_SYNC$DISABLED": {
+ "en": "Disabled",
+ "ja": "無効",
+ "zh-CN": "已禁用",
+ "zh-TW": "已停用",
+ "ko-KR": "비활성화됨",
+ "no": "Deaktivert",
+ "ar": "غير مُفعّل",
+ "de": "Deaktiviert",
+ "fr": "Désactivée",
+ "it": "Disabilitata",
+ "pt": "Desativado",
+ "es": "Desactivada",
+ "ca": "Desactivada",
+ "tr": "Devre dışı",
+ "uk": "Вимкнено"
+ },
+ "AUTOMATIONS$GIT_SYNC$ENCRYPTED": {
+ "en": "Encrypted",
+ "ja": "暗号化済み",
+ "zh-CN": "已加密",
+ "zh-TW": "已加密",
+ "ko-KR": "암호화됨",
+ "no": "Kryptert",
+ "ar": "مشفّر",
+ "de": "Verschlüsselt",
+ "fr": "Chiffré",
+ "it": "Crittografato",
+ "pt": "Criptografado",
+ "es": "Cifrado",
+ "ca": "Xifrat",
+ "tr": "Şifrelenmiş",
+ "uk": "Зашифровано"
+ },
+ "AUTOMATIONS$GIT_SYNC$NOT_ENCRYPTED": {
+ "en": "Not encrypted",
+ "ja": "暗号化なし",
+ "zh-CN": "未加密",
+ "zh-TW": "未加密",
+ "ko-KR": "암호화되지 않음",
+ "no": "Ikke kryptert",
+ "ar": "غير مشفّر",
+ "de": "Nicht verschlüsselt",
+ "fr": "Non chiffré",
+ "it": "Non crittografato",
+ "pt": "Não criptografado",
+ "es": "Sin cifrar",
+ "ca": "Sense xifrar",
+ "tr": "Şifrelenmemiş",
+ "uk": "Не зашифровано"
+ },
+ "AUTOMATIONS$GIT_SYNC$SAVE_AND_SYNC": {
+ "en": "Save and sync now",
+ "ja": "保存して今すぐ同期",
+ "zh-CN": "保存并立即同步",
+ "zh-TW": "儲存並立即同步",
+ "ko-KR": "저장 후 지금 동기화",
+ "no": "Lagre og synkroniser nå",
+ "ar": "الحفظ والمزامنة الآن",
+ "de": "Speichern und jetzt synchronisieren",
+ "fr": "Enregistrer et synchroniser maintenant",
+ "it": "Salva e sincronizza ora",
+ "pt": "Salvar e sincronizar agora",
+ "es": "Guardar y sincronizar ahora",
+ "ca": "Desa i sincronitza ara",
+ "tr": "Kaydet ve şimdi senkronize et",
+ "uk": "Зберегти й синхронізувати зараз"
+ },
+ "AUTOMATIONS$GIT_SYNC$SYNC_NOW": {
+ "en": "Sync now",
+ "ja": "今すぐ同期",
+ "zh-CN": "立即同步",
+ "zh-TW": "立即同步",
+ "ko-KR": "지금 동기화",
+ "no": "Synkroniser nå",
+ "ar": "مزامنة الآن",
+ "de": "Jetzt synchronisieren",
+ "fr": "Synchroniser maintenant",
+ "it": "Sincronizza ora",
+ "pt": "Sincronizar agora",
+ "es": "Sincronizar ahora",
+ "ca": "Sincronitza ara",
+ "tr": "Şimdi senkronize et",
+ "uk": "Синхронізувати зараз"
+ },
+ "AUTOMATIONS$GIT_SYNC$SYNCING": {
+ "en": "Syncing...",
+ "ja": "同期中...",
+ "zh-CN": "同步中...",
+ "zh-TW": "同步中...",
+ "ko-KR": "동기화 중...",
+ "no": "Synkroniserer...",
+ "ar": "جارٍ المزامنة...",
+ "de": "Wird synchronisiert...",
+ "fr": "Synchronisation en cours...",
+ "it": "Sincronizzazione in corso...",
+ "pt": "Sincronizando...",
+ "es": "Sincronizando...",
+ "ca": "Sincronitzant...",
+ "tr": "Senkronize ediliyor...",
+ "uk": "Синхронізація..."
+ },
+ "AUTOMATIONS$GIT_SYNC$SYNC_STARTED_AGO": {
+ "en": "started {{time}} ago",
+ "ja": "{{time}}前に開始",
+ "zh-CN": "{{time}}前开始",
+ "zh-TW": "{{time}}前開始",
+ "ko-KR": "{{time}} 전 시작",
+ "no": "startet for {{time}} siden",
+ "ar": "بدأت قبل {{time}}",
+ "de": "vor {{time}} gestartet",
+ "fr": "démarrée il y a {{time}}",
+ "it": "iniziata {{time}} fa",
+ "pt": "iniciada há {{time}}",
+ "es": "iniciada hace {{time}}",
+ "ca": "iniciada fa {{time}}",
+ "tr": "{{time}} önce başladı",
+ "uk": "почалася {{time}} тому"
+ },
+ "AUTOMATIONS$GIT_SYNC$SYNC_PENDING_COUNT": {
+ "en": "{{count}} pending",
+ "ja": "保留中 {{count}} 件",
+ "zh-CN": "待同步 {{count}} 项",
+ "zh-TW": "待同步 {{count}} 項",
+ "ko-KR": "대기 중 {{count}}개",
+ "no": "{{count}} venter",
+ "ar": "{{count}} قيد الانتظار",
+ "de": "{{count}} ausstehend",
+ "fr": "{{count}} en attente",
+ "it": "{{count}} in attesa",
+ "pt": "{{count}} pendentes",
+ "es": "{{count}} pendientes",
+ "ca": "{{count}} pendents",
+ "tr": "{{count}} bekliyor",
+ "uk": "{{count}} в очікуванні"
+ },
+ "AUTOMATIONS$GIT_SYNC$SYNC_COMPLETED": {
+ "en": "Sync complete",
+ "ja": "同期が完了しました",
+ "zh-CN": "同步完成",
+ "zh-TW": "同步完成",
+ "ko-KR": "동기화 완료",
+ "no": "Synkronisering fullført",
+ "ar": "اكتملت المزامنة",
+ "de": "Synchronisierung abgeschlossen",
+ "fr": "Synchronisation terminée",
+ "it": "Sincronizzazione completata",
+ "pt": "Sincronização concluída",
+ "es": "Sincronización completada",
+ "ca": "Sincronització completada",
+ "tr": "Eşitleme tamamlandı",
+ "uk": "Синхронізацію завершено"
+ },
+ "AUTOMATIONS$GIT_SYNC$SYNC_FAILED": {
+ "en": "Sync failed",
+ "ja": "同期に失敗しました",
+ "zh-CN": "同步失败",
+ "zh-TW": "同步失敗",
+ "ko-KR": "동기화 실패",
+ "no": "Synkronisering mislyktes",
+ "ar": "فشلت المزامنة",
+ "de": "Synchronisierung fehlgeschlagen",
+ "fr": "Échec de la synchronisation",
+ "it": "Sincronizzazione non riuscita",
+ "pt": "Falha na sincronização",
+ "es": "Error en la sincronización",
+ "ca": "Ha fallat la sincronització",
+ "tr": "Eşitleme başarısız oldu",
+ "uk": "Синхронізація не вдалася"
+ },
+ "AUTOMATIONS$GIT_SYNC$SYNC_DISABLED_ERROR": {
+ "en": "Enable Git Sync before triggering a sync.",
+ "ja": "同期をトリガーする前にGit同期を有効にしてください。",
+ "zh-CN": "请先启用 Git 同步,然后再触发同步。",
+ "zh-TW": "請先啟用 Git 同步,再觸發同步。",
+ "ko-KR": "동기화를 실행하려면 먼저 Git 동기화를 활성화하세요.",
+ "no": "Aktiver Git-synkronisering før du utløser en synkronisering.",
+ "ar": "فعّل مزامنة Git قبل بدء المزامنة.",
+ "de": "Aktivieren Sie Git-Synchronisierung, bevor Sie eine Synchronisierung auslösen.",
+ "fr": "Activez la synchronisation Git avant de déclencher une synchronisation.",
+ "it": "Abilita la sincronizzazione Git prima di avviare una sincronizzazione.",
+ "pt": "Ative a sincronização Git antes de acionar uma sincronização.",
+ "es": "Activa la sincronización de Git antes de iniciar una sincronización.",
+ "ca": "Activa la sincronització de Git abans d'iniciar una sincronització.",
+ "tr": "Senkronizasyonu tetiklemeden önce Git Senkronizasyonunu etkinleştirin.",
+ "uk": "Увімкніть Git-синхронізацію, перш ніж запускати синхронізацію."
+ },
+ "AUTOMATIONS$GIT_SYNC$REPOSITORY": {
+ "en": "Repository",
+ "ja": "リポジトリ",
+ "zh-CN": "仓库",
+ "zh-TW": "儲存庫",
+ "ko-KR": "저장소",
+ "no": "Repository",
+ "ar": "المستودع",
+ "de": "Repository",
+ "fr": "Dépôt",
+ "it": "Repository",
+ "pt": "Repositório",
+ "es": "Repositorio",
+ "ca": "Repositori",
+ "tr": "Depo",
+ "uk": "Репозиторій"
+ },
+ "AUTOMATIONS$GIT_SYNC$NOT_CONFIGURED": {
+ "en": "Not configured",
+ "ja": "未設定",
+ "zh-CN": "未配置",
+ "zh-TW": "未設定",
+ "ko-KR": "구성되지 않음",
+ "no": "Ikke konfigurert",
+ "ar": "غير مُهيأ",
+ "de": "Nicht konfiguriert",
+ "fr": "Non configuré",
+ "it": "Non configurato",
+ "pt": "Não configurado",
+ "es": "No configurado",
+ "ca": "No configurat",
+ "tr": "Yapılandırılmamış",
+ "uk": "Не налаштовано"
+ },
+ "AUTOMATIONS$GIT_SYNC$LAST_SYNCED_COMMIT": {
+ "en": "Last synced commit",
+ "ja": "最終同期コミット",
+ "zh-CN": "最近同步的提交",
+ "zh-TW": "最近同步的提交",
+ "ko-KR": "마지막 동기화 커밋",
+ "no": "Sist synkroniserte commit",
+ "ar": "آخر تزامن للـ commit",
+ "de": "Zuletzt synchronisierter Commit",
+ "fr": "Dernier commit synchronisé",
+ "it": "Ultimo commit sincronizzato",
+ "pt": "Último commit sincronizado",
+ "es": "Último commit sincronizado",
+ "ca": "Últim commit sincronitzat",
+ "tr": "Son senkronize edilen commit",
+ "uk": "Останній синхронізований коміт"
+ },
+ "AUTOMATIONS$GIT_SYNC$LAST_SYNCED_AT": {
+ "en": "Last synced",
+ "ja": "最終同期日時",
+ "zh-CN": "最近同步时间",
+ "zh-TW": "最近同步時間",
+ "ko-KR": "마지막 동기화 시간",
+ "no": "Sist synkronisert",
+ "ar": "آخر مزامنة",
+ "de": "Zuletzt synchronisiert",
+ "fr": "Dernière synchronisation",
+ "it": "Ultima sincronizzazione",
+ "pt": "Última sincronização",
+ "es": "Última sincronización",
+ "ca": "Última sincronització",
+ "tr": "Son senkronizasyon",
+ "uk": "Остання синхронізація"
+ },
+ "AUTOMATIONS$GIT_SYNC$PENDING_CHANGES": {
+ "en": "Pending changes",
+ "ja": "保留中の変更",
+ "zh-CN": "待处理的更改",
+ "zh-TW": "待處理的變更",
+ "ko-KR": "대기 중인 변경 사항",
+ "no": "Ventende endringer",
+ "ar": "التغييرات المعلّقة",
+ "de": "Ausstehende Änderungen",
+ "fr": "Modifications en attente",
+ "it": "Modifiche in sospeso",
+ "pt": "Alterações pendentes",
+ "es": "Cambios pendientes",
+ "ca": "Canvis pendents",
+ "tr": "Bekleyen değişiklikler",
+ "uk": "Очікувані зміни"
+ },
+ "AUTOMATIONS$GIT_SYNC$NEVER_SYNCED": {
+ "en": "Never synced",
+ "ja": "同期履歴なし",
+ "zh-CN": "从未同步",
+ "zh-TW": "從未同步",
+ "ko-KR": "동기화된 적 없음",
+ "no": "Aldri synkronisert",
+ "ar": "لم تتم المزامنة أبدًا",
+ "de": "Nie synchronisiert",
+ "fr": "Jamais synchronisé",
+ "it": "Mai sincronizzato",
+ "pt": "Nunca sincronizado",
+ "es": "Nunca sincronizado",
+ "ca": "Mai sincronitzat",
+ "tr": "Hiç senkronize edilmedi",
+ "uk": "Ніколи не синхронізувалося"
+ },
+ "AUTOMATIONS$GIT_SYNC$LAST_ERROR_TITLE": {
+ "en": "Last sync error",
+ "ja": "直近の同期エラー",
+ "zh-CN": "最近一次同步错误",
+ "zh-TW": "最近一次同步錯誤",
+ "ko-KR": "최근 동기화 오류",
+ "no": "Siste synkroniseringsfeil",
+ "ar": "آخر خطأ في المزامنة",
+ "de": "Letzter Synchronisierungsfehler",
+ "fr": "Dernière erreur de synchronisation",
+ "it": "Ultimo errore di sincronizzazione",
+ "pt": "Último erro de sincronização",
+ "es": "Último error de sincronización",
+ "ca": "Últim error de sincronització",
+ "tr": "Son senkronizasyon hatası",
+ "uk": "Остання помилка синхронізації"
+ },
+ "AUTOMATIONS$GIT_SYNC$FIELD_REPO_URL": {
+ "en": "Repository URL",
+ "ja": "リポジトリURL",
+ "zh-CN": "仓库 URL",
+ "zh-TW": "儲存庫 URL",
+ "ko-KR": "저장소 URL",
+ "no": "Repository-URL",
+ "ar": "رابط المستودع",
+ "de": "Repository-URL",
+ "fr": "URL du dépôt",
+ "it": "URL del repository",
+ "pt": "URL do repositório",
+ "es": "URL del repositorio",
+ "ca": "URL del repositori",
+ "tr": "Depo URL'si",
+ "uk": "URL репозиторію"
+ },
+ "AUTOMATIONS$GIT_SYNC$REPO_URL_PLACEHOLDER": {
+ "en": "https://github.com/org/repo.git",
+ "ja": "https://github.com/org/repo.git",
+ "zh-CN": "https://github.com/org/repo.git",
+ "zh-TW": "https://github.com/org/repo.git",
+ "ko-KR": "https://github.com/org/repo.git",
+ "no": "https://github.com/org/repo.git",
+ "ar": "https://github.com/org/repo.git",
+ "de": "https://github.com/org/repo.git",
+ "fr": "https://github.com/org/repo.git",
+ "it": "https://github.com/org/repo.git",
+ "pt": "https://github.com/org/repo.git",
+ "es": "https://github.com/org/repo.git",
+ "ca": "https://github.com/org/repo.git",
+ "tr": "https://github.com/org/repo.git",
+ "uk": "https://github.com/org/repo.git"
+ },
+ "AUTOMATIONS$GIT_SYNC$FIELD_BRANCH": {
+ "en": "Branch",
+ "ja": "ブランチ",
+ "zh-CN": "分支",
+ "zh-TW": "分支",
+ "ko-KR": "브랜치",
+ "no": "Gren",
+ "ar": "الفرع",
+ "de": "Branch",
+ "fr": "Branche",
+ "it": "Branch",
+ "pt": "Branch",
+ "es": "Rama",
+ "ca": "Branca",
+ "tr": "Dal",
+ "uk": "Гілка"
+ },
+ "AUTOMATIONS$GIT_SYNC$BRANCH_PLACEHOLDER": {
+ "en": "main",
+ "ja": "main",
+ "zh-CN": "main",
+ "zh-TW": "main",
+ "ko-KR": "main",
+ "no": "main",
+ "ar": "main",
+ "de": "main",
+ "fr": "main",
+ "it": "main",
+ "pt": "main",
+ "es": "main",
+ "ca": "main",
+ "tr": "main",
+ "uk": "main"
+ },
+ "AUTOMATIONS$GIT_SYNC$FIELD_PATH": {
+ "en": "Path",
+ "ja": "パス",
+ "zh-CN": "路径",
+ "zh-TW": "路徑",
+ "ko-KR": "경로",
+ "no": "Sti",
+ "ar": "المسار",
+ "de": "Pfad",
+ "fr": "Chemin",
+ "it": "Percorso",
+ "pt": "Caminho",
+ "es": "Ruta",
+ "ca": "Camí",
+ "tr": "Yol",
+ "uk": "Шлях"
+ },
+ "AUTOMATIONS$GIT_SYNC$PATH_PLACEHOLDER": {
+ "en": "automations",
+ "ja": "automations",
+ "zh-CN": "automations",
+ "zh-TW": "automations",
+ "ko-KR": "automations",
+ "no": "automations",
+ "ar": "automations",
+ "de": "automations",
+ "fr": "automations",
+ "it": "automations",
+ "pt": "automations",
+ "es": "automations",
+ "ca": "automations",
+ "tr": "automations",
+ "uk": "automations"
+ },
+ "AUTOMATIONS$GIT_SYNC$FIELD_AUTHOR_NAME": {
+ "en": "Commit author name",
+ "ja": "コミット作成者名",
+ "zh-CN": "提交作者姓名",
+ "zh-TW": "提交作者姓名",
+ "ko-KR": "커밋 작성자 이름",
+ "no": "Navn på commit-forfatter",
+ "ar": "اسم مؤلف الـ commit",
+ "de": "Name des Commit-Autors",
+ "fr": "Nom de l'auteur du commit",
+ "it": "Nome autore commit",
+ "pt": "Nome do autor do commit",
+ "es": "Nombre del autor del commit",
+ "ca": "Nom de l'autor del commit",
+ "tr": "Commit yazarının adı",
+ "uk": "Ім'я автора коміту"
+ },
+ "AUTOMATIONS$GIT_SYNC$FIELD_AUTHOR_EMAIL": {
+ "en": "Commit author email",
+ "ja": "コミット作成者メールアドレス",
+ "zh-CN": "提交作者邮箱",
+ "zh-TW": "提交作者電子郵件",
+ "ko-KR": "커밋 작성자 이메일",
+ "no": "E-post til commit-forfatter",
+ "ar": "البريد الإلكتروني لمؤلف الـ commit",
+ "de": "E-Mail des Commit-Autors",
+ "fr": "E-mail de l'auteur du commit",
+ "it": "Email autore commit",
+ "pt": "E-mail do autor do commit",
+ "es": "Correo del autor del commit",
+ "ca": "Correu de l'autor del commit",
+ "tr": "Commit yazarının e-postası",
+ "uk": "Електронна пошта автора коміту"
+ },
+ "AUTOMATIONS$GIT_SYNC$AUTHOR_HELP": {
+ "en": "Leave blank to use the backend's default commit author.",
+ "ja": "空欄のままにすると、バックエンドの既定のコミット作成者を使用します。",
+ "zh-CN": "留空则使用后端的默认提交作者。",
+ "zh-TW": "留空則使用後端的預設提交作者。",
+ "ko-KR": "비워 두면 백엔드의 기본 커밋 작성자를 사용합니다.",
+ "no": "La stå tomt for å bruke backendens standard commit-forfatter.",
+ "ar": "اتركه فارغًا لاستخدام مؤلف الالتزامات الافتراضي للخدمة الخلفية.",
+ "de": "Leer lassen, um den Standard-Commit-Autor des Backends zu verwenden.",
+ "fr": "Laissez vide pour utiliser l'auteur de commit par défaut du backend.",
+ "it": "Lascia vuoto per usare l'autore dei commit predefinito del backend.",
+ "pt": "Deixe em branco para usar o autor de commit padrão do backend.",
+ "es": "Déjalo en blanco para usar el autor de commits predeterminado del backend.",
+ "ca": "Deixa-ho en blanc per fer servir l'autor de comissions predeterminat del backend.",
+ "tr": "Arka ucun varsayılan commit yazarını kullanmak için boş bırakın.",
+ "uk": "Залиште порожнім, щоб використовувати типового автора комітів бекенда."
+ },
+ "AUTOMATIONS$GIT_SYNC$FIELD_TOKEN": {
+ "en": "Access token",
+ "ja": "アクセストークン",
+ "zh-CN": "访问令牌",
+ "zh-TW": "存取權杖",
+ "ko-KR": "액세스 토큰",
+ "no": "Tilgangstoken",
+ "ar": "رمز الوصول",
+ "de": "Zugriffstoken",
+ "fr": "Jeton d'accès",
+ "it": "Token di accesso",
+ "pt": "Token de acesso",
+ "es": "Token de acceso",
+ "ca": "Testimoni d'accés",
+ "tr": "Erişim belirteci",
+ "uk": "Токен доступу"
+ },
+ "AUTOMATIONS$GIT_SYNC$FIELD_ENCRYPTION_KEY": {
+ "en": "Encryption key",
+ "ja": "暗号化キー",
+ "zh-CN": "加密密钥",
+ "zh-TW": "加密金鑰",
+ "ko-KR": "암호화 키",
+ "no": "Krypteringsnøkkel",
+ "ar": "مفتاح التشفير",
+ "de": "Verschlüsselungsschlüssel",
+ "fr": "Clé de chiffrement",
+ "it": "Chiave di crittografia",
+ "pt": "Chave de criptografia",
+ "es": "Clave de cifrado",
+ "ca": "Clau de xifratge",
+ "tr": "Şifreleme anahtarı",
+ "uk": "Ключ шифрування"
+ },
+ "AUTOMATIONS$GIT_SYNC$TOKEN_HELP": {
+ "en": "Required for private repositories. Leave blank to keep the existing token unchanged.",
+ "ja": "プライベートリポジトリには必須です。空欄のままにすると既存のトークンは変更されません。",
+ "zh-CN": "私有仓库需要此项。留空则保留现有令牌不变。",
+ "zh-TW": "私有儲存庫需要此項。留空則保留現有權杖不變。",
+ "ko-KR": "비공개 저장소에 필요합니다. 비워 두면 기존 토큰이 변경되지 않습니다.",
+ "no": "Kreves for private repositories. La stå tomt for å beholde eksisterende token uendret.",
+ "ar": "مطلوب للمستودعات الخاصة. اتركه فارغًا للاحتفاظ بالرمز الحالي دون تغيير.",
+ "de": "Erforderlich für private Repositories. Leer lassen, um das bestehende Token unverändert zu lassen.",
+ "fr": "Requis pour les dépôts privés. Laissez vide pour conserver le jeton existant inchangé.",
+ "it": "Obbligatorio per i repository privati. Lascia vuoto per mantenere invariato il token esistente.",
+ "pt": "Obrigatório para repositórios privados. Deixe em branco para manter o token existente inalterado.",
+ "es": "Obligatorio para repositorios privados. Déjalo en blanco para mantener el token existente sin cambios.",
+ "ca": "Obligatori per a repositoris privats. Deixa-ho en blanc per mantenir el testimoni existent sense canvis.",
+ "tr": "Özel depolar için gereklidir. Mevcut belirteci değiştirmeden bırakmak için boş bırakın.",
+ "uk": "Обов'язково для приватних репозиторіїв. Залиште порожнім, щоб зберегти наявний токен без змін."
+ },
+ "AUTOMATIONS$GIT_SYNC$TOKEN_PLACEHOLDER": {
+ "en": "Leave blank to keep the current token",
+ "ja": "空欄のままにすると現在のトークンを維持します",
+ "zh-CN": "留空以保留当前令牌",
+ "zh-TW": "留空以保留目前的權杖",
+ "ko-KR": "비워 두면 현재 토큰을 유지합니다",
+ "no": "La stå tomt for å beholde gjeldende token",
+ "ar": "اتركه فارغًا للاحتفاظ بالرمز الحالي",
+ "de": "Leer lassen, um das aktuelle Token beizubehalten",
+ "fr": "Laissez vide pour conserver le jeton actuel",
+ "it": "Lascia vuoto per mantenere il token attuale",
+ "pt": "Deixe em branco para manter o token atual",
+ "es": "Déjalo en blanco para mantener el token actual",
+ "ca": "Deixa-ho en blanc per mantenir el testimoni actual",
+ "tr": "Mevcut belirteci korumak için boş bırakın",
+ "uk": "Залиште порожнім, щоб зберегти поточний токен"
+ },
+ "AUTOMATIONS$GIT_SYNC$KEY_SET_PLACEHOLDER": {
+ "en": "An encryption key is currently set",
+ "ja": "暗号化キーは現在設定されています",
+ "zh-CN": "当前已设置加密密钥",
+ "zh-TW": "目前已設定加密金鑰",
+ "ko-KR": "현재 암호화 키가 설정되어 있습니다",
+ "no": "En krypteringsnøkkel er for øyeblikket angitt",
+ "ar": "تم تعيين مفتاح تشفير حاليًا",
+ "de": "Derzeit ist ein Verschlüsselungsschlüssel festgelegt",
+ "fr": "Une clé de chiffrement est actuellement définie",
+ "it": "Al momento è impostata una chiave di crittografia",
+ "pt": "Uma chave de criptografia está definida atualmente",
+ "es": "Actualmente hay una clave de cifrado configurada",
+ "ca": "Actualment hi ha una clau de xifratge configurada",
+ "tr": "Şu anda bir şifreleme anahtarı ayarlanmış",
+ "uk": "Наразі встановлено ключ шифрування"
+ },
+ "AUTOMATIONS$GIT_SYNC$KEY_UNSET_PLACEHOLDER": {
+ "en": "No encryption key set",
+ "ja": "暗号化キーは設定されていません",
+ "zh-CN": "未设置加密密钥",
+ "zh-TW": "尚未設定加密金鑰",
+ "ko-KR": "설정된 암호화 키가 없습니다",
+ "no": "Ingen krypteringsnøkkel angitt",
+ "ar": "لم يتم تعيين مفتاح تشفير",
+ "de": "Kein Verschlüsselungsschlüssel festgelegt",
+ "fr": "Aucune clé de chiffrement définie",
+ "it": "Nessuna chiave di crittografia impostata",
+ "pt": "Nenhuma chave de criptografia definida",
+ "es": "No hay ninguna clave de cifrado configurada",
+ "ca": "No hi ha cap clau de xifratge configurada",
+ "tr": "Şifreleme anahtarı ayarlanmamış",
+ "uk": "Ключ шифрування не встановлено"
+ },
+ "AUTOMATIONS$GIT_SYNC$ENCRYPTION_KEY_HELP": {
+ "en": "Optional. Encrypts automation files before they are committed, so the repository stores ciphertext instead of readable YAML. Keep a copy of the key — without it the repository cannot be read or restored.",
+ "ja": "任意。コミット前に自動化ファイルを暗号化するため、リポジトリには読み取り可能な YAML ではなく暗号文が保存されます。キーのコピーを保管してください。キーがないとリポジトリを読み取ることも復元することもできません。",
+ "zh-CN": "可选。提交前会加密自动化文件,因此仓库中保存的是密文而非可读的 YAML。请妥善保存密钥副本;没有它将无法读取或恢复该仓库。",
+ "zh-TW": "選填。提交前會加密自動化檔案,因此儲存庫中保存的是密文而非可讀的 YAML。請妥善保存金鑰副本;沒有它將無法讀取或還原該儲存庫。",
+ "ko-KR": "선택 사항입니다. 커밋하기 전에 자동화 파일을 암호화하므로 저장소에는 읽을 수 있는 YAML 대신 암호문이 저장됩니다. 키 사본을 보관하세요. 키가 없으면 저장소를 읽거나 복원할 수 없습니다.",
+ "no": "Valgfritt. Krypterer automasjonsfilene før de blir commitet, slik at repositoriet lagrer chiffertekst i stedet for lesbar YAML. Ta vare på en kopi av nøkkelen – uten den kan ikke repositoriet leses eller gjenopprettes.",
+ "ar": "اختياري. يشفّر ملفات الأتمتة قبل تثبيتها، فيخزّن المستودع نصًا مشفّرًا بدلاً من YAML قابل للقراءة. احتفظ بنسخة من المفتاح؛ فبدونه لا يمكن قراءة المستودع أو استعادته.",
+ "de": "Optional. Verschlüsselt die Automatisierungsdateien vor dem Commit, sodass das Repository Chiffretext statt lesbarem YAML enthält. Eine Kopie des Schlüssels aufbewahren – ohne ihn lässt sich das Repository weder lesen noch wiederherstellen.",
+ "fr": "Facultatif. Chiffre les fichiers d'automatisation avant leur commit : le dépôt contient alors du texte chiffré au lieu de YAML lisible. Conservez une copie de la clé — sans elle, le dépôt ne peut être ni lu ni restauré.",
+ "it": "Facoltativo. Cifra i file delle automazioni prima del commit, così il repository contiene testo cifrato invece di YAML leggibile. Conserva una copia della chiave: senza di essa il repository non può essere letto né ripristinato.",
+ "pt": "Opcional. Criptografa os arquivos de automação antes do commit, de modo que o repositório armazena texto cifrado em vez de YAML legível. Guarde uma cópia da chave — sem ela, o repositório não pode ser lido nem restaurado.",
+ "es": "Opcional. Cifra los archivos de automatización antes de confirmarlos, de modo que el repositorio almacena texto cifrado en lugar de YAML legible. Guarda una copia de la clave: sin ella, el repositorio no se puede leer ni restaurar.",
+ "ca": "Opcional. Xifra els fitxers d'automatització abans de confirmar-los, de manera que el repositori emmagatzema text xifrat en lloc de YAML llegible. Desa una còpia de la clau: sense ella, el repositori no es pot llegir ni restaurar.",
+ "tr": "İsteğe bağlı. Otomasyon dosyalarını commit edilmeden önce şifreler; böylece depo okunabilir YAML yerine şifreli metin saklar. Anahtarın bir kopyasını saklayın; anahtar olmadan depo okunamaz veya geri yüklenemez.",
+ "uk": "Необов'язково. Шифрує файли автоматизацій перед комітом, тож репозиторій зберігає шифротекст замість читабельного YAML. Збережіть копію ключа — без нього репозиторій неможливо прочитати чи відновити."
+ },
+ "AUTOMATIONS$GIT_SYNC$CLEAR_TOKEN": {
+ "en": "Clear existing token",
+ "ja": "既存のトークンを削除",
+ "zh-CN": "清除现有令牌",
+ "zh-TW": "清除現有權杖",
+ "ko-KR": "기존 토큰 지우기",
+ "no": "Fjern eksisterende token",
+ "ar": "مسح الرمز الحالي",
+ "de": "Vorhandenes Token löschen",
+ "fr": "Effacer le jeton existant",
+ "it": "Cancella token esistente",
+ "pt": "Limpar token existente",
+ "es": "Borrar token existente",
+ "ca": "Esborra el testimoni existent",
+ "tr": "Mevcut belirteci temizle",
+ "uk": "Очистити наявний токен"
+ },
+ "AUTOMATIONS$GIT_SYNC$CLEAR_ENCRYPTION_KEY": {
+ "en": "Clear existing encryption key",
+ "ja": "既存の暗号化キーを削除",
+ "zh-CN": "清除现有加密密钥",
+ "zh-TW": "清除現有加密金鑰",
+ "ko-KR": "기존 암호화 키 지우기",
+ "no": "Fjern eksisterende krypteringsnøkkel",
+ "ar": "مسح مفتاح التشفير الحالي",
+ "de": "Vorhandenen Verschlüsselungsschlüssel löschen",
+ "fr": "Effacer la clé de chiffrement existante",
+ "it": "Cancella chiave di crittografia esistente",
+ "pt": "Limpar chave de criptografia existente",
+ "es": "Borrar clave de cifrado existente",
+ "ca": "Esborra la clau de xifratge existent",
+ "tr": "Mevcut şifreleme anahtarını temizle",
+ "uk": "Очистити наявний ключ шифрування"
+ },
+ "AUTOMATIONS$GIT_SYNC$CONFIG_SAVED": {
+ "en": "Git Sync settings saved.",
+ "ja": "Git同期設定を保存しました。",
+ "zh-CN": "Git 同步设置已保存。",
+ "zh-TW": "Git 同步設定已儲存。",
+ "ko-KR": "Git 동기화 설정이 저장되었습니다.",
+ "no": "Git-synkroniseringsinnstillinger lagret.",
+ "ar": "تم حفظ إعدادات مزامنة Git.",
+ "de": "Git-Synchronisierungseinstellungen gespeichert.",
+ "fr": "Paramètres de synchronisation Git enregistrés.",
+ "it": "Impostazioni di sincronizzazione Git salvate.",
+ "pt": "Configurações de sincronização Git salvas.",
+ "es": "Configuración de sincronización de Git guardada.",
+ "ca": "Configuració de sincronització de Git desada.",
+ "tr": "Git Senkronizasyon ayarları kaydedildi.",
+ "uk": "Налаштування Git-синхронізації збережено."
+ },
+ "AUTOMATIONS$GIT_SYNC$CHECKING": {
+ "en": "Checking repository...",
+ "ja": "リポジトリを確認しています...",
+ "zh-CN": "正在检查仓库...",
+ "zh-TW": "正在檢查儲存庫...",
+ "ko-KR": "저장소 확인 중...",
+ "no": "Sjekker repositoriet ...",
+ "ar": "جارٍ التحقق من المستودع...",
+ "de": "Repository wird geprüft ...",
+ "fr": "Vérification du dépôt...",
+ "it": "Verifica del repository in corso...",
+ "pt": "A verificar o repositório...",
+ "es": "Comprobando el repositorio...",
+ "ca": "S'està comprovant el repositori...",
+ "tr": "Depo denetleniyor...",
+ "uk": "Перевірка репозиторію..."
+ },
+ "AUTOMATIONS$GIT_SYNC$CHECK_FAILED_TITLE": {
+ "en": "Could not reach the repository with these settings",
+ "ja": "この設定ではリポジトリに接続できませんでした",
+ "zh-CN": "使用这些设置无法访问仓库",
+ "zh-TW": "使用這些設定無法存取儲存庫",
+ "ko-KR": "이 설정으로는 저장소에 연결할 수 없습니다",
+ "no": "Kunne ikke nå repositoriet med disse innstillingene",
+ "ar": "تعذّر الوصول إلى المستودع بهذه الإعدادات",
+ "de": "Mit diesen Einstellungen war das Repository nicht erreichbar",
+ "fr": "Impossible d'accéder au dépôt avec ces paramètres",
+ "it": "Impossibile raggiungere il repository con queste impostazioni",
+ "pt": "Não foi possível aceder ao repositório com estas definições",
+ "es": "No se pudo acceder al repositorio con esta configuración",
+ "ca": "No s'ha pogut accedir al repositori amb aquesta configuració",
+ "tr": "Bu ayarlarla depoya erişilemedi",
+ "uk": "Не вдалося отримати доступ до репозиторію з цими налаштуваннями"
+ },
+ "AUTOMATIONS$GIT_SYNC$CHECK_FAILED_HINT": {
+ "en": "Fix the settings above, or press Save again to store them anyway.",
+ "ja": "上記の設定を修正するか、もう一度「保存」を押すとこのまま保存します。",
+ "zh-CN": "请修改上面的设置,或再次点击“保存”仍然保存。",
+ "zh-TW": "請修改上面的設定,或再次點擊「儲存」仍然儲存。",
+ "ko-KR": "위 설정을 수정하거나 저장을 다시 누르면 그대로 저장됩니다.",
+ "no": "Rett innstillingene over, eller trykk Lagre igjen for å lagre likevel.",
+ "ar": "صحّح الإعدادات أعلاه، أو اضغط على حفظ مرة أخرى لحفظها على أي حال.",
+ "de": "Korrigieren Sie die Einstellungen oben oder klicken Sie erneut auf Speichern, um sie trotzdem zu speichern.",
+ "fr": "Corrigez les paramètres ci-dessus ou appuyez à nouveau sur Enregistrer pour les enregistrer malgré tout.",
+ "it": "Correggi le impostazioni sopra oppure premi di nuovo Salva per salvarle comunque.",
+ "pt": "Corrija as definições acima ou prima Guardar novamente para as guardar mesmo assim.",
+ "es": "Corrige la configuración anterior o pulsa Guardar de nuevo para guardarla igualmente.",
+ "ca": "Corregeix la configuració anterior o torna a prémer Desa per desar-la igualment.",
+ "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$UNSUPPORTED_TITLE": {
+ "en": "Git Sync is not available on this backend",
+ "ja": "このバックエンドでは Git 同期を利用できません",
+ "zh-CN": "此后端不支持 Git 同步",
+ "zh-TW": "此後端不支援 Git 同步",
+ "ko-KR": "이 백엔드에서는 Git 동기화를 사용할 수 없습니다",
+ "no": "Git-synkronisering er ikke tilgjengelig på denne backenden",
+ "ar": "مزامنة Git غير متاحة على هذه الخدمة الخلفية",
+ "de": "Git-Synchronisierung ist auf diesem Backend nicht verfügbar",
+ "fr": "La synchronisation Git n'est pas disponible sur ce backend",
+ "it": "La sincronizzazione Git non è disponibile su questo backend",
+ "pt": "A sincronização do Git não está disponível neste backend",
+ "es": "La sincronización de Git no está disponible en este backend",
+ "ca": "La sincronització de Git no està disponible en aquest backend",
+ "tr": "Bu arka uçta Git eşitlemesi kullanılamıyor",
+ "uk": "Синхронізація Git недоступна на цьому бекенді"
+ },
+ "AUTOMATIONS$GIT_SYNC$UNSUPPORTED_MESSAGE": {
+ "en": "The automation backend is running a version without the Git Sync API. Update it to a version that supports Git Sync.",
+ "ja": "オートメーションバックエンドは Git 同期 API を持たないバージョンで動作しています。Git 同期に対応したバージョンに更新してください。",
+ "zh-CN": "自动化后端运行的版本不包含 Git 同步 API。请将其更新到支持 Git 同步的版本。",
+ "zh-TW": "自動化後端執行的版本不包含 Git 同步 API。請將其更新到支援 Git 同步的版本。",
+ "ko-KR": "자동화 백엔드가 Git 동기화 API가 없는 버전으로 실행 중입니다. Git 동기화를 지원하는 버전으로 업데이트하세요.",
+ "no": "Automatiserings-backenden kjører en versjon uten Git-synkroniserings-API-et. Oppdater den til en versjon som støtter Git-synkronisering.",
+ "ar": "تعمل الخدمة الخلفية للأتمتة بإصدار لا يتضمن واجهة برمجة مزامنة Git. حدّثها إلى إصدار يدعم مزامنة Git.",
+ "de": "Das Automatisierungs-Backend läuft in einer Version ohne die Git-Sync-API. Aktualisieren Sie es auf eine Version, die Git-Synchronisierung unterstützt.",
+ "fr": "Le backend d'automatisation exécute une version sans l'API de synchronisation Git. Mettez-le à jour vers une version qui la prend en charge.",
+ "it": "Il backend di automazione esegue una versione priva dell'API di sincronizzazione Git. Aggiornalo a una versione che la supporti.",
+ "pt": "O backend de automação está executando uma versão sem a API de sincronização do Git. Atualize-o para uma versão compatível.",
+ "es": "El backend de automatización ejecuta una versión sin la API de sincronización de Git. Actualízalo a una versión compatible.",
+ "ca": "El backend d'automatització executa una versió sense l'API de sincronització de Git. Actualitza'l a una versió compatible.",
+ "tr": "Otomasyon arka ucu, Git eşitleme API'si olmayan bir sürümü çalıştırıyor. Git eşitlemeyi destekleyen bir sürüme güncelleyin.",
+ "uk": "Бекенд автоматизації працює на версії без API синхронізації Git. Оновіть його до версії з підтримкою синхронізації Git."
+ },
+ "AUTOMATIONS$GIT_SYNC$FIELD_INTERVAL": {
+ "en": "Sync every (seconds)",
+ "ja": "同期間隔(秒)",
+ "zh-CN": "同步间隔(秒)",
+ "zh-TW": "同步間隔(秒)",
+ "ko-KR": "동기화 주기(초)",
+ "no": "Synkroniser hvert (sekunder)",
+ "ar": "المزامنة كل (ثوانٍ)",
+ "de": "Synchronisieren alle (Sekunden)",
+ "fr": "Synchroniser toutes les (secondes)",
+ "it": "Sincronizza ogni (secondi)",
+ "pt": "Sincronizar a cada (segundos)",
+ "es": "Sincronizar cada (segundos)",
+ "ca": "Sincronitza cada (segons)",
+ "tr": "Şu sıklıkta senkronize et (saniye)",
+ "uk": "Синхронізувати кожні (секунд)"
+ },
+ "AUTOMATIONS$GIT_SYNC$INTERVAL_HELP": {
+ "en": "Set to 0 to sync only when you press Sync now.",
+ "ja": "0に設定すると、「今すぐ同期」を押したときだけ同期します。",
+ "zh-CN": "设置为 0 则仅在点击“立即同步”时同步。",
+ "zh-TW": "設定為 0 則僅在點擊「立即同步」時同步。",
+ "ko-KR": "0으로 설정하면 '지금 동기화'를 누를 때만 동기화됩니다.",
+ "no": "Sett til 0 for å synkronisere bare når du trykker Synkroniser nå.",
+ "ar": "اضبطه على 0 للمزامنة فقط عند الضغط على «مزامنة الآن».",
+ "de": "Auf 0 setzen, um nur bei Klick auf „Jetzt synchronisieren“ zu synchronisieren.",
+ "fr": "Mettez 0 pour synchroniser uniquement lorsque vous cliquez sur Synchroniser maintenant.",
+ "it": "Imposta 0 per sincronizzare solo quando premi Sincronizza ora.",
+ "pt": "Defina 0 para sincronizar apenas ao clicar em Sincronizar agora.",
+ "es": "Ponlo en 0 para sincronizar solo cuando pulses Sincronizar ahora.",
+ "ca": "Posa-ho a 0 per sincronitzar només quan premis Sincronitza ara.",
+ "tr": "Yalnızca «Şimdi senkronize et» düğmesine bastığınızda senkronize etmek için 0 girin.",
+ "uk": "Установіть 0, щоб синхронізувати лише після натискання «Синхронізувати зараз»."
+ },
+ "AUTOMATIONS$GIT_SYNC$MANUAL_ONLY": {
+ "en": "Manual only",
+ "ja": "手動のみ",
+ "zh-CN": "仅手动",
+ "zh-TW": "僅手動",
+ "ko-KR": "수동 전용",
+ "no": "Kun manuelt",
+ "ar": "يدوي فقط",
+ "de": "Nur manuell",
+ "fr": "Manuel uniquement",
+ "it": "Solo manuale",
+ "pt": "Apenas manual",
+ "es": "Solo manual",
+ "ca": "Només manual",
+ "tr": "Yalnızca elle",
+ "uk": "Лише вручну"
+ },
+ "AUTOMATIONS$GIT_SYNC$EVERY_N_SECONDS": {
+ "en": "Every {{count}}s",
+ "ja": "{{count}}秒ごと",
+ "zh-CN": "每 {{count}} 秒",
+ "zh-TW": "每 {{count}} 秒",
+ "ko-KR": "{{count}}초마다",
+ "no": "Hvert {{count}}. sekund",
+ "ar": "كل {{count}} ثانية",
+ "de": "Alle {{count}}s",
+ "fr": "Toutes les {{count}}s",
+ "it": "Ogni {{count}}s",
+ "pt": "A cada {{count}}s",
+ "es": "Cada {{count}}s",
+ "ca": "Cada {{count}}s",
+ "tr": "Her {{count}}sn",
+ "uk": "Кожні {{count}} с"
}
}
diff --git a/src/routes.ts b/src/routes.ts
index 732978b79f..bcabc43fee 100644
--- a/src/routes.ts
+++ b/src/routes.ts
@@ -32,6 +32,7 @@ export default [
]),
route("oauth/device/verify", "routes/device-verify.tsx"),
route("automations", "routes/automations-list.tsx"),
+ route("automations/git-sync", "routes/automation-git-sync.tsx"),
route("automations/templates", "routes/automation-templates.tsx"),
route("automations/new/:automationId", "routes/automation-setup-route.tsx"),
route("automations/:automationId", "routes/automation-detail.tsx"),
diff --git a/src/routes/automation-git-sync.tsx b/src/routes/automation-git-sync.tsx
new file mode 100644
index 0000000000..9cb2073b4c
--- /dev/null
+++ b/src/routes/automation-git-sync.tsx
@@ -0,0 +1,232 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+import { getApiErrorMessage } from "#/utils/api-error-message";
+import { getErrorStatus } from "#/hooks/query/use-settings";
+import {
+ useGitSyncStatus,
+ useTriggerGitSync,
+} from "#/hooks/query/use-git-sync";
+import { useAutomationHealth } from "#/hooks/query/use-automation-health";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import { useHasPermission } from "#/hooks/use-has-permission";
+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 { 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";
+import { GitSyncConfigForm } from "#/components/features/automations/git-sync/git-sync-config-form";
+import type { GitSyncStatus } from "#/types/git-sync";
+
+// While a cycle is running the status is followed closely, so its result
+// (new commit, dirty count, or error) lands without a page refresh; the idle
+// cadence exists to notice a cycle the backend's own interval started.
+const POLL_INTERVAL_MS = 3_000;
+const IDLE_POLL_INTERVAL_MS = 15_000;
+// How long to keep following a cycle we triggered but have never seen the
+// backend report as running -- the fallback for an automation backend that
+// predates `sync_in_progress`.
+const POLL_WINDOW_MS = 30_000;
+
+type SyncActivity =
+ | { state: "idle" | "succeeded" | "failed" }
+ | {
+ state: "running";
+ startedAt: string;
+ // What the last outcome was when this cycle began: the cycle has landed
+ // once the backend reports a newer success or failure than these.
+ lastSyncedAt: string | null;
+ lastErrorAt: string | null;
+ };
+
+const runningSince = (status: GitSyncStatus): SyncActivity => ({
+ state: "running",
+ startedAt: status.sync_started_at ?? new Date().toISOString(),
+ lastSyncedAt: status.last_synced_at,
+ lastErrorAt: status.last_error_at,
+});
+
+export default function AutomationGitSync() {
+ const { t } = useTranslation("openhands");
+ const active = useActiveBackend();
+ const canManage = useHasPermission("manage_automations");
+ const [activity, setActivity] = useState<SyncActivity>({ state: "idle" });
+ const isRunning = activity.state === "running";
+
+ const {
+ data: healthData,
+ isLoading: isHealthLoading,
+ refetch: refetchHealth,
+ } = useAutomationHealth();
+ const isBackendHealthy = healthData?.status === "ok";
+
+ const isLocalBackend = active.backend.kind === "local";
+
+ const {
+ data: status,
+ isLoading,
+ error,
+ refetch,
+ } = useGitSyncStatus({
+ enabled: isBackendHealthy && isLocalBackend,
+ refetchInterval: isRunning ? POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS,
+ });
+
+ // Follow a cycle this page did not trigger -- the periodic loop's, or
+ // another operator's -- so it shows up here too.
+ useEffect(() => {
+ if (!status?.sync_in_progress) return;
+ setActivity((current) =>
+ current.state === "running" ? current : runningSince(status),
+ );
+ }, [status]);
+
+ // A cycle is done once the backend reports an outcome newer than the one it
+ // started from. That releases the page as soon as the sync really ends,
+ // rather than at the end of a fixed window.
+ useEffect(() => {
+ if (activity.state !== "running" || !status) return;
+ if (status.last_error_at && status.last_error_at !== activity.lastErrorAt) {
+ setActivity({ state: "failed" });
+ } else if (
+ status.last_synced_at &&
+ status.last_synced_at !== activity.lastSyncedAt
+ ) {
+ setActivity({ state: "succeeded" });
+ }
+ }, [status, activity]);
+
+ // Give up on a cycle we never saw the backend confirm. A backend that does
+ // report `sync_in_progress` immediately re-enters the running state above,
+ // so this only bounds the blind case.
+ useEffect(() => {
+ if (!isRunning) return undefined;
+ const timer = setTimeout(
+ () => setActivity({ state: "idle" }),
+ POLL_WINDOW_MS,
+ );
+ return () => clearTimeout(timer);
+ }, [isRunning, activity]);
+
+ const triggerMutation = useTriggerGitSync();
+
+ if (!isLocalBackend) {
+ return (
+ <div className="min-h-full">
+ <div className="p-6 max-w-4xl mx-auto">
+ <GitSyncNotLocalState />
+ </div>
+ </div>
+ );
+ }
+
+ if (isHealthLoading) {
+ return (
+ <div className="min-h-full">
+ <div className="p-6 max-w-4xl mx-auto">
+ <GitSyncSkeleton />
+ </div>
+ </div>
+ );
+ }
+
+ if (!isBackendHealthy) {
+ return (
+ <div className="min-h-full">
+ <div className="p-6 max-w-4xl mx-auto">
+ <BackendNotConfigured onRetry={refetchHealth} />
+ </div>
+ </div>
+ );
+ }
+
+ if (isLoading) {
+ return (
+ <div className="min-h-full">
+ <div className="p-6 max-w-4xl mx-auto">
+ <GitSyncSkeleton />
+ </div>
+ </div>
+ );
+ }
+
+ // A missing status replaces the page; a failure with one still cached does
+ // not. `isError` alone is true for a failed background poll too, and this
+ // page polls every few seconds after a sync -- unmounting on one of those
+ // would throw away whatever is half-typed in the config form below.
+ if (!status) {
+ return (
+ <div className="min-h-full">
+ <div className="p-6 max-w-4xl mx-auto">
+ {getErrorStatus(error) === 404 ? (
+ <GitSyncUnsupportedState />
+ ) : (
+ <ErrorState onRetry={() => refetch()} />
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ const handleSyncNow = () => {
+ triggerMutation.mutate(undefined, {
+ // No success toast: the trigger only means the cycle was scheduled, and
+ // a toast that fires and disappears can't report how it ends. The
+ // activity row in the card follows it through to its outcome instead --
+ // including when `triggered` is false, which means a cycle was already
+ // running and is the one to follow.
+ onSuccess: () => setActivity(runningSince(status)),
+ onError: (error) => {
+ const errorStatus = getErrorStatus(error);
+ displayErrorToast(
+ errorStatus === 503
+ ? t(I18nKey.AUTOMATIONS$GIT_SYNC$SYNC_DISABLED_ERROR)
+ : getApiErrorMessage(error, t(I18nKey.ERROR$GENERIC)),
+ );
+ },
+ });
+ };
+
+ return (
+ <div className="min-h-full">
+ <div className="p-6 max-w-4xl mx-auto">
+ <div className="flex flex-col gap-4">
+ <BackLink />
+ <div>
+ <h1 className="text-xl font-semibold text-content">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$TITLE)}
+ </h1>
+ <p className="mt-1 text-sm text-muted">
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$SUBTITLE)}
+ </p>
+ </div>
+ {status.last_error && (
+ <GitSyncErrorBanner
+ error={status.last_error}
+ errorAt={status.last_error_at}
+ />
+ )}
+ <GitSyncOverviewSection
+ status={status}
+ onSyncNow={handleSyncNow}
+ // The POST returns as soon as the cycle is scheduled, so the
+ // activity state is what tracks the sync actually running.
+ isSyncing={triggerMutation.isPending || isRunning}
+ syncActivity={activity.state}
+ syncStartedAt={isRunning ? activity.startedAt : null}
+ canManage={canManage}
+ />
+ <GitSyncConfigForm
+ status={status}
+ canManage={canManage}
+ onSyncNow={handleSyncNow}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/routes/automations-list.tsx b/src/routes/automations-list.tsx
index 143253ce7c..4d5560736f 100644
--- a/src/routes/automations-list.tsx
+++ b/src/routes/automations-list.tsx
@@ -6,7 +6,7 @@ import {
type ChangeEvent,
type ReactNode,
} from "react";
-import { FileUp } from "lucide-react";
+import { FileUp, RefreshCw } from "lucide-react";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
import {
@@ -24,6 +24,7 @@ import {
} from "#/hooks/query/use-automations";
import { useAutomationHealth } from "#/hooks/query/use-automation-health";
import { useActiveBackend } from "#/contexts/active-backend-context";
+import { useNavigation } from "#/context/navigation-context";
import { SearchInput } from "#/components/features/automations/search-input";
import { AutomationGroup } from "#/components/features/automations/automation-group";
import { AutomationViewToggle } from "#/components/features/automations/automation-view-toggle";
@@ -109,6 +110,7 @@ export default function AutomationsList() {
const importInputRef = useRef<HTMLInputElement>(null);
const active = useActiveBackend();
+ const { navigate } = useNavigation();
// Edit is a local-backend-only feature in MVP — cloud automations
// are managed elsewhere and we don't yet surface them here.
const canEdit = active.backend.kind === "local";
@@ -372,6 +374,18 @@ export default function AutomationsList() {
</p>
</div>
<div className="flex shrink-0 flex-wrap justify-end gap-2">
+ {canEdit && (
+ <BrandButton
+ type="button"
+ variant="secondary"
+ testId="automations-git-sync"
+ className="whitespace-nowrap"
+ onClick={() => navigate?.("/automations/git-sync")}
+ startContent={<RefreshCw className="size-4" aria-hidden />}
+ >
+ {t(I18nKey.AUTOMATIONS$GIT_SYNC$NAV_BUTTON)}
+ </BrandButton>
+ )}
<BrandButton
type="button"
variant="secondary"
diff --git a/src/types/git-sync.ts b/src/types/git-sync.ts
new file mode 100644
index 0000000000..9b4437e588
--- /dev/null
+++ b/src/types/git-sync.ts
@@ -0,0 +1,54 @@
+export interface GitSyncStatus {
+ enabled: boolean;
+ repo_url: string;
+ branch: string;
+ path: string;
+ encryption_enabled: boolean;
+ /** Seconds between automatic syncs; 0 means manual-only. */
+ interval_seconds: number;
+ last_synced_commit: string | null;
+ last_synced_at: string | null;
+ last_error: string | null;
+ last_error_at: string | null;
+ dirty_count: number;
+ /**
+ * Whether a sync cycle is running right now, including one the backend's own
+ * interval started. A cycle reports its outcome only once it ends, so
+ * without this the page cannot tell a sync in flight from one that never
+ * started. Absent on automation backends that predate the field.
+ */
+ sync_in_progress?: boolean;
+ sync_started_at?: string | null;
+}
+
+export interface GitSyncConfigUpdateRequest {
+ enabled?: boolean | null;
+ interval_seconds?: number | null;
+ repo_url?: string | null;
+ branch?: string | null;
+ path?: string | null;
+ token?: string | null;
+ encryption_key?: string | null;
+ author_name?: string | null;
+ author_email?: string | null;
+}
+
+export interface GitSyncTriggerResponse {
+ triggered: boolean;
+}
+
+/**
+ * Whether a configuration can reach its repo, from `POST /v1/git-sync/check`.
+ *
+ * `ok` is about reachability only -- the backend runs a single `git ls-remote`
+ * rather than a sync, so a token without write scope passes here and still
+ * fails at push time, and the encryption key is never exercised.
+ * `branch_exists: false` alongside `ok: true` is normal for a repo that has
+ * never been synced: the first cycle creates the branch.
+ */
+export interface GitSyncCheckResponse {
+ ok: boolean;
+ branch_exists: boolean;
+ /** git's own failure output, with credentials in the URL redacted. */
+ detail: string | null;
+}