Skip to content

🙌 OpenHands: AI-Driven Development

feat(frontend): browser-side git provider integrations (#96)

Hiep Lee90db6fa5375
diff --git a/__tests__/api/conversation-metadata-store.test.ts b/__tests__/api/conversation-metadata-store.test.ts
new file mode 100644
index 0000000000..0ea25cffad
--- /dev/null
+++ b/__tests__/api/conversation-metadata-store.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { toV1AppConversation } from "#/api/agent-server-adapter";
+import {
+ getStoredConversationMetadata,
+ removeStoredConversationMetadata,
+ setStoredConversationMetadata,
+} from "#/api/conversation-metadata-store";
+
+const directInfo = (id: string) => ({
+ id,
+ created_at: "2026-05-05T00:00:00Z",
+ updated_at: "2026-05-05T00:00:00Z",
+});
+
+describe("conversation-metadata-store", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ });
+ afterEach(() => {
+ window.localStorage.clear();
+ });
+
+ it("toV1AppConversation hydrates repo/branch/git_provider from the store", () => {
+ setStoredConversationMetadata("conv-1", {
+ selected_repository: "octocat/hello-world",
+ selected_branch: "main",
+ git_provider: "github",
+ });
+
+ const conversation = toV1AppConversation(directInfo("conv-1"));
+
+ expect(conversation).toMatchObject({
+ selected_repository: "octocat/hello-world",
+ selected_branch: "main",
+ git_provider: "github",
+ });
+ });
+
+ it("toV1AppConversation falls back to nulls when no metadata is stored", () => {
+ const conversation = toV1AppConversation(directInfo("conv-2"));
+
+ expect(conversation.selected_repository).toBeNull();
+ expect(conversation.selected_branch).toBeNull();
+ expect(conversation.git_provider).toBeNull();
+ });
+
+ it("removeStoredConversationMetadata clears the entry so the adapter goes back to nulls", () => {
+ setStoredConversationMetadata("conv-3", {
+ selected_repository: "octocat/repo",
+ selected_branch: "trunk",
+ git_provider: "github",
+ });
+
+ removeStoredConversationMetadata("conv-3");
+
+ expect(getStoredConversationMetadata("conv-3")).toBeNull();
+ expect(toV1AppConversation(directInfo("conv-3")).selected_repository).toBeNull();
+ });
+});
diff --git a/__tests__/api/git-providers/git-service-wiring.test.ts b/__tests__/api/git-providers/git-service-wiring.test.ts
new file mode 100644
index 0000000000..639d7fca0d
--- /dev/null
+++ b/__tests__/api/git-providers/git-service-wiring.test.ts
@@ -0,0 +1,67 @@
+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
new file mode 100644
index 0000000000..ebc8e2ab92
--- /dev/null
+++ b/__tests__/api/git-providers/github-service.test.ts
@@ -0,0 +1,334 @@
+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
new file mode 100644
index 0000000000..2c4facc360
--- /dev/null
+++ b/__tests__/api/git-providers/non-github-services.test.ts
@@ -0,0 +1,144 @@
+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
new file mode 100644
index 0000000000..89a62d4d6a
--- /dev/null
+++ b/__tests__/api/git-providers/paging-utils.test.ts
@@ -0,0 +1,33 @@
+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
new file mode 100644
index 0000000000..b1fc4b4880
--- /dev/null
+++ b/__tests__/api/git-providers/provider-handler.test.ts
@@ -0,0 +1,106 @@
+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("throws GitProviderAuthError when no providers are configured", async () => {
+ await expect(ProviderHandler.getUserGitInfo()).rejects.toBeInstanceOf(
+ GitProviderAuthError,
+ );
+ });
+});
diff --git a/__tests__/api/use-create-conversation-metadata.test.ts b/__tests__/api/use-create-conversation-metadata.test.ts
new file mode 100644
index 0000000000..1bc99b2e21
--- /dev/null
+++ b/__tests__/api/use-create-conversation-metadata.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
+import { renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import React from "react";
+import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";
+import { getStoredConversationMetadata } from "#/api/conversation-metadata-store";
+
+const { mockHttpPost, mockCreateHttpClient, mockGetSettings } = vi.hoisted(
+ () => ({
+ mockHttpPost: vi.fn(),
+ mockCreateHttpClient: vi.fn(),
+ mockGetSettings: vi.fn(),
+ }),
+);
+
+vi.mock("#/api/typescript-client", () => ({
+ createHttpClient: mockCreateHttpClient,
+ createRemoteWorkspace: vi.fn(),
+ createVSCodeClient: vi.fn(),
+}));
+
+vi.mock("#/api/agent-server-config", () => ({
+ DEFAULT_WORKING_DIR: "workspace/project",
+ getAgentServerBaseUrl: vi.fn(() => "http://localhost:54928"),
+ getAgentServerSessionApiKey: vi.fn(() => null),
+ getAgentServerWorkingDir: vi.fn(() => "/workspace/project/agent-server-gui"),
+ buildConversationWorkingDir: vi.fn(
+ (id: string) => `/state/workspaces/${id.replace(/-/g, "")}`,
+ ),
+ getConfiguredWorkerUrls: vi.fn(() => []),
+}));
+
+vi.mock("#/api/settings-service/settings-service.api", () => ({
+ default: { getSettings: mockGetSettings },
+}));
+
+vi.mock("#/hooks/use-tracking", () => ({
+ useTracking: () => ({ trackConversationCreated: vi.fn() }),
+}));
+
+const wrapper = ({ children }: { children: React.ReactNode }) => {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ return React.createElement(QueryClientProvider, { client }, children);
+};
+
+describe("useCreateConversation persists selected repository metadata", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ mockHttpPost.mockReset();
+ mockCreateHttpClient.mockReset();
+ mockGetSettings.mockResolvedValue({
+ agent_settings: { llm: { model: "gpt-4o" } },
+ conversation_settings: {},
+ });
+ mockCreateHttpClient.mockReturnValue({
+ get: vi.fn(),
+ post: mockHttpPost,
+ patch: vi.fn(),
+ delete: vi.fn(),
+ });
+ mockHttpPost.mockResolvedValue({
+ data: {
+ id: "conv-new",
+ created_at: "2026-05-05T00:00:00Z",
+ updated_at: "2026-05-05T00:00:00Z",
+ },
+ });
+ });
+
+ afterEach(() => {
+ window.localStorage.clear();
+ });
+
+ it("stores the selected repo/branch/provider in the metadata store after a successful create", async () => {
+ const { result } = renderHook(() => useCreateConversation(), { wrapper });
+
+ result.current.mutate({
+ query: "ship it",
+ repository: {
+ name: "octocat/hello-world",
+ gitProvider: "github",
+ branch: "main",
+ },
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(getStoredConversationMetadata("conv-new")).toEqual({
+ selected_repository: "octocat/hello-world",
+ selected_branch: "main",
+ git_provider: "github",
+ });
+ });
+
+ it("does not write metadata when no repository is selected", async () => {
+ const { result } = renderHook(() => useCreateConversation(), { wrapper });
+
+ result.current.mutate({ query: "scratch session" });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(getStoredConversationMetadata("conv-new")).toBeNull();
+ });
+});
diff --git a/__tests__/components/features/home/repo-selection-form.test.tsx b/__tests__/components/features/home/repo-selection-form.test.tsx
index 7b0fcb7e18..7dfe98b8be 100644
--- a/__tests__/components/features/home/repo-selection-form.test.tsx
+++ b/__tests__/components/features/home/repo-selection-form.test.tsx
@@ -1,10 +1,13 @@
import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
import { describe, expect, vi, beforeEach, it } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { RepositorySelectionForm } from "../../../../src/components/features/home/repo-selection-form";
+import { LaunchTabs } from "../../../../src/components/features/home/launch-tabs";
import GitService from "#/api/git-service/git-service.api";
import { GitRepository } from "#/types/git";
import { useHomeStore } from "#/stores/home-store";
+import { useWorkspacesStore } from "#/stores/workspaces-store";
// Create mock functions
const mockUseUserRepositories = vi.fn();
@@ -327,4 +330,35 @@ describe("RepositorySelectionForm", () => {
screen.queryByTestId("git-provider-dropdown"),
).not.toBeInTheDocument();
});
+
+ it("LaunchTabs defaults to Repositories and switches to Workspaces", async () => {
+ mockUseUserProviders.mockReturnValue({ providers: ["github"] });
+ useWorkspacesStore.setState({ workspaces: [] });
+
+ render(<LaunchTabs onRepoSelection={mockOnRepoSelection} />, {
+ wrapper: ({ children }) => (
+ <QueryClientProvider
+ client={
+ new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ }
+ >
+ {children}
+ </QueryClientProvider>
+ ),
+ });
+
+ expect(await screen.findByTestId("git-repo-dropdown")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("workspace-launch-button"),
+ ).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByTestId("workspaces-tab"));
+
+ expect(
+ await screen.findByTestId("workspace-launch-button"),
+ ).toBeInTheDocument();
+ expect(screen.queryByTestId("git-repo-dropdown")).not.toBeInTheDocument();
+ });
});
diff --git a/__tests__/components/features/home/task-card.test.tsx b/__tests__/components/features/home/task-card.test.tsx
index ad0d2ce1dc..b946d9de0b 100644
--- a/__tests__/components/features/home/task-card.test.tsx
+++ b/__tests__/components/features/home/task-card.test.tsx
@@ -134,6 +134,12 @@ describe("TaskCard", () => {
undefined,
undefined,
undefined,
+ {
+ selected_repository: MOCK_TASK_1.repo,
+ selected_branch: null,
+ git_provider: MOCK_TASK_1.git_provider,
+ },
+ undefined,
);
});
});
diff --git a/__tests__/components/features/home/workspace-selection-form.test.tsx b/__tests__/components/features/home/workspace-selection-form.test.tsx
new file mode 100644
index 0000000000..d495dbb63f
--- /dev/null
+++ b/__tests__/components/features/home/workspace-selection-form.test.tsx
@@ -0,0 +1,191 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, expect, vi, beforeEach, it } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { WorkspaceSelectionForm } from "../../../../src/components/features/home/workspace-selection-form";
+import V1ConversationService from "#/api/conversation-service/v1-conversation-service.api";
+import FilesService from "#/api/files-service/files-service.api";
+import { useWorkspacesStore } from "#/stores/workspaces-store";
+import { LocalWorkspace } from "#/types/workspace";
+
+const mockNavigate = vi.fn();
+const mockUseIsCreatingConversation = vi.fn();
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("#/context/navigation-context", () => ({
+ useNavigation: () => ({
+ currentPath: "/",
+ conversationId: null,
+ isNavigating: false,
+ navigate: mockNavigate,
+ }),
+}));
+
+vi.mock("#/hooks/use-is-creating-conversation", () => ({
+ useIsCreatingConversation: () => mockUseIsCreatingConversation(),
+}));
+
+vi.mock("#/hooks/use-tracking", () => ({
+ useTracking: () => ({
+ trackConversationCreated: vi.fn(),
+ trackLoginButtonClick: vi.fn(),
+ }),
+}));
+
+mockUseIsCreatingConversation.mockReturnValue(false);
+
+function makeStartTask(overrides: Record<string, unknown> = {}) {
+ return {
+ id: "conv-abc",
+ created_by_user_id: null,
+ status: "READY",
+ detail: null,
+ app_conversation_id: "conv-abc",
+ agent_server_url: "http://agent-server.local",
+ request: { initial_message: undefined, plugins: null },
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ ...overrides,
+ } as never;
+}
+
+function renderForm(initialWorkspaces: LocalWorkspace[] = []) {
+ useWorkspacesStore.setState({ workspaces: initialWorkspaces });
+ return render(<WorkspaceSelectionForm />, {
+ wrapper: ({ children }) => (
+ <QueryClientProvider
+ client={
+ new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ })
+ }
+ >
+ {children}
+ </QueryClientProvider>
+ ),
+ });
+}
+
+describe("WorkspaceSelectionForm", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+ mockUseIsCreatingConversation.mockReturnValue(false);
+ useWorkspacesStore.setState({ workspaces: [] });
+ });
+
+ it("Add Workspaces opens Finder-like modal, navigates, and imports subfolders deduped on repeat", async () => {
+ vi.spyOn(FilesService, "getHome").mockResolvedValue({ home: "/Users/me" });
+ const listSpy = vi
+ .spyOn(FilesService, "listSubdirs")
+ .mockImplementation(async (path: string) => {
+ if (path === "/Users/me") {
+ return {
+ path,
+ subdirs: [{ name: "dev", path: "/Users/me/dev" }],
+ };
+ }
+ if (path === "/Users/me/dev") {
+ return {
+ path,
+ subdirs: [
+ { name: "repo1", path: "/Users/me/dev/repo1" },
+ { name: "repo2", path: "/Users/me/dev/repo2" },
+ { name: "repo3", path: "/Users/me/dev/repo3" },
+ ],
+ };
+ }
+ throw new Error(`unexpected path ${path}`);
+ });
+
+ // Pre-seed one workspace to verify dedup
+ renderForm([
+ { id: "/Users/me/dev/repo1", name: "repo1", path: "/Users/me/dev/repo1" },
+ ]);
+ const user = userEvent.setup();
+
+ for (let i = 0; i < 2; i += 1) {
+ await user.click(screen.getByTestId("workspace-dropdown"));
+ const addButton = await screen.findByTestId("add-workspaces-button");
+ await user.click(addButton);
+
+ // Modal opens at home; dropdown menu is closed.
+ await screen.findByTestId("folder-browser-modal");
+ expect(
+ screen.queryByTestId("add-workspaces-button"),
+ ).not.toBeInTheDocument();
+
+ // Navigate into "dev" then click "Use this folder"
+ const devEntry = await screen.findByTestId("folder-browser-entry-dev");
+ await user.click(devEntry);
+ await screen.findByTestId("folder-browser-entry-repo2");
+ await user.click(screen.getByTestId("folder-browser-use"));
+
+ await waitFor(() =>
+ expect(
+ screen.queryByTestId("folder-browser-modal"),
+ ).not.toBeInTheDocument(),
+ );
+ }
+
+ const stored = useWorkspacesStore.getState().workspaces;
+ expect(stored.map((w) => w.path).sort()).toEqual([
+ "/Users/me/dev/repo1",
+ "/Users/me/dev/repo2",
+ "/Users/me/dev/repo3",
+ ]);
+ expect(listSpy).toHaveBeenCalledWith("/Users/me/dev");
+ });
+
+ it("Launch creates a v1 conversation with the selected workspace path as working_dir", async () => {
+ const workspaces: LocalWorkspace[] = [
+ { id: "/Users/me/dev/repo1", name: "repo1", path: "/Users/me/dev/repo1" },
+ { id: "/Users/me/dev/repo2", name: "repo2", path: "/Users/me/dev/repo2" },
+ ];
+ const createSpy = vi
+ .spyOn(V1ConversationService, "createConversation")
+ .mockResolvedValue(makeStartTask({ app_conversation_id: "conv-xyz" }));
+
+ renderForm(workspaces);
+ const user = userEvent.setup();
+
+ await user.click(screen.getByTestId("workspace-dropdown"));
+ const items = await screen.findAllByText(/repo[12]/);
+ await user.click(items.find((el) => el.textContent === "repo2")!);
+ await user.click(screen.getByTestId("workspace-launch-button"));
+
+ await waitFor(() => expect(createSpy).toHaveBeenCalledTimes(1));
+ expect(createSpy).toHaveBeenCalledWith(
+ undefined,
+ undefined,
+ undefined,
+ null,
+ "/Users/me/dev/repo2",
+ );
+ await waitFor(() =>
+ expect(mockNavigate).toHaveBeenCalledWith("/conversations/conv-xyz"),
+ );
+ });
+
+ it("Launch button is disabled until a workspace is selected", async () => {
+ renderForm([
+ { id: "/Users/me/dev/repo1", name: "repo1", path: "/Users/me/dev/repo1" },
+ ]);
+
+ const launchButton = screen.getByTestId("workspace-launch-button");
+ expect(launchButton).toBeDisabled();
+
+ const user = userEvent.setup();
+ await user.click(screen.getByTestId("workspace-dropdown"));
+ await user.click(await screen.findByText("repo1"));
+
+ expect(launchButton).toBeEnabled();
+ });
+});
diff --git a/__tests__/hooks/mutation/use-create-conversation.test.tsx b/__tests__/hooks/mutation/use-create-conversation.test.tsx
index a5651a4bfa..0fe3c9252e 100644
--- a/__tests__/hooks/mutation/use-create-conversation.test.tsx
+++ b/__tests__/hooks/mutation/use-create-conversation.test.tsx
@@ -75,6 +75,12 @@ describe("useCreateConversation", () => {
"Please address the comments",
"Focus on review comments",
undefined,
+ {
+ selected_repository: "owner/repo",
+ selected_branch: "main",
+ git_provider: "github",
+ },
+ undefined,
);
});
});
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index aa577b9c55..9916337dee 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -15,6 +15,7 @@ import {
V1AppConversationPage,
} from "./conversation-service/v1-conversation-service.types";
import { createHttpClient, createSkillsClient } from "./typescript-client";
+import { getStoredConversationMetadata } from "./conversation-metadata-store";
export interface DirectConversationInfo {
id: string;
@@ -65,12 +66,13 @@ export function getDefaultConversationTitle(conversationId: string): string {
export function toV1AppConversation(
info: DirectConversationInfo,
): V1AppConversation {
+ const metadata = getStoredConversationMetadata(info.id);
return {
id: info.id,
created_by_user_id: null,
- selected_repository: null,
- selected_branch: null,
- git_provider: null,
+ selected_repository: metadata?.selected_repository ?? null,
+ selected_branch: metadata?.selected_branch ?? null,
+ git_provider: metadata?.git_provider ?? null,
title: info.title?.trim() ? info.title : getDefaultConversationTitle(info.id),
trigger: null,
pr_number: [],
diff --git a/src/api/conversation-metadata-store.ts b/src/api/conversation-metadata-store.ts
new file mode 100644
index 0000000000..054772aba4
--- /dev/null
+++ b/src/api/conversation-metadata-store.ts
@@ -0,0 +1,55 @@
+import { Provider } from "#/types/settings";
+
+const STORAGE_KEY = "openhands-agent-server-conversation-metadata";
+
+export interface ConversationMetadata {
+ selected_repository: string | null;
+ selected_branch: string | null;
+ git_provider: Provider | null;
+}
+
+type StoredMetadata = Record<string, ConversationMetadata>;
+
+const readAll = (): StoredMetadata => {
+ if (typeof window === "undefined") return {};
+ try {
+ const raw = window.localStorage.getItem(STORAGE_KEY);
+ if (!raw) return {};
+ const parsed = JSON.parse(raw) as unknown;
+ if (!parsed || typeof parsed !== "object") return {};
+ return parsed as StoredMetadata;
+ } catch {
+ return {};
+ }
+};
+
+const writeAll = (next: StoredMetadata): void => {
+ if (typeof window === "undefined") return;
+ if (Object.keys(next).length === 0) {
+ window.localStorage.removeItem(STORAGE_KEY);
+ return;
+ }
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
+};
+
+export const getStoredConversationMetadata = (
+ conversationId: string,
+): ConversationMetadata | null => readAll()[conversationId] ?? null;
+
+export const setStoredConversationMetadata = (
+ conversationId: string,
+ metadata: ConversationMetadata,
+): void => {
+ const all = readAll();
+ all[conversationId] = metadata;
+ writeAll(all);
+};
+
+export const removeStoredConversationMetadata = (
+ conversationId: string,
+): void => {
+ const all = readAll();
+ if (!(conversationId in all)) return;
+ delete all[conversationId];
+ writeAll(all);
+};
diff --git a/src/api/conversation-service/v1-conversation-service.api.ts b/src/api/conversation-service/v1-conversation-service.api.ts
index 9c3d704cdd..5d716e176f 100644
--- a/src/api/conversation-service/v1-conversation-service.api.ts
+++ b/src/api/conversation-service/v1-conversation-service.api.ts
@@ -22,6 +22,11 @@ import {
createVSCodeClient,
} from "../typescript-client";
import SettingsService from "../settings-service/settings-service.api";
+import {
+ ConversationMetadata,
+ removeStoredConversationMetadata,
+ setStoredConversationMetadata,
+} from "../conversation-metadata-store";
import type {
GetHooksResponse,
GetSkillsResponse,
@@ -55,10 +60,13 @@ class V1ConversationService {
initialUserMsg?: string,
conversationInstructions?: string,
plugins?: PluginSpec[],
+ metadata?: ConversationMetadata | null,
+ workingDirOverride?: string,
): Promise<V1AppConversationStartTask> {
const settings = await SettingsService.getSettings();
const conversationId = crypto.randomUUID();
- const workingDir = buildConversationWorkingDir(conversationId);
+ const workingDir =
+ workingDirOverride ?? buildConversationWorkingDir(conversationId);
const payload = buildStartConversationRequest({
settings,
query: initialUserMsg,
@@ -74,6 +82,13 @@ class V1ConversationService {
);
const { data } = response;
+ if (metadata?.selected_repository) {
+ // The agent-server runtime has no concept of selected repo/branch, so
+ // persist the home-page selection client-side. toV1AppConversation
+ // reads the same store when the chat page hydrates the badges.
+ setStoredConversationMetadata(data.id, metadata);
+ }
+
return {
id: data.id,
created_by_user_id: null,
@@ -206,10 +221,19 @@ class V1ConversationService {
static async updateConversationRepository(
conversationId: string,
- _repository: string | null,
- _branch?: string | null,
- _gitProvider?: string | null,
+ repository: string | null,
+ branch?: string | null,
+ gitProvider?: string | null,
): Promise<V1AppConversation> {
+ if (repository) {
+ setStoredConversationMetadata(conversationId, {
+ selected_repository: repository,
+ selected_branch: branch ?? null,
+ git_provider: (gitProvider as Provider | null | undefined) ?? null,
+ });
+ } else {
+ removeStoredConversationMetadata(conversationId);
+ }
const results = await this.batchGetAppConversations([conversationId]);
return results[0] as V1AppConversation;
}
@@ -313,6 +337,7 @@ class V1ConversationService {
static async deleteConversation(conversationId: string): Promise<void> {
await createHttpClient().delete(`/api/conversations/${conversationId}`);
+ removeStoredConversationMetadata(conversationId);
}
static async updateConversationTitle(
diff --git a/src/api/files-service/files-service.api.ts b/src/api/files-service/files-service.api.ts
new file mode 100644
index 0000000000..f98c56c19a
--- /dev/null
+++ b/src/api/files-service/files-service.api.ts
@@ -0,0 +1,33 @@
+import { createHttpClient } from "../typescript-client";
+
+export interface SubdirectoryEntry {
+ name: string;
+ path: string;
+}
+
+export interface ListSubdirsResponse {
+ path: string;
+ subdirs: SubdirectoryEntry[];
+}
+
+export interface HomeResponse {
+ home: string;
+}
+
+const FilesService = {
+ async listSubdirs(path: string): Promise<ListSubdirsResponse> {
+ const response = await createHttpClient().get<ListSubdirsResponse>(
+ "/api/file/list_subdirs",
+ { params: { path } },
+ );
+ return response.data;
+ },
+
+ async getHome(): Promise<HomeResponse> {
+ const response =
+ await createHttpClient().get<HomeResponse>("/api/file/home");
+ return response.data;
+ },
+};
+
+export default FilesService;
diff --git a/src/api/git-providers/azure-devops-service.ts b/src/api/git-providers/azure-devops-service.ts
new file mode 100644
index 0000000000..3a68473dbc
--- /dev/null
+++ b/src/api/git-providers/azure-devops-service.ts
@@ -0,0 +1,176 @@
+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
new file mode 100644
index 0000000000..5d4144fc6b
--- /dev/null
+++ b/src/api/git-providers/bitbucket-dc-service.ts
@@ -0,0 +1,188 @@
+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
new file mode 100644
index 0000000000..0b63ebc27e
--- /dev/null
+++ b/src/api/git-providers/bitbucket-service.ts
@@ -0,0 +1,217 @@
+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
new file mode 100644
index 0000000000..14b76dc41a
--- /dev/null
+++ b/src/api/git-providers/forgejo-service.ts
@@ -0,0 +1,195 @@
+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
new file mode 100644
index 0000000000..23d35b647c
--- /dev/null
+++ b/src/api/git-providers/github-service.ts
@@ -0,0 +1,521 @@
+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
new file mode 100644
index 0000000000..adcc74999b
--- /dev/null
+++ b/src/api/git-providers/gitlab-service.ts
@@ -0,0 +1,307 @@
+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
new file mode 100644
index 0000000000..6754f434ec
--- /dev/null
+++ b/src/api/git-providers/paging-utils.ts
@@ -0,0 +1,61 @@
+/**
+ * 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
new file mode 100644
index 0000000000..3247774cad
--- /dev/null
+++ b/src/api/git-providers/provider-handler.ts
@@ -0,0 +1,140 @@
+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 => {
+ const all = collectAllServices();
+ if (all.length === 0) {
+ throw new GitProviderAuthError("No git provider configured");
+ }
+ return all[0];
+};
+
+export const ProviderHandler = {
+ getServiceForProvider: getServiceFor,
+
+ async getUserGitInfo(provider?: Provider): Promise<GitUser> {
+ const service = provider
+ ? requireService(provider)
+ : firstConfiguredService();
+ return service.getUser();
+ },
+
+ 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
new file mode 100644
index 0000000000..8ff5c7aa2b
--- /dev/null
+++ b/src/api/git-providers/types.ts
@@ -0,0 +1,73 @@
+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 3a38995b56..317c90f648 100644
--- a/src/api/git-service/git-service.api.ts
+++ b/src/api/git-service/git-service.api.ts
@@ -1,47 +1,71 @@
import { RepositoryPage, BranchPage, InstallationPage } from "#/types/git";
+import { Provider } from "#/types/settings";
import { GitChange, GitChangeDiff } from "../open-hands.types";
import V1ConversationService from "../conversation-service/v1-conversation-service.api";
import { createRemoteWorkspace } from "../typescript-client";
import { mapAnyGitStatusToV0Status } from "#/utils/git-status-mapper";
+import { ProviderHandler } from "../git-providers/provider-handler";
+
+const safeProvider = (value: string): Provider => value as Provider;
class GitService {
static async searchGitRepositories(
- _query: string,
- _provider: string,
- _limit = 100,
- _pageId?: string,
- _installationId?: string,
+ query: string,
+ provider: string,
+ limit = 100,
+ pageId?: string,
+ installationId?: string,
): Promise<RepositoryPage> {
- return { items: [], next_page_id: null };
+ return ProviderHandler.searchRepositories(safeProvider(provider), {
+ query: query || undefined,
+ installationId,
+ pageId,
+ limit,
+ });
}
static async retrieveUserGitRepositories(
- _provider: string,
- _pageId?: string,
- _limit = 30,
- _installationId?: string,
+ provider: string,
+ pageId?: string,
+ limit = 30,
+ installationId?: string,
): Promise<RepositoryPage> {
- return { items: [], next_page_id: null };
+ return ProviderHandler.searchRepositories(safeProvider(provider), {
+ installationId,
+ pageId,
+ limit,
+ });
}
static async retrieveInstallationRepositories(
- _provider: string,
- _installationIndex: number,
- _installations: string[],
- _pageId?: string,
- _limit = 30,
+ provider: string,
+ installationIndex: number,
+ installations: string[],
+ pageId?: string,
+ limit = 30,
): Promise<RepositoryPage> {
- return { items: [], next_page_id: null };
+ const installationId = installations[installationIndex];
+ if (!installationId) return { items: [], next_page_id: null };
+ return ProviderHandler.searchRepositories(safeProvider(provider), {
+ installationId,
+ pageId,
+ limit,
+ });
}
static async getRepositoryBranches(
- _repository: string,
- _provider: string,
- _query: string = "",
- _pageId?: string,
- _limit = 30,
+ repository: string,
+ provider: string,
+ query: string = "",
+ pageId?: string,
+ limit = 30,
): Promise<BranchPage> {
- return { items: [], next_page_id: null };
+ return ProviderHandler.getBranches(safeProvider(provider), {
+ repository,
+ query: query || undefined,
+ pageId,
+ limit,
+ });
}
static async searchRepositoryBranches(
@@ -51,21 +75,23 @@ class GitService {
pageId?: string,
limit = 30,
): Promise<BranchPage> {
- return this.getRepositoryBranches(
+ return ProviderHandler.getBranches(safeProvider(provider), {
repository,
- provider,
query,
pageId,
limit,
- );
+ });
}
static async getUserInstallations(
- _provider: string,
- _pageId?: string,
- _limit = 100,
+ provider: string,
+ pageId?: string,
+ limit = 100,
): Promise<InstallationPage> {
- return { items: [], next_page_id: null };
+ return ProviderHandler.getInstallations(safeProvider(provider), {
+ pageId,
+ limit,
+ });
}
static async getGitChanges(conversationId: string): Promise<GitChange[]> {
diff --git a/src/api/secrets-service.ts b/src/api/secrets-service.ts
index c855791de5..9f264979fc 100644
--- a/src/api/secrets-service.ts
+++ b/src/api/secrets-service.ts
@@ -84,6 +84,13 @@ const writeStoredGitProviders = (providers: StoredGitProviderTokens) => {
);
};
+export const getStoredGitProviders = (): StoredGitProviderTokens =>
+ readStoredGitProviders();
+
+export const getStoredGitProviderToken = (
+ provider: Provider,
+): ProviderToken | null => readStoredGitProviders()[provider] ?? null;
+
const buildProviderTokensSet = (
providers: StoredGitProviderTokens,
): Partial<Record<Provider, string | null>> =>
diff --git a/src/api/suggestions-service/suggestions-service.api.ts b/src/api/suggestions-service/suggestions-service.api.ts
index b9219a0b7c..e6172dca55 100644
--- a/src/api/suggestions-service/suggestions-service.api.ts
+++ b/src/api/suggestions-service/suggestions-service.api.ts
@@ -1,31 +1,19 @@
import { SuggestedTask } from "#/utils/types";
-import { openHands } from "../open-hands-axios";
-
-interface SuggestedTaskPage {
- items: SuggestedTask[];
- next_page_id: string | null;
-}
+import { ProviderHandler } from "../git-providers/provider-handler";
export class SuggestionsService {
/**
- * Get suggested tasks for the user with pagination.
+ * Aggregate suggested tasks across every configured git provider.
*
- * @param pageId - Optional cursor for the next page (from previous response's next_page_id)
- * @param limit - Max number of results per page (default: 30, max: 100)
+ * Mirrors the OSS /api/v1/git/suggested-tasks/search shape but resolves
+ * tasks client-side because the agent-server runtime has no integrations
+ * router.
*/
static async getSuggestedTasks(
pageId?: string,
limit: number = 30,
): Promise<SuggestedTask[]> {
- const { data } = await openHands.get<SuggestedTaskPage>(
- "/api/v1/git/suggested-tasks/search",
- {
- params: {
- page_id: pageId ?? undefined,
- limit,
- },
- },
- );
- return data.items;
+ const page = await ProviderHandler.getSuggestedTasks(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
index 886f9e3086..822bd88a56 100644
--- a/src/api/user-service/user-service.api.ts
+++ b/src/api/user-service/user-service.api.ts
@@ -1,17 +1,15 @@
-import { openHands } from "../open-hands-axios";
import { GitUser } from "#/types/git";
+import { ProviderHandler } from "../git-providers/provider-handler";
/**
- * User Service API - Handles all user-related API endpoints
+ * User Service API - Handles all user-related API endpoints.
+ *
+ * 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.
*/
class UserService {
- /**
- * Get the current user's Git information
- * @returns Git user information
- */
static async getUser(): Promise<GitUser> {
- const { data } = await openHands.get<GitUser>("/api/v1/users/git-info");
- return data;
+ return ProviderHandler.getUserGitInfo();
}
}
diff --git a/src/components/features/home/launch-tabs.tsx b/src/components/features/home/launch-tabs.tsx
new file mode 100644
index 0000000000..6465a25365
--- /dev/null
+++ b/src/components/features/home/launch-tabs.tsx
@@ -0,0 +1,88 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+
+import { cn } from "#/utils/utils";
+import { I18nKey } from "#/i18n/declaration";
+import { GitRepository } from "#/types/git";
+
+import { RepositorySelectionForm } from "./repo-selection-form";
+import { WorkspaceSelectionForm } from "./workspace-selection-form";
+
+type LaunchTab = "repositories" | "workspaces";
+
+interface LaunchTabsProps {
+ onRepoSelection: (repo: GitRepository | null) => void;
+ isLoadingSettings?: boolean;
+}
+
+interface TabButtonProps {
+ isActive: boolean;
+ onClick: () => void;
+ children: React.ReactNode;
+ testId: string;
+}
+
+function TabButton({ isActive, onClick, children, testId }: TabButtonProps) {
+ return (
+ <button
+ type="button"
+ role="tab"
+ aria-selected={isActive}
+ data-testid={testId}
+ onClick={onClick}
+ className={cn(
+ "px-4 py-2 text-sm font-medium border-b-2 transition-colors cursor-pointer",
+ isActive
+ ? "border-[#C9B974] text-white"
+ : "border-transparent text-[#B7BDC2] hover:text-white",
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+export function LaunchTabs({
+ onRepoSelection,
+ isLoadingSettings = false,
+}: LaunchTabsProps) {
+ const { t } = useTranslation("openhands");
+ const [activeTab, setActiveTab] = React.useState<LaunchTab>("repositories");
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div
+ role="tablist"
+ className="flex border-b border-[#727987]"
+ data-testid="launch-tabs"
+ >
+ <TabButton
+ testId="repositories-tab"
+ isActive={activeTab === "repositories"}
+ onClick={() => setActiveTab("repositories")}
+ >
+ {t(I18nKey.HOME$REPOSITORIES_TAB)}
+ </TabButton>
+ <TabButton
+ testId="workspaces-tab"
+ isActive={activeTab === "workspaces"}
+ onClick={() => setActiveTab("workspaces")}
+ >
+ {t(I18nKey.HOME$WORKSPACES_TAB)}
+ </TabButton>
+ </div>
+
+ <div className="min-h-[240px]">
+ {activeTab === "repositories" && (
+ <RepositorySelectionForm
+ onRepoSelection={onRepoSelection}
+ isLoadingSettings={isLoadingSettings}
+ />
+ )}
+ {activeTab === "workspaces" && (
+ <WorkspaceSelectionForm isLoadingSettings={isLoadingSettings} />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/features/home/repo-connector.tsx b/src/components/features/home/repo-connector.tsx
index 5e49d03e0c..b09984c625 100644
--- a/src/components/features/home/repo-connector.tsx
+++ b/src/components/features/home/repo-connector.tsx
@@ -1,5 +1,5 @@
import { ConnectToProviderMessage } from "./connect-to-provider-message";
-import { RepositorySelectionForm } from "./repo-selection-form";
+import { LaunchTabs } from "./launch-tabs";
import { useUserProviders } from "#/hooks/use-user-providers";
import { GitRepository } from "#/types/git";
@@ -19,7 +19,7 @@ export function RepoConnector({ onRepoSelection }: RepoConnectorProps) {
>
{!providersAreSet && <ConnectToProviderMessage />}
{providersAreSet && (
- <RepositorySelectionForm
+ <LaunchTabs
onRepoSelection={onRepoSelection}
isLoadingSettings={isLoadingSettings}
/>
diff --git a/src/components/features/home/workspace-dropdown/folder-browser-modal.tsx b/src/components/features/home/workspace-dropdown/folder-browser-modal.tsx
new file mode 100644
index 0000000000..779738c463
--- /dev/null
+++ b/src/components/features/home/workspace-dropdown/folder-browser-modal.tsx
@@ -0,0 +1,284 @@
+import React, { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+
+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { I18nKey } from "#/i18n/declaration";
+import { LocalWorkspace } from "#/types/workspace";
+import {
+ useHomeDirectory,
+ useListSubdirs,
+} from "#/hooks/query/use-list-subdirs";
+import { cn } from "#/utils/utils";
+import FolderIcon from "#/icons/folder.svg?react";
+import ChevronLeft from "#/icons/chevron-left-small.svg?react";
+
+interface FolderBrowserModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ onAdd: (items: LocalWorkspace[]) => void;
+}
+
+interface SidebarEntry {
+ label: string;
+ path: string;
+}
+
+interface SidebarSectionProps {
+ label: string;
+ entries: SidebarEntry[];
+ currentPath: string | null;
+ onPick: (path: string) => void;
+}
+
+function SidebarSection({
+ label,
+ entries,
+ currentPath,
+ onPick,
+}: SidebarSectionProps) {
+ if (entries.length === 0) return null;
+ return (
+ <div className="px-2 pb-3">
+ <div className="px-2 pb-1 text-[11px] uppercase tracking-wide text-[#A3A3A3] font-semibold">
+ {label}
+ </div>
+ <ul>
+ {entries.map((entry) => {
+ const isActive = currentPath === entry.path;
+ return (
+ <li key={entry.path}>
+ <button
+ type="button"
+ onClick={() => onPick(entry.path)}
+ data-testid={`folder-browser-sidebar-${entry.label.toLowerCase()}`}
+ className={cn(
+ "flex items-center gap-2 w-full px-2 py-1 rounded text-sm cursor-pointer",
+ isActive
+ ? "bg-[#3A3D44] text-white"
+ : "text-[#D6D6D6] hover:bg-[#2F3137]",
+ )}
+ >
+ <FolderIcon width={14} height={14} className="shrink-0" />
+ <span className="truncate">{entry.label}</span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+}
+
+function getParentPath(path: string): string | null {
+ const trimmed = path.replace(/\/+$/, "");
+ if (!trimmed || trimmed === "/") return null;
+ const idx = trimmed.lastIndexOf("/");
+ if (idx <= 0) return "/";
+ return trimmed.slice(0, idx);
+}
+
+function buildSidebar(home: string | null): {
+ favorites: SidebarEntry[];
+ locations: SidebarEntry[];
+} {
+ if (!home) {
+ return { favorites: [], locations: [{ label: "/", path: "/" }] };
+ }
+ const trimmed = home.replace(/\/+$/, "");
+ return {
+ favorites: [
+ { label: "Home", path: trimmed },
+ { label: "Desktop", path: `${trimmed}/Desktop` },
+ { label: "Documents", path: `${trimmed}/Documents` },
+ { label: "Downloads", path: `${trimmed}/Downloads` },
+ ],
+ locations: [{ label: "/", path: "/" }],
+ };
+}
+
+export function FolderBrowserModal({
+ isOpen,
+ onClose,
+ onAdd,
+}: FolderBrowserModalProps) {
+ const { t } = useTranslation("openhands");
+ const [currentPath, setCurrentPath] = useState<string | null>(null);
+
+ const { data: homeData } = useHomeDirectory();
+
+ // Initialize / reset to home each time the modal is opened
+ useEffect(() => {
+ if (isOpen && homeData?.home && currentPath === null) {
+ setCurrentPath(homeData.home);
+ }
+ if (!isOpen) {
+ setCurrentPath(null);
+ }
+ }, [isOpen, homeData?.home, currentPath]);
+
+ const {
+ data: listing,
+ isLoading,
+ isError,
+ error,
+ } = useListSubdirs(isOpen ? currentPath : null);
+
+ const sidebar = useMemo(
+ () => buildSidebar(homeData?.home ?? null),
+ [homeData?.home],
+ );
+
+ if (!isOpen) return null;
+
+ const subdirs = listing?.subdirs ?? [];
+ const parent = currentPath ? getParentPath(currentPath) : null;
+
+ const handleUseThisFolder = () => {
+ if (subdirs.length === 0) return;
+ const items: LocalWorkspace[] = subdirs.map((s) => ({
+ id: s.path,
+ name: s.name,
+ path: s.path,
+ }));
+ onAdd(items);
+ onClose();
+ };
+
+ return (
+ <ModalBackdrop
+ onClose={onClose}
+ aria-label={t(I18nKey.HOME$ADD_WORKSPACES_TITLE)}
+ >
+ <div
+ data-testid="folder-browser-modal"
+ className={cn(
+ "flex flex-col bg-[#26282D] border border-[#727987] rounded-xl",
+ "w-[720px] max-w-[90vw] h-[480px]",
+ )}
+ >
+ {/* Title bar */}
+ <div className="flex items-center justify-between px-5 py-3 border-b border-[#727987]">
+ <span className="text-sm font-semibold text-white">
+ {t(I18nKey.HOME$ADD_WORKSPACES_TITLE)}
+ </span>
+ </div>
+
+ {/* Body: sidebar + main */}
+ <div className="flex flex-1 min-h-0">
+ {/* Sidebar */}
+ <aside
+ data-testid="folder-browser-sidebar"
+ className="w-[180px] shrink-0 border-r border-[#727987] bg-[#1F2125] py-3 overflow-y-auto"
+ >
+ <SidebarSection
+ label={t(I18nKey.HOME$FAVORITES)}
+ entries={sidebar.favorites}
+ currentPath={currentPath}
+ onPick={setCurrentPath}
+ />
+ <SidebarSection
+ label={t(I18nKey.HOME$LOCATIONS)}
+ entries={sidebar.locations}
+ currentPath={currentPath}
+ onPick={setCurrentPath}
+ />
+ </aside>
+
+ {/* Main */}
+ <div className="flex-1 flex flex-col min-w-0">
+ {/* Nav row */}
+ <div className="flex items-center gap-2 px-4 py-2 border-b border-[#727987]">
+ <button
+ type="button"
+ data-testid="folder-browser-up"
+ onClick={() => parent && setCurrentPath(parent)}
+ disabled={!parent}
+ aria-label="Up"
+ className="p-1 rounded hover:bg-[#5C5D62] text-white disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"
+ >
+ <ChevronLeft width={16} height={16} />
+ </button>
+ <span
+ className="text-xs text-[#A3A3A3] truncate"
+ data-testid="folder-browser-current-path"
+ >
+ {currentPath ?? ""}
+ </span>
+ </div>
+
+ {/* Column headers */}
+ <div className="grid grid-cols-[1fr_120px] px-4 py-1 border-b border-[#727987] text-xs text-[#B7BDC2] font-semibold">
+ <span>{t(I18nKey.HOME$NAME)}</span>
+ <span>{t(I18nKey.HOME$KIND)}</span>
+ </div>
+
+ {/* List */}
+ <ul
+ className="flex-1 overflow-auto custom-scrollbar-always"
+ data-testid="folder-browser-list"
+ >
+ {isLoading && (
+ <li className="px-4 py-2 text-sm text-[#B7BDC2]">
+ {t(I18nKey.HOME$LOADING)}
+ </li>
+ )}
+ {isError && (
+ <li
+ className="px-4 py-2 text-sm text-red-400"
+ data-testid="folder-browser-error"
+ >
+ {(error as Error | undefined)?.message ?? "Failed to load"}
+ </li>
+ )}
+ {!isLoading && !isError && subdirs.length === 0 && (
+ <li className="px-4 py-2 text-sm text-[#B7BDC2]">
+ {t(I18nKey.HOME$NO_WORKSPACES)}
+ </li>
+ )}
+ {subdirs.map((entry) => (
+ <li key={entry.path}>
+ <button
+ type="button"
+ onClick={() => setCurrentPath(entry.path)}
+ className="grid grid-cols-[1fr_120px] items-center w-full text-left px-4 py-1.5 text-sm text-white hover:bg-[#5C5D62] cursor-pointer"
+ data-testid={`folder-browser-entry-${entry.name}`}
+ >
+ <span className="flex items-center gap-2 min-w-0">
+ <FolderIcon width={16} height={16} className="shrink-0" />
+ <span className="truncate">{entry.name}</span>
+ </span>
+ <span className="text-[#B7BDC2] text-xs">
+ {t(I18nKey.HOME$FOLDER)}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+
+ {/* Footer */}
+ <div className="flex justify-end gap-2 px-5 py-3 border-t border-[#727987]">
+ <BrandButton
+ type="button"
+ variant="secondary"
+ onClick={onClose}
+ testId="folder-browser-cancel"
+ >
+ {t(I18nKey.HOME$CANCEL)}
+ </BrandButton>
+ <BrandButton
+ type="button"
+ variant="primary"
+ onClick={handleUseThisFolder}
+ isDisabled={subdirs.length === 0}
+ testId="folder-browser-use"
+ >
+ {t(I18nKey.HOME$USE_THIS_FOLDER)}
+ </BrandButton>
+ </div>
+ </div>
+ </ModalBackdrop>
+ );
+}
diff --git a/src/components/features/home/workspace-dropdown/workspace-dropdown.tsx b/src/components/features/home/workspace-dropdown/workspace-dropdown.tsx
new file mode 100644
index 0000000000..c6745af5b5
--- /dev/null
+++ b/src/components/features/home/workspace-dropdown/workspace-dropdown.tsx
@@ -0,0 +1,191 @@
+import React, { useState, useMemo, useCallback, useRef } from "react";
+import { useCombobox } from "downshift";
+import { useTranslation } from "react-i18next";
+
+import { cn } from "#/utils/utils";
+import { LocalWorkspace } from "#/types/workspace";
+import { I18nKey } from "#/i18n/declaration";
+import RepoIcon from "#/icons/repo.svg?react";
+
+import { ClearButton } from "../shared/clear-button";
+import { ToggleButton } from "../shared/toggle-button";
+import { DropdownItem } from "../shared/dropdown-item";
+import { EmptyState } from "../shared/empty-state";
+import { GenericDropdownMenu } from "../shared/generic-dropdown-menu";
+
+export interface WorkspaceDropdownProps {
+ workspaces: LocalWorkspace[];
+ value: LocalWorkspace | null;
+ placeholder?: string;
+ className?: string;
+ disabled?: boolean;
+ onChange: (workspace: LocalWorkspace | null) => void;
+ onAddClick: () => void;
+}
+
+export function WorkspaceDropdown({
+ workspaces,
+ value,
+ placeholder,
+ className,
+ disabled = false,
+ onChange,
+ onAddClick,
+}: WorkspaceDropdownProps) {
+ const { t } = useTranslation("openhands");
+ const [inputValue, setInputValue] = useState(value?.name ?? "");
+ const menuRef = useRef<HTMLUListElement>(null);
+
+ const filteredWorkspaces = useMemo(() => {
+ const trimmed = inputValue.trim().toLowerCase();
+ if (!trimmed) return workspaces;
+ return workspaces.filter(
+ (w) =>
+ w.name.toLowerCase().includes(trimmed) ||
+ w.path.toLowerCase().includes(trimmed),
+ );
+ }, [workspaces, inputValue]);
+
+ const handleSelectionChange = useCallback(
+ (selectedItem: LocalWorkspace | null) => {
+ onChange(selectedItem);
+ if (selectedItem) {
+ setInputValue(selectedItem.name);
+ }
+ },
+ [onChange],
+ );
+
+ const handleClear = useCallback(() => {
+ handleSelectionChange(null);
+ setInputValue("");
+ }, [handleSelectionChange]);
+
+ const {
+ isOpen,
+ getToggleButtonProps,
+ getMenuProps,
+ getInputProps,
+ highlightedIndex,
+ getItemProps,
+ selectedItem,
+ closeMenu,
+ } = useCombobox<LocalWorkspace>({
+ items: filteredWorkspaces,
+ itemToString: (item) => item?.name ?? "",
+ selectedItem: value,
+ onSelectedItemChange: ({ selectedItem: newSelectedItem }) => {
+ handleSelectionChange(newSelectedItem ?? null);
+ },
+ inputValue,
+ stateReducer: (state, actionAndChanges) =>
+ actionAndChanges.type === useCombobox.stateChangeTypes.InputClick &&
+ state.isOpen
+ ? { ...actionAndChanges.changes, isOpen: true }
+ : actionAndChanges.changes,
+ });
+
+ const renderItem = (
+ item: LocalWorkspace,
+ index: number,
+ itemHighlightedIndex: number,
+ itemSelectedItem: LocalWorkspace | null,
+ itemGetItemProps: any, // eslint-disable-line @typescript-eslint/no-explicit-any
+ ) => (
+ <DropdownItem
+ key={item.id}
+ item={item}
+ index={index}
+ isSelected={itemSelectedItem?.id === item.id}
+ getItemProps={itemGetItemProps}
+ getDisplayText={(workspace) => workspace.name}
+ getItemKey={(workspace) => workspace.id}
+ />
+ );
+
+ const renderEmptyState = (emptyInputValue: string) => (
+ <EmptyState
+ inputValue={emptyInputValue}
+ searchMessage={t(I18nKey.HOME$NO_WORKSPACES)}
+ emptyMessage={t(I18nKey.HOME$NO_WORKSPACES)}
+ testId="workspace-dropdown-empty"
+ />
+ );
+
+ const stickyFooterItem = useMemo(
+ () => (
+ <button
+ type="button"
+ data-testid="add-workspaces-button"
+ className="flex items-center w-full px-2 py-2 text-sm text-white hover:bg-[#5C5D62] rounded-md transition-colors duration-150 font-normal"
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ }}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ closeMenu();
+ onAddClick();
+ }}
+ >
+ {t(I18nKey.HOME$ADD_WORKSPACES)}
+ </button>
+ ),
+ [onAddClick, t, closeMenu],
+ );
+
+ return (
+ <div className={cn("relative", className)}>
+ <div className="relative">
+ <div className="absolute left-2 top-1/2 transform -translate-y-1/2 z-10">
+ <RepoIcon width={16} height={16} />
+ </div>
+ <input
+ // eslint-disable-next-line react/jsx-props-no-spreading
+ {...getInputProps({
+ disabled,
+ placeholder: placeholder ?? t(I18nKey.HOME$WORKSPACE_PLACEHOLDER),
+ className: cn(
+ "w-full px-3 py-2 border border-[#727987] rounded-sm shadow-none h-[42px] min-h-[42px] max-h-[42px]",
+ "bg-[#454545] text-[#A3A3A3] placeholder:text-[#A3A3A3]",
+ "focus:outline-none focus:ring-0 focus:border-[#727987]",
+ "disabled:bg-[#363636] disabled:cursor-not-allowed disabled:opacity-60",
+ "pl-7 pr-16 text-sm font-normal leading-5",
+ ),
+ onChange: (e: React.ChangeEvent<HTMLInputElement>) => {
+ setInputValue(e.target.value);
+ },
+ })}
+ data-testid="workspace-dropdown"
+ />
+
+ <div className="absolute right-1 top-1/2 transform -translate-y-1/2 flex items-center">
+ {value && <ClearButton disabled={disabled} onClear={handleClear} />}
+ <ToggleButton
+ isOpen={isOpen}
+ disabled={disabled}
+ getToggleButtonProps={getToggleButtonProps}
+ iconClassName="w-10 h-10"
+ />
+ </div>
+ </div>
+
+ <GenericDropdownMenu<LocalWorkspace>
+ isOpen={isOpen}
+ filteredItems={filteredWorkspaces}
+ inputValue={inputValue}
+ highlightedIndex={highlightedIndex}
+ selectedItem={selectedItem}
+ getMenuProps={getMenuProps}
+ getItemProps={getItemProps}
+ menuRef={menuRef}
+ renderItem={renderItem}
+ renderEmptyState={renderEmptyState}
+ stickyFooterItem={stickyFooterItem}
+ testId="workspace-dropdown-menu"
+ itemKey={(item) => item.id}
+ />
+ </div>
+ );
+}
diff --git a/src/components/features/home/workspace-selection-form.tsx b/src/components/features/home/workspace-selection-form.tsx
new file mode 100644
index 0000000000..3907d5c61f
--- /dev/null
+++ b/src/components/features/home/workspace-selection-form.tsx
@@ -0,0 +1,91 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+
+import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";
+import { useNavigation } from "#/context/navigation-context";
+import { useIsCreatingConversation } from "#/hooks/use-is-creating-conversation";
+import { useWorkspacesStore } from "#/stores/workspaces-store";
+import { LocalWorkspace } from "#/types/workspace";
+import { I18nKey } from "#/i18n/declaration";
+import FolderIcon from "#/icons/folder.svg?react";
+
+import { BrandButton } from "../settings/brand-button";
+import { WorkspaceDropdown } from "./workspace-dropdown/workspace-dropdown";
+import { FolderBrowserModal } from "./workspace-dropdown/folder-browser-modal";
+
+interface WorkspaceSelectionFormProps {
+ isLoadingSettings?: boolean;
+}
+
+export function WorkspaceSelectionForm({
+ isLoadingSettings = false,
+}: WorkspaceSelectionFormProps) {
+ const { t } = useTranslation("openhands");
+ const { navigate } = useNavigation();
+
+ const { workspaces, addWorkspaces } = useWorkspacesStore();
+ const [selectedWorkspace, setSelectedWorkspace] =
+ React.useState<LocalWorkspace | null>(null);
+ const [isBrowserOpen, setIsBrowserOpen] = React.useState(false);
+
+ const {
+ mutate: createConversation,
+ isPending,
+ isSuccess,
+ } = useCreateConversation();
+ const isCreatingConversationElsewhere = useIsCreatingConversation();
+ const isCreatingConversation =
+ isPending || isSuccess || isCreatingConversationElsewhere;
+
+ const handleLaunch = () => {
+ if (!selectedWorkspace) return;
+ createConversation(
+ { workingDir: selectedWorkspace.path },
+ {
+ onSuccess: (data) => navigate(`/conversations/${data.conversation_id}`),
+ },
+ );
+ };
+
+ return (
+ <div className="flex flex-col">
+ <div className="flex items-center gap-[10px] pb-4">
+ <FolderIcon width={24} height={24} />
+ <span className="leading-5 font-bold text-base text-white">
+ {t(I18nKey.HOME$WORKSPACES_TAB)}
+ </span>
+ </div>
+
+ <div className="flex flex-col gap-[10px] pb-4">
+ <WorkspaceDropdown
+ workspaces={workspaces}
+ value={selectedWorkspace}
+ disabled={isLoadingSettings}
+ onChange={setSelectedWorkspace}
+ onAddClick={() => setIsBrowserOpen(true)}
+ className="max-w-auto"
+ />
+ </div>
+
+ <BrandButton
+ testId="workspace-launch-button"
+ variant="primary"
+ type="button"
+ isDisabled={
+ !selectedWorkspace || isCreatingConversation || isLoadingSettings
+ }
+ onClick={handleLaunch}
+ className="w-auto absolute bottom-5 left-5 right-5 font-semibold"
+ >
+ {!isCreatingConversation && "Launch"}
+ {isCreatingConversation && t(I18nKey.HOME$LOADING)}
+ </BrandButton>
+
+ <FolderBrowserModal
+ isOpen={isBrowserOpen}
+ onClose={() => setIsBrowserOpen(false)}
+ onAdd={(items) => addWorkspaces(items)}
+ />
+ </div>
+ );
+}
diff --git a/src/hooks/mutation/use-create-conversation.ts b/src/hooks/mutation/use-create-conversation.ts
index 7e1e2edb50..19d3fbd06a 100644
--- a/src/hooks/mutation/use-create-conversation.ts
+++ b/src/hooks/mutation/use-create-conversation.ts
@@ -17,6 +17,7 @@ interface CreateConversationVariables {
parentConversationId?: string;
agentType?: "default" | "plan";
plugins?: PluginSpec[];
+ workingDir?: string;
}
// Response type for V1 conversations
@@ -37,12 +38,26 @@ export const useCreateConversation = () => {
mutationFn: async (
variables: CreateConversationVariables,
): Promise<CreateConversationResponse> => {
- const { query, conversationInstructions, plugins } = variables;
+ const {
+ query,
+ conversationInstructions,
+ plugins,
+ repository,
+ workingDir,
+ } = variables;
const conversation = await V1ConversationService.createConversation(
query,
conversationInstructions,
plugins,
+ repository
+ ? {
+ selected_repository: repository.name,
+ selected_branch: repository.branch ?? null,
+ git_provider: repository.gitProvider,
+ }
+ : null,
+ workingDir,
);
return {
diff --git a/src/hooks/query/use-list-subdirs.ts b/src/hooks/query/use-list-subdirs.ts
new file mode 100644
index 0000000000..b95e80ad44
--- /dev/null
+++ b/src/hooks/query/use-list-subdirs.ts
@@ -0,0 +1,20 @@
+import { useQuery } from "@tanstack/react-query";
+import FilesService from "#/api/files-service/files-service.api";
+
+export const useListSubdirs = (path: string | null) =>
+ useQuery({
+ queryKey: ["file", "list_subdirs", path],
+ queryFn: () => FilesService.listSubdirs(path as string),
+ enabled: !!path,
+ retry: false,
+ meta: { disableToast: true },
+ });
+
+export const useHomeDirectory = () =>
+ useQuery({
+ queryKey: ["file", "home"],
+ queryFn: () => FilesService.getHome(),
+ retry: false,
+ meta: { disableToast: true },
+ staleTime: Infinity,
+ });
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 55739a8faf..f163f21bdf 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -15475,6 +15475,227 @@
"uk": "+ Додати репозиторії GitHub",
"ca": "+ Afegeix repositoris de GitHub"
},
+ "HOME$REPOSITORIES_TAB": {
+ "en": "Repositories",
+ "ja": "リポジトリ",
+ "zh-CN": "仓库",
+ "zh-TW": "儲存庫",
+ "ko-KR": "저장소",
+ "no": "Repositorier",
+ "it": "Repository",
+ "pt": "Repositórios",
+ "es": "Repositorios",
+ "ar": "المستودعات",
+ "fr": "Dépôts",
+ "tr": "Depolar",
+ "de": "Repositories",
+ "uk": "Репозиторії",
+ "ca": "Repositoris"
+ },
+ "HOME$WORKSPACES_TAB": {
+ "en": "Workspaces",
+ "ja": "ワークスペース",
+ "zh-CN": "工作区",
+ "zh-TW": "工作區",
+ "ko-KR": "작업 공간",
+ "no": "Arbeidsområder",
+ "it": "Aree di lavoro",
+ "pt": "Espaços de trabalho",
+ "es": "Espacios de trabajo",
+ "ar": "مساحات العمل",
+ "fr": "Espaces de travail",
+ "tr": "Çalışma alanları",
+ "de": "Arbeitsbereiche",
+ "uk": "Робочі області",
+ "ca": "Espais de treball"
+ },
+ "HOME$ADD_WORKSPACES": {
+ "en": "+ Add Workspaces",
+ "ja": "+ ワークスペースを追加",
+ "zh-CN": "+ 添加工作区",
+ "zh-TW": "+ 新增工作區",
+ "ko-KR": "+ 작업 공간 추가",
+ "no": "+ Legg til arbeidsområder",
+ "it": "+ Aggiungi aree di lavoro",
+ "pt": "+ Adicionar espaços de trabalho",
+ "es": "+ Agregar espacios de trabajo",
+ "ar": "+ إضافة مساحات عمل",
+ "fr": "+ Ajouter des espaces de travail",
+ "tr": "+ Çalışma alanı ekle",
+ "de": "+ Arbeitsbereiche hinzufügen",
+ "uk": "+ Додати робочі області",
+ "ca": "+ Afegeix espais de treball"
+ },
+ "HOME$NO_WORKSPACES": {
+ "en": "No workspaces yet",
+ "ja": "ワークスペースはまだありません",
+ "zh-CN": "暂无工作区",
+ "zh-TW": "尚無工作區",
+ "ko-KR": "작업 공간이 없습니다",
+ "no": "Ingen arbeidsområder ennå",
+ "it": "Nessuna area di lavoro ancora",
+ "pt": "Nenhum espaço de trabalho ainda",
+ "es": "Aún no hay espacios de trabajo",
+ "ar": "لا توجد مساحات عمل بعد",
+ "fr": "Aucun espace de travail",
+ "tr": "Henüz çalışma alanı yok",
+ "de": "Noch keine Arbeitsbereiche",
+ "uk": "Робочих областей ще немає",
+ "ca": "Encara no hi ha espais de treball"
+ },
+ "HOME$WORKSPACE_PLACEHOLDER": {
+ "en": "Select a workspace",
+ "ja": "ワークスペースを選択",
+ "zh-CN": "选择工作区",
+ "zh-TW": "選擇工作區",
+ "ko-KR": "작업 공간 선택",
+ "no": "Velg et arbeidsområde",
+ "it": "Seleziona un'area di lavoro",
+ "pt": "Selecione um espaço de trabalho",
+ "es": "Selecciona un espacio de trabajo",
+ "ar": "اختر مساحة عمل",
+ "fr": "Sélectionner un espace de travail",
+ "tr": "Bir çalışma alanı seçin",
+ "de": "Arbeitsbereich auswählen",
+ "uk": "Виберіть робочу область",
+ "ca": "Selecciona un espai de treball"
+ },
+ "HOME$ADD_WORKSPACES_TITLE": {
+ "en": "Add workspaces",
+ "ja": "ワークスペースを追加",
+ "zh-CN": "添加工作区",
+ "zh-TW": "新增工作區",
+ "ko-KR": "작업 공간 추가",
+ "no": "Legg til arbeidsområder",
+ "it": "Aggiungi aree di lavoro",
+ "pt": "Adicionar espaços de trabalho",
+ "es": "Agregar espacios de trabajo",
+ "ar": "إضافة مساحات عمل",
+ "fr": "Ajouter des espaces de travail",
+ "tr": "Çalışma alanı ekle",
+ "de": "Arbeitsbereiche hinzufügen",
+ "uk": "Додати робочі області",
+ "ca": "Afegeix espais de treball"
+ },
+ "HOME$CANCEL": {
+ "en": "Cancel",
+ "ja": "キャンセル",
+ "zh-CN": "取消",
+ "zh-TW": "取消",
+ "ko-KR": "취소",
+ "no": "Avbryt",
+ "it": "Annulla",
+ "pt": "Cancelar",
+ "es": "Cancelar",
+ "ar": "إلغاء",
+ "fr": "Annuler",
+ "tr": "İptal",
+ "de": "Abbrechen",
+ "uk": "Скасувати",
+ "ca": "Cancel·la"
+ },
+ "HOME$USE_THIS_FOLDER": {
+ "en": "Use this folder",
+ "ja": "このフォルダを使用",
+ "zh-CN": "使用此文件夹",
+ "zh-TW": "使用此資料夾",
+ "ko-KR": "이 폴더 사용",
+ "no": "Bruk denne mappen",
+ "it": "Usa questa cartella",
+ "pt": "Usar esta pasta",
+ "es": "Usar esta carpeta",
+ "ar": "استخدم هذا المجلد",
+ "fr": "Utiliser ce dossier",
+ "tr": "Bu klasörü kullan",
+ "de": "Diesen Ordner verwenden",
+ "uk": "Використати цю папку",
+ "ca": "Utilitza aquesta carpeta"
+ },
+ "HOME$FAVORITES": {
+ "en": "Favorites",
+ "ja": "よく使う項目",
+ "zh-CN": "个人收藏",
+ "zh-TW": "個人收藏",
+ "ko-KR": "즐겨찾기",
+ "no": "Favoritter",
+ "it": "Preferiti",
+ "pt": "Favoritos",
+ "es": "Favoritos",
+ "ar": "المفضلة",
+ "fr": "Favoris",
+ "tr": "Favoriler",
+ "de": "Favoriten",
+ "uk": "Обране",
+ "ca": "Preferits"
+ },
+ "HOME$LOCATIONS": {
+ "en": "Locations",
+ "ja": "場所",
+ "zh-CN": "位置",
+ "zh-TW": "位置",
+ "ko-KR": "위치",
+ "no": "Steder",
+ "it": "Posizioni",
+ "pt": "Localizações",
+ "es": "Ubicaciones",
+ "ar": "المواقع",
+ "fr": "Emplacements",
+ "tr": "Konumlar",
+ "de": "Orte",
+ "uk": "Розташування",
+ "ca": "Ubicacions"
+ },
+ "HOME$NAME": {
+ "en": "Name",
+ "ja": "名前",
+ "zh-CN": "名称",
+ "zh-TW": "名稱",
+ "ko-KR": "이름",
+ "no": "Navn",
+ "it": "Nome",
+ "pt": "Nome",
+ "es": "Nombre",
+ "ar": "الاسم",
+ "fr": "Nom",
+ "tr": "Ad",
+ "de": "Name",
+ "uk": "Назва",
+ "ca": "Nom"
+ },
+ "HOME$KIND": {
+ "en": "Kind",
+ "ja": "種類",
+ "zh-CN": "种类",
+ "zh-TW": "種類",
+ "ko-KR": "종류",
+ "no": "Type",
+ "it": "Tipo",
+ "pt": "Tipo",
+ "es": "Tipo",
+ "ar": "النوع",
+ "fr": "Type",
+ "tr": "Tür",
+ "de": "Art",
+ "uk": "Тип",
+ "ca": "Tipus"
+ },
+ "HOME$FOLDER": {
+ "en": "Folder",
+ "ja": "フォルダ",
+ "zh-CN": "文件夹",
+ "zh-TW": "資料夾",
+ "ko-KR": "폴더",
+ "no": "Mappe",
+ "it": "Cartella",
+ "pt": "Pasta",
+ "es": "Carpeta",
+ "ar": "مجلد",
+ "fr": "Dossier",
+ "tr": "Klasör",
+ "de": "Ordner",
+ "uk": "Папка",
+ "ca": "Carpeta"
+ },
"REPOSITORY$SELECT_BRANCH": {
"en": "Select a branch",
"ja": "ブランチを選択",
diff --git a/src/stores/workspaces-store.ts b/src/stores/workspaces-store.ts
new file mode 100644
index 0000000000..669cf5496c
--- /dev/null
+++ b/src/stores/workspaces-store.ts
@@ -0,0 +1,46 @@
+import { create } from "zustand";
+import { persist, createJSONStorage } from "zustand/middleware";
+import { LocalWorkspace } from "#/types/workspace";
+
+interface WorkspacesState {
+ workspaces: LocalWorkspace[];
+}
+
+interface WorkspacesActions {
+ addWorkspaces: (items: LocalWorkspace[]) => void;
+ removeWorkspace: (path: string) => void;
+ clearWorkspaces: () => void;
+}
+
+type WorkspacesStore = WorkspacesState & WorkspacesActions;
+
+const initialState: WorkspacesState = {
+ workspaces: [],
+};
+
+export const useWorkspacesStore = create<WorkspacesStore>()(
+ persist(
+ (set) => ({
+ ...initialState,
+
+ addWorkspaces: (items: LocalWorkspace[]) =>
+ set((state) => {
+ const existingPaths = new Set(state.workspaces.map((w) => w.path));
+ const newOnes = items.filter((item) => !existingPaths.has(item.path));
+ if (newOnes.length === 0) return state;
+ return { workspaces: [...state.workspaces, ...newOnes] };
+ }),
+
+ removeWorkspace: (path: string) =>
+ set((state) => ({
+ workspaces: state.workspaces.filter((w) => w.path !== path),
+ })),
+
+ clearWorkspaces: () => set(() => ({ workspaces: [] })),
+ }),
+ {
+ name: "workspaces-store",
+ storage: createJSONStorage(() => localStorage),
+ },
+ ),
+);
diff --git a/src/types/workspace.ts b/src/types/workspace.ts
new file mode 100644
index 0000000000..a106df5786
--- /dev/null
+++ b/src/types/workspace.ts
@@ -0,0 +1,5 @@
+export interface LocalWorkspace {
+ id: string;
+ name: string;
+ path: string;
+}