Skip to content

πŸ™Œ OpenHands: AI-Driven Development

refactor: remove dead integrations page and third-party Git API layer (#367)

Hiep Le68c9b77147b8
diff --git a/__tests__/api/cloud/suggestions-service.test.ts b/__tests__/api/cloud/suggestions-service.test.ts
new file mode 100644
index 0000000000..b71b3ee42d
--- /dev/null
+++ b/__tests__/api/cloud/suggestions-service.test.ts
@@ -0,0 +1,48 @@
+import axios from "axios";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import { getCloudSuggestedTasks } from "#/api/cloud/suggestions-service.api";
+import type { Backend } from "#/api/backend-registry/types";
+
+vi.mock("axios");
+
+const cloudBackend: Backend = {
+ id: "prod",
+ name: "Production",
+ host: "https://app.all-hands.dev",
+ apiKey: "bearer-token",
+ kind: "cloud",
+};
+
+beforeEach(() => {
+ __resetActiveStoreForTests();
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+ vi.mocked(axios.post).mockReset();
+ vi.mocked(axios.post).mockResolvedValue({
+ data: { items: [], next_page_id: null },
+ });
+});
+
+afterEach(() => {
+ __resetActiveStoreForTests();
+ vi.mocked(axios.post).mockReset();
+});
+
+describe("getCloudSuggestedTasks", () => {
+ it("forwards limit and pageId to the upstream /api/v1/git/suggested-tasks/search endpoint", async () => {
+ // Act
+ await getCloudSuggestedTasks({ limit: 10, pageId: "p2" });
+
+ // Assert
+ const [, body] = vi.mocked(axios.post).mock.calls[0]!;
+ const path = (body as { path: string }).path;
+ expect(path).toContain("/api/v1/git/suggested-tasks/search");
+ expect(path).toContain("limit=10");
+ expect(path).toContain("page_id=p2");
+ });
+});
diff --git a/__tests__/api/git-providers/git-service-wiring.test.ts b/__tests__/api/git-providers/git-service-wiring.test.ts
deleted file mode 100644
index 639d7fca0d..0000000000
--- a/__tests__/api/git-providers/git-service-wiring.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { http, HttpResponse } from "msw";
-import { server } from "#/mocks/node";
-import GitService from "#/api/git-service/git-service.api";
-
-const writeProviders = (
- providers: Record<string, { token: string; host: string | null }>,
-) => {
- window.localStorage.setItem(
- "openhands-agent-server-git-provider-tokens",
- JSON.stringify(providers),
- );
-};
-
-describe("GitService legacy contract", () => {
- beforeEach(() => {
- window.localStorage.clear();
- server.resetHandlers();
- });
- afterEach(() => {
- window.localStorage.clear();
- server.resetHandlers();
- });
-
- it("searchGitRepositories scopes the GitHub query to the user's own repos and orgs", async () => {
- writeProviders({ github: { token: "ghp_test", host: null } });
- server.use(
- http.get("https://api.github.com/user", () =>
- HttpResponse.json({ id: 1, login: "octocat" }),
- ),
- http.get("https://api.github.com/user/orgs", () => HttpResponse.json([])),
- http.get(
- "https://api.github.com/search/repositories",
- ({ request }) => {
- const q = new URL(request.url).searchParams.get("q") ?? "";
- // Only the scoped query should ever execute; bare "react" is what
- // returned global popular repos before the fix.
- expect(q).toBe("in:name react user:octocat");
- return HttpResponse.json({
- items: [
- {
- id: 100,
- full_name: "octocat/react-app",
- private: false,
- default_branch: "main",
- },
- {
- id: 101,
- full_name: "octocat/react-utils",
- private: true,
- default_branch: "main",
- },
- ],
- });
- },
- ),
- );
-
- const page = await GitService.searchGitRepositories("react", "github", 30);
-
- expect(page.items.map((repo) => repo.full_name)).toEqual([
- "octocat/react-app",
- "octocat/react-utils",
- ]);
- expect(page.items.every((repo) => repo.git_provider === "github")).toBe(true);
- });
-});
diff --git a/__tests__/api/git-providers/github-service.test.ts b/__tests__/api/git-providers/github-service.test.ts
deleted file mode 100644
index ebc8e2ab92..0000000000
--- a/__tests__/api/git-providers/github-service.test.ts
+++ /dev/null
@@ -1,334 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { http, HttpResponse } from "msw";
-import { server } from "#/mocks/node";
-import { GitHubService } from "#/api/git-providers/github-service";
-
-const buildService = (host: string | null = null) =>
- new GitHubService({ token: "ghp_test_token", host });
-
-describe("GitHubService", () => {
- beforeEach(() => {
- server.resetHandlers();
- });
- afterEach(() => {
- server.resetHandlers();
- });
-
- it("getUser falls back to /user/emails when /user payload omits email", async () => {
- server.use(
- http.get("https://api.github.com/user", () =>
- HttpResponse.json({
- id: 4711,
- login: "octocat",
- avatar_url: "https://avatars.example/octocat.png",
- company: "GitHub",
- name: "The Octocat",
- email: null,
- }),
- ),
- http.get("https://api.github.com/user/emails", () =>
- HttpResponse.json([
- { email: "[email protected]", primary: false, verified: true },
- { email: "[email protected]", primary: true, verified: true },
- ]),
- ),
- );
-
- const user = await buildService().getUser();
-
- expect(user).toEqual({
- id: "4711",
- login: "octocat",
- avatar_url: "https://avatars.example/octocat.png",
- company: "GitHub",
- name: "The Octocat",
- email: "[email protected]",
- });
- });
-
- it("getSuggestedTasks discriminates conflict / failure / review-comment / open-issue", async () => {
- let graphqlCalls = 0;
- server.use(
- http.get("https://api.github.com/user", () =>
- HttpResponse.json({ id: 1, login: "octocat" }),
- ),
- http.post("https://api.github.com/graphql", async () => {
- graphqlCalls += 1;
- if (graphqlCalls === 1) {
- return HttpResponse.json({
- data: {
- user: {
- pullRequests: {
- nodes: [
- {
- number: 1,
- title: "Conflict PR",
- repository: { nameWithOwner: "octocat/repo" },
- mergeable: "CONFLICTING",
- commits: { nodes: [] },
- reviews: { nodes: [] },
- },
- {
- number: 2,
- title: "Failing PR",
- repository: { nameWithOwner: "octocat/repo" },
- mergeable: "MERGEABLE",
- commits: {
- nodes: [
- {
- commit: {
- statusCheckRollup: { state: "FAILURE" },
- },
- },
- ],
- },
- reviews: { nodes: [] },
- },
- {
- number: 3,
- title: "Reviewed PR",
- repository: { nameWithOwner: "octocat/repo" },
- mergeable: "MERGEABLE",
- commits: {
- nodes: [
- {
- commit: {
- statusCheckRollup: { state: "SUCCESS" },
- },
- },
- ],
- },
- reviews: { nodes: [{ state: "CHANGES_REQUESTED" }] },
- },
- {
- number: 4,
- title: "Plain open PR",
- repository: { nameWithOwner: "octocat/repo" },
- mergeable: "MERGEABLE",
- commits: { nodes: [] },
- reviews: { nodes: [] },
- },
- ],
- },
- },
- },
- });
- }
- return HttpResponse.json({
- data: {
- user: {
- issues: {
- nodes: [
- {
- number: 5,
- title: "Investigate flake",
- repository: { nameWithOwner: "octocat/repo" },
- },
- ],
- },
- },
- },
- });
- }),
- );
-
- const tasks = await buildService().getSuggestedTasks();
-
- expect(tasks).toEqual([
- {
- git_provider: "github",
- task_type: "MERGE_CONFLICTS",
- repo: "octocat/repo",
- issue_number: 1,
- title: "Conflict PR",
- },
- {
- git_provider: "github",
- task_type: "FAILING_CHECKS",
- repo: "octocat/repo",
- issue_number: 2,
- title: "Failing PR",
- },
- {
- git_provider: "github",
- task_type: "UNRESOLVED_COMMENTS",
- repo: "octocat/repo",
- issue_number: 3,
- title: "Reviewed PR",
- },
- {
- git_provider: "github",
- task_type: "OPEN_ISSUE",
- repo: "octocat/repo",
- issue_number: 5,
- title: "Investigate flake",
- },
- ]);
- });
-
- it("searchRepositories paginates user repositories using the Link header", async () => {
- let firstPage = true;
- server.use(
- http.get("https://api.github.com/user/repos", ({ request }) => {
- const params = new URL(request.url).searchParams;
- const page = params.get("page");
- if (firstPage) {
- firstPage = false;
- return HttpResponse.json(
- [
- {
- id: 1,
- full_name: "octocat/repo-1",
- default_branch: "main",
- private: false,
- pushed_at: "2025-01-01T00:00:00Z",
- },
- {
- id: 2,
- full_name: "octocat/repo-2",
- default_branch: "main",
- private: true,
- },
- ],
- {
- headers: {
- Link: '<https://api.github.com/user/repos?page=2>; rel="next"',
- },
- },
- );
- }
- expect(page).toBe("2");
- return HttpResponse.json([
- {
- id: 3,
- full_name: "octocat/repo-3",
- default_branch: "trunk",
- private: false,
- },
- ]);
- }),
- );
-
- const service = buildService();
- const first = await service.searchRepositories({ limit: 2 });
-
- expect(first.items.map((repo) => repo.full_name)).toEqual([
- "octocat/repo-1",
- "octocat/repo-2",
- ]);
- expect(first.next_page_id).not.toBeNull();
-
- const second = await service.searchRepositories({
- limit: 2,
- pageId: first.next_page_id ?? undefined,
- });
-
- expect(second.items.map((repo) => repo.full_name)).toEqual(["octocat/repo-3"]);
- expect(second.next_page_id).toBeNull();
- });
-
- it("getBranches maps the GitHub branches response into BranchPage", async () => {
- server.use(
- http.get("https://api.github.com/repos/octocat/repo/branches", () =>
- HttpResponse.json([
- {
- name: "main",
- commit: {
- sha: "deadbeef",
- commit: { committer: { date: "2025-04-01T00:00:00Z" } },
- },
- protected: true,
- },
- ]),
- ),
- );
-
- const branches = await buildService().getBranches({
- repository: "octocat/repo",
- limit: 30,
- });
-
- expect(branches.items).toEqual([
- {
- name: "main",
- commit_sha: "deadbeef",
- protected: true,
- last_push_date: "2025-04-01T00:00:00Z",
- },
- ]);
- });
-
- it("scopes searchRepositories to the user's own repos and orgs (no global GitHub search)", async () => {
- const observedQs: string[] = [];
- server.use(
- http.get("https://api.github.com/user", () =>
- HttpResponse.json({ id: 1, login: "octocat" }),
- ),
- http.get("https://api.github.com/user/orgs", () =>
- HttpResponse.json([{ login: "acme-co" }]),
- ),
- http.get(
- "https://api.github.com/search/repositories",
- ({ request }) => {
- const q = new URL(request.url).searchParams.get("q") ?? "";
- observedQs.push(q);
- if (q.includes("user:octocat")) {
- return HttpResponse.json({
- items: [
- { id: 10, full_name: "octocat/test-helpers", private: true },
- ],
- });
- }
- if (q.includes("org:acme-co")) {
- return HttpResponse.json({
- items: [
- { id: 20, full_name: "acme-co/test-runner", private: false },
- // duplicate id from another sub-query β€” should be deduped
- { id: 10, full_name: "octocat/test-helpers", private: true },
- ],
- });
- }
- return HttpResponse.json({ items: [] });
- },
- ),
- );
-
- const page = await buildService().searchRepositories({
- query: "test",
- limit: 30,
- });
-
- expect(observedQs).toEqual(
- expect.arrayContaining([
- "in:name test user:octocat",
- "org:acme-co in:name test",
- ]),
- );
- // Crucially, NO bare `q=test` request should ever fire.
- expect(observedQs).not.toContain("test");
- expect(page.items.map((repo) => repo.full_name)).toEqual([
- "octocat/test-helpers",
- "acme-co/test-runner",
- ]);
- });
-
- it("uses the Enterprise base URL when host is configured", async () => {
- let calledUrl = "";
- server.use(
- http.get(
- "https://github.example.com/api/v3/user",
- ({ request }) => {
- calledUrl = request.url;
- return HttpResponse.json({ id: 1, login: "ghe-user" });
- },
- ),
- );
-
- await new GitHubService({
- token: "ghp_x",
- host: "github.example.com",
- }).getUser();
-
- expect(calledUrl).toBe("https://github.example.com/api/v3/user");
- });
-});
diff --git a/__tests__/api/git-providers/non-github-services.test.ts b/__tests__/api/git-providers/non-github-services.test.ts
deleted file mode 100644
index 2c4facc360..0000000000
--- a/__tests__/api/git-providers/non-github-services.test.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { afterEach, describe, expect, it } from "vitest";
-import { http, HttpResponse } from "msw";
-import { server } from "#/mocks/node";
-import { GitLabService } from "#/api/git-providers/gitlab-service";
-import { BitbucketService } from "#/api/git-providers/bitbucket-service";
-import { BitbucketDataCenterService } from "#/api/git-providers/bitbucket-dc-service";
-import { AzureDevOpsService } from "#/api/git-providers/azure-devops-service";
-import { ForgejoService } from "#/api/git-providers/forgejo-service";
-
-afterEach(() => {
- server.resetHandlers();
-});
-
-describe("GitLabService.getUser", () => {
- it("maps GitLab /user payload into GitUser", async () => {
- server.use(
- http.get("https://gitlab.com/api/v4/user", () =>
- HttpResponse.json({
- id: 17,
- username: "glab-user",
- avatar_url: "https://gitlab.example/avatar.png",
- name: "GLab User",
- email: "[email protected]",
- organization: "GitLab Inc",
- }),
- ),
- );
-
- const user = await new GitLabService({ token: "glpat", host: null }).getUser();
-
- expect(user).toMatchObject({
- id: "17",
- login: "glab-user",
- email: "[email protected]",
- company: "GitLab Inc",
- });
- });
-});
-
-describe("BitbucketService.getUser", () => {
- it("uses the Cloud /user response and the primary email fallback", async () => {
- server.use(
- http.get("https://api.bitbucket.org/2.0/user", () =>
- HttpResponse.json({
- account_id: "acc-1",
- username: "bbuser",
- display_name: "Bitbucket User",
- links: { avatar: { href: "https://bb.example/a.png" } },
- }),
- ),
- http.get("https://api.bitbucket.org/2.0/user/emails", () =>
- HttpResponse.json({
- values: [
- { email: "[email protected]", is_primary: true, is_confirmed: true },
- ],
- }),
- ),
- );
-
- const user = await new BitbucketService({
- token: "bbtoken",
- host: null,
- }).getUser();
-
- expect(user).toMatchObject({
- id: "acc-1",
- login: "bbuser",
- email: "[email protected]",
- });
- });
-});
-
-describe("BitbucketDataCenterService.getUser", () => {
- it("returns an empty profile placeholder until OAuth is wired", async () => {
- const user = await new BitbucketDataCenterService({
- token: "bbdc",
- host: "bitbucket.example",
- }).getUser();
-
- expect(user).toEqual({
- id: "",
- login: "",
- avatar_url: "",
- name: null,
- email: null,
- company: null,
- });
- });
-});
-
-describe("AzureDevOpsService.getUser", () => {
- it("maps the Azure DevOps profile endpoint into GitUser", async () => {
- server.use(
- http.get(
- "https://app.vssps.visualstudio.com/_apis/profile/profiles/me",
- () =>
- HttpResponse.json({
- id: "az-1",
- displayName: "Az User",
- emailAddress: "[email protected]",
- }),
- ),
- );
-
- const user = await new AzureDevOpsService({
- token: "azpat",
- host: null,
- }).getUser();
-
- expect(user).toMatchObject({
- id: "az-1",
- login: "Az User",
- email: "[email protected]",
- });
- });
-});
-
-describe("ForgejoService.getUser", () => {
- it("maps Forgejo /user into GitUser via the configured host", async () => {
- server.use(
- http.get("https://forgejo.example.com/api/v1/user", () =>
- HttpResponse.json({
- id: 5,
- username: "fjuser",
- avatar_url: "https://forgejo.example.com/avatar.png",
- full_name: "Forgejo User",
- email: "[email protected]",
- }),
- ),
- );
-
- const user = await new ForgejoService({
- token: "fjtoken",
- host: "forgejo.example.com",
- }).getUser();
-
- expect(user).toMatchObject({
- id: "5",
- login: "fjuser",
- email: "[email protected]",
- name: "Forgejo User",
- });
- });
-});
diff --git a/__tests__/api/git-providers/paging-utils.test.ts b/__tests__/api/git-providers/paging-utils.test.ts
deleted file mode 100644
index 89a62d4d6a..0000000000
--- a/__tests__/api/git-providers/paging-utils.test.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- decodePageId,
- encodePageId,
- paginateResults,
-} from "#/api/git-providers/paging-utils";
-
-describe("paging-utils", () => {
- it("round-trips offsets through opaque base64 page ids", () => {
- const encoded = encodePageId(42);
-
- expect(encoded).not.toBe("42"); // opaque, not a raw int
- expect(decodePageId(encoded)).toBe(42);
- expect(decodePageId(null)).toBeNull();
- expect(decodePageId("not-base64-???")).toBeNull();
- });
-
- it("paginates fully-loaded lists with limit+1 next-page semantics", () => {
- const items = ["a", "b", "c", "d", "e"];
-
- const firstPage = paginateResults(items, null, 2);
-
- expect(firstPage.items).toEqual(["a", "b"]);
- expect(firstPage.next_page_id).not.toBeNull();
-
- const secondPage = paginateResults(items, firstPage.next_page_id, 2);
- const lastPage = paginateResults(items, secondPage.next_page_id, 2);
-
- expect(secondPage.items).toEqual(["c", "d"]);
- expect(lastPage.items).toEqual(["e"]);
- expect(lastPage.next_page_id).toBeNull();
- });
-});
diff --git a/__tests__/api/git-providers/provider-handler.test.ts b/__tests__/api/git-providers/provider-handler.test.ts
deleted file mode 100644
index c30b0048d3..0000000000
--- a/__tests__/api/git-providers/provider-handler.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { http, HttpResponse } from "msw";
-import { server } from "#/mocks/node";
-import {
- GitProviderAuthError,
- ProviderHandler,
-} from "#/api/git-providers/provider-handler";
-
-const writeProviders = (
- providers: Record<string, { token: string; host: string | null }>,
-) => {
- window.localStorage.setItem(
- "openhands-agent-server-git-provider-tokens",
- JSON.stringify(providers),
- );
-};
-
-describe("ProviderHandler", () => {
- beforeEach(() => {
- window.localStorage.clear();
- server.resetHandlers();
- });
- afterEach(() => {
- server.resetHandlers();
- window.localStorage.clear();
- });
-
- it("aggregates suggested tasks across every configured provider", async () => {
- writeProviders({
- github: { token: "ghp_test", host: null },
- gitlab: { token: "glpat_test", host: null },
- });
-
- let githubCall = 0;
- server.use(
- http.get("https://api.github.com/user", () =>
- HttpResponse.json({ id: 1, login: "octocat" }),
- ),
- http.post("https://api.github.com/graphql", () => {
- githubCall += 1;
- if (githubCall === 1) {
- return HttpResponse.json({
- data: {
- user: {
- pullRequests: {
- nodes: [
- {
- number: 1,
- title: "GH conflict",
- repository: { nameWithOwner: "octocat/r" },
- mergeable: "CONFLICTING",
- commits: { nodes: [] },
- reviews: { nodes: [] },
- },
- ],
- },
- },
- },
- });
- }
- return HttpResponse.json({ data: { user: { issues: { nodes: [] } } } });
- }),
- http.get("https://gitlab.com/api/v4/user", () =>
- HttpResponse.json({ id: 99, username: "glab-user" }),
- ),
- http.post("https://gitlab.com/api/graphql", () =>
- HttpResponse.json({
- data: {
- currentUser: {
- authoredMergeRequests: {
- nodes: [
- {
- iid: "7",
- title: "GL conflict",
- project: { fullPath: "glab-user/r" },
- conflicts: true,
- pipelines: { nodes: [] },
- discussions: { nodes: [] },
- },
- ],
- },
- },
- },
- }),
- ),
- http.get("https://gitlab.com/api/v4/issues", () => HttpResponse.json([])),
- );
-
- const page = await ProviderHandler.getSuggestedTasks(undefined, 30);
-
- expect(page.items).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ git_provider: "github", repo: "octocat/r" }),
- expect.objectContaining({ git_provider: "gitlab", repo: "glab-user/r" }),
- ]),
- );
- expect(page.items).toHaveLength(2);
- expect(page.next_page_id).toBeNull();
- });
-
- it("returns null when no providers are configured (no throw)", async () => {
- // Switching from cloud β†’ local while settings is briefly stale
- // would otherwise hit this code path with no local tokens. Throwing
- // surfaces as a global error toast β€” returning null lets the caller
- // (`useGitUser`) render an empty user-info state instead.
- const result = await ProviderHandler.getUserGitInfo();
- expect(result).toBeNull();
- });
-
- it("still throws GitProviderAuthError when an explicit provider is requested but missing", async () => {
- await expect(
- ProviderHandler.getUserGitInfo("github"),
- ).rejects.toBeInstanceOf(GitProviderAuthError);
- });
-});
diff --git a/__tests__/api/git-service.test.ts b/__tests__/api/git-service.test.ts
index 34d319c127..57ba9496f4 100644
--- a/__tests__/api/git-service.test.ts
+++ b/__tests__/api/git-service.test.ts
@@ -1,26 +1,14 @@
import { describe, expect, vi, beforeEach, it, afterEach } from "vitest";
import GitService from "#/api/git-service/git-service.api";
import * as cloudGitService from "#/api/cloud/git-service.api";
-import { ProviderHandler } from "#/api/git-providers/provider-handler";
import * as activeStore from "#/api/backend-registry/active-store";
-// Mock the cloud git service
vi.mock("#/api/cloud/git-service.api", () => ({
searchCloudRepositories: vi.fn(),
getCloudInstallations: vi.fn(),
getCloudRepositoryBranches: vi.fn(),
}));
-// Mock the provider handler
-vi.mock("#/api/git-providers/provider-handler", () => ({
- ProviderHandler: {
- searchRepositories: vi.fn(),
- getInstallations: vi.fn(),
- getBranches: vi.fn(),
- },
-}));
-
-// Mock the active backend store
vi.mock("#/api/backend-registry/active-store", () => ({
getActiveBackend: vi.fn(),
}));
@@ -34,15 +22,32 @@ const mockGetCloudInstallations = vi.mocked(
const mockGetCloudRepositoryBranches = vi.mocked(
cloudGitService.getCloudRepositoryBranches,
);
-const mockProviderSearchRepositories = vi.mocked(
- ProviderHandler.searchRepositories,
-);
-const mockProviderGetInstallations = vi.mocked(
- ProviderHandler.getInstallations,
-);
-const mockProviderGetBranches = vi.mocked(ProviderHandler.getBranches);
const mockGetActiveBackend = vi.mocked(activeStore.getActiveBackend);
+const cloudActive = () =>
+ mockGetActiveBackend.mockReturnValue({
+ backend: {
+ kind: "cloud",
+ id: "test",
+ name: "Test",
+ host: "https://example.com",
+ apiKey: "test-key",
+ },
+ orgId: "org-1",
+ });
+
+const localActive = () =>
+ mockGetActiveBackend.mockReturnValue({
+ backend: {
+ kind: "local",
+ id: "test",
+ name: "Test",
+ host: "http://localhost",
+ apiKey: "test-key",
+ },
+ orgId: null,
+ });
+
describe("GitService", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -65,10 +70,7 @@ describe("GitService", () => {
it.each(invalidProviders)(
"should return empty results when provider is $name (cloud mode)",
async ({ value }) => {
- mockGetActiveBackend.mockReturnValue({
- backend: { kind: "cloud", id: "test", name: "Test", host: "https://example.com", apiKey: "test-key" },
- orgId: "org-1",
- });
+ cloudActive();
const result = await GitService.searchGitRepositories(
"test query",
@@ -79,34 +81,13 @@ describe("GitService", () => {
expect(mockSearchCloudRepositories).not.toHaveBeenCalled();
},
);
-
- it.each(invalidProviders)(
- "should return empty results when provider is $name (local mode)",
- async ({ value }) => {
- mockGetActiveBackend.mockReturnValue({
- backend: { kind: "local", id: "test", name: "Test", host: "http://localhost", apiKey: "test-key" },
- orgId: null,
- });
-
- const result = await GitService.searchGitRepositories(
- "test query",
- value as string,
- );
-
- expect(result).toEqual({ items: [], next_page_id: null });
- expect(mockProviderSearchRepositories).not.toHaveBeenCalled();
- },
- );
});
describe("retrieveUserGitRepositories", () => {
it.each(invalidProviders)(
"should return empty results when provider is $name",
async ({ value }) => {
- mockGetActiveBackend.mockReturnValue({
- backend: { kind: "cloud", id: "test", name: "Test", host: "https://example.com", apiKey: "test-key" },
- orgId: "org-1",
- });
+ cloudActive();
const result = await GitService.retrieveUserGitRepositories(
value as string,
@@ -122,10 +103,7 @@ describe("GitService", () => {
it.each(invalidProviders)(
"should return empty results when provider is $name",
async ({ value }) => {
- mockGetActiveBackend.mockReturnValue({
- backend: { kind: "cloud", id: "test", name: "Test", host: "https://example.com", apiKey: "test-key" },
- orgId: "org-1",
- });
+ cloudActive();
const result = await GitService.retrieveInstallationRepositories(
value as string,
@@ -141,12 +119,9 @@ describe("GitService", () => {
describe("getUserInstallations", () => {
it.each(invalidProviders)(
- "should return empty results when provider is $name (cloud mode)",
+ "should return empty results when provider is $name",
async ({ value }) => {
- mockGetActiveBackend.mockReturnValue({
- backend: { kind: "cloud", id: "test", name: "Test", host: "https://example.com", apiKey: "test-key" },
- orgId: "org-1",
- });
+ cloudActive();
const result = await GitService.getUserInstallations(value as string);
@@ -154,31 +129,13 @@ describe("GitService", () => {
expect(mockGetCloudInstallations).not.toHaveBeenCalled();
},
);
-
- it.each(invalidProviders)(
- "should return empty results when provider is $name (local mode)",
- async ({ value }) => {
- mockGetActiveBackend.mockReturnValue({
- backend: { kind: "local", id: "test", name: "Test", host: "http://localhost", apiKey: "test-key" },
- orgId: null,
- });
-
- const result = await GitService.getUserInstallations(value as string);
-
- expect(result).toEqual({ items: [], next_page_id: null });
- expect(mockProviderGetInstallations).not.toHaveBeenCalled();
- },
- );
});
describe("getRepositoryBranches", () => {
it.each(invalidProviders)(
"should return empty results when provider is $name",
async ({ value }) => {
- mockGetActiveBackend.mockReturnValue({
- backend: { kind: "cloud", id: "test", name: "Test", host: "https://example.com", apiKey: "test-key" },
- orgId: "org-1",
- });
+ cloudActive();
const result = await GitService.getRepositoryBranches(
"owner/repo",
@@ -195,10 +152,7 @@ describe("GitService", () => {
it.each(invalidProviders)(
"should return empty results when provider is $name",
async ({ value }) => {
- mockGetActiveBackend.mockReturnValue({
- backend: { kind: "cloud", id: "test", name: "Test", host: "https://example.com", apiKey: "test-key" },
- orgId: "org-1",
- });
+ cloudActive();
const result = await GitService.searchRepositoryBranches(
"owner/repo",
@@ -215,12 +169,16 @@ describe("GitService", () => {
describe("valid provider behavior", () => {
it("should call cloud API when provider is valid and cloud is active", async () => {
- mockGetActiveBackend.mockReturnValue({
- backend: { kind: "cloud", id: "test", name: "Test", host: "https://example.com", apiKey: "test-key" },
- orgId: "org-1",
- });
+ cloudActive();
mockSearchCloudRepositories.mockResolvedValue({
- items: [{ id: "1", full_name: "owner/repo", git_provider: "github", is_public: true }],
+ items: [
+ {
+ id: "1",
+ full_name: "owner/repo",
+ git_provider: "github",
+ is_public: true,
+ },
+ ],
next_page_id: null,
});
@@ -236,25 +194,13 @@ describe("GitService", () => {
expect(result.items).toHaveLength(1);
});
- it("should call provider handler when provider is valid and local is active", async () => {
- mockGetActiveBackend.mockReturnValue({
- backend: { kind: "local", id: "test", name: "Test", host: "http://localhost", apiKey: "test-key" },
- orgId: null,
- });
- mockProviderSearchRepositories.mockResolvedValue({
- items: [{ id: "1", full_name: "owner/repo", git_provider: "github", is_public: true }],
- next_page_id: null,
- });
+ it("should short-circuit to empty results when provider is valid but local backend is active", async () => {
+ localActive();
const result = await GitService.searchGitRepositories("test", "github");
- expect(mockProviderSearchRepositories).toHaveBeenCalledWith("github", {
- query: "test",
- installationId: undefined,
- pageId: undefined,
- limit: 100,
- });
- expect(result.items).toHaveLength(1);
+ expect(result).toEqual({ items: [], next_page_id: null });
+ expect(mockSearchCloudRepositories).not.toHaveBeenCalled();
});
});
});
diff --git a/__tests__/api/secrets-service.test.ts b/__tests__/api/secrets-service.test.ts
deleted file mode 100644
index 0e94a35e96..0000000000
--- a/__tests__/api/secrets-service.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { beforeEach, describe, expect, it } from "vitest";
-import { SecretsService } from "#/api/secrets-service";
-import { Provider, ProviderToken } from "#/types/settings";
-
-const GIT_PROVIDER_STORAGE_KEY = "openhands-agent-server-git-provider-tokens";
-
-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 },
- ...overrides,
-});
-
-describe("SecretsService", () => {
- beforeEach(() => {
- window.localStorage.clear();
- });
-
- it("stores connected Git providers in local cache and calls secrets API", async () => {
- // The SecretsService stores git provider tokens via the secrets API
- // and keeps a local cache for UI purposes (host mappings)
- // Method returns void (throws on failure)
- await SecretsService.addGitProvider(
- buildProviders({
- github: {
- token: "ghp_test_123",
- host: "github.example.com",
- },
- }),
- );
-
- // Verify local cache was updated
- const cached = JSON.parse(
- window.localStorage.getItem(GIT_PROVIDER_STORAGE_KEY) || "{}",
- );
- expect(cached.github).toEqual({
- token: "ghp_test_123",
- host: "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",
- },
- }),
- );
-
- // Update only the host, empty token means keep existing
- await SecretsService.addGitProvider(
- buildProviders({
- github: {
- token: "",
- host: "github.internal.example.com",
- },
- }),
- );
-
- // Verify local cache preserves the token and updates the host
- const cached = JSON.parse(
- window.localStorage.getItem(GIT_PROVIDER_STORAGE_KEY) || "{}",
- );
- expect(cached.github).toEqual({
- token: "ghp_test_123",
- host: "github.internal.example.com",
- });
- });
-
- it("clears connected Git providers from local cache", async () => {
- await SecretsService.addGitProvider(
- buildProviders({
- github: {
- token: "ghp_test_123",
- host: "github.com",
- },
- }),
- );
-
- // Method returns void (throws on failure)
- await SecretsService.deleteGitProviders();
-
- // Verify local cache was cleared
- expect(window.localStorage.getItem(GIT_PROVIDER_STORAGE_KEY)).toBeNull();
- });
-});
diff --git a/__tests__/api/settings-service.test.ts b/__tests__/api/settings-service.test.ts
index 5521b3c4ad..90789ad563 100644
--- a/__tests__/api/settings-service.test.ts
+++ b/__tests__/api/settings-service.test.ts
@@ -258,6 +258,26 @@ describe("SettingsService", () => {
});
});
+ it("ignores any stale localStorage git-provider-tokens key (PAT layer removed)", async () => {
+ // Arrange: a previous version of the app may have written PATs to
+ // localStorage under this key. After removing the integrations page and
+ // the PAT layer, getSettings must not resurrect those stale tokens into
+ // provider_tokens_set β€” that would re-enable the removed flow.
+ window.localStorage.setItem(
+ "openhands-agent-server-git-provider-tokens",
+ JSON.stringify({
+ github: { token: "ghp_stale_xyz", host: "github.com" },
+ gitlab: { token: "glpat_stale_xyz", host: null },
+ }),
+ );
+
+ // Act
+ const settings = await SettingsService.getSettings();
+
+ // Assert
+ expect(settings.provider_tokens_set).toEqual({});
+ });
+
it("lets the cloud response override locally-stored app preferences", async () => {
// Arrange: localStorage holds a stale "fr" while the cloud is the
// authoritative source and returns "ja".
@@ -278,28 +298,4 @@ describe("SettingsService", () => {
expect(settings.language).toBe("ja");
});
- it("derives provider_tokens_set from locally stored git provider tokens", async () => {
- // Arrange: simulate post-save state. SecretsService.addGitProvider writes to
- // this localStorage key after the server PUT /api/settings/secrets succeeds.
- // The agent-server API never returns provider_tokens_set, so the GUI must
- // derive it from local state for useUserProviders to recognize the
- // configured providers.
- window.localStorage.setItem(
- "openhands-agent-server-git-provider-tokens",
- JSON.stringify({
- github: { token: "ghp_test_123", host: "github.com" },
- gitlab: { token: "glpat_test_456", host: null },
- }),
- );
-
- // Act
- const settings = await SettingsService.getSettings();
-
- // Assert: each stored provider surfaces in provider_tokens_set with its host
- // (or null), which is what consumers like useUserProviders read.
- expect(settings.provider_tokens_set).toEqual({
- github: "github.com",
- gitlab: null,
- });
- });
});
diff --git a/__tests__/api/suggestions-service.test.ts b/__tests__/api/suggestions-service.test.ts
new file mode 100644
index 0000000000..6cd904c501
--- /dev/null
+++ b/__tests__/api/suggestions-service.test.ts
@@ -0,0 +1,83 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import * as cloudSuggestions from "#/api/cloud/suggestions-service.api";
+import { SuggestionsService } from "#/api/suggestions-service/suggestions-service.api";
+import type { Backend } from "#/api/backend-registry/types";
+import type { SuggestedTask } from "#/utils/types";
+
+vi.mock("#/api/cloud/suggestions-service.api", () => ({
+ getCloudSuggestedTasks: vi.fn(),
+}));
+
+const mockGetCloudSuggestedTasks = vi.mocked(
+ cloudSuggestions.getCloudSuggestedTasks,
+);
+
+const localBackend: Backend = {
+ id: "local",
+ name: "Local",
+ host: "http://localhost",
+ apiKey: "local-key",
+ kind: "local",
+};
+
+const cloudBackend: Backend = {
+ id: "prod",
+ name: "Production",
+ host: "https://app.all-hands.dev",
+ apiKey: "bearer",
+ kind: "cloud",
+};
+
+beforeEach(() => {
+ __resetActiveStoreForTests();
+ mockGetCloudSuggestedTasks.mockReset();
+});
+
+afterEach(() => {
+ __resetActiveStoreForTests();
+});
+
+describe("SuggestionsService.getSuggestedTasks", () => {
+ it("returns the cloud endpoint items when the active backend is cloud", async () => {
+ // Arrange
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+ const items: SuggestedTask[] = [
+ {
+ issue_number: 1,
+ title: "Fix CI",
+ repo: "octo/foo",
+ task_type: "FAILING_CHECKS",
+ git_provider: "github",
+ },
+ ];
+ mockGetCloudSuggestedTasks.mockResolvedValueOnce({
+ items,
+ next_page_id: null,
+ });
+
+ // Act
+ const result = await SuggestionsService.getSuggestedTasks();
+
+ // Assert
+ expect(result).toEqual(items);
+ });
+
+ it("returns an empty list without calling the cloud endpoint when the active backend is local", async () => {
+ // Arrange
+ setRegisteredBackends([localBackend]);
+ setActiveSelection({ backendId: localBackend.id });
+
+ // Act
+ const result = await SuggestionsService.getSuggestedTasks();
+
+ // Assert
+ expect(result).toEqual([]);
+ expect(mockGetCloudSuggestedTasks).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/api/user-service-cloud.test.ts b/__tests__/api/user-service-cloud.test.ts
deleted file mode 100644
index 8006bf39c9..0000000000
--- a/__tests__/api/user-service-cloud.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- __resetActiveStoreForTests,
- setActiveSelection,
- setRegisteredBackends,
-} from "#/api/backend-registry/active-store";
-import type { Backend } from "#/api/backend-registry/types";
-import UserService from "#/api/user-service/user-service.api";
-
-const cloudGitUser = vi.fn();
-const providerHandlerGetUser = vi.fn();
-
-vi.mock("#/api/cloud/user-service.api", () => ({
- getCloudGitUser: () => cloudGitUser(),
-}));
-vi.mock("#/api/git-providers/provider-handler", () => ({
- ProviderHandler: {
- getUserGitInfo: () => providerHandlerGetUser(),
- },
-}));
-
-const cloudBackend: Backend = {
- id: "prod",
- name: "Production",
- host: "https://app.all-hands.dev",
- apiKey: "bearer-token",
- kind: "cloud",
-};
-
-beforeEach(() => {
- window.localStorage.clear();
- __resetActiveStoreForTests();
- cloudGitUser.mockReset();
- providerHandlerGetUser.mockReset();
-});
-
-afterEach(() => {
- window.localStorage.clear();
- __resetActiveStoreForTests();
-});
-
-describe("UserService.getUser branch by backend kind", () => {
- it("uses the cloud /api/v1/users/git-info path when active is cloud (no false 'No git provider' toast)", async () => {
- setRegisteredBackends([cloudBackend]);
- setActiveSelection({ backendId: cloudBackend.id });
- cloudGitUser.mockResolvedValue({
- id: "u1",
- login: "alice",
- avatar_url: "",
- company: null,
- name: null,
- email: null,
- });
-
- const user = await UserService.getUser();
-
- expect(cloudGitUser).toHaveBeenCalledOnce();
- // The local "no git provider" check must NOT run for cloud β€” it would
- // throw on a clean install where the user has not pasted a local PAT.
- expect(providerHandlerGetUser).not.toHaveBeenCalled();
- expect(user?.login).toBe("alice");
- });
-
- it("uses the local ProviderHandler when active is local (preserves the local 'No git provider' check)", async () => {
- providerHandlerGetUser.mockResolvedValue({
- id: "u2",
- login: "bob",
- avatar_url: "",
- company: null,
- name: null,
- email: null,
- });
-
- await UserService.getUser();
-
- expect(providerHandlerGetUser).toHaveBeenCalledOnce();
- expect(cloudGitUser).not.toHaveBeenCalled();
- });
-});
diff --git a/__tests__/components/features/home/task-suggestions.test.tsx b/__tests__/components/features/home/task-suggestions.test.tsx
index 198475e0db..f0dd90f25e 100644
--- a/__tests__/components/features/home/task-suggestions.test.tsx
+++ b/__tests__/components/features/home/task-suggestions.test.tsx
@@ -125,21 +125,6 @@ describe("TaskSuggestions", () => {
await screen.findByText("TASKS$NO_TASKS_AVAILABLE");
});
- it("falls back to the generic empty message when no Git providers are connected and exposes no link to the removed Integrations page", async () => {
- useUserProvidersMock.mockReturnValueOnce({
- providers: [],
- isLoading: false,
- });
- getSuggestedTasksSpy.mockResolvedValue([]);
-
- renderTaskSuggestions();
-
- await screen.findByText("TASKS$NO_TASKS_AVAILABLE");
- expect(
- screen.queryByRole("link", { name: /integrations/i }),
- ).not.toBeInTheDocument();
- });
-
it("should render the task groups with the correct titles", async () => {
getSuggestedTasksSpy.mockResolvedValue(MOCK_TASKS);
renderTaskSuggestions();
diff --git a/__tests__/components/features/settings/webhook-status-badge.test.tsx b/__tests__/components/features/settings/webhook-status-badge.test.tsx
deleted file mode 100644
index 361c0d2590..0000000000
--- a/__tests__/components/features/settings/webhook-status-badge.test.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-import { render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-import { WebhookStatusBadge } from "#/components/features/settings/git-settings/webhook-status-badge";
-
-// Mock react-i18next
-vi.mock("react-i18next", () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-describe("WebhookStatusBadge", () => {
- it("should display installed status when webhook is installed", () => {
- // Arrange
- const props = {
- webhookInstalled: true,
- };
-
- // Act
- render(<WebhookStatusBadge {...props} />);
-
- // Assert
- const badge = screen.getByText("GITLAB$WEBHOOK_STATUS_INSTALLED");
- expect(badge).toBeInTheDocument();
- });
-
- it("should display not installed status when webhook is not installed", () => {
- // Arrange
- const props = {
- webhookInstalled: false,
- };
-
- // Act
- render(<WebhookStatusBadge {...props} />);
-
- // Assert
- const badge = screen.getByText("GITLAB$WEBHOOK_STATUS_NOT_INSTALLED");
- expect(badge).toBeInTheDocument();
- });
-
- it("should display installed status when installation result is successful", () => {
- // Arrange
- const props = {
- webhookInstalled: false,
- installationResult: {
- success: true,
- error: null,
- },
- };
-
- // Act
- render(<WebhookStatusBadge {...props} />);
-
- // Assert
- const badge = screen.getByText("GITLAB$WEBHOOK_STATUS_INSTALLED");
- expect(badge).toBeInTheDocument();
- });
-
- it("should display failed status when installation result has error", () => {
- // Arrange
- const props = {
- webhookInstalled: false,
- installationResult: {
- success: false,
- error: "Installation failed",
- },
- };
-
- // Act
- render(<WebhookStatusBadge {...props} />);
-
- // Assert
- const badge = screen.getByText("GITLAB$WEBHOOK_STATUS_FAILED");
- expect(badge).toBeInTheDocument();
- });
-
- it("should show error message when installation fails", () => {
- // Arrange
- const errorMessage = "Permission denied";
- const props = {
- webhookInstalled: false,
- installationResult: {
- success: false,
- error: errorMessage,
- },
- };
-
- // Act
- render(<WebhookStatusBadge {...props} />);
-
- // Assert
- const badgeContainer = screen.getByText(
- "GITLAB$WEBHOOK_STATUS_FAILED",
- ).parentElement;
- expect(badgeContainer).toHaveAttribute("title", errorMessage);
- });
-});
diff --git a/__tests__/components/features/sidebar/sidebar.test.tsx b/__tests__/components/features/sidebar/sidebar.test.tsx
index 8548b2a7fb..e26af87e1f 100644
--- a/__tests__/components/features/sidebar/sidebar.test.tsx
+++ b/__tests__/components/features/sidebar/sidebar.test.tsx
@@ -7,10 +7,6 @@ import {
type NavigationContextValue,
} from "#/context/navigation-context";
-vi.mock("#/hooks/query/use-git-user", () => ({
- useGitUser: () => ({ data: undefined, isFetching: false }),
-}));
-
vi.mock("#/hooks/query/use-config", () => ({
useConfig: () => ({ data: { feature_flags: {} } }),
}));
diff --git a/__tests__/hooks/mutation/use-add-git-providers.test.tsx b/__tests__/hooks/mutation/use-add-git-providers.test.tsx
deleted file mode 100644
index 6e8c88d9de..0000000000
--- a/__tests__/hooks/mutation/use-add-git-providers.test.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { renderHook } from "@testing-library/react";
-import React from "react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { SecretsService } from "#/api/secrets-service";
-import { useAddGitProviders } from "#/hooks/mutation/use-add-git-providers";
-import { Provider, ProviderToken } from "#/types/settings";
-
-const mockTrackGitProviderConnected = vi.fn();
-
-vi.mock("#/hooks/use-tracking", () => ({
- useTracking: () => ({
- trackGitProviderConnected: mockTrackGitProviderConnected,
- }),
-}));
-
-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 },
- ...overrides,
-});
-
-describe("useAddGitProviders", () => {
- let queryClient: QueryClient;
-
- beforeEach(() => {
- vi.restoreAllMocks();
- mockTrackGitProviderConnected.mockReset();
- queryClient = new QueryClient({
- defaultOptions: {
- queries: { retry: false },
- mutations: { retry: false },
- },
- });
- });
-
- it("invalidates personal settings queries after saving providers", async () => {
- vi.spyOn(SecretsService, "addGitProvider").mockResolvedValue(undefined);
-
- const personalSettingsQueryKey = ["settings", "personal"] as const;
- queryClient.setQueryData(personalSettingsQueryKey, {
- provider_tokens_set: {},
- });
-
- const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");
-
- const wrapper = ({ children }: { children: React.ReactNode }) => (
- <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
- );
-
- const { result } = renderHook(() => useAddGitProviders(), { wrapper });
-
- await result.current.mutateAsync({
- providers: buildProviders({
- github: { token: "ghp_test_123", host: null },
- }),
- });
-
- expect(invalidateSpy).toHaveBeenCalled();
- expect(
- queryClient.getQueryState(personalSettingsQueryKey)?.isInvalidated,
- ).toBe(true);
- });
-});
diff --git a/__tests__/hooks/use-git-user.test.tsx b/__tests__/hooks/use-git-user.test.tsx
deleted file mode 100644
index 5344ffdf23..0000000000
--- a/__tests__/hooks/use-git-user.test.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
-import { renderHook, waitFor } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import React from "react";
-import { useGitUser } from "#/hooks/query/use-git-user";
-import UserService from "#/api/user-service/user-service.api";
-import * as useShouldShowUserFeaturesModule from "#/hooks/use-should-show-user-features";
-import { AxiosError } from "axios";
-
-vi.mock("#/hooks/use-should-show-user-features");
-vi.mock("#/api/user-service/user-service.api");
-
-const identifyMock = vi.fn();
-
-vi.mock("posthog-js/react", () => ({
- usePostHog: vi.fn(() => ({
- identify: identifyMock,
- })),
-}));
-
-describe("useGitUser", () => {
- beforeEach(() => {
- vi.clearAllMocks();
-
- vi.mocked(useShouldShowUserFeaturesModule.useShouldShowUserFeatures).mockReturnValue(true);
- });
-
- const createWrapper = () => {
- const queryClient = new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- },
- },
- });
-
- return ({ children }: { children: React.ReactNode }) => (
- <QueryClientProvider client={queryClient}>
- {children}
- </QueryClientProvider>
- );
- };
-
- it("keeps OSS git-user failures local when the backend returns 401", async () => {
- const mockError = new AxiosError("Unauthorized", "401", undefined, undefined, {
- status: 401,
- data: { message: "Unauthorized" },
- } as any);
-
- vi.mocked(UserService.getUser).mockRejectedValue(mockError);
-
- const { result } = renderHook(() => useGitUser(), {
- wrapper: createWrapper(),
- });
-
- await waitFor(() => {
- expect(result.current.status).toBe("error");
- });
-
- expect(identifyMock).not.toHaveBeenCalled();
- });
-
- it("identifies the user when the git profile loads successfully", async () => {
- vi.mocked(UserService.getUser).mockResolvedValue({
- login: "octocat",
- company: "GitHub",
- name: "The Octocat",
- email: "[email protected]",
- } as never);
-
- const { result } = renderHook(() => useGitUser(), {
- wrapper: createWrapper(),
- });
-
- await waitFor(() => {
- expect(result.current.status).toBe("success");
- });
-
- expect(identifyMock).toHaveBeenCalledWith("octocat", {
- company: "GitHub",
- name: "The Octocat",
- email: "[email protected]",
- user: "octocat",
- });
- });
-});
diff --git a/__tests__/routes/git-settings.test.tsx b/__tests__/routes/git-settings.test.tsx
deleted file mode 100644
index 1c8fa7fce2..0000000000
--- a/__tests__/routes/git-settings.test.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { render, screen, waitFor } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import SettingsService from "#/api/settings-service/settings-service.api";
-import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
-import { GitSettingsScreen } from "#/routes/git-settings";
-import { Settings } from "#/types/settings";
-
-function buildSettings(overrides: Partial<Settings> = {}): Settings {
- return {
- ...MOCK_DEFAULT_USER_SETTINGS,
- ...overrides,
- provider_tokens_set: {
- ...MOCK_DEFAULT_USER_SETTINGS.provider_tokens_set,
- ...overrides.provider_tokens_set,
- },
- agent_settings: {
- ...MOCK_DEFAULT_USER_SETTINGS.agent_settings,
- ...overrides.agent_settings,
- },
- };
-}
-
-function renderGitSettingsScreen() {
- return render(<GitSettingsScreen />, {
- wrapper: ({ children }) => (
- <QueryClientProvider
- client={new QueryClient({
- defaultOptions: { queries: { retry: false } },
- })}
- >
- {children}
- </QueryClientProvider>
- ),
- });
-}
-
-describe("GitSettingsScreen", () => {
- beforeEach(() => {
- vi.restoreAllMocks();
- });
-
- it("renders OSS git provider token inputs", async () => {
- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings());
-
- renderGitSettingsScreen();
-
- const githubTokenInput = await screen.findByTestId("github-token-input");
-
- expect(githubTokenInput).toBeInTheDocument();
- expect(screen.getByTestId("gitlab-token-input")).toBeInTheDocument();
- expect(screen.getByTestId("submit-button")).toBeDisabled();
- });
-
- it("enables saving after a provider token changes", async () => {
- vi.spyOn(SettingsService, "getSettings").mockResolvedValue(buildSettings());
-
- renderGitSettingsScreen();
-
- const user = userEvent.setup();
- const githubTokenInput = await screen.findByTestId("github-token-input");
- const submitButton = screen.getByTestId("submit-button");
-
- expect(submitButton).toBeDisabled();
-
- await user.type(githubTokenInput, "ghp_test_token");
-
- 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();
- });
- });
-});
\ No newline at end of file
diff --git a/__tests__/routes/root-layout.test.tsx b/__tests__/routes/root-layout.test.tsx
index 1607209b95..0d607ed974 100644
--- a/__tests__/routes/root-layout.test.tsx
+++ b/__tests__/routes/root-layout.test.tsx
@@ -26,10 +26,6 @@ vi.mock("#/hooks/use-sync-posthog-consent", () => ({
useSyncPostHogConsent: () => {},
}));
-vi.mock("#/hooks/query/use-cloud-git-user", () => ({
- useCloudGitUser: () => ({ data: undefined, isLoading: false }),
-}));
-
vi.mock("#/hooks/use-app-title", () => ({
useAppTitle: () => "OpenHands",
}));
diff --git a/__tests__/routes/settings.test.tsx b/__tests__/routes/settings.test.tsx
index ae86778ad5..cfa55e7559 100644
--- a/__tests__/routes/settings.test.tsx
+++ b/__tests__/routes/settings.test.tsx
@@ -4,12 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createRoutesStub } from "react-router";
import SettingsScreen, { clientLoader } from "#/routes/settings";
import OptionService from "#/api/option-service/option-service.api";
-import {
- __resetActiveStoreForTests,
- setActiveSelection,
- setRegisteredBackends,
-} from "#/api/backend-registry/active-store";
-import type { Backend } from "#/api/backend-registry/types";
+import { __resetActiveStoreForTests } from "#/api/backend-registry/active-store";
import { getFirstAvailablePath } from "#/utils/settings-utils";
import { OSS_NAV_ITEMS } from "#/constants/settings-nav";
import { ActiveBackendProvider } from "#/contexts/active-backend-context";
@@ -23,14 +18,6 @@ vi.mock("#/hooks/use-settings-nav-items", () => ({
).map((item) => ({ type: "item", item })),
}));
-const cloudBackend: Backend = {
- id: "prod",
- name: "Production",
- host: "https://app.all-hands.dev",
- apiKey: "bearer-token",
- kind: "cloud",
-};
-
describe("settings route", () => {
beforeEach(() => {
vi.restoreAllMocks();
@@ -77,20 +64,6 @@ describe("settings route", () => {
expect(response.headers.get("Location")).toBe("/settings/app");
});
- it("redirects /integrations to /conversations when the active backend is cloud", async () => {
- setRegisteredBackends([cloudBackend]);
- setActiveSelection({ backendId: cloudBackend.id });
-
- const { clientLoader: integrationsLoader } = await import(
- "#/routes/git-settings"
- );
-
- const response = integrationsLoader() as Response;
-
- expect(response.status).toBe(302);
- expect(response.headers.get("Location")).toBe("/conversations");
- });
-
it("does not redirect unrelated removed nested paths through the settings loader", async () => {
vi.spyOn(OptionService, "getConfig").mockResolvedValue({
posthog_client_key: null,
diff --git a/src/api/cloud/suggestions-service.api.ts b/src/api/cloud/suggestions-service.api.ts
new file mode 100644
index 0000000000..425ee0e2bb
--- /dev/null
+++ b/src/api/cloud/suggestions-service.api.ts
@@ -0,0 +1,36 @@
+import { SuggestedTask } from "#/utils/types";
+import { getActiveBackend } from "../backend-registry/active-store";
+import type { Backend } from "../backend-registry/types";
+import { callCloudProxy } from "./proxy";
+
+function getActiveCloudBackend(): Backend {
+ const active = getActiveBackend().backend;
+ if (active.kind !== "cloud") {
+ throw new Error("Cloud suggested-tasks call requires a cloud backend.");
+ }
+ return active;
+}
+
+export async function getCloudSuggestedTasks(args: {
+ pageId?: string;
+ limit?: number;
+}): Promise<{ items: SuggestedTask[]; next_page_id: string | null }> {
+ const backend = getActiveCloudBackend();
+ const params = new URLSearchParams();
+ params.set("limit", String(args.limit ?? 30));
+ if (args.pageId) params.set("page_id", args.pageId);
+
+ const data = await callCloudProxy<{
+ items: SuggestedTask[];
+ next_page_id: string | null;
+ }>({
+ backend,
+ method: "GET",
+ path: `/api/v1/git/suggested-tasks/search?${params.toString()}`,
+ });
+
+ return {
+ items: data?.items ?? [],
+ next_page_id: data?.next_page_id ?? null,
+ };
+}
diff --git a/src/api/cloud/user-service.api.ts b/src/api/cloud/user-service.api.ts
deleted file mode 100644
index c5fe911e9b..0000000000
--- a/src/api/cloud/user-service.api.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { getActiveBackend } from "../backend-registry/active-store";
-import type { Backend } from "../backend-registry/types";
-import { callCloudProxy } from "./proxy";
-import type { CloudGitUser } from "./types";
-
-function getActiveCloudBackend(): Backend {
- const active = getActiveBackend().backend;
- if (active.kind !== "cloud") {
- throw new Error("Cloud user calls require a cloud backend.");
- }
- return active;
-}
-
-/**
- * Fetch the SaaS git-info record (`GET /api/v1/users/git-info`). Returns
- * the currently authenticated user's identity across the connected git
- * providers β€” login, avatar, etc.
- *
- * Routed through the bundled agent-server's cloud proxy.
- */
-export async function getCloudGitUser(
- backend?: Backend,
-): Promise<CloudGitUser> {
- const target = backend ?? getActiveCloudBackend();
- const data = await callCloudProxy<CloudGitUser>({
- backend: target,
- method: "GET",
- path: "/api/v1/users/git-info",
- });
- return data;
-}
diff --git a/src/api/git-providers/azure-devops-service.ts b/src/api/git-providers/azure-devops-service.ts
deleted file mode 100644
index 3a68473dbc..0000000000
--- a/src/api/git-providers/azure-devops-service.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-import { SuggestedTask } from "#/utils/types";
-import { ProviderToken } from "#/types/settings";
-import {
- Branch,
- BranchPage,
- GitRepository,
- GitUser,
- InstallationPage,
- RepositoryPage,
-} from "#/types/git";
-import {
- GitProviderAuthError,
- GitProviderService,
- ListBranchesOptions,
- ListInstallationsOptions,
- SearchRepositoriesOptions,
-} from "./types";
-import { paginateResults } from "./paging-utils";
-
-const PROFILE_URL =
- "https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=7.1";
-const ACCOUNTS_URL_BASE =
- "https://app.vssps.visualstudio.com/_apis/accounts?api-version=7.1";
-
-const buildAuthHeader = (token: string): string => {
- if (token.includes(":")) {
- const encoded =
- typeof window === "undefined"
- ? Buffer.from(token).toString("base64")
- : btoa(token);
- return `Basic ${encoded}`;
- }
- // Azure DevOps PATs use Basic auth with empty username.
- const encoded =
- typeof window === "undefined"
- ? Buffer.from(`:${token}`).toString("base64")
- : btoa(`:${token}`);
- return `Basic ${encoded}`;
-};
-
-interface AzureDevOpsRepo {
- id: string;
- name: string;
- project?: { name?: string };
- defaultBranch?: string;
-}
-
-interface AzureDevOpsRef {
- name: string;
- objectId: string;
-}
-
-export class AzureDevOpsService implements GitProviderService {
- readonly provider = "azure_devops" as const;
-
- private readonly token: string;
-
- constructor(credentials: ProviderToken) {
- if (!credentials.token) {
- throw new GitProviderAuthError("Azure DevOps token is empty");
- }
- this.token = credentials.token;
- }
-
- private headers(): HeadersInit {
- return {
- Authorization: buildAuthHeader(this.token),
- Accept: "application/json",
- };
- }
-
- private async fetchJson<T>(url: string): Promise<T> {
- const response = await fetch(url, { headers: this.headers() });
- if (response.status === 401) {
- throw new GitProviderAuthError("Azure DevOps token rejected (401)");
- }
- if (!response.ok) {
- throw new Error(`Azure DevOps request failed (${response.status})`);
- }
- return (await response.json()) as T;
- }
-
- async getUser(): Promise<GitUser> {
- const data = await this.fetchJson<{
- id: string;
- displayName?: string;
- emailAddress?: string;
- coreAttributes?: { Avatar?: { value?: { value?: string } } };
- }>(PROFILE_URL);
- return {
- id: String(data.id ?? ""),
- login: data.displayName ?? "",
- avatar_url: data.coreAttributes?.Avatar?.value?.value ?? "",
- name: data.displayName ?? null,
- email: data.emailAddress ?? null,
- company: null,
- };
- }
-
- // eslint-disable-next-line class-methods-use-this
- async getSuggestedTasks(): Promise<SuggestedTask[]> {
- return [];
- }
-
- async searchRepositories(
- options: SearchRepositoriesOptions,
- ): Promise<RepositoryPage> {
- const { installationId, query, pageId, limit } = options;
- if (!installationId) {
- // Without an organization the API can't enumerate repos.
- return { items: [], next_page_id: null };
- }
- const data = await this.fetchJson<{ value: AzureDevOpsRepo[] }>(
- `https://dev.azure.com/${encodeURIComponent(installationId)}/_apis/git/repositories?api-version=7.1`,
- );
- let repos = data.value;
- if (query) {
- const lowered = query.toLowerCase();
- repos = repos.filter((r) => r.name.toLowerCase().includes(lowered));
- }
- const mapped = repos.map((r) =>
- this.parseRepository(r, installationId, r.project?.name ?? ""),
- );
- return paginateResults(mapped, pageId, limit);
- }
-
- async getBranches(options: ListBranchesOptions): Promise<BranchPage> {
- const { repository, query, pageId, limit } = options;
- const parts = repository.split("/");
- if (parts.length < 3) return { items: [], next_page_id: null };
- const [org, project, repo] = [parts[0], parts[1], parts.slice(2).join("/")];
- const data = await this.fetchJson<{ value: AzureDevOpsRef[] }>(
- `https://dev.azure.com/${encodeURIComponent(org)}/${encodeURIComponent(project)}/_apis/git/repositories/${encodeURIComponent(repo)}/refs?api-version=7.1&filter=heads/`,
- );
- let branches = data.value.map((ref) => ({
- name: ref.name.replace(/^refs\/heads\//u, ""),
- objectId: ref.objectId,
- }));
- if (query) {
- const lowered = query.toLowerCase();
- branches = branches.filter((b) => b.name.toLowerCase().includes(lowered));
- }
- const items: Branch[] = branches.map((b) => ({
- name: b.name,
- commit_sha: b.objectId,
- protected: false,
- }));
- return paginateResults(items, pageId, limit);
- }
-
- async getInstallations(
- options: ListInstallationsOptions,
- ): Promise<InstallationPage> {
- const profile = await this.fetchJson<{ id: string }>(PROFILE_URL);
- const accounts = await this.fetchJson<{
- value: Array<{ accountName: string }>;
- }>(`${ACCOUNTS_URL_BASE}&memberId=${encodeURIComponent(profile.id)}`);
- const items = accounts.value.map((account) => account.accountName);
- return paginateResults(items, options.pageId, options.limit);
- }
-
- // eslint-disable-next-line class-methods-use-this
- private parseRepository(
- repo: AzureDevOpsRepo,
- organization: string,
- project: string,
- ): GitRepository {
- return {
- id: repo.id,
- full_name: `${organization}/${project}/${repo.name}`,
- git_provider: "azure_devops",
- is_public: false,
- main_branch: repo.defaultBranch?.replace(/^refs\/heads\//u, ""),
- };
- }
-}
diff --git a/src/api/git-providers/bitbucket-dc-service.ts b/src/api/git-providers/bitbucket-dc-service.ts
deleted file mode 100644
index 5d4144fc6b..0000000000
--- a/src/api/git-providers/bitbucket-dc-service.ts
+++ /dev/null
@@ -1,188 +0,0 @@
-import { SuggestedTask } from "#/utils/types";
-import { ProviderToken } from "#/types/settings";
-import {
- Branch,
- BranchPage,
- GitRepository,
- GitUser,
- InstallationPage,
- RepositoryPage,
-} from "#/types/git";
-import {
- GitProviderAuthError,
- GitProviderService,
- ListBranchesOptions,
- ListInstallationsOptions,
- SearchRepositoriesOptions,
-} from "./types";
-import { decodePageId, encodePageId } from "./paging-utils";
-
-const buildAuthHeader = (token: string): string =>
- token.includes(":")
- ? `Basic ${typeof window === "undefined" ? Buffer.from(token).toString("base64") : btoa(token)}`
- : `Bearer ${token}`;
-
-interface BitbucketDCRepo {
- id: number | string;
- slug: string;
- project: { key: string };
- public?: boolean;
-}
-
-interface BitbucketDCBranch {
- id?: string;
- displayId?: string;
- latestCommit?: string;
-}
-
-export class BitbucketDataCenterService implements GitProviderService {
- readonly provider = "bitbucket_data_center" as const;
-
- private readonly token: string;
-
- private readonly baseUrl: string;
-
- constructor(credentials: ProviderToken) {
- if (!credentials.token) {
- throw new GitProviderAuthError("Bitbucket DC token is empty");
- }
- if (!credentials.host) {
- throw new GitProviderAuthError("Bitbucket DC requires a host URL");
- }
- this.token = credentials.token;
- const trimmed = credentials.host
- .replace(/^https?:\/\//iu, "")
- .replace(/\/+$/u, "");
- this.baseUrl = `https://${trimmed}/rest/api/1.0`;
- }
-
- private headers(): HeadersInit {
- return {
- Authorization: buildAuthHeader(this.token),
- Accept: "application/json",
- };
- }
-
- private async fetchJson<T>(url: string): Promise<T> {
- const response = await fetch(url, { headers: this.headers() });
- if (response.status === 401) {
- throw new GitProviderAuthError("Bitbucket DC token rejected (401)");
- }
- if (!response.ok) {
- throw new Error(`Bitbucket DC request failed (${response.status})`);
- }
- return (await response.json()) as T;
- }
-
- // eslint-disable-next-line class-methods-use-this
- async getUser(): Promise<GitUser> {
- // Bitbucket DC's /user endpoint returns nothing useful for HTTP access
- // tokens. Fall back to the empty-but-valid response the Python service
- // returns so the UI can detect "no profile" gracefully.
- return {
- id: "",
- login: "",
- avatar_url: "",
- name: null,
- email: null,
- company: null,
- };
- }
-
- // eslint-disable-next-line class-methods-use-this
- async getSuggestedTasks(): Promise<SuggestedTask[]> {
- return [];
- }
-
- async searchRepositories(
- options: SearchRepositoriesOptions,
- ): Promise<RepositoryPage> {
- const { query, installationId, pageId, limit } = options;
- const projectKey =
- installationId ??
- (query?.includes("/") ? query.split("/")[0] : undefined);
- if (!projectKey) {
- return { items: [], next_page_id: null };
- }
- const start = decodePageId(pageId) ?? 0;
- const params = new URLSearchParams({
- limit: String(limit),
- start: String(start),
- });
- const data = await this.fetchJson<{
- values: BitbucketDCRepo[];
- isLastPage?: boolean;
- nextPageStart?: number;
- }>(`${this.baseUrl}/projects/${projectKey}/repos?${params.toString()}`);
- const items = data.values.map((repo) => this.parseRepository(repo));
- const nextPageId =
- !data.isLastPage && typeof data.nextPageStart === "number"
- ? encodePageId(data.nextPageStart)
- : null;
- return { items, next_page_id: nextPageId };
- }
-
- async getBranches(options: ListBranchesOptions): Promise<BranchPage> {
- const { repository, query, pageId, limit } = options;
- const parts = repository.split("/");
- if (parts.length < 2) return { items: [], next_page_id: null };
- const [project, slug] = [parts[parts.length - 2], parts[parts.length - 1]];
- const start = decodePageId(pageId) ?? 0;
- const params = new URLSearchParams({
- limit: String(limit),
- start: String(start),
- orderBy: "MODIFICATION",
- });
- if (query) params.set("filterText", query);
- const data = await this.fetchJson<{
- values: BitbucketDCBranch[];
- isLastPage?: boolean;
- nextPageStart?: number;
- }>(
- `${this.baseUrl}/projects/${project}/repos/${slug}/branches?${params.toString()}`,
- );
- const items: Branch[] = data.values.map((branch) => ({
- name: branch.displayId ?? branch.id?.replace("refs/heads/", "") ?? "",
- commit_sha: branch.latestCommit ?? "",
- protected: false,
- }));
- const nextPageId =
- !data.isLastPage && typeof data.nextPageStart === "number"
- ? encodePageId(data.nextPageStart)
- : null;
- return { items, next_page_id: nextPageId };
- }
-
- async getInstallations(
- options: ListInstallationsOptions,
- ): Promise<InstallationPage> {
- const { pageId, limit } = options;
- const start = decodePageId(pageId) ?? 0;
- const data = await this.fetchJson<{
- values: Array<{ key: string }>;
- isLastPage?: boolean;
- nextPageStart?: number;
- }>(
- `${this.baseUrl}/projects?${new URLSearchParams({
- limit: String(limit),
- start: String(start),
- }).toString()}`,
- );
- const items = data.values.map((p) => p.key);
- const nextPageId =
- !data.isLastPage && typeof data.nextPageStart === "number"
- ? encodePageId(data.nextPageStart)
- : null;
- return { items, next_page_id: nextPageId };
- }
-
- // eslint-disable-next-line class-methods-use-this
- private parseRepository(repo: BitbucketDCRepo): GitRepository {
- return {
- id: String(repo.id ?? ""),
- full_name: `${repo.project.key}/${repo.slug}`,
- git_provider: "bitbucket_data_center",
- is_public: repo.public ?? false,
- };
- }
-}
diff --git a/src/api/git-providers/bitbucket-service.ts b/src/api/git-providers/bitbucket-service.ts
deleted file mode 100644
index 0b63ebc27e..0000000000
--- a/src/api/git-providers/bitbucket-service.ts
+++ /dev/null
@@ -1,217 +0,0 @@
-import { SuggestedTask } from "#/utils/types";
-import { ProviderToken } from "#/types/settings";
-import {
- Branch,
- BranchPage,
- GitRepository,
- GitUser,
- InstallationPage,
- RepositoryPage,
-} from "#/types/git";
-import {
- GitProviderAuthError,
- GitProviderService,
- ListBranchesOptions,
- ListInstallationsOptions,
- SearchRepositoriesOptions,
-} from "./types";
-import { decodePageId, encodePageId } from "./paging-utils";
-
-const BASE_URL = "https://api.bitbucket.org/2.0";
-
-const buildAuthHeader = (token: string): string =>
- token.includes(":")
- ? `Basic ${typeof window === "undefined" ? Buffer.from(token).toString("base64") : btoa(token)}`
- : `Bearer ${token}`;
-
-interface BitbucketRepoResponse {
- uuid: string;
- slug: string;
- workspace?: { slug?: string };
- is_private?: boolean;
- updated_on?: string;
- mainbranch?: { name?: string };
-}
-
-interface BitbucketBranchResponse {
- name: string;
- target?: { hash?: string; date?: string };
-}
-
-export class BitbucketService implements GitProviderService {
- readonly provider = "bitbucket" as const;
-
- private readonly token: string;
-
- constructor(credentials: ProviderToken) {
- if (!credentials.token) {
- throw new GitProviderAuthError("Bitbucket token is empty");
- }
- this.token = credentials.token;
- }
-
- private headers(): HeadersInit {
- return {
- Authorization: buildAuthHeader(this.token),
- Accept: "application/json",
- };
- }
-
- private async fetchJson<T>(url: string): Promise<T> {
- const response = await fetch(url, { headers: this.headers() });
- if (response.status === 401) {
- throw new GitProviderAuthError("Bitbucket token rejected (401)");
- }
- if (!response.ok) {
- throw new Error(`Bitbucket request failed (${response.status})`);
- }
- return (await response.json()) as T;
- }
-
- async getUser(): Promise<GitUser> {
- const data = await this.fetchJson<{
- account_id?: string;
- username?: string;
- display_name?: string;
- links?: { avatar?: { href?: string } };
- }>(`${BASE_URL}/user`);
- let email: string | null = null;
- try {
- const emails = await this.fetchJson<{
- values: Array<{
- email: string;
- is_primary: boolean;
- is_confirmed: boolean;
- }>;
- }>(`${BASE_URL}/user/emails`);
- const primary = emails.values.find((e) => e.is_primary && e.is_confirmed);
- email = primary?.email ?? null;
- } catch {
- email = null;
- }
- return {
- id: data.account_id ?? "",
- login: data.username ?? "",
- avatar_url: data.links?.avatar?.href ?? "",
- name: data.display_name ?? null,
- email,
- company: null,
- };
- }
-
- // eslint-disable-next-line class-methods-use-this
- async getSuggestedTasks(): Promise<SuggestedTask[]> {
- return [];
- }
-
- async searchRepositories(
- options: SearchRepositoriesOptions,
- ): Promise<RepositoryPage> {
- const { query, installationId, pageId, limit } = options;
- const numericPage = Math.max(
- 1,
- Math.floor((decodePageId(pageId) ?? 0) / limit + 1),
- );
-
- const workspace =
- installationId ??
- (query?.includes("/") ? query.split("/")[0] : undefined);
- if (!workspace) {
- // Match the Python flow: when there's no workspace context yet, list
- // workspaces so the UI can let the user pick one. Returning empty here
- // keeps the existing dropdown experience predictable.
- return { items: [], next_page_id: null };
- }
-
- const params = new URLSearchParams({
- pagelen: String(limit),
- page: String(numericPage),
- sort: "-updated_on",
- });
- if (query?.includes("/")) {
- const [, slug] = query.split("/", 2);
- if (slug) params.set("q", `name~"${slug}"`);
- } else if (query) {
- params.set("q", `name~"${query}"`);
- }
-
- const data = await this.fetchJson<{
- values: BitbucketRepoResponse[];
- next?: string;
- }>(`${BASE_URL}/repositories/${workspace}?${params.toString()}`);
- const items = data.values.map((repo) => this.parseRepository(repo));
- const nextPageId = data.next ? encodePageId(numericPage * limit) : null;
- return { items, next_page_id: nextPageId };
- }
-
- async getBranches(options: ListBranchesOptions): Promise<BranchPage> {
- const { repository, query, pageId, limit } = options;
- const parts = repository.split("/");
- if (parts.length < 2) return { items: [], next_page_id: null };
- const [workspace, slug] = [
- parts[parts.length - 2],
- parts[parts.length - 1],
- ];
- const numericPage = Math.max(
- 1,
- Math.floor((decodePageId(pageId) ?? 0) / limit + 1),
- );
- const params = new URLSearchParams({
- pagelen: String(limit),
- page: String(numericPage),
- sort: "-target.date",
- });
- if (query) params.set("q", `name~"${query}"`);
- const data = await this.fetchJson<{
- values: BitbucketBranchResponse[];
- next?: string;
- }>(
- `${BASE_URL}/repositories/${workspace}/${slug}/refs/branches?${params.toString()}`,
- );
- const items: Branch[] = data.values.map((b) => ({
- name: b.name,
- commit_sha: b.target?.hash ?? "",
- protected: false,
- last_push_date: b.target?.date,
- }));
- const nextPageId = data.next ? encodePageId(numericPage * limit) : null;
- return { items, next_page_id: nextPageId };
- }
-
- async getInstallations(
- options: ListInstallationsOptions,
- ): Promise<InstallationPage> {
- const { pageId, limit } = options;
- const numericPage = Math.max(
- 1,
- Math.floor((decodePageId(pageId) ?? 0) / limit + 1),
- );
- const data = await this.fetchJson<{
- values: Array<{ slug: string }>;
- next?: string;
- }>(
- `${BASE_URL}/workspaces?${new URLSearchParams({
- pagelen: String(limit),
- page: String(numericPage),
- }).toString()}`,
- );
- const items = data.values.map((w) => w.slug);
- const nextPageId = data.next ? encodePageId(numericPage * limit) : null;
- return { items, next_page_id: nextPageId };
- }
-
- // eslint-disable-next-line class-methods-use-this
- private parseRepository(repo: BitbucketRepoResponse): GitRepository {
- const workspaceSlug = repo.workspace?.slug ?? "";
- const fullName =
- workspaceSlug && repo.slug ? `${workspaceSlug}/${repo.slug}` : "";
- return {
- id: repo.uuid ?? "",
- full_name: fullName,
- git_provider: "bitbucket",
- is_public: !(repo.is_private ?? true),
- pushed_at: repo.updated_on,
- main_branch: repo.mainbranch?.name,
- };
- }
-}
diff --git a/src/api/git-providers/forgejo-service.ts b/src/api/git-providers/forgejo-service.ts
deleted file mode 100644
index 14b76dc41a..0000000000
--- a/src/api/git-providers/forgejo-service.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { SuggestedTask } from "#/utils/types";
-import { ProviderToken } from "#/types/settings";
-import {
- Branch,
- BranchPage,
- GitRepository,
- GitUser,
- InstallationPage,
- RepositoryPage,
-} from "#/types/git";
-import {
- GitProviderAuthError,
- GitProviderService,
- ListBranchesOptions,
- SearchRepositoriesOptions,
-} from "./types";
-import { decodePageId, encodePageId } from "./paging-utils";
-
-const DEFAULT_BASE_URL = "https://codeberg.org/api/v1";
-
-const resolveBaseUrl = (host: string | null): string => {
- if (!host) return DEFAULT_BASE_URL;
- const normalized = host.replace(/\/+$/u, "");
- if (/^https?:\/\//iu.test(normalized)) {
- return normalized.includes("/api/") ? normalized : `${normalized}/api/v1`;
- }
- return `https://${normalized}/api/v1`;
-};
-
-interface ForgejoRepo {
- id: number | string;
- full_name: string;
- default_branch?: string;
- stars_count?: number;
- updated_at?: string;
- private?: boolean;
-}
-
-interface ForgejoBranch {
- name: string;
- commit?: { id?: string; sha?: string };
- protected?: boolean;
-}
-
-export class ForgejoService implements GitProviderService {
- readonly provider = "forgejo" as const;
-
- private readonly token: string;
-
- private readonly baseUrl: string;
-
- private cachedUserId: string | null = null;
-
- constructor(credentials: ProviderToken) {
- if (!credentials.token) {
- throw new GitProviderAuthError("Forgejo token is empty");
- }
- this.token = credentials.token;
- this.baseUrl = resolveBaseUrl(credentials.host ?? null);
- }
-
- private headers(): HeadersInit {
- return {
- Authorization: `token ${this.token}`,
- Accept: "application/json",
- };
- }
-
- private async fetchJson<T>(url: string): Promise<T> {
- const response = await fetch(url, { headers: this.headers() });
- if (response.status === 401) {
- throw new GitProviderAuthError("Forgejo token rejected (401)");
- }
- if (!response.ok) {
- throw new Error(`Forgejo request failed (${response.status})`);
- }
- return (await response.json()) as T;
- }
-
- async getUser(): Promise<GitUser> {
- const data = await this.fetchJson<{
- id: number | string;
- username: string;
- avatar_url?: string;
- full_name?: string;
- email?: string;
- organization?: string;
- }>(`${this.baseUrl}/user`);
- return {
- id: String(data.id ?? ""),
- login: data.username ?? "",
- avatar_url: data.avatar_url ?? "",
- name: data.full_name ?? null,
- email: data.email ?? null,
- company: data.organization ?? null,
- };
- }
-
- // eslint-disable-next-line class-methods-use-this
- async getSuggestedTasks(): Promise<SuggestedTask[]> {
- return [];
- }
-
- async searchRepositories(
- options: SearchRepositoriesOptions,
- ): Promise<RepositoryPage> {
- const { query, pageId, limit } = options;
- const numericPage = Math.max(
- 1,
- Math.floor((decodePageId(pageId) ?? 0) / limit + 1),
- );
- const params = new URLSearchParams({
- page: String(numericPage),
- limit: String(limit),
- sort: "updated",
- });
- let url = `${this.baseUrl}/user/repos?${params.toString()}`;
- if (query) {
- // /repos/search is global by default; restrict to repos owned by the
- // authenticated user via uid so we mirror the OpenHands behavior.
- const uid = await this.resolveUserId();
- params.set("q", query);
- params.set("mode", "source");
- if (uid) params.set("uid", uid);
- url = `${this.baseUrl}/repos/search?${params.toString()}`;
- }
- const data = await this.fetchJson<ForgejoRepo[] | { data: ForgejoRepo[] }>(
- url,
- );
- const repos = Array.isArray(data) ? data : data.data;
- const items = repos.map((r) => this.parseRepository(r));
- const nextPageId =
- items.length === limit ? encodePageId(numericPage * limit) : null;
- return { items, next_page_id: nextPageId };
- }
-
- private async resolveUserId(): Promise<string | null> {
- if (this.cachedUserId !== null) return this.cachedUserId;
- try {
- const user = await this.getUser();
- this.cachedUserId = user.id || null;
- } catch {
- this.cachedUserId = null;
- }
- return this.cachedUserId;
- }
-
- async getBranches(options: ListBranchesOptions): Promise<BranchPage> {
- const { repository, query, pageId, limit } = options;
- const numericPage = Math.max(
- 1,
- Math.floor((decodePageId(pageId) ?? 0) / limit + 1),
- );
- const params = new URLSearchParams({
- page: String(numericPage),
- limit: String(limit),
- });
- const data = await this.fetchJson<ForgejoBranch[]>(
- `${this.baseUrl}/repos/${repository}/branches?${params.toString()}`,
- );
- let branches = data;
- if (query) {
- const lowered = query.toLowerCase();
- branches = branches.filter((b) => b.name.toLowerCase().includes(lowered));
- }
- const items: Branch[] = branches.map((b) => ({
- name: b.name,
- commit_sha: b.commit?.id ?? b.commit?.sha ?? "",
- protected: b.protected ?? false,
- }));
- const nextPageId =
- !query && data.length === limit
- ? encodePageId(numericPage * limit)
- : null;
- return { items, next_page_id: nextPageId };
- }
-
- // eslint-disable-next-line class-methods-use-this
- async getInstallations(): Promise<InstallationPage> {
- return { items: [], next_page_id: null };
- }
-
- // eslint-disable-next-line class-methods-use-this
- private parseRepository(repo: ForgejoRepo): GitRepository {
- return {
- id: String(repo.id ?? ""),
- full_name: repo.full_name,
- git_provider: "forgejo",
- is_public: !(repo.private ?? false),
- stargazers_count: repo.stars_count,
- pushed_at: repo.updated_at,
- main_branch: repo.default_branch,
- };
- }
-}
diff --git a/src/api/git-providers/github-service.ts b/src/api/git-providers/github-service.ts
deleted file mode 100644
index 23d35b647c..0000000000
--- a/src/api/git-providers/github-service.ts
+++ /dev/null
@@ -1,521 +0,0 @@
-import { SuggestedTask, SuggestedTaskType } from "#/utils/types";
-import { ProviderToken } from "#/types/settings";
-import {
- Branch,
- BranchPage,
- GitRepository,
- GitUser,
- InstallationPage,
- RepositoryPage,
-} from "#/types/git";
-import {
- GitProviderAuthError,
- GitProviderService,
- ListBranchesOptions,
- SearchRepositoriesOptions,
- SortOrder,
-} from "./types";
-import { decodePageId, encodePageId, paginateResults } from "./paging-utils";
-
-const DEFAULT_BASE_URL = "https://api.github.com";
-const DEFAULT_GRAPHQL_URL = "https://api.github.com/graphql";
-
-const SUGGESTED_TASK_PR_QUERY = `
- query GetUserPRs($login: String!) {
- user(login: $login) {
- pullRequests(first: 50, states: [OPEN], orderBy: {field: UPDATED_AT, direction: DESC}) {
- nodes {
- number
- title
- repository { nameWithOwner }
- mergeable
- commits(last: 1) {
- nodes {
- commit { statusCheckRollup { state } }
- }
- }
- reviews(first: 50, states: [CHANGES_REQUESTED, COMMENTED]) {
- nodes { state }
- }
- }
- }
- }
- }
-`;
-
-const SUGGESTED_TASK_ISSUE_QUERY = `
- query GetUserIssues($login: String!) {
- user(login: $login) {
- issues(first: 50, states: [OPEN], filterBy: {assignee: $login}, orderBy: {field: UPDATED_AT, direction: DESC}) {
- nodes {
- number
- title
- repository { nameWithOwner }
- }
- }
- }
- }
-`;
-
-const SEARCH_BRANCHES_QUERY = `
- query SearchBranches($owner: String!, $name: String!, $query: String!, $perPage: Int!) {
- repository(owner: $owner, name: $name) {
- refs(refPrefix: "refs/heads/", query: $query, first: $perPage, orderBy: {field: ALPHABETICAL, direction: ASC}) {
- nodes {
- name
- target {
- __typename
- ... on Commit { oid committedDate }
- }
- }
- }
- }
- }
-`;
-
-const sortOrderToParams = (
- sortOrder: SortOrder | undefined,
-): { sort: string; order: "asc" | "desc" } | null => {
- if (!sortOrder) return null;
- const lastDash = sortOrder.lastIndexOf("-");
- if (lastDash < 0) return null;
- const sort = sortOrder.slice(0, lastDash);
- const order = sortOrder.slice(lastDash + 1) as "asc" | "desc";
- return { sort, order };
-};
-
-const buildSearchUrl = (
- base: string,
- params: Record<string, string>,
-): string => {
- const search = new URLSearchParams(params);
- return `${base}?${search.toString()}`;
-};
-
-const githubBaseUrls = (host: string | null) => {
- if (!host) {
- return { rest: DEFAULT_BASE_URL, graphql: DEFAULT_GRAPHQL_URL };
- }
- const trimmed = host.replace(/^https?:\/\//iu, "").replace(/\/+$/u, "");
- return {
- rest: `https://${trimmed}/api/v3`,
- graphql: `https://${trimmed}/api/graphql`,
- };
-};
-
-const parseLinkHeaderHasNext = (linkHeader: string | null): boolean =>
- !!linkHeader && /rel="next"/u.test(linkHeader);
-
-interface GitHubRepoResponse {
- id: number | string;
- full_name: string;
- default_branch?: string;
- stargazers_count?: number;
- pushed_at?: string;
- private?: boolean;
-}
-
-interface GitHubBranchResponse {
- name: string;
- commit?: { sha?: string; commit?: { committer?: { date?: string } } };
- protected?: boolean;
-}
-
-export class GitHubService implements GitProviderService {
- readonly provider = "github" as const;
-
- private readonly token: string;
-
- private readonly host: string | null;
-
- private readonly baseUrl: string;
-
- private readonly graphqlUrl: string;
-
- private cachedLogin: string | null = null;
-
- private cachedOrgs: string[] | null = null;
-
- constructor(credentials: ProviderToken) {
- if (!credentials.token) {
- throw new GitProviderAuthError("GitHub token is empty");
- }
- this.token = credentials.token;
- this.host = credentials.host ?? null;
- const urls = githubBaseUrls(this.host);
- this.baseUrl = urls.rest;
- this.graphqlUrl = urls.graphql;
- }
-
- private headers(): HeadersInit {
- return {
- Authorization: `Bearer ${this.token}`,
- Accept: "application/vnd.github.v3+json",
- };
- }
-
- private async fetchJson<T>(
- url: string,
- ): Promise<{ data: T; linkHeader: string | null }> {
- const response = await fetch(url, { headers: this.headers() });
- if (response.status === 401) {
- throw new GitProviderAuthError("GitHub token rejected (401)");
- }
- if (!response.ok) {
- throw new Error(`GitHub request failed (${response.status}): ${url}`);
- }
- const data = (await response.json()) as T;
- return { data, linkHeader: response.headers.get("Link") };
- }
-
- private async graphql<T>(
- query: string,
- variables: Record<string, unknown>,
- ): Promise<T> {
- const response = await fetch(this.graphqlUrl, {
- method: "POST",
- headers: { ...this.headers(), "Content-Type": "application/json" },
- body: JSON.stringify({ query, variables }),
- });
- if (response.status === 401) {
- throw new GitProviderAuthError("GitHub token rejected (401)");
- }
- if (!response.ok) {
- throw new Error(`GitHub GraphQL request failed (${response.status})`);
- }
- const payload = (await response.json()) as { data: T; errors?: unknown };
- if (payload.errors) {
- throw new Error(
- `GitHub GraphQL error: ${JSON.stringify(payload.errors)}`,
- );
- }
- return payload.data;
- }
-
- async getUser(): Promise<GitUser> {
- const { data } = await this.fetchJson<{
- id: number | string;
- login: string;
- avatar_url?: string;
- company?: string | null;
- name?: string | null;
- email?: string | null;
- }>(`${this.baseUrl}/user`);
-
- let email = data.email ?? null;
- if (!email) {
- try {
- const { data: emails } = await this.fetchJson<
- Array<{ email: string; primary: boolean; verified: boolean }>
- >(`${this.baseUrl}/user/emails`);
- const primary = emails.find((entry) => entry.primary && entry.verified);
- email = primary?.email ?? null;
- } catch {
- email = null;
- }
- }
-
- return {
- id: String(data.id ?? ""),
- login: data.login ?? "",
- avatar_url: data.avatar_url ?? "",
- company: data.company ?? null,
- name: data.name ?? null,
- email,
- };
- }
-
- async getSuggestedTasks(): Promise<SuggestedTask[]> {
- const user = await this.getUser();
- const tasks: SuggestedTask[] = [];
-
- try {
- const prData = await this.graphql<{
- user: {
- pullRequests: {
- nodes: Array<{
- number: number;
- title: string;
- repository: { nameWithOwner: string };
- mergeable: string;
- commits: {
- nodes: Array<{
- commit: { statusCheckRollup: { state: string } | null };
- }>;
- };
- reviews: { nodes: Array<{ state: string }> };
- }>;
- };
- };
- }>(SUGGESTED_TASK_PR_QUERY, { login: user.login });
-
- for (const pr of prData.user.pullRequests.nodes) {
- let taskType: SuggestedTaskType | "OPEN_PR" = "OPEN_PR";
- if (pr.mergeable === "CONFLICTING") {
- taskType = "MERGE_CONFLICTS";
- } else {
- const lastCommit = pr.commits.nodes[0]?.commit;
- const status = lastCommit?.statusCheckRollup?.state;
- if (status === "FAILURE") {
- taskType = "FAILING_CHECKS";
- } else if (
- pr.reviews.nodes.some(
- (review) =>
- review.state === "CHANGES_REQUESTED" ||
- review.state === "COMMENTED",
- )
- ) {
- taskType = "UNRESOLVED_COMMENTS";
- }
- }
-
- if (taskType !== "OPEN_PR") {
- tasks.push({
- git_provider: "github",
- task_type: taskType,
- repo: pr.repository.nameWithOwner,
- issue_number: pr.number,
- title: pr.title,
- });
- }
- }
- } catch {
- // Mirror Python: PR query failures should not block the issues query.
- }
-
- try {
- const issueData = await this.graphql<{
- user: {
- issues: {
- nodes: Array<{
- number: number;
- title: string;
- repository: { nameWithOwner: string };
- }>;
- };
- };
- }>(SUGGESTED_TASK_ISSUE_QUERY, { login: user.login });
-
- for (const issue of issueData.user.issues.nodes) {
- tasks.push({
- git_provider: "github",
- task_type: "OPEN_ISSUE",
- repo: issue.repository.nameWithOwner,
- issue_number: issue.number,
- title: issue.title,
- });
- }
- } catch {
- // Already collected PR tasks; surface what we have.
- }
-
- return tasks;
- }
-
- async searchRepositories(
- options: SearchRepositoriesOptions,
- ): Promise<RepositoryPage> {
- const { query, installationId, pageId, limit, sortOrder } = options;
-
- if (query) {
- // GitHub's /search/repositories endpoint searches the entire public
- // corpus when q has no user:/org: qualifier. Mirror the OpenHands OSS
- // behavior and scope to repos the authenticated user can reach: their
- // own + every org they belong to. Aggregate, dedupe by id, then
- // paginate client-side so the UI keeps cursor semantics.
- const aggregated = await this.searchUserScopedRepositories(
- query,
- sortOrder,
- );
- return paginateResults(aggregated, pageId, limit);
- }
-
- const numericPage = Math.max(
- 1,
- Math.floor((decodePageId(pageId) ?? 0) / limit + 1),
- );
- const params: Record<string, string> = {
- per_page: String(limit),
- page: String(numericPage),
- };
- const sort = sortOrderToParams(sortOrder);
- if (sort) {
- params.sort = sort.sort;
- params.direction = sort.order;
- } else {
- params.sort = "pushed";
- }
-
- const baseUrl = installationId
- ? `${this.baseUrl}/user/installations/${installationId}/repositories`
- : `${this.baseUrl}/user/repos`;
- const url = buildSearchUrl(baseUrl, params);
- const { data, linkHeader } = await this.fetchJson<
- GitHubRepoResponse[] | { repositories: GitHubRepoResponse[] }
- >(url);
- const reposRaw = Array.isArray(data) ? data : (data.repositories ?? []);
- const items = reposRaw.map((repo) =>
- this.parseRepository(repo, linkHeader),
- );
- const nextPageId = parseLinkHeaderHasNext(linkHeader)
- ? encodePageId(numericPage * limit)
- : null;
- return { items, next_page_id: nextPageId };
- }
-
- private async searchUserScopedRepositories(
- query: string,
- sortOrder: SortOrder | undefined,
- ): Promise<GitRepository[]> {
- const baseParams: Record<string, string> = { per_page: "30" };
- const sort = sortOrderToParams(sortOrder);
- if (sort) {
- baseParams.sort = sort.sort;
- baseParams.order = sort.order;
- }
-
- const qualifiers: string[] = [];
- if (query.includes("/")) {
- const [owner, repoFragment] = query.split("/", 2);
- if (owner && repoFragment) {
- qualifiers.push(`org:${owner} in:name ${repoFragment}`);
- }
- } else {
- const login = await this.resolveLogin();
- qualifiers.push(`in:name ${query} user:${login}`);
- const orgs = await this.resolveOrgs();
- for (const org of orgs) {
- qualifiers.push(`org:${org} in:name ${query}`);
- }
- }
-
- const responses = await Promise.all(
- qualifiers.map(async (q) => {
- try {
- const url = buildSearchUrl(`${this.baseUrl}/search/repositories`, {
- ...baseParams,
- q,
- });
- const { data } = await this.fetchJson<{
- items: GitHubRepoResponse[];
- }>(url);
- return data.items;
- } catch {
- return [] as GitHubRepoResponse[];
- }
- }),
- );
-
- const seen = new Set<string>();
- const repos: GitRepository[] = [];
- for (const raw of responses.flat()) {
- const id = String(raw.id);
- if (!seen.has(id)) {
- seen.add(id);
- repos.push(this.parseRepository(raw));
- }
- }
- return repos;
- }
-
- private async resolveLogin(): Promise<string> {
- if (this.cachedLogin) return this.cachedLogin;
- const user = await this.getUser();
- this.cachedLogin = user.login;
- return user.login;
- }
-
- private async resolveOrgs(): Promise<string[]> {
- if (this.cachedOrgs) return this.cachedOrgs;
- try {
- const { data } = await this.fetchJson<Array<{ login: string }>>(
- `${this.baseUrl}/user/orgs?per_page=100`,
- );
- this.cachedOrgs = data.map((org) => org.login).filter(Boolean);
- } catch {
- this.cachedOrgs = [];
- }
- return this.cachedOrgs;
- }
-
- async getBranches(options: ListBranchesOptions): Promise<BranchPage> {
- const { repository, query, pageId, limit } = options;
-
- if (query) {
- const parts = repository.split("/");
- if (parts.length < 2) {
- return { items: [], next_page_id: null };
- }
- const [owner, name] = [parts[parts.length - 2], parts[parts.length - 1]];
- const perPage = Math.min(Math.max(limit, 1), 100);
- const data = await this.graphql<{
- repository: {
- refs: {
- nodes: Array<{
- name: string;
- target: {
- __typename?: string;
- oid?: string;
- committedDate?: string;
- } | null;
- }>;
- } | null;
- } | null;
- }>(SEARCH_BRANCHES_QUERY, { owner, name, query, perPage });
- const nodes = data.repository?.refs?.nodes ?? [];
- const items: Branch[] = nodes.map((node) => ({
- name: node.name,
- commit_sha: node.target?.oid ?? "",
- protected: false,
- last_push_date: node.target?.committedDate,
- }));
- return { items, next_page_id: null };
- }
-
- const numericPage = Math.max(
- 1,
- Math.floor((decodePageId(pageId) ?? 0) / limit + 1),
- );
- const url = buildSearchUrl(`${this.baseUrl}/repos/${repository}/branches`, {
- per_page: String(limit),
- page: String(numericPage),
- });
- const { data, linkHeader } =
- await this.fetchJson<GitHubBranchResponse[]>(url);
- const items: Branch[] = data.map((branch) => ({
- name: branch.name,
- commit_sha: branch.commit?.sha ?? "",
- protected: branch.protected ?? false,
- last_push_date: branch.commit?.commit?.committer?.date,
- }));
- const nextPageId = parseLinkHeaderHasNext(linkHeader)
- ? encodePageId(numericPage * limit)
- : null;
- return { items, next_page_id: nextPageId };
- }
-
- async getInstallations(): Promise<InstallationPage> {
- const { data } = await this.fetchJson<{
- installations?: Array<{ id: number | string }>;
- }>(`${this.baseUrl}/user/installations`);
- const items = (data.installations ?? []).map((entry) => String(entry.id));
- return { items, next_page_id: null };
- }
-
- // eslint-disable-next-line class-methods-use-this
- private parseRepository(
- repo: GitHubRepoResponse,
- linkHeader?: string | null,
- ): GitRepository {
- return {
- id: String(repo.id ?? ""),
- full_name: repo.full_name,
- git_provider: "github",
- is_public: !(repo.private ?? true),
- stargazers_count: repo.stargazers_count,
- pushed_at: repo.pushed_at,
- main_branch: repo.default_branch,
- link_header: linkHeader ?? undefined,
- };
- }
-}
diff --git a/src/api/git-providers/gitlab-service.ts b/src/api/git-providers/gitlab-service.ts
deleted file mode 100644
index adcc74999b..0000000000
--- a/src/api/git-providers/gitlab-service.ts
+++ /dev/null
@@ -1,307 +0,0 @@
-import { SuggestedTask, SuggestedTaskType } from "#/utils/types";
-import { ProviderToken } from "#/types/settings";
-import {
- Branch,
- BranchPage,
- GitRepository,
- GitUser,
- InstallationPage,
- RepositoryPage,
-} from "#/types/git";
-import {
- GitProviderAuthError,
- GitProviderService,
- ListBranchesOptions,
- SearchRepositoriesOptions,
-} from "./types";
-import { decodePageId, encodePageId } from "./paging-utils";
-
-const DEFAULT_BASE_URL = "https://gitlab.com/api/v4";
-const DEFAULT_GRAPHQL_URL = "https://gitlab.com/api/graphql";
-
-const SUGGESTED_TASK_QUERY = `
- query GetUserTasks {
- currentUser {
- authoredMergeRequests(state: opened, sort: UPDATED_DESC, first: 100) {
- nodes {
- iid
- title
- project { fullPath }
- conflicts
- mergeStatus
- pipelines(first: 1) { nodes { status } }
- discussions(first: 100) {
- nodes {
- notes { nodes { resolvable resolved } }
- }
- }
- }
- }
- }
- }
-`;
-
-const gitlabBaseUrls = (host: string | null) => {
- if (!host) {
- return { rest: DEFAULT_BASE_URL, graphql: DEFAULT_GRAPHQL_URL };
- }
- const trimmed = host.replace(/^https?:\/\//iu, "").replace(/\/+$/u, "");
- return {
- rest: `https://${trimmed}/api/v4`,
- graphql: `https://${trimmed}/api/graphql`,
- };
-};
-
-const encodeProjectId = (repository: string): string =>
- encodeURIComponent(repository);
-
-interface GitLabProject {
- id: number | string;
- path_with_namespace: string;
- star_count?: number;
- visibility?: string;
- default_branch?: string;
- last_activity_at?: string;
-}
-
-interface GitLabBranch {
- name: string;
- protected?: boolean;
- commit?: { id?: string; committed_date?: string };
-}
-
-export class GitLabService implements GitProviderService {
- readonly provider = "gitlab" as const;
-
- private readonly token: string;
-
- private readonly baseUrl: string;
-
- private readonly graphqlUrl: string;
-
- constructor(credentials: ProviderToken) {
- if (!credentials.token) {
- throw new GitProviderAuthError("GitLab token is empty");
- }
- this.token = credentials.token;
- const urls = gitlabBaseUrls(credentials.host ?? null);
- this.baseUrl = urls.rest;
- this.graphqlUrl = urls.graphql;
- }
-
- private headers(): HeadersInit {
- return { Authorization: `Bearer ${this.token}` };
- }
-
- private async fetchJson<T>(url: string): Promise<T> {
- const response = await fetch(url, { headers: this.headers() });
- if (response.status === 401) {
- throw new GitProviderAuthError("GitLab token rejected (401)");
- }
- if (!response.ok) {
- throw new Error(`GitLab request failed (${response.status}): ${url}`);
- }
- return (await response.json()) as T;
- }
-
- private async graphql<T>(query: string): Promise<T> {
- const response = await fetch(this.graphqlUrl, {
- method: "POST",
- headers: { ...this.headers(), "Content-Type": "application/json" },
- body: JSON.stringify({ query }),
- });
- if (!response.ok) {
- throw new Error(`GitLab GraphQL failed (${response.status})`);
- }
- const payload = (await response.json()) as { data: T; errors?: unknown };
- if (payload.errors) {
- throw new Error(
- `GitLab GraphQL error: ${JSON.stringify(payload.errors)}`,
- );
- }
- return payload.data;
- }
-
- async getUser(): Promise<GitUser> {
- const data = await this.fetchJson<{
- id: number | string;
- username: string;
- avatar_url?: string | null;
- name?: string | null;
- email?: string | null;
- organization?: string | null;
- }>(`${this.baseUrl}/user`);
- return {
- id: String(data.id ?? ""),
- login: data.username ?? "",
- avatar_url: data.avatar_url ?? "",
- name: data.name ?? null,
- email: data.email ?? null,
- company: data.organization ?? null,
- };
- }
-
- async getSuggestedTasks(): Promise<SuggestedTask[]> {
- const tasks: SuggestedTask[] = [];
-
- try {
- const user = await this.getUser();
- const data = await this.graphql<{
- currentUser: {
- authoredMergeRequests: {
- nodes: Array<{
- iid: string;
- title: string;
- project: { fullPath: string };
- conflicts: boolean;
- pipelines: { nodes: Array<{ status: string }> };
- discussions: {
- nodes: Array<{
- notes: {
- nodes: Array<{ resolvable: boolean; resolved: boolean }>;
- };
- }>;
- };
- }>;
- };
- };
- }>(SUGGESTED_TASK_QUERY);
-
- for (const mr of data.currentUser?.authoredMergeRequests?.nodes ?? []) {
- let taskType: SuggestedTaskType | "OPEN_PR" = "OPEN_PR";
- if (mr.conflicts) {
- taskType = "MERGE_CONFLICTS";
- } else if (mr.pipelines.nodes[0]?.status === "FAILED") {
- taskType = "FAILING_CHECKS";
- } else {
- const hasUnresolved = mr.discussions.nodes.some((d) =>
- d.notes.nodes.some((n) => n.resolvable && !n.resolved),
- );
- if (hasUnresolved) {
- taskType = "UNRESOLVED_COMMENTS";
- }
- }
- if (taskType !== "OPEN_PR") {
- tasks.push({
- git_provider: "gitlab",
- task_type: taskType,
- repo: mr.project.fullPath,
- issue_number: Number.parseInt(mr.iid, 10),
- title: mr.title,
- });
- }
- }
-
- const issues = await this.fetchJson<
- Array<{
- iid: number;
- title: string;
- references?: { full?: string };
- }>
- >(
- `${this.baseUrl}/issues?${new URLSearchParams({
- assignee_username: user.login,
- state: "opened",
- scope: "assigned_to_me",
- }).toString()}`,
- );
-
- for (const issue of issues) {
- const repo = (issue.references?.full ?? "").split("#")[0]?.trim() ?? "";
- tasks.push({
- git_provider: "gitlab",
- task_type: "OPEN_ISSUE",
- repo,
- issue_number: issue.iid,
- title: issue.title,
- });
- }
- } catch {
- // Surface whatever we collected; mirrors Python's blanket except.
- }
-
- return tasks;
- }
-
- async searchRepositories(
- options: SearchRepositoriesOptions,
- ): Promise<RepositoryPage> {
- const { query, pageId, limit } = options;
- const numericPage = Math.max(
- 1,
- Math.floor((decodePageId(pageId) ?? 0) / limit + 1),
- );
- const params = new URLSearchParams({
- page: String(numericPage),
- per_page: String(limit),
- order_by: "last_activity_at",
- sort: "desc",
- membership: "true",
- });
- if (query) {
- params.set("search", query);
- params.set("search_namespaces", "true");
- }
-
- const projects = await this.fetchJson<GitLabProject[]>(
- `${this.baseUrl}/projects?${params.toString()}`,
- );
- const items = projects.map((project) => this.parseRepository(project));
- const nextPageId =
- items.length === limit ? encodePageId(numericPage * limit) : null;
- return { items, next_page_id: nextPageId };
- }
-
- async getBranches(options: ListBranchesOptions): Promise<BranchPage> {
- const { repository, query, pageId, limit } = options;
- const projectId = encodeProjectId(repository);
- const params = new URLSearchParams({ per_page: String(limit) });
- if (query) {
- params.set("search", query);
- } else {
- const numericPage = Math.max(
- 1,
- Math.floor((decodePageId(pageId) ?? 0) / limit + 1),
- );
- params.set("page", String(numericPage));
- }
- const data = await this.fetchJson<GitLabBranch[]>(
- `${this.baseUrl}/projects/${projectId}/repository/branches?${params.toString()}`,
- );
- const items: Branch[] = data.map((branch) => ({
- name: branch.name,
- commit_sha: branch.commit?.id ?? "",
- protected: branch.protected ?? false,
- last_push_date: branch.commit?.committed_date,
- }));
- const numericPage = Math.max(
- 1,
- Math.floor((decodePageId(pageId) ?? 0) / limit + 1),
- );
- const nextPageId =
- !query && items.length === limit
- ? encodePageId(numericPage * limit)
- : null;
- return { items, next_page_id: nextPageId };
- }
-
- // GitLab has no "installation" concept β€” return an empty page like the
- // Python backend does for providers without app installations.
- // eslint-disable-next-line class-methods-use-this
- async getInstallations(): Promise<InstallationPage> {
- return { items: [], next_page_id: null };
- }
-
- // eslint-disable-next-line class-methods-use-this
- private parseRepository(project: GitLabProject): GitRepository {
- return {
- id: String(project.id ?? ""),
- full_name: project.path_with_namespace,
- git_provider: "gitlab",
- is_public: project.visibility === "public",
- stargazers_count: project.star_count,
- pushed_at: project.last_activity_at,
- main_branch: project.default_branch,
- };
- }
-}
diff --git a/src/api/git-providers/paging-utils.ts b/src/api/git-providers/paging-utils.ts
deleted file mode 100644
index 6754f434ec..0000000000
--- a/src/api/git-providers/paging-utils.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * Pagination helpers ported from
- * openhands/app_server/utils/paging_utils.py.
- *
- * The page id is intentionally opaque β€” callers should round-trip the string
- * we hand back rather than parsing it. We base64 url-encode the underlying
- * offset so the wire format matches what the original Python backend used.
- */
-
-const stripPadding = (value: string): string => value.replace(/=+$/u, "");
-
-const restorePadding = (value: string): string => {
- const padLength = (4 - (value.length % 4)) % 4;
- return value + "=".repeat(padLength);
-};
-
-export const encodePageId = (value: number): string => {
- if (typeof window === "undefined") {
- return stripPadding(Buffer.from(String(value)).toString("base64url"));
- }
- const base64 = btoa(String(value));
- return stripPadding(base64.replace(/\+/g, "-").replace(/\//g, "_"));
-};
-
-export const decodePageId = (
- pageId: string | null | undefined,
-): number | null => {
- if (!pageId) return null;
- try {
- const padded = restorePadding(pageId);
- const decoded =
- typeof window === "undefined"
- ? Buffer.from(padded, "base64url").toString("utf-8")
- : atob(padded.replace(/-/g, "+").replace(/_/g, "/"));
- const parsed = Number.parseInt(decoded, 10);
- return Number.isFinite(parsed) ? parsed : null;
- } catch {
- return null;
- }
-};
-
-export interface Paginated<T> {
- items: T[];
- next_page_id: string | null;
-}
-
-/**
- * Slice a fully-loaded list into a page using the same offset semantics as
- * paginate_results() in the Python backend.
- */
-export const paginateResults = <T>(
- items: T[],
- pageId: string | null | undefined,
- limit: number,
-): Paginated<T> => {
- const start = decodePageId(pageId) ?? 0;
- const end = start + limit;
- const slice = items.slice(start, end);
- const nextPageId = end < items.length ? encodePageId(end) : null;
- return { items: slice, next_page_id: nextPageId };
-};
diff --git a/src/api/git-providers/provider-handler.ts b/src/api/git-providers/provider-handler.ts
deleted file mode 100644
index 2d8e9e0532..0000000000
--- a/src/api/git-providers/provider-handler.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { SuggestedTask } from "#/utils/types";
-import { Provider, ProviderToken } from "#/types/settings";
-import {
- BranchPage,
- GitUser,
- InstallationPage,
- RepositoryPage,
-} from "#/types/git";
-import { getStoredGitProviderToken } from "../secrets-service";
-import {
- GitProviderAuthError,
- GitProviderService,
- ListBranchesOptions,
- ListInstallationsOptions,
- SearchRepositoriesOptions,
- SuggestedTaskPage,
-} from "./types";
-import { GitHubService } from "./github-service";
-import { GitLabService } from "./gitlab-service";
-import { BitbucketService } from "./bitbucket-service";
-import { BitbucketDataCenterService } from "./bitbucket-dc-service";
-import { AzureDevOpsService } from "./azure-devops-service";
-import { ForgejoService } from "./forgejo-service";
-import { paginateResults } from "./paging-utils";
-
-const PROVIDER_ORDER: Provider[] = [
- "github",
- "gitlab",
- "bitbucket",
- "bitbucket_data_center",
- "azure_devops",
- "forgejo",
-];
-
-const buildService = (
- provider: Provider,
- credentials: ProviderToken,
-): GitProviderService | null => {
- try {
- switch (provider) {
- case "github":
- return new GitHubService(credentials);
- case "gitlab":
- return new GitLabService(credentials);
- case "bitbucket":
- return new BitbucketService(credentials);
- case "bitbucket_data_center":
- return new BitbucketDataCenterService(credentials);
- case "azure_devops":
- return new AzureDevOpsService(credentials);
- case "forgejo":
- return new ForgejoService(credentials);
- default:
- return null;
- }
- } catch (error) {
- if (error instanceof GitProviderAuthError) {
- return null;
- }
- throw error;
- }
-};
-
-const getServiceFor = (provider: Provider): GitProviderService | null => {
- const credentials = getStoredGitProviderToken(provider);
- if (!credentials?.token) return null;
- return buildService(provider, credentials);
-};
-
-const collectAllServices = (): GitProviderService[] =>
- PROVIDER_ORDER.flatMap((provider) => {
- const service = getServiceFor(provider);
- return service ? [service] : [];
- });
-
-const requireService = (provider: Provider): GitProviderService => {
- const service = getServiceFor(provider);
- if (!service) {
- throw new GitProviderAuthError(
- `No git provider configured for ${provider}`,
- );
- }
- return service;
-};
-
-const firstConfiguredService = (): GitProviderService | null => {
- const all = collectAllServices();
- return all[0] ?? null;
-};
-
-export const ProviderHandler = {
- getServiceForProvider: getServiceFor,
-
- /**
- * Resolve the calling user's git profile from any locally-configured
- * provider. Returns `null` when no provider is configured β€” the
- * caller (e.g. `useGitUser`) treats that as "no info to show", which
- * is the right outcome for a clean local install or for the brief
- * window after a Cloud β†’ Local switch where settings haven't refetched
- * yet. Throwing here would surface as a global error toast.
- *
- * When a `provider` is passed explicitly, missing local credentials
- * are still an error β€” the caller asked for that specific provider,
- * so we propagate `requireService`'s `GitProviderAuthError`.
- */
- async getUserGitInfo(provider?: Provider): Promise<GitUser | null> {
- if (provider) {
- return requireService(provider).getUser();
- }
- const service = firstConfiguredService();
- return service ? service.getUser() : null;
- },
-
- async getSuggestedTasks(
- pageId?: string | null,
- limit = 30,
- ): Promise<SuggestedTaskPage> {
- const services = collectAllServices();
- const results = await Promise.all(
- services.map((service) =>
- service.getSuggestedTasks().catch(() => [] as SuggestedTask[]),
- ),
- );
- const all = results.flat();
- return paginateResults(all, pageId ?? null, limit);
- },
-
- async searchRepositories(
- provider: Provider,
- options: SearchRepositoriesOptions,
- ): Promise<RepositoryPage> {
- return requireService(provider).searchRepositories(options);
- },
-
- async getBranches(
- provider: Provider,
- options: ListBranchesOptions,
- ): Promise<BranchPage> {
- return requireService(provider).getBranches(options);
- },
-
- async getInstallations(
- provider: Provider,
- options: ListInstallationsOptions,
- ): Promise<InstallationPage> {
- return requireService(provider).getInstallations(options);
- },
-};
-
-export { GitProviderAuthError };
diff --git a/src/api/git-providers/types.ts b/src/api/git-providers/types.ts
deleted file mode 100644
index 8ff5c7aa2b..0000000000
--- a/src/api/git-providers/types.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { SuggestedTask } from "#/utils/types";
-import { Provider, ProviderToken } from "#/types/settings";
-import {
- BranchPage,
- GitUser,
- InstallationPage,
- RepositoryPage,
-} from "#/types/git";
-
-export type SortOrder =
- | "stars-desc"
- | "stars-asc"
- | "forks-desc"
- | "forks-asc"
- | "updated-desc"
- | "updated-asc";
-
-export interface SuggestedTaskPage {
- items: SuggestedTask[];
- next_page_id: string | null;
-}
-
-export interface SearchRepositoriesOptions {
- query?: string;
- installationId?: string;
- pageId?: string | null;
- limit: number;
- sortOrder?: SortOrder;
-}
-
-export interface ListBranchesOptions {
- repository: string;
- query?: string;
- pageId?: string | null;
- limit: number;
-}
-
-export interface ListInstallationsOptions {
- pageId?: string | null;
- limit: number;
-}
-
-/**
- * Mirror of openhands/app_server/integrations/service_types.py:GitService.
- *
- * Each provider implements this interface against its own REST/GraphQL API.
- * Methods return shapes compatible with the v1 router contract so the
- * existing UI hooks do not need to change.
- */
-export interface GitProviderService {
- readonly provider: Provider;
- getUser(): Promise<GitUser>;
- getSuggestedTasks(): Promise<SuggestedTask[]>;
- searchRepositories(
- options: SearchRepositoriesOptions,
- ): Promise<RepositoryPage>;
- getBranches(options: ListBranchesOptions): Promise<BranchPage>;
- getInstallations(
- options: ListInstallationsOptions,
- ): Promise<InstallationPage>;
-}
-
-export interface ProviderCredentials {
- provider: Provider;
- token: ProviderToken;
-}
-
-export class GitProviderAuthError extends Error {
- constructor(message: string) {
- super(message);
- this.name = "GitProviderAuthError";
- }
-}
diff --git a/src/api/git-service/git-service.api.ts b/src/api/git-service/git-service.api.ts
index 63d114531a..2721cce006 100644
--- a/src/api/git-service/git-service.api.ts
+++ b/src/api/git-service/git-service.api.ts
@@ -4,7 +4,6 @@ import { GitChange, GitChangeDiff } from "../open-hands.types";
import AgentServerConversationService from "../conversation-service/agent-server-conversation-service.api";
import { createRemoteWorkspace } from "../typescript-client";
import { mapAnyGitStatusToClientStatus } from "#/utils/git-status-mapper";
-import { ProviderHandler } from "../git-providers/provider-handler";
import { getActiveBackend } from "../backend-registry/active-store";
import {
getCloudInstallations,
@@ -39,23 +38,15 @@ class GitService {
pageId?: string,
installationId?: string,
): Promise<RepositoryPage> {
- if (isInvalidProvider(provider)) {
+ if (isInvalidProvider(provider) || !isCloudActive()) {
return EMPTY_REPOSITORY_PAGE;
}
- if (isCloudActive()) {
- return searchCloudRepositories({
- provider: safeProvider(provider),
- query: query || undefined,
- limit,
- pageId,
- installationId,
- });
- }
- return ProviderHandler.searchRepositories(safeProvider(provider), {
+ return searchCloudRepositories({
+ provider: safeProvider(provider),
query: query || undefined,
- installationId,
- pageId,
limit,
+ pageId,
+ installationId,
});
}
@@ -65,21 +56,14 @@ class GitService {
limit = 30,
installationId?: string,
): Promise<RepositoryPage> {
- if (isInvalidProvider(provider)) {
+ if (isInvalidProvider(provider) || !isCloudActive()) {
return EMPTY_REPOSITORY_PAGE;
}
- if (isCloudActive()) {
- return searchCloudRepositories({
- provider: safeProvider(provider),
- limit,
- pageId,
- installationId,
- });
- }
- return ProviderHandler.searchRepositories(safeProvider(provider), {
- installationId,
- pageId,
+ return searchCloudRepositories({
+ provider: safeProvider(provider),
limit,
+ pageId,
+ installationId,
});
}
@@ -90,23 +74,16 @@ class GitService {
pageId?: string,
limit = 30,
): Promise<RepositoryPage> {
- if (isInvalidProvider(provider)) {
+ if (isInvalidProvider(provider) || !isCloudActive()) {
return EMPTY_REPOSITORY_PAGE;
}
const installationId = installations[installationIndex];
if (!installationId) return EMPTY_REPOSITORY_PAGE;
- if (isCloudActive()) {
- return searchCloudRepositories({
- provider: safeProvider(provider),
- installationId,
- limit,
- pageId,
- });
- }
- return ProviderHandler.searchRepositories(safeProvider(provider), {
+ return searchCloudRepositories({
+ provider: safeProvider(provider),
installationId,
- pageId,
limit,
+ pageId,
});
}
@@ -117,19 +94,11 @@ class GitService {
pageId?: string,
limit = 30,
): Promise<BranchPage> {
- if (isInvalidProvider(provider)) {
+ if (isInvalidProvider(provider) || !isCloudActive()) {
return EMPTY_BRANCH_PAGE;
}
- if (isCloudActive()) {
- return getCloudRepositoryBranches({
- provider: safeProvider(provider),
- repository,
- query: query || undefined,
- pageId,
- limit,
- });
- }
- return ProviderHandler.getBranches(safeProvider(provider), {
+ return getCloudRepositoryBranches({
+ provider: safeProvider(provider),
repository,
query: query || undefined,
pageId,
@@ -144,19 +113,11 @@ class GitService {
pageId?: string,
limit = 30,
): Promise<BranchPage> {
- if (isInvalidProvider(provider)) {
+ if (isInvalidProvider(provider) || !isCloudActive()) {
return EMPTY_BRANCH_PAGE;
}
- if (isCloudActive()) {
- return getCloudRepositoryBranches({
- provider: safeProvider(provider),
- repository,
- query,
- pageId,
- limit,
- });
- }
- return ProviderHandler.getBranches(safeProvider(provider), {
+ return getCloudRepositoryBranches({
+ provider: safeProvider(provider),
repository,
query,
pageId,
@@ -169,17 +130,11 @@ class GitService {
pageId?: string,
limit = 100,
): Promise<InstallationPage> {
- if (isInvalidProvider(provider)) {
+ if (isInvalidProvider(provider) || !isCloudActive()) {
return EMPTY_INSTALLATION_PAGE;
}
- if (isCloudActive()) {
- return getCloudInstallations({
- provider: safeProvider(provider),
- pageId,
- limit,
- });
- }
- return ProviderHandler.getInstallations(safeProvider(provider), {
+ return getCloudInstallations({
+ provider: safeProvider(provider),
pageId,
limit,
});
diff --git a/src/api/secrets-service.ts b/src/api/secrets-service.ts
index 0a48b2799f..cb51051386 100644
--- a/src/api/secrets-service.ts
+++ b/src/api/secrets-service.ts
@@ -7,7 +7,6 @@ import {
} from "./cloud/secrets-service.api";
import { createHttpClient } from "./typescript-client";
import { CustomSecretWithoutValue } from "./secrets-service.types";
-import { Provider, ProviderOptions, ProviderToken } from "#/types/settings";
/**
* Response from GET /api/settings/secrets (agent-server API)
@@ -37,11 +36,6 @@ interface CreateSecretResponse {
description?: string;
}
-const normalizeHost = (host: string | null | undefined): string | null => {
- const trimmed = typeof host === "string" ? host.trim() : "";
- return trimmed.length > 0 ? trimmed : null;
-};
-
/**
* Retry helper for API calls with exponential backoff.
*/
@@ -70,107 +64,6 @@ async function withRetry<T>(
throw new Error("Retry attempts exhausted");
}
-/**
- * Get the secret name for a git provider token.
- */
-function getGitProviderSecretName(provider: Provider): string {
- return `GIT_PROVIDER_${provider.toUpperCase()}_TOKEN`;
-}
-
-// ============================================================================
-// Git Provider Token Storage (for frontend git API calls)
-// ============================================================================
-// Note: Git provider tokens need to be accessible from the frontend to make
-// direct API calls to GitHub/GitLab/etc. for repo search, branches, etc.
-// These are stored in localStorage for frontend use AND synced to the server
-// for agent runtime use.
-// ============================================================================
-
-const GIT_PROVIDER_STORAGE_KEY = "openhands-agent-server-git-provider-tokens";
-
-type StoredGitProviderTokens = Partial<Record<Provider, ProviderToken>>;
-
-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),
- );
-};
-
-/**
- * Get stored git provider tokens for frontend API calls.
- * These are stored locally for making direct GitHub/GitLab API calls.
- */
-export const getStoredGitProviders = (): StoredGitProviderTokens =>
- readStoredGitProviders();
-
-/**
- * Get a specific git provider token for frontend API calls.
- */
-export const getStoredGitProviderToken = (
- provider: Provider,
-): ProviderToken | null => readStoredGitProviders()[provider] ?? null;
-
export class SecretsService {
/**
* List all custom secrets (names and descriptions only, no values).
@@ -281,71 +174,4 @@ export class SecretsService {
throw error;
}
}
-
- /**
- * Add or update git provider tokens.
- * Stores tokens in both:
- * 1. localStorage - for frontend git API calls (repo search, branches, etc.)
- * 2. Agent server secrets API - for agent runtime use
- *
- * Both stores must succeed for the operation to complete successfully.
- *
- * @throws Error if the server API call fails after retries
- */
- static async addGitProvider(
- providers: Partial<Record<Provider, ProviderToken>>,
- ): Promise<void> {
- const storedProviders = readStoredGitProviders();
- const nextProviders: StoredGitProviderTokens = { ...storedProviders };
-
- const entries = Object.entries(providers) as [Provider, ProviderToken][];
-
- for (const [provider, value] of entries) {
- const token = value.token.trim();
- const host = normalizeHost(value.host);
- const nextToken = token || nextProviders[provider]?.token;
-
- if (nextToken) {
- const secretName = getGitProviderSecretName(provider);
- // eslint-disable-next-line no-await-in-loop
- await this.createSecret(
- secretName,
- nextToken,
- `Git provider token for ${provider}${host ? ` (${host})` : ""}`,
- );
-
- // Only update localStorage after server storage succeeds
- nextProviders[provider] = { token: nextToken, host };
- }
- }
-
- // Update localStorage for frontend git API calls
- writeStoredGitProviders(nextProviders);
- }
-
- /**
- * Delete all git provider tokens from both localStorage and server.
- */
- static async deleteGitProviders(): Promise<void> {
- const storedProviders = readStoredGitProviders();
-
- // Delete each provider's secret from the server
- await Promise.all(
- (Object.keys(storedProviders) as Provider[]).map(async (provider) => {
- const secretName = getGitProviderSecretName(provider);
- try {
- await this.deleteSecret(secretName);
- } catch (error) {
- // Log but continue - we still want to clear other providers
- console.warn(
- `Failed to delete git provider secret for ${provider}:`,
- error,
- );
- }
- }),
- );
-
- // Clear localStorage
- writeStoredGitProviders({});
- }
}
diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.ts
index d51ebd96dc..f4c3b1fb4c 100644
--- a/src/api/settings-service/settings-service.api.ts
+++ b/src/api/settings-service/settings-service.api.ts
@@ -1,16 +1,10 @@
import { DEFAULT_SETTINGS } from "#/services/settings";
-import {
- Provider,
- Settings,
- SettingsSchema,
- SettingsValue,
-} from "#/types/settings";
+import { Settings, SettingsSchema, SettingsValue } from "#/types/settings";
import {
extractAppPreferences,
readStoredAppPreferences,
writeStoredAppPreferences,
} from "../app-preferences-store";
-import { getStoredGitProviders } from "../secrets-service";
import { getActiveBackend } from "../backend-registry/active-store";
import {
fetchCloudConversationSettingsSchema,
@@ -138,17 +132,6 @@ const syncDerivedSettings = (settings: Partial<Settings>): Settings => {
settings.conversation_settings ?? {},
);
- // The agent-server has no concept of provider_tokens_set; the GUI derives it
- // from locally-stored git provider credentials so the UI knows which
- // providers are configured after a save.
- const storedProviders = getStoredGitProviders();
- const derivedProviderTokensSet = Object.fromEntries(
- Object.entries(storedProviders).map(([provider, value]) => [
- provider,
- value?.host ?? null,
- ]),
- ) as Partial<Record<Provider, string | null>>;
-
// App-level user preferences (language, git identity, sound notifications,
// analytics consent) live in localStorage in local mode. In cloud mode the
// server response carries them and overrides the local cache.
@@ -161,7 +144,6 @@ const syncDerivedSettings = (settings: Partial<Settings>): Settings => {
provider_tokens_set: {
...(DEFAULT_SETTINGS.provider_tokens_set ?? {}),
...(settings.provider_tokens_set ?? {}),
- ...derivedProviderTokensSet,
},
agent_settings: agentSettings,
conversation_settings: conversationSettings,
diff --git a/src/api/suggestions-service/suggestions-service.api.ts b/src/api/suggestions-service/suggestions-service.api.ts
index e6172dca55..708073edbf 100644
--- a/src/api/suggestions-service/suggestions-service.api.ts
+++ b/src/api/suggestions-service/suggestions-service.api.ts
@@ -1,19 +1,23 @@
import { SuggestedTask } from "#/utils/types";
-import { ProviderHandler } from "../git-providers/provider-handler";
+import { getActiveBackend } from "../backend-registry/active-store";
+import { getCloudSuggestedTasks } from "../cloud/suggestions-service.api";
export class SuggestionsService {
/**
- * Aggregate suggested tasks across every configured git provider.
- *
- * Mirrors the OSS /api/v1/git/suggested-tasks/search shape but resolves
- * tasks client-side because the agent-server runtime has no integrations
- * router.
+ * Aggregate suggested tasks for the calling user. Cloud SaaS exposes
+ * `/api/v1/git/suggested-tasks/search` which the proxy forwards to.
+ * Local agent-server has no equivalent endpoint, so we return an
+ * empty list there β€” the home page's `<TaskSuggestions />` already
+ * renders nothing when the active backend is local.
*/
static async getSuggestedTasks(
pageId?: string,
limit: number = 30,
): Promise<SuggestedTask[]> {
- const page = await ProviderHandler.getSuggestedTasks(pageId, limit);
+ if (getActiveBackend().backend.kind !== "cloud") {
+ return [];
+ }
+ const page = await getCloudSuggestedTasks({ pageId, limit });
return page.items;
}
}
diff --git a/src/api/user-service/user-service.api.ts b/src/api/user-service/user-service.api.ts
deleted file mode 100644
index 9991098966..0000000000
--- a/src/api/user-service/user-service.api.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { GitUser } from "#/types/git";
-import { getActiveBackend } from "../backend-registry/active-store";
-import { getCloudGitUser } from "../cloud/user-service.api";
-import { ProviderHandler } from "../git-providers/provider-handler";
-
-/**
- * User Service API - Handles all user-related API endpoints.
- *
- * Local mode: the OSS agent-server runtime does not expose
- * `/api/v1/users/git-info`, so we resolve the user directly from the
- * configured git provider in the browser via `ProviderHandler`. If no
- * provider tokens are stored locally, this throws
- * "No git provider configured" β€” the right signal for local operation.
- *
- * Cloud mode: the SaaS exposes `/api/v1/users/git-info` and holds
- * provider tokens server-side. There is nothing local to check, so we
- * route through the cloud proxy. The local "no provider configured"
- * check is meaningless for cloud and would otherwise surface as a false
- * toast β€” branching here keeps it scoped to local.
- */
-class UserService {
- static async getUser(): Promise<GitUser | null> {
- if (getActiveBackend().backend.kind === "cloud") {
- return getCloudGitUser();
- }
- return ProviderHandler.getUserGitInfo();
- }
-}
-
-export default UserService;
diff --git a/src/components/features/settings/git-settings/azure-devops-token-help-anchor.tsx b/src/components/features/settings/git-settings/azure-devops-token-help-anchor.tsx
deleted file mode 100644
index edee1335ea..0000000000
--- a/src/components/features/settings/git-settings/azure-devops-token-help-anchor.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-
-export function AzureDevOpsTokenHelpAnchor() {
- const { t } = useTranslation("openhands");
-
- return (
- <p data-testid="azure-devops-token-help-anchor" className="text-xs">
- <a
- href="https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate"
- target="_blank"
- className="underline underline-offset-2"
- rel="noopener noreferrer"
- aria-label={t(I18nKey.GIT$AZURE_DEVOPS_TOKEN_HELP)}
- >
- {t(I18nKey.GIT$AZURE_DEVOPS_TOKEN_HELP)}
- </a>
- </p>
- );
-}
diff --git a/src/components/features/settings/git-settings/azure-devops-token-input.tsx b/src/components/features/settings/git-settings/azure-devops-token-input.tsx
deleted file mode 100644
index df451e7854..0000000000
--- a/src/components/features/settings/git-settings/azure-devops-token-input.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-import { SettingsInput } from "../settings-input";
-import { AzureDevOpsTokenHelpAnchor } from "./azure-devops-token-help-anchor";
-import { KeyStatusIcon } from "../key-status-icon";
-
-interface AzureDevOpsTokenInputProps {
- onChange: (value: string) => void;
- onAzureDevOpsHostChange: (value: string) => void;
- isAzureDevOpsTokenSet: boolean;
- name: string;
- azureDevOpsHostSet: string | null | undefined;
-}
-
-export function AzureDevOpsTokenInput({
- onChange,
- onAzureDevOpsHostChange,
- isAzureDevOpsTokenSet,
- name,
- azureDevOpsHostSet,
-}: AzureDevOpsTokenInputProps) {
- const { t } = useTranslation("openhands");
-
- return (
- <div className="flex flex-col gap-6">
- <SettingsInput
- testId={name}
- name={name}
- onChange={onChange}
- label={t(I18nKey.GIT$AZURE_DEVOPS_TOKEN)}
- type="password"
- className="w-full max-w-[680px]"
- placeholder={isAzureDevOpsTokenSet ? "<hidden>" : ""}
- startContent={
- isAzureDevOpsTokenSet && (
- <KeyStatusIcon
- testId="azure-devops-set-token-indicator"
- isSet={isAzureDevOpsTokenSet}
- />
- )
- }
- />
-
- <SettingsInput
- onChange={onAzureDevOpsHostChange || (() => {})}
- name="azure-devops-host-input"
- testId="azure-devops-host-input"
- label={t(I18nKey.GIT$AZURE_DEVOPS_HOST)}
- type="text"
- className="w-full max-w-[680px]"
- placeholder={t(I18nKey.GIT$AZURE_DEVOPS_HOST_PLACEHOLDER)}
- defaultValue={azureDevOpsHostSet || undefined}
- startContent={
- azureDevOpsHostSet &&
- azureDevOpsHostSet.trim() !== "" && (
- <KeyStatusIcon testId="azure-devops-set-host-indicator" isSet />
- )
- }
- />
-
- <AzureDevOpsTokenHelpAnchor />
- </div>
- );
-}
diff --git a/src/components/features/settings/git-settings/bitbucket-dc-token-help-anchor.tsx b/src/components/features/settings/git-settings/bitbucket-dc-token-help-anchor.tsx
deleted file mode 100644
index 46935f9d71..0000000000
--- a/src/components/features/settings/git-settings/bitbucket-dc-token-help-anchor.tsx
+++ /dev/null
@@ -1,28 +0,0 @@
-import { Trans, useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-
-export function BitbucketDCTokenHelpAnchor() {
- const { t } = useTranslation("openhands");
-
- return (
- <p
- data-testid="bitbucket-dc-token-help-anchor"
- className="text-xs max-w-[680px]"
- >
- <Trans
- ns="openhands"
- i18nKey={I18nKey.BITBUCKET_DATA_CENTER$TOKEN_HELP_TEXT}
- components={[
- <a
- key="bitbucket-dc-token-help-anchor-link"
- aria-label={t(I18nKey.GIT$BITBUCKET_DC_TOKEN_HELP_LINK)}
- href="https://confluence.atlassian.com/bitbucketserver/http-access-tokens-939515499.html"
- target="_blank"
- className="underline underline-offset-2"
- rel="noopener noreferrer"
- />,
- ]}
- />
- </p>
- );
-}
diff --git a/src/components/features/settings/git-settings/bitbucket-dc-token-help-input.tsx b/src/components/features/settings/git-settings/bitbucket-dc-token-help-input.tsx
deleted file mode 100644
index c0043bd494..0000000000
--- a/src/components/features/settings/git-settings/bitbucket-dc-token-help-input.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-import { SettingsInput } from "../settings-input";
-import { BitbucketDCTokenHelpAnchor } from "./bitbucket-dc-token-help-anchor";
-import { KeyStatusIcon } from "../key-status-icon";
-import { cn } from "#/utils/utils";
-
-interface BitbucketDCTokenInputProps {
- onChange: (value: string) => void;
- onBitbucketDCHostChange: (value: string) => void;
- isBitbucketDCTokenSet: boolean;
- name: string;
- bitbucketDCHostSet: string | null | undefined;
- className?: string;
-}
-
-export function BitbucketDCTokenInput({
- onChange,
- onBitbucketDCHostChange,
- isBitbucketDCTokenSet,
- name,
- bitbucketDCHostSet,
- className,
-}: BitbucketDCTokenInputProps) {
- const { t } = useTranslation("openhands");
-
- return (
- <div className={cn("flex flex-col gap-6", className)}>
- <SettingsInput
- testId={name}
- name={name}
- onChange={onChange}
- label={t(I18nKey.BITBUCKET_DATA_CENTER$TOKEN_LABEL)}
- type="password"
- className="w-full max-w-[680px]"
- placeholder={isBitbucketDCTokenSet ? "<hidden>" : "username:token"}
- startContent={
- isBitbucketDCTokenSet && (
- <KeyStatusIcon
- testId="bb-dc-set-token-indicator"
- isSet={isBitbucketDCTokenSet}
- />
- )
- }
- />
-
- <SettingsInput
- onChange={onBitbucketDCHostChange || (() => {})}
- name="bitbucket-dc-host-input"
- testId="bitbucket-dc-host-input"
- label={t(I18nKey.BITBUCKET_DATA_CENTER$HOST_LABEL)}
- type="text"
- className="w-full max-w-[680px]"
- placeholder="bitbucket.your-company.com"
- defaultValue={bitbucketDCHostSet || undefined}
- startContent={
- bitbucketDCHostSet &&
- bitbucketDCHostSet.trim() !== "" && (
- <KeyStatusIcon testId="bb-dc-set-host-indicator" isSet />
- )
- }
- />
-
- <BitbucketDCTokenHelpAnchor />
- </div>
- );
-}
diff --git a/src/components/features/settings/git-settings/bitbucket-token-help-anchor.tsx b/src/components/features/settings/git-settings/bitbucket-token-help-anchor.tsx
deleted file mode 100644
index 9c70f3874d..0000000000
--- a/src/components/features/settings/git-settings/bitbucket-token-help-anchor.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { Trans, useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-
-export function BitbucketTokenHelpAnchor() {
- const { t } = useTranslation("openhands");
-
- return (
- <p data-testid="bitbucket-token-help-anchor" className="text-xs">
- <Trans
- ns="openhands"
- i18nKey={I18nKey.BITBUCKET$TOKEN_HELP_TEXT}
- components={[
- <a
- key="bitbucket-token-help-anchor-link"
- aria-label={t(I18nKey.GIT$BITBUCKET_TOKEN_HELP_LINK)}
- href="https://bitbucket.org/account/settings/app-passwords/new?scopes=repository:write,pullrequest:write,issue:write"
- target="_blank"
- className="underline underline-offset-2"
- rel="noopener noreferrer"
- />,
- <a
- key="bitbucket-token-help-anchor-link-2"
- aria-label={t(I18nKey.GIT$BITBUCKET_TOKEN_SEE_MORE_LINK)}
- href="https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/"
- target="_blank"
- className="underline underline-offset-2"
- rel="noopener noreferrer"
- />,
- ]}
- />
- </p>
- );
-}
diff --git a/src/components/features/settings/git-settings/bitbucket-token-input.tsx b/src/components/features/settings/git-settings/bitbucket-token-input.tsx
deleted file mode 100644
index 121022fe3a..0000000000
--- a/src/components/features/settings/git-settings/bitbucket-token-input.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-import { SettingsInput } from "../settings-input";
-import { BitbucketTokenHelpAnchor } from "./bitbucket-token-help-anchor";
-import { KeyStatusIcon } from "../key-status-icon";
-import { cn } from "#/utils/utils";
-
-interface BitbucketTokenInputProps {
- onChange: (value: string) => void;
- onBitbucketHostChange: (value: string) => void;
- isBitbucketTokenSet: boolean;
- name: string;
- bitbucketHostSet: string | null | undefined;
- className?: string;
-}
-
-export function BitbucketTokenInput({
- onChange,
- onBitbucketHostChange,
- isBitbucketTokenSet,
- name,
- bitbucketHostSet,
- className,
-}: BitbucketTokenInputProps) {
- const { t } = useTranslation("openhands");
-
- return (
- <div className={cn("flex flex-col gap-6", className)}>
- <SettingsInput
- testId={name}
- name={name}
- onChange={onChange}
- label={t(I18nKey.BITBUCKET$TOKEN_LABEL)}
- type="password"
- className="w-full max-w-[680px]"
- placeholder={isBitbucketTokenSet ? "<hidden>" : "username:app_password"}
- startContent={
- isBitbucketTokenSet && (
- <KeyStatusIcon
- testId="bb-set-token-indicator"
- isSet={isBitbucketTokenSet}
- />
- )
- }
- />
-
- <SettingsInput
- onChange={onBitbucketHostChange || (() => {})}
- name="bitbucket-host-input"
- testId="bitbucket-host-input"
- label={t(I18nKey.BITBUCKET$HOST_LABEL)}
- type="text"
- className="w-full max-w-[680px]"
- placeholder="bitbucket.org"
- defaultValue={bitbucketHostSet || undefined}
- startContent={
- bitbucketHostSet &&
- bitbucketHostSet.trim() !== "" && (
- <KeyStatusIcon testId="bb-set-host-indicator" isSet />
- )
- }
- />
-
- <BitbucketTokenHelpAnchor />
- </div>
- );
-}
diff --git a/src/components/features/settings/git-settings/configure-github-repositories-anchor.tsx b/src/components/features/settings/git-settings/configure-github-repositories-anchor.tsx
deleted file mode 100644
index 14e0b383c2..0000000000
--- a/src/components/features/settings/git-settings/configure-github-repositories-anchor.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-import { BrandButton } from "../brand-button";
-
-interface ConfigureGitHubRepositoriesAnchorProps {
- slug: string;
-}
-
-export function ConfigureGitHubRepositoriesAnchor({
- slug,
-}: ConfigureGitHubRepositoriesAnchorProps) {
- const { t } = useTranslation("openhands");
-
- return (
- <div data-testid="configure-github-repositories-button" className="py-9">
- <BrandButton
- type="button"
- variant="primary"
- className="w-55"
- onClick={() =>
- window.open(
- `https://github.com/apps/${slug}/installations/new`,
- "_blank",
- "noreferrer noopener",
- )
- }
- >
- {t(I18nKey.GITHUB$CONFIGURE_REPOS)}
- </BrandButton>
- </div>
- );
-}
diff --git a/src/components/features/settings/git-settings/forgejo-token-input.tsx b/src/components/features/settings/git-settings/forgejo-token-input.tsx
deleted file mode 100644
index d9df2059dd..0000000000
--- a/src/components/features/settings/git-settings/forgejo-token-input.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-import { SettingsInput } from "../settings-input";
-import { KeyStatusIcon } from "../key-status-icon";
-import { cn } from "#/utils/utils";
-
-interface ForgejoTokenInputProps {
- onChange: (value: string) => void;
- onForgejoHostChange: (value: string) => void;
- isForgejoTokenSet: boolean;
- name: string;
- forgejoHostSet: string | null | undefined;
- className?: string;
-}
-
-export function ForgejoTokenInput({
- onChange,
- onForgejoHostChange,
- isForgejoTokenSet,
- name,
- forgejoHostSet,
- className,
-}: ForgejoTokenInputProps) {
- const { t } = useTranslation("openhands");
-
- return (
- <div className={cn("flex flex-col gap-6", className)}>
- <SettingsInput
- testId={name}
- name={name}
- onChange={onChange}
- label={t(I18nKey.FORGEJO$TOKEN_LABEL)}
- type="password"
- className="w-full max-w-[680px]"
- placeholder={isForgejoTokenSet ? "<hidden>" : ""}
- startContent={
- isForgejoTokenSet && (
- <KeyStatusIcon
- testId="forgejo-set-token-indicator"
- isSet={isForgejoTokenSet}
- />
- )
- }
- />
-
- <SettingsInput
- onChange={onForgejoHostChange || (() => {})}
- name="forgejo-host-input"
- testId="forgejo-host-input"
- label={t(I18nKey.FORGEJO$HOST_LABEL)}
- type="text"
- className="w-full max-w-[680px]"
- placeholder="codeberg.org"
- defaultValue={forgejoHostSet || undefined}
- startContent={
- forgejoHostSet &&
- forgejoHostSet.trim() !== "" && (
- <KeyStatusIcon testId="forgejo-set-host-indicator" isSet />
- )
- }
- />
- </div>
- );
-}
diff --git a/src/components/features/settings/git-settings/github-settings-inputs-skeleton.tsx b/src/components/features/settings/git-settings/github-settings-inputs-skeleton.tsx
deleted file mode 100644
index 9885b98cec..0000000000
--- a/src/components/features/settings/git-settings/github-settings-inputs-skeleton.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import { InputSkeleton } from "../input-skeleton";
-import { SubtextSkeleton } from "../subtext-skeleton";
-
-export function GitSettingInputsSkeleton() {
- return (
- <div className="px-11 py-9 flex flex-col gap-12">
- <div className="flex flex-col gap-6">
- <InputSkeleton />
- <SubtextSkeleton />
- </div>
-
- <div className="flex flex-col gap-6">
- <InputSkeleton />
- <SubtextSkeleton />
- </div>
- </div>
- );
-}
diff --git a/src/components/features/settings/git-settings/github-token-help-anchor.tsx b/src/components/features/settings/git-settings/github-token-help-anchor.tsx
deleted file mode 100644
index 3566cd32a0..0000000000
--- a/src/components/features/settings/git-settings/github-token-help-anchor.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { Trans, useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-
-export function GitHubTokenHelpAnchor() {
- const { t } = useTranslation("openhands");
-
- return (
- <p data-testid="github-token-help-anchor" className="text-xs">
- <Trans
- ns="openhands"
- i18nKey={I18nKey.GITHUB$TOKEN_HELP_TEXT}
- components={[
- <a
- key="github-token-help-anchor-link"
- aria-label={t(I18nKey.GIT$GITHUB_TOKEN_HELP_LINK)}
- href="https://github.com/settings/tokens/new?description=openhands-app&scopes=repo,user,workflow"
- target="_blank"
- className="underline underline-offset-2"
- rel="noopener noreferrer"
- />,
- <a
- key="github-token-help-anchor-link-2"
- aria-label={t(I18nKey.GIT$GITHUB_TOKEN_SEE_MORE_LINK)}
- href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token"
- target="_blank"
- className="underline underline-offset-2"
- rel="noopener noreferrer"
- />,
- ]}
- />
- </p>
- );
-}
diff --git a/src/components/features/settings/git-settings/github-token-input.tsx b/src/components/features/settings/git-settings/github-token-input.tsx
deleted file mode 100644
index d6d0fa3b1b..0000000000
--- a/src/components/features/settings/git-settings/github-token-input.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-import { SettingsInput } from "../settings-input";
-import { GitHubTokenHelpAnchor } from "./github-token-help-anchor";
-import { KeyStatusIcon } from "../key-status-icon";
-import { cn } from "#/utils/utils";
-
-interface GitHubTokenInputProps {
- onChange: (value: string) => void;
- onGitHubHostChange: (value: string) => void;
- isGitHubTokenSet: boolean;
- name: string;
- githubHostSet: string | null | undefined;
- className?: string;
-}
-
-export function GitHubTokenInput({
- onChange,
- onGitHubHostChange,
- isGitHubTokenSet,
- name,
- githubHostSet,
- className,
-}: GitHubTokenInputProps) {
- const { t } = useTranslation("openhands");
-
- return (
- <div className={cn("flex flex-col gap-6", className)}>
- <SettingsInput
- testId={name}
- name={name}
- onChange={onChange}
- label={t(I18nKey.GITHUB$TOKEN_LABEL)}
- type="password"
- className="w-full max-w-[680px]"
- placeholder={isGitHubTokenSet ? "<hidden>" : ""}
- startContent={
- isGitHubTokenSet && (
- <KeyStatusIcon
- testId="gh-set-token-indicator"
- isSet={isGitHubTokenSet}
- />
- )
- }
- />
-
- <SettingsInput
- onChange={onGitHubHostChange || (() => {})}
- name="github-host-input"
- testId="github-host-input"
- label={t(I18nKey.GITHUB$HOST_LABEL)}
- type="text"
- className="w-full max-w-[680px]"
- placeholder="github.com"
- defaultValue={githubHostSet || undefined}
- startContent={
- githubHostSet &&
- githubHostSet.trim() !== "" && (
- <KeyStatusIcon testId="gh-set-host-indicator" isSet />
- )
- }
- />
-
- <GitHubTokenHelpAnchor />
- </div>
- );
-}
diff --git a/src/components/features/settings/git-settings/gitlab-token-help-anchor.tsx b/src/components/features/settings/git-settings/gitlab-token-help-anchor.tsx
deleted file mode 100644
index a871d8ee30..0000000000
--- a/src/components/features/settings/git-settings/gitlab-token-help-anchor.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { Trans, useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-
-export function GitLabTokenHelpAnchor() {
- const { t } = useTranslation("openhands");
-
- return (
- <p data-testid="gitlab-token-help-anchor" className="text-xs">
- <Trans
- ns="openhands"
- i18nKey={I18nKey.GITLAB$TOKEN_HELP_TEXT}
- components={[
- <a
- key="gitlab-token-help-anchor-link"
- aria-label={t(I18nKey.GIT$GITLAB_TOKEN_HELP_LINK)}
- href="https://gitlab.com/-/user_settings/personal_access_tokens?name=openhands-app&scopes=api,read_user,read_repository,write_repository"
- target="_blank"
- className="underline underline-offset-2"
- rel="noopener noreferrer"
- />,
- <a
- key="gitlab-token-help-anchor-link-2"
- aria-label={t(I18nKey.GIT$GITLAB_TOKEN_SEE_MORE_LINK)}
- href="https://docs.gitlab.com/user/profile/personal_access_tokens/"
- target="_blank"
- className="underline underline-offset-2"
- rel="noopener noreferrer"
- />,
- ]}
- />
- </p>
- );
-}
diff --git a/src/components/features/settings/git-settings/gitlab-token-input.tsx b/src/components/features/settings/git-settings/gitlab-token-input.tsx
deleted file mode 100644
index cd9ce6c256..0000000000
--- a/src/components/features/settings/git-settings/gitlab-token-input.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-import { SettingsInput } from "../settings-input";
-import { GitLabTokenHelpAnchor } from "./gitlab-token-help-anchor";
-import { KeyStatusIcon } from "../key-status-icon";
-import { cn } from "#/utils/utils";
-
-interface GitLabTokenInputProps {
- onChange: (value: string) => void;
- onGitLabHostChange: (value: string) => void;
- isGitLabTokenSet: boolean;
- name: string;
- gitlabHostSet: string | null | undefined;
- className?: string;
-}
-
-export function GitLabTokenInput({
- onChange,
- onGitLabHostChange,
- isGitLabTokenSet,
- name,
- gitlabHostSet,
- className,
-}: GitLabTokenInputProps) {
- const { t } = useTranslation("openhands");
-
- return (
- <div className={cn("flex flex-col gap-6", className)}>
- <SettingsInput
- testId={name}
- name={name}
- onChange={onChange}
- label={t(I18nKey.GITLAB$TOKEN_LABEL)}
- type="password"
- className="w-full max-w-[680px]"
- placeholder={isGitLabTokenSet ? "<hidden>" : ""}
- startContent={
- isGitLabTokenSet && (
- <KeyStatusIcon
- testId="gl-set-token-indicator"
- isSet={isGitLabTokenSet}
- />
- )
- }
- />
-
- <SettingsInput
- onChange={onGitLabHostChange || (() => {})}
- name="gitlab-host-input"
- testId="gitlab-host-input"
- label={t(I18nKey.GITLAB$HOST_LABEL)}
- type="text"
- className="w-full max-w-[680px]"
- placeholder="gitlab.com"
- defaultValue={gitlabHostSet || undefined}
- startContent={
- gitlabHostSet &&
- gitlabHostSet.trim() !== "" && (
- <KeyStatusIcon testId="gl-set-host-indicator" isSet />
- )
- }
- />
-
- <GitLabTokenHelpAnchor />
- </div>
- );
-}
diff --git a/src/components/features/settings/git-settings/install-slack-app-anchor.tsx b/src/components/features/settings/git-settings/install-slack-app-anchor.tsx
deleted file mode 100644
index 2edc452b9b..0000000000
--- a/src/components/features/settings/git-settings/install-slack-app-anchor.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-import { BrandButton } from "../brand-button";
-
-export function InstallSlackAppAnchor() {
- const { t } = useTranslation("openhands");
-
- return (
- <div data-testid="install-slack-app-button" className="py-9">
- <BrandButton
- type="button"
- variant="primary"
- className="w-55"
- onClick={() =>
- window.open(
- "https://slack.com/oauth/v2/authorize?client_id=7477886716822.8729519890534&scope=app_mentions:read,channels:history,chat:write,groups:history,im:history,mpim:history,users:read&user_scope=",
- "_blank",
- "noreferrer noopener",
- )
- }
- >
- {t(I18nKey.SLACK$INSTALL_APP)}
- </BrandButton>
- </div>
- );
-}
diff --git a/src/components/features/settings/git-settings/webhook-status-badge.tsx b/src/components/features/settings/git-settings/webhook-status-badge.tsx
deleted file mode 100644
index 159a0c6275..0000000000
--- a/src/components/features/settings/git-settings/webhook-status-badge.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-import { Typography } from "#/ui/typography";
-
-export interface WebhookStatusBadgeProps {
- webhookInstalled: boolean;
- installationResult?: { success: boolean; error: string | null } | null;
-}
-
-export function WebhookStatusBadge({
- webhookInstalled,
- installationResult,
-}: WebhookStatusBadgeProps) {
- const { t } = useTranslation("openhands");
-
- if (installationResult) {
- if (installationResult.success) {
- return (
- <Typography.Text className="px-2 py-1 text-xs rounded bg-green-500/20 text-green-400">
- {t(I18nKey.GITLAB$WEBHOOK_STATUS_INSTALLED)}
- </Typography.Text>
- );
- }
- return (
- <span title={installationResult.error || undefined}>
- <Typography.Text className="px-2 py-1 text-xs rounded bg-red-500/20 text-red-400">
- {t(I18nKey.GITLAB$WEBHOOK_STATUS_FAILED)}
- </Typography.Text>
- </span>
- );
- }
-
- if (webhookInstalled) {
- return (
- <Typography.Text className="px-2 py-1 text-xs rounded bg-green-500/20 text-green-400">
- {t(I18nKey.GITLAB$WEBHOOK_STATUS_INSTALLED)}
- </Typography.Text>
- );
- }
-
- return (
- <Typography.Text className="px-2 py-1 text-xs rounded bg-gray-500/20 text-gray-400">
- {t(I18nKey.GITLAB$WEBHOOK_STATUS_NOT_INSTALLED)}
- </Typography.Text>
- );
-}
diff --git a/src/components/features/sidebar/sidebar.tsx b/src/components/features/sidebar/sidebar.tsx
index f653598487..44be944b47 100644
--- a/src/components/features/sidebar/sidebar.tsx
+++ b/src/components/features/sidebar/sidebar.tsx
@@ -243,17 +243,6 @@ export function Sidebar() {
collapsed={collapsed}
icon={<AutomationsIcon width={ICON_SIZE} height={ICON_SIZE} />}
/>
- {/*
- Integrations tab is currently hidden because it isn't working yet.
- The underlying route and logic are still wired up β€” devs are
- welcome to uncomment this block and experiment.
- */}
- {/* <SidebarNavLink
- to="/integrations"
- label={t(I18nKey.SIDEBAR$INTEGRATIONS)}
- testId="sidebar-integrations-link"
- disabled={linkDisabled}
- /> */}
<div className="hidden md:flex flex-col gap-0.5">
{collapsed ? (
// Collapsed: render Settings as a single icon link to /settings
diff --git a/src/hooks/mutation/use-add-git-providers.ts b/src/hooks/mutation/use-add-git-providers.ts
deleted file mode 100644
index d4ce49d348..0000000000
--- a/src/hooks/mutation/use-add-git-providers.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { SecretsService } from "#/api/secrets-service";
-import { Provider, ProviderToken } from "#/types/settings";
-import { useTracking } from "#/hooks/use-tracking";
-import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";
-
-export const useAddGitProviders = () => {
- const queryClient = useQueryClient();
- const { trackGitProviderConnected } = useTracking();
-
- return useMutation({
- mutationFn: ({
- providers,
- }: {
- providers: Partial<Record<Provider, ProviderToken>>;
- }) => SecretsService.addGitProvider(providers),
- onSuccess: async (_, { providers }) => {
- const connectedProviders = Object.entries(providers)
- .filter(([, value]) => value?.token && value.token.trim() !== "")
- .map(([key]) => key);
-
- if (connectedProviders.length > 0) {
- trackGitProviderConnected({
- providers: connectedProviders,
- });
- }
-
- await queryClient.invalidateQueries({
- queryKey: SETTINGS_QUERY_KEYS.personal(),
- });
- },
- meta: {
- disableToast: true,
- },
- });
-};
diff --git a/src/hooks/mutation/use-delete-git-providers.ts b/src/hooks/mutation/use-delete-git-providers.ts
deleted file mode 100644
index b646dd9ab2..0000000000
--- a/src/hooks/mutation/use-delete-git-providers.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { SecretsService } from "#/api/secrets-service";
-import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";
-
-export const useDeleteGitProviders = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: () => SecretsService.deleteGitProviders(),
- onSuccess: async () => {
- await queryClient.invalidateQueries({
- queryKey: SETTINGS_QUERY_KEYS.personal(),
- });
- },
- meta: {
- disableToast: true,
- },
- });
-};
diff --git a/src/hooks/query/use-cloud-git-user.ts b/src/hooks/query/use-cloud-git-user.ts
deleted file mode 100644
index c93c66c002..0000000000
--- a/src/hooks/query/use-cloud-git-user.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { getCloudGitUser } from "#/api/cloud/user-service.api";
-import { useActiveBackend } from "#/contexts/active-backend-context";
-
-/**
- * Fetch `GET /api/v1/users/git-info` for the active cloud backend.
- *
- * Mirrors OpenHands' `useGitUser` β€” returns the calling user's identity
- * across connected git providers. Disabled when the active backend is
- * local (the local agent-server has no equivalent).
- */
-export function useCloudGitUser() {
- const active = useActiveBackend();
- const enabled = active.backend.kind === "cloud";
-
- return useQuery({
- queryKey: ["cloud-git-user", active.backend.id],
- queryFn: () => getCloudGitUser(),
- enabled,
- staleTime: 1000 * 60 * 5,
- gcTime: 1000 * 60 * 15,
- retry: false,
- meta: { disableToast: true },
- });
-}
diff --git a/src/hooks/query/use-git-user.ts b/src/hooks/query/use-git-user.ts
deleted file mode 100644
index cb1e7b0077..0000000000
--- a/src/hooks/query/use-git-user.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import React from "react";
-import { usePostHog } from "posthog-js/react";
-import UserService from "#/api/user-service/user-service.api";
-import { useActiveBackend } from "#/contexts/active-backend-context";
-import { useShouldShowUserFeatures } from "#/hooks/use-should-show-user-features";
-
-export const useGitUser = () => {
- const posthog = usePostHog();
- const shouldFetchUser = useShouldShowUserFeatures();
- const active = useActiveBackend();
-
- const user = useQuery({
- // Backend identity in the key β€” different backends have different
- // git users; switching gives each its own cache slot.
- queryKey: ["user", active.backend.id, active.orgId],
- queryFn: UserService.getUser,
- enabled: shouldFetchUser,
- retry: false,
- staleTime: 1000 * 60 * 5,
- gcTime: 1000 * 60 * 15,
- // The "no git provider configured" condition is now a `null` data
- // value (see ProviderHandler.getUserGitInfo) rather than an error,
- // but suppressing this query's global error toast is still the
- // right policy: any failure here is a UX-affecting empty-state
- // signal rather than an actionable user error.
- meta: { disableToast: true },
- });
-
- React.useEffect(() => {
- if (user.data) {
- posthog.identify(user.data.login, {
- company: user.data.company,
- name: user.data.name,
- email: user.data.email,
- user: user.data.login,
- });
- }
- }, [posthog, user.data]);
-
- return user;
-};
diff --git a/src/hooks/use-tracking.ts b/src/hooks/use-tracking.ts
index cdd49a0798..9c2e333e00 100644
--- a/src/hooks/use-tracking.ts
+++ b/src/hooks/use-tracking.ts
@@ -52,17 +52,6 @@ export const useTracking = () => {
});
};
- const trackGitProviderConnected = ({
- providers,
- }: {
- providers: string[];
- }) => {
- posthog.capture("git_provider_connected", {
- providers,
- ...commonProperties,
- });
- };
-
const trackUserSignupCompleted = () => {
posthog.capture("user_signup_completed", {
signup_timestamp: new Date().toISOString(),
@@ -76,7 +65,6 @@ export const useTracking = () => {
trackPushButtonClick,
trackPullButtonClick,
trackCreatePrButtonClick,
- trackGitProviderConnected,
trackUserSignupCompleted,
};
};
diff --git a/src/routes.ts b/src/routes.ts
index 5672ef104b..4edd5de8a5 100644
--- a/src/routes.ts
+++ b/src/routes.ts
@@ -13,7 +13,6 @@ export default [
route("launch", "routes/launch.tsx"),
route("skills", "routes/skills-settings.tsx"),
route("mcp", "routes/mcp.tsx"),
- route("integrations", "routes/git-settings.tsx"),
route("settings", "routes/settings.tsx", [
index("routes/llm-settings.tsx"),
route("condenser", "routes/condenser-settings.tsx"),
diff --git a/src/routes/git-settings.tsx b/src/routes/git-settings.tsx
deleted file mode 100644
index 39b8f4fecc..0000000000
--- a/src/routes/git-settings.tsx
+++ /dev/null
@@ -1,307 +0,0 @@
-import React from "react";
-import { redirect } from "react-router";
-import { useTranslation } from "react-i18next";
-import { useSettings } from "#/hooks/query/use-settings";
-import { getActiveBackend } from "#/api/backend-registry/active-store";
-import { BrandButton } from "#/components/features/settings/brand-button";
-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";
-import { BitbucketDCTokenInput } from "#/components/features/settings/git-settings/bitbucket-dc-token-help-input";
-import { AzureDevOpsTokenInput } from "#/components/features/settings/git-settings/azure-devops-token-input";
-import { ForgejoTokenInput } from "#/components/features/settings/git-settings/forgejo-token-input";
-import { I18nKey } from "#/i18n/declaration";
-import {
- displayErrorToast,
- displaySuccessToast,
-} from "#/utils/custom-toast-handlers";
-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 { Provider, ProviderToken } from "#/types/settings";
-
-// /integrations is a local-only page; cloud backends do not expose it.
-export const clientLoader = () => {
- if (getActiveBackend().backend.kind === "cloud") {
- return redirect("/conversations");
- }
- return null;
-};
-
-export function GitSettingsScreen() {
- const { t } = useTranslation("openhands");
-
- const { mutate: saveGitProviders, isPending } = useAddGitProviders();
- const { mutate: disconnectGitTokens, isPending: isDisconnecting } =
- useDeleteGitProviders();
-
- const { data: settings, isLoading } = useSettings();
- const { providers } = useUserProviders();
-
- const [githubTokenInputHasValue, setGithubTokenInputHasValue] =
- React.useState(false);
- const [gitlabTokenInputHasValue, setGitlabTokenInputHasValue] =
- React.useState(false);
- const [bitbucketTokenInputHasValue, setBitbucketTokenInputHasValue] =
- React.useState(false);
- const [bitbucketDCTokenInputHasValue, setBitbucketDCTokenInputHasValue] =
- React.useState(false);
- const [azureDevOpsTokenInputHasValue, setAzureDevOpsTokenInputHasValue] =
- React.useState(false);
- const [forgejoTokenInputHasValue, setForgejoTokenInputHasValue] =
- React.useState(false);
-
- const [githubHostInputHasValue, setGithubHostInputHasValue] =
- React.useState(false);
- const [gitlabHostInputHasValue, setGitlabHostInputHasValue] =
- React.useState(false);
- const [bitbucketHostInputHasValue, setBitbucketHostInputHasValue] =
- React.useState(false);
- const [bitbucketDCHostInputHasValue, setBitbucketDCHostInputHasValue] =
- React.useState(false);
- const [azureDevOpsHostInputHasValue, setAzureDevOpsHostInputHasValue] =
- React.useState(false);
- const [forgejoHostInputHasValue, setForgejoHostInputHasValue] =
- React.useState(false);
-
- const existingGithubHost = settings?.provider_tokens_set.github;
- const existingGitlabHost = settings?.provider_tokens_set.gitlab;
- const existingBitbucketHost = settings?.provider_tokens_set.bitbucket;
- const existingBitbucketDCHost =
- settings?.provider_tokens_set.bitbucket_data_center;
- const existingAzureDevOpsHost = settings?.provider_tokens_set.azure_devops;
- const existingForgejoHost = settings?.provider_tokens_set.forgejo;
-
- const isGitHubTokenSet = providers.includes("github");
- const isGitLabTokenSet = providers.includes("gitlab");
- const isBitbucketTokenSet = providers.includes("bitbucket");
- const isBitbucketDCTokenSet = providers.includes("bitbucket_data_center");
- const isAzureDevOpsTokenSet = providers.includes("azure_devops");
- const isForgejoTokenSet = providers.includes("forgejo");
-
- const formAction = async (formData: FormData) => {
- const disconnectButtonClicked =
- formData.get("disconnect-tokens-button") !== null;
-
- if (disconnectButtonClicked) {
- 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 providerTokens: Partial<Record<Provider, ProviderToken>> = {
- github: { token: githubToken, host: githubHost },
- gitlab: { token: gitlabToken, host: gitlabHost },
- bitbucket: { token: bitbucketToken, host: bitbucketHost },
- bitbucket_data_center: { token: bitbucketDCToken, host: bitbucketDCHost },
- azure_devops: { token: azureDevOpsToken, host: azureDevOpsHost },
- forgejo: { token: forgejoToken, host: forgejoHost },
- };
-
- saveGitProviders(
- {
- providers: providerTokens,
- },
- {
- onSuccess: () => {
- displaySuccessToast(t(I18nKey.SETTINGS$SAVED));
- },
- onError: (error) => {
- const errorMessage = retrieveAxiosErrorMessage(error);
- displayErrorToast(errorMessage || t(I18nKey.ERROR$GENERIC));
- },
- onSettled: () => {
- setGithubTokenInputHasValue(false);
- setGitlabTokenInputHasValue(false);
- setBitbucketTokenInputHasValue(false);
- setBitbucketDCTokenInputHasValue(false);
- setAzureDevOpsTokenInputHasValue(false);
- setForgejoTokenInputHasValue(false);
- setGithubHostInputHasValue(false);
- setGitlabHostInputHasValue(false);
- setBitbucketHostInputHasValue(false);
- setBitbucketDCHostInputHasValue(false);
- setAzureDevOpsHostInputHasValue(false);
- setForgejoHostInputHasValue(false);
- },
- },
- );
- };
-
- const formIsClean =
- !githubTokenInputHasValue &&
- !gitlabTokenInputHasValue &&
- !bitbucketTokenInputHasValue &&
- !bitbucketDCTokenInputHasValue &&
- !azureDevOpsTokenInputHasValue &&
- !forgejoTokenInputHasValue &&
- !githubHostInputHasValue &&
- !gitlabHostInputHasValue &&
- !bitbucketHostInputHasValue &&
- !bitbucketDCHostInputHasValue &&
- !azureDevOpsHostInputHasValue &&
- !forgejoHostInputHasValue;
-
- return (
- <form
- data-testid="git-settings-screen"
- action={formAction}
- className="flex flex-col h-full justify-between"
- >
- {!isLoading && (
- <div className="flex flex-col gap-4">
- <GitHubTokenInput
- name="github-token-input"
- isGitHubTokenSet={isGitHubTokenSet}
- onChange={(value) => {
- setGithubTokenInputHasValue(!!value);
- }}
- onGitHubHostChange={(value) => {
- setGithubHostInputHasValue(!!value);
- }}
- githubHostSet={existingGithubHost}
- />
-
- <GitLabTokenInput
- name="gitlab-token-input"
- isGitLabTokenSet={isGitLabTokenSet}
- onChange={(value) => {
- setGitlabTokenInputHasValue(!!value);
- }}
- onGitLabHostChange={(value) => {
- setGitlabHostInputHasValue(!!value);
- }}
- gitlabHostSet={existingGitlabHost}
- />
-
- <BitbucketTokenInput
- name="bitbucket-token-input"
- isBitbucketTokenSet={isBitbucketTokenSet}
- onChange={(value) => {
- setBitbucketTokenInputHasValue(!!value);
- }}
- onBitbucketHostChange={(value) => {
- setBitbucketHostInputHasValue(!!value);
- }}
- bitbucketHostSet={existingBitbucketHost}
- />
-
- <BitbucketDCTokenInput
- name="bitbucket-dc-token-input"
- isBitbucketDCTokenSet={isBitbucketDCTokenSet}
- onChange={(value) => {
- setBitbucketDCTokenInputHasValue(!!value);
- }}
- onBitbucketDCHostChange={(value) => {
- setBitbucketDCHostInputHasValue(!!value);
- }}
- bitbucketDCHostSet={existingBitbucketDCHost}
- />
-
- <AzureDevOpsTokenInput
- name="azure-devops-token-input"
- isAzureDevOpsTokenSet={isAzureDevOpsTokenSet}
- onChange={(value) => {
- setAzureDevOpsTokenInputHasValue(!!value);
- }}
- onAzureDevOpsHostChange={(value) => {
- setAzureDevOpsHostInputHasValue(!!value);
- }}
- azureDevOpsHostSet={existingAzureDevOpsHost}
- />
-
- <ForgejoTokenInput
- name="forgejo-token-input"
- isForgejoTokenSet={isForgejoTokenSet}
- onChange={(value) => {
- setForgejoTokenInputHasValue(!!value);
- }}
- onForgejoHostChange={(value) => {
- setForgejoHostInputHasValue(!!value);
- }}
- forgejoHostSet={existingForgejoHost}
- />
- </div>
- )}
-
- {isLoading && <GitSettingInputsSkeleton />}
-
- <div className="flex gap-6 p-6 justify-end">
- <BrandButton
- testId="disconnect-tokens-button"
- name="disconnect-tokens-button"
- type="submit"
- variant="secondary"
- isDisabled={
- isDisconnecting ||
- (!isGitHubTokenSet &&
- !isGitLabTokenSet &&
- !isBitbucketTokenSet &&
- !isBitbucketDCTokenSet &&
- !isAzureDevOpsTokenSet &&
- !isForgejoTokenSet)
- }
- >
- {t("GIT$DISCONNECT_TOKENS")}
- </BrandButton>
- <BrandButton
- testId="submit-button"
- type="submit"
- variant="primary"
- isDisabled={isPending || isDisconnecting || formIsClean}
- >
- {!isPending && t("SETTINGS$SAVE_CHANGES")}
- {isPending && t("SETTINGS$SAVING")}
- </BrandButton>
- </div>
- </form>
- );
-}
-
-export default GitSettingsScreen;
diff --git a/src/utils/settings-utils.ts b/src/utils/settings-utils.ts
index 1ceaf92ecf..38e68408c9 100644
--- a/src/utils/settings-utils.ts
+++ b/src/utils/settings-utils.ts
@@ -57,15 +57,6 @@ export function isSettingsPageHidden(
return false;
}
-// Top-level pages that only make sense against a local agent-server.
-// Hidden from navigation and blocked at the route loader when the active
-// backend is a cloud SaaS environment.
-export const LOCAL_ONLY_SETTINGS_PATHS = new Set<string>(["/integrations"]);
-
-export function isLocalOnlySettingsPath(path: string): boolean {
- return LOCAL_ONLY_SETTINGS_PATHS.has(path);
-}
-
export function getFirstAvailablePath(
featureFlags: WebClientFeatureFlags | undefined,
): string | null {