Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Restore Git settings with local provider token persistence (#45)

Graham Neubig82f27cc6611f
diff --git a/AGENTS.md b/AGENTS.md
index c5fe9f80f7..990a892253 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -59,6 +59,8 @@
- OpenHands Cloud sandbox development note: do **not** reuse the sandbox's existing agent-server for this frontend. Current agent-server releases use a shared `openhands` tmux socket and default `workspace/conversations`, so a naive second server in the same sandbox can kill the cloud session's tmux state or attach to the same persisted conversations. `npm run dev` is now the recommended local workflow and starts an isolated local agent-server for the checkout by overriding `TMUX_TMPDIR`, `OH_CONVERSATIONS_PATH`, `OH_BASH_EVENTS_DIR`, and `OH_VSCODE_PORT` under `.openhands-dev/`; use `npm run dev:frontend` only when intentionally pointing at a separately managed backend, or `npm run dev:mock` for mock mode.
- A successful end-to-end live run in this environment required a real LLM config (`LLM_MODEL` + `LLM_API_KEY`). The default `litellm_proxy/...` model with no `llm_api_key` failed at runtime with a `litellm.AuthenticationError`.
+- Git provider token persistence note: this direct-agent-server frontend now persists `Settings > Git` provider tokens locally in browser storage instead of posting to an app-backend secrets route. `src/api/secrets-service.ts` writes the token payload to localStorage, mirrors provider hosts into `provider_tokens_set` through `SettingsService.saveSettings()`, and `use-delete-git-providers` clears that local state.
+
- README expectation: keep the first section as a concrete, chronological from-scratch quickstart for running this frontend against a real `openhands-agent-server` (clone, install backend, optional `.env`, run `npm run dev`).
- Keep README user-focused and move contributor/developer-specific workflows (Cloud sandbox debugging, `dev:safe`, mock mode, detailed env vars/build-test notes) into `DEVELOPMENT.md`.
diff --git a/__tests__/api/secrets-service.test.ts b/__tests__/api/secrets-service.test.ts
new file mode 100644
index 0000000000..fb588c98a7
--- /dev/null
+++ b/__tests__/api/secrets-service.test.ts
@@ -0,0 +1,85 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import { SecretsService } from "#/api/secrets-service";
+import { Provider, ProviderToken } from "#/types/settings";
+
+const buildProviders = (
+ overrides: Partial<Record<Provider, ProviderToken>> = {},
+): Record<Provider, ProviderToken> => ({
+ github: { token: "", host: null },
+ gitlab: { token: "", host: null },
+ bitbucket: { token: "", host: null },
+ bitbucket_data_center: { token: "", host: null },
+ azure_devops: { token: "", host: null },
+ forgejo: { token: "", host: null },
+ enterprise_sso: { token: "", host: null },
+ ...overrides,
+});
+
+describe("SecretsService", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ });
+
+ it("stores connected Git providers in local settings", async () => {
+ await expect(
+ SecretsService.addGitProvider(
+ buildProviders({
+ github: {
+ token: "ghp_test_123",
+ host: "github.example.com",
+ },
+ }),
+ ),
+ ).resolves.toBe(true);
+
+ const settings = await SettingsService.getSettings();
+
+ expect(settings.provider_tokens_set).toEqual({
+ github: "github.example.com",
+ });
+ });
+
+ it("preserves an existing provider token when only the host changes", async () => {
+ await SecretsService.addGitProvider(
+ buildProviders({
+ github: {
+ token: "ghp_test_123",
+ host: "github.com",
+ },
+ }),
+ );
+
+ await SecretsService.addGitProvider(
+ buildProviders({
+ github: {
+ token: "",
+ host: "github.internal.example.com",
+ },
+ }),
+ );
+
+ const settings = await SettingsService.getSettings();
+
+ expect(settings.provider_tokens_set).toEqual({
+ github: "github.internal.example.com",
+ });
+ });
+
+ it("clears connected Git providers from local settings", async () => {
+ await SecretsService.addGitProvider(
+ buildProviders({
+ github: {
+ token: "ghp_test_123",
+ host: "github.com",
+ },
+ }),
+ );
+
+ await expect(SecretsService.deleteGitProviders()).resolves.toBe(true);
+
+ const settings = await SettingsService.getSettings();
+
+ expect(settings.provider_tokens_set).toEqual({});
+ });
+});
diff --git a/__tests__/hooks/mutation/use-add-git-providers.test.tsx b/__tests__/hooks/mutation/use-add-git-providers.test.tsx
index 0862dce1ff..f979d768b1 100644
--- a/__tests__/hooks/mutation/use-add-git-providers.test.tsx
+++ b/__tests__/hooks/mutation/use-add-git-providers.test.tsx
@@ -14,10 +14,6 @@ vi.mock("#/hooks/use-tracking", () => ({
}),
}));
-vi.mock("#/context/use-selected-organization", () => ({
- useSelectedOrganizationId: () => ({ organizationId: "org-1" }),
-}));
-
const buildProviders = (
overrides: Partial<Record<Provider, ProviderToken>> = {},
): Record<Provider, ProviderToken> => ({
@@ -48,7 +44,7 @@ describe("useAddGitProviders", () => {
it("invalidates personal settings queries after saving providers", async () => {
vi.spyOn(SecretsService, "addGitProvider").mockResolvedValue(true);
- const personalSettingsQueryKey = ["settings", "personal", "org-1"] as const;
+ const personalSettingsQueryKey = ["settings", "personal"] as const;
queryClient.setQueryData(personalSettingsQueryKey, {
provider_tokens_set: {},
});
diff --git a/__tests__/routes/git-settings.test.tsx b/__tests__/routes/git-settings.test.tsx
index d79af44a1c..d8e9e6d0fe 100644
--- a/__tests__/routes/git-settings.test.tsx
+++ b/__tests__/routes/git-settings.test.tsx
@@ -1,10 +1,10 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { render, screen } from "@testing-library/react";
+import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import GitSettingsScreen, { clientLoader } from "#/routes/git-settings";
import SettingsService from "#/api/settings-service/settings-service.api";
import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
+import GitSettingsScreen, { clientLoader } from "#/routes/git-settings";
import { Settings } from "#/types/settings";
function buildSettings(overrides: Partial<Settings> = {}): Settings {
@@ -68,6 +68,22 @@ describe("GitSettingsScreen", () => {
expect(submitButton).toBeEnabled();
});
+
+ it("enables disconnecting when a provider is already configured", async () => {
+ vi.spyOn(SettingsService, "getSettings").mockResolvedValue(
+ buildSettings({
+ provider_tokens_set: {
+ github: "github.com",
+ },
+ }),
+ );
+
+ renderGitSettingsScreen();
+
+ await waitFor(() => {
+ expect(screen.getByTestId("disconnect-tokens-button")).toBeEnabled();
+ });
+ });
});
describe("clientLoader permission checks", () => {
diff --git a/src/api/secrets-service.ts b/src/api/secrets-service.ts
index dbd755b77c..f1dfc00805 100644
--- a/src/api/secrets-service.ts
+++ b/src/api/secrets-service.ts
@@ -1,12 +1,88 @@
+import SettingsService from "./settings-service/settings-service.api";
import { openHands } from "./open-hands-axios";
import {
CustomSecret,
CustomSecretPage,
CustomSecretWithoutValue,
- POSTProviderTokens,
SearchSecretsParams,
} from "./secrets-service.types";
-import { Provider, ProviderToken } from "#/types/settings";
+import { Provider, ProviderOptions, ProviderToken } from "#/types/settings";
+
+const GIT_PROVIDER_STORAGE_KEY = "openhands-agent-server-git-provider-tokens";
+
+type StoredGitProviderTokens = Partial<Record<Provider, ProviderToken>>;
+
+const normalizeHost = (host: string | null | undefined): string | null => {
+ const trimmed = typeof host === "string" ? host.trim() : "";
+ return trimmed.length > 0 ? trimmed : null;
+};
+
+const readStoredGitProviders = (): StoredGitProviderTokens => {
+ if (typeof window === "undefined") {
+ return {};
+ }
+
+ try {
+ const raw = window.localStorage.getItem(GIT_PROVIDER_STORAGE_KEY);
+ if (!raw) {
+ return {};
+ }
+
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
+ if (!parsed || typeof parsed !== "object") {
+ return {};
+ }
+
+ return Object.fromEntries(
+ Object.entries(parsed).flatMap(([provider, value]) => {
+ if (!(provider in ProviderOptions) || !value || typeof value !== "object") {
+ return [];
+ }
+
+ const token =
+ typeof (value as ProviderToken).token === "string"
+ ? (value as ProviderToken).token.trim()
+ : "";
+
+ if (!token) {
+ return [];
+ }
+
+ return [
+ [
+ provider,
+ {
+ token,
+ host: normalizeHost((value as ProviderToken).host),
+ },
+ ],
+ ];
+ }),
+ ) as StoredGitProviderTokens;
+ } catch {
+ return {};
+ }
+};
+
+const writeStoredGitProviders = (providers: StoredGitProviderTokens) => {
+ if (typeof window === "undefined") {
+ return;
+ }
+
+ if (Object.keys(providers).length === 0) {
+ window.localStorage.removeItem(GIT_PROVIDER_STORAGE_KEY);
+ return;
+ }
+
+ window.localStorage.setItem(GIT_PROVIDER_STORAGE_KEY, JSON.stringify(providers));
+};
+
+const buildProviderTokensSet = (
+ providers: StoredGitProviderTokens,
+): Partial<Record<Provider, string | null>> =>
+ Object.fromEntries(
+ Object.entries(providers).map(([provider, value]) => [provider, value?.host ?? null]),
+ ) as Partial<Record<Provider, string | null>>;
export class SecretsService {
/**
@@ -39,13 +115,10 @@ export class SecretsService {
* @deprecated Use searchSecrets instead. This method uses the deprecated V0 API.
*/
static async getSecrets(): Promise<CustomSecretWithoutValue[]> {
- // Fetch all secrets by iterating through pages
const allSecrets: CustomSecretWithoutValue[] = [];
let pageId: string | null = null;
- // eslint-disable-next-line no-await-in-loop
for (;;) {
- // eslint-disable-next-line no-await-in-loop
const page = await SecretsService.searchSecrets({
page_id: pageId ?? undefined,
limit: 100,
@@ -84,14 +157,41 @@ export class SecretsService {
return status === 200;
}
- static async addGitProvider(providers: Record<Provider, ProviderToken>) {
- const tokens: POSTProviderTokens = {
- provider_tokens: providers,
- };
- const { data } = await openHands.post<boolean>(
- "/api/v1/secrets/git-providers",
- tokens,
- );
- return data;
+ static async addGitProvider(
+ providers: Partial<Record<Provider, ProviderToken>>,
+ ): Promise<boolean> {
+ const storedProviders = readStoredGitProviders();
+ const nextProviders: StoredGitProviderTokens = { ...storedProviders };
+
+ for (const [provider, value] of Object.entries(providers) as [
+ Provider,
+ ProviderToken,
+ ][]) {
+ const token = value.token.trim();
+ const host = normalizeHost(value.host);
+
+ if (token) {
+ nextProviders[provider] = { token, host };
+ continue;
+ }
+
+ const existing = nextProviders[provider];
+ if (existing) {
+ nextProviders[provider] = {
+ token: existing.token,
+ host,
+ };
+ }
+ }
+
+ writeStoredGitProviders(nextProviders);
+ return SettingsService.saveSettings({
+ provider_tokens_set: buildProviderTokensSet(nextProviders),
+ });
+ }
+
+ static async deleteGitProviders(): Promise<boolean> {
+ writeStoredGitProviders({});
+ return SettingsService.saveSettings({ provider_tokens_set: {} });
}
}
diff --git a/src/api/secrets-service.types.ts b/src/api/secrets-service.types.ts
index 44faba23db..6998aa0843 100644
--- a/src/api/secrets-service.types.ts
+++ b/src/api/secrets-service.types.ts
@@ -1,5 +1,3 @@
-import { Provider, ProviderToken } from "#/types/settings";
-
export type CustomSecret = {
name: string;
value: string;
@@ -19,10 +17,6 @@ export interface GetSecretsResponse {
custom_secrets: CustomSecretWithoutValue[];
}
-export interface POSTProviderTokens {
- provider_tokens: Record<Provider, ProviderToken>;
-}
-
export interface SearchSecretsParams {
name__contains?: string;
page_id?: string;
diff --git a/src/hooks/mutation/use-add-git-providers.ts b/src/hooks/mutation/use-add-git-providers.ts
index b902ffc73f..8d3c79603f 100644
--- a/src/hooks/mutation/use-add-git-providers.ts
+++ b/src/hooks/mutation/use-add-git-providers.ts
@@ -11,11 +11,11 @@ export const useAddGitProviders = () => {
mutationFn: ({
providers,
}: {
- providers: Record<Provider, ProviderToken>;
+ providers: Partial<Record<Provider, ProviderToken>>;
}) => SecretsService.addGitProvider(providers),
onSuccess: async (_, { providers }) => {
const connectedProviders = Object.entries(providers)
- .filter(([, value]) => value.token && value.token.trim() !== "")
+ .filter(([, value]) => value?.token && value.token.trim() !== "")
.map(([key]) => key);
if (connectedProviders.length > 0) {
diff --git a/src/hooks/mutation/use-delete-git-providers.ts b/src/hooks/mutation/use-delete-git-providers.ts
new file mode 100644
index 0000000000..5c6efd1427
--- /dev/null
+++ b/src/hooks/mutation/use-delete-git-providers.ts
@@ -0,0 +1,18 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { SecretsService } from "#/api/secrets-service";
+
+export const useDeleteGitProviders = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: () => SecretsService.deleteGitProviders(),
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: ["settings", "personal"],
+ });
+ },
+ meta: {
+ disableToast: true,
+ },
+ });
+};
diff --git a/src/mocks/settings-handlers.ts b/src/mocks/settings-handlers.ts
index 6d52a8fb2a..20b7d80223 100644
--- a/src/mocks/settings-handlers.ts
+++ b/src/mocks/settings-handlers.ts
@@ -1,7 +1,7 @@
import { http, delay, HttpResponse } from "msw";
import { WebClientConfig } from "#/api/option-service/option.types";
import { DEFAULT_SETTINGS } from "#/services/settings";
-import { Provider, Settings, SettingsValue } from "#/types/settings";
+import { Settings, SettingsValue } from "#/types/settings";
/** Simple recursive merge β€” objects merge, scalars overwrite. */
function deepMerge(
@@ -567,30 +567,4 @@ export const SETTINGS_HANDLERS = [
return HttpResponse.json(null, { status: 400 });
}),
- http.post("/api/add-git-providers", async ({ request }) => {
- const body = await request.json();
-
- if (typeof body === "object" && body?.provider_tokens) {
- const rawTokens = body.provider_tokens as Record<
- string,
- { token?: string }
- >;
-
- const providerTokensSet: Partial<Record<Provider, string | null>> =
- Object.fromEntries(
- Object.entries(rawTokens)
- .filter(([, val]) => val?.token)
- .map(([provider]) => [provider as Provider, ""]),
- );
-
- MOCK_USER_PREFERENCES.settings = {
- ...(MOCK_USER_PREFERENCES.settings || MOCK_DEFAULT_USER_SETTINGS),
- provider_tokens_set: providerTokensSet,
- };
-
- return HttpResponse.json(true, { status: 200 });
- }
-
- return HttpResponse.json(null, { status: 400 });
- }),
];
diff --git a/src/routes/git-settings.tsx b/src/routes/git-settings.tsx
index 0389bfc5e0..3b4ae9d944 100644
--- a/src/routes/git-settings.tsx
+++ b/src/routes/git-settings.tsx
@@ -4,7 +4,6 @@ import { useConfig } from "#/hooks/query/use-config";
import { createPermissionGuard } from "#/utils/org/permission-guard";
import { useSettings } from "#/hooks/query/use-settings";
import { BrandButton } from "#/components/features/settings/brand-button";
-import { useLogout } from "#/hooks/mutation/use-logout";
import { GitHubTokenInput } from "#/components/features/settings/git-settings/github-token-input";
import { GitLabTokenInput } from "#/components/features/settings/git-settings/gitlab-token-input";
import { BitbucketTokenInput } from "#/components/features/settings/git-settings/bitbucket-token-input";
@@ -19,8 +18,10 @@ import {
import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";
import { GitSettingInputsSkeleton } from "#/components/features/settings/git-settings/github-settings-inputs-skeleton";
import { useAddGitProviders } from "#/hooks/mutation/use-add-git-providers";
+import { useDeleteGitProviders } from "#/hooks/mutation/use-delete-git-providers";
import { useUserProviders } from "#/hooks/use-user-providers";
import { ProjectManagementIntegration } from "#/components/features/settings/project-management/project-management-integration";
+import { Provider, ProviderToken } from "#/types/settings";
export const clientLoader = createPermissionGuard("manage_integrations");
@@ -28,7 +29,8 @@ function GitSettingsScreen() {
const { t } = useTranslation();
const { mutate: saveGitProviders, isPending } = useAddGitProviders();
- const { mutate: disconnectGitTokens } = useLogout();
+ const { mutate: disconnectGitTokens, isPending: isDisconnecting } =
+ useDeleteGitProviders();
const { data: settings, isLoading } = useSettings();
const { providers } = useUserProviders();
@@ -80,48 +82,44 @@ function GitSettingsScreen() {
formData.get("disconnect-tokens-button") !== null;
if (disconnectButtonClicked) {
- disconnectGitTokens();
+ disconnectGitTokens(undefined, {
+ onSuccess: () => {
+ displaySuccessToast(t(I18nKey.SETTINGS$SAVED));
+ },
+ onError: (error) => {
+ const errorMessage = retrieveAxiosErrorMessage(error);
+ displayErrorToast(errorMessage || t(I18nKey.ERROR$GENERIC));
+ },
+ });
return;
}
- const githubToken = (
- formData.get("github-token-input")?.toString() || ""
- ).trim();
- const gitlabToken = (
- formData.get("gitlab-token-input")?.toString() || ""
- ).trim();
- const bitbucketToken = (
- formData.get("bitbucket-token-input")?.toString() || ""
- ).trim();
- const bitbucketDCToken = (
- formData.get("bitbucket-dc-token-input")?.toString() || ""
- ).trim();
- const azureDevOpsToken = (
- formData.get("azure-devops-token-input")?.toString() || ""
- ).trim();
- const forgejoToken = (
- formData.get("forgejo-token-input")?.toString() || ""
- ).trim();
- const githubHost = (
- formData.get("github-host-input")?.toString() || ""
- ).trim();
- const gitlabHost = (
- formData.get("gitlab-host-input")?.toString() || ""
- ).trim();
- const bitbucketHost = (
- formData.get("bitbucket-host-input")?.toString() || ""
- ).trim();
- const bitbucketDCHost = (
- formData.get("bitbucket-dc-host-input")?.toString() || ""
- ).trim();
- const azureDevOpsHost = (
- formData.get("azure-devops-host-input")?.toString() || ""
- ).trim();
- const forgejoHost = (
- formData.get("forgejo-host-input")?.toString() || ""
- ).trim();
+ const githubToken =
+ (formData.get("github-token-input")?.toString() || "").trim();
+ const gitlabToken =
+ (formData.get("gitlab-token-input")?.toString() || "").trim();
+ const bitbucketToken =
+ (formData.get("bitbucket-token-input")?.toString() || "").trim();
+ const bitbucketDCToken =
+ (formData.get("bitbucket-dc-token-input")?.toString() || "").trim();
+ const azureDevOpsToken =
+ (formData.get("azure-devops-token-input")?.toString() || "").trim();
+ const forgejoToken =
+ (formData.get("forgejo-token-input")?.toString() || "").trim();
+ const githubHost =
+ (formData.get("github-host-input")?.toString() || "").trim();
+ const gitlabHost =
+ (formData.get("gitlab-host-input")?.toString() || "").trim();
+ const bitbucketHost =
+ (formData.get("bitbucket-host-input")?.toString() || "").trim();
+ const bitbucketDCHost =
+ (formData.get("bitbucket-dc-host-input")?.toString() || "").trim();
+ const azureDevOpsHost =
+ (formData.get("azure-devops-host-input")?.toString() || "").trim();
+ const forgejoHost =
+ (formData.get("forgejo-host-input")?.toString() || "").trim();
- const providerTokens: Record<string, { token: string; host: string }> = {
+ const providerTokens: Partial<Record<Provider, ProviderToken>> = {
github: { token: githubToken, host: githubHost },
gitlab: { token: gitlabToken, host: gitlabHost },
bitbucket: { token: bitbucketToken, host: bitbucketHost },
@@ -276,12 +274,13 @@ function GitSettingsScreen() {
type="submit"
variant="secondary"
isDisabled={
- !isGitHubTokenSet &&
- !isGitLabTokenSet &&
- !isBitbucketTokenSet &&
- !isBitbucketDCTokenSet &&
- !isAzureDevOpsTokenSet &&
- !isForgejoTokenSet
+ isDisconnecting ||
+ (!isGitHubTokenSet &&
+ !isGitLabTokenSet &&
+ !isBitbucketTokenSet &&
+ !isBitbucketDCTokenSet &&
+ !isAzureDevOpsTokenSet &&
+ !isForgejoTokenSet)
}
>
{t(I18nKey.GIT$DISCONNECT_TOKENS)}
@@ -290,7 +289,7 @@ function GitSettingsScreen() {
testId="submit-button"
type="submit"
variant="primary"
- isDisabled={isPending || formIsClean}
+ isDisabled={isPending || isDisconnecting || formIsClean}
>
{!isPending && t("SETTINGS$SAVE_CHANGES")}
{isPending && t("SETTINGS$SAVING")}