π OpenHands: AI-Driven Development
test: strengthen home project setup and launch (#17364)
aivong-openhandsfe67a27bb001
diff --git a/.pr/refactor-home-git-launch-vitest.png b/.pr/refactor-home-git-launch-vitest.pngnew file mode 100644index 0000000000..0106b810b4Binary files /dev/null and b/.pr/refactor-home-git-launch-vitest.png differdiff --git a/__tests__/components/features/home/git-repo-dropdown.test.tsx b/__tests__/components/features/home/git-repo-dropdown.test.tsxindex 77d43e871b..8203f60be8 100644--- a/__tests__/components/features/home/git-repo-dropdown.test.tsx+++ b/__tests__/components/features/home/git-repo-dropdown.test.tsx@@ -1,9 +1,28 @@-import { render, screen, waitFor } from "@testing-library/react";-import { describe, expect, vi, beforeEach, it } from "vitest";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import { describe, expect, vi, it } from "vitest";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import userEvent from "@testing-library/user-event";import { GitRepoDropdown } from "../../../../src/components/features/home/git-repo-dropdown/git-repo-dropdown";import { GitRepository } from "#/types/git";+import { I18nKey } from "#/i18n/declaration";++const useTranslationMock = vi.hoisted(() =>+ vi.fn((namespace: string) => ({+ t: (key: string) => `${namespace}:${key}`,+ })),+);++vi.mock("react-i18next", () => ({+ useTranslation: useTranslationMock,+}));++const translated = (key: I18nKey) => `openhands:${key}`;// Mock the repository data hookconst mockUseRepositoryData = vi.fn();@@ -20,14 +39,22 @@ vi.mock("#/components/features/home/git-repo-dropdown/use-url-search", () => ({useUrlSearch: (...args: unknown[]) => mockUseUrlSearch(...args),}));+vi.mock("#/hooks/use-debounce", () => ({+ useDebounce: (value: string) => value,+}));+// Mock useConfigvi.mock("#/hooks/query/use-config", () => ({useConfig: () => ({ data: null }),}));+const homeStore = vi.hoisted(() => ({+ recentRepositories: [] as GitRepository[],+}));+// Mock useHomeStorevi.mock("#/stores/home-store", () => ({- useHomeStore: () => ({ recentRepositories: [] }),+ useHomeStore: () => homeStore,}));const MOCK_REPOSITORIES: GitRepository[] = [@@ -57,6 +84,7 @@ const setupDefaultMocks = (repositoryDataOverrides: Partial<ReturnType<typeof mockUseRepositoryData>> = {},+ urlSearchOverrides: Partial<ReturnType<typeof mockUseUrlSearch>> = {},) => {mockUseRepositoryData.mockReturnValue({repositories: MOCK_REPOSITORIES,@@ -73,6 +101,7 @@ const setupDefaultMocks = (mockUseUrlSearch.mockReturnValue({urlSearchResults: [],isUrlSearchLoading: false,+ ...urlSearchOverrides,});};@@ -81,9 +110,13 @@ const renderDropdown = (repositoryDataOverrides: Partial<ReturnType<typeof mockUseRepositoryData>> = {},+ urlSearchOverrides: Partial<ReturnType<typeof mockUseUrlSearch>> = {},+ recentRepositories: GitRepository[] = [],) => {+ vi.clearAllMocks();+ homeStore.recentRepositories = recentRepositories;// Set up mocks with optional overrides- setupDefaultMocks(repositoryDataOverrides);+ setupDefaultMocks(repositoryDataOverrides, urlSearchOverrides);return render(<GitRepoDropdown@@ -112,12 +145,70 @@ const renderDropdown = ();};-describe("GitRepoDropdown", () => {- beforeEach(() => {- vi.clearAllMocks();+function setMenuScrollMetrics(+ menu: HTMLElement,+ {+ scrollTop,+ scrollHeight = 100,+ clientHeight = 20,+ }: { scrollTop: number; scrollHeight?: number; clientHeight?: number },+) {+ Object.defineProperties(menu, {+ scrollTop: { configurable: true, value: scrollTop },+ scrollHeight: { configurable: true, value: scrollHeight },+ clientHeight: { configurable: true, value: clientHeight },});+}+describe("GitRepoDropdown", () => {describe("dropdown behavior", () => {+ it("renders localized defaults and preserves presentation overrides", () => {+ const view = renderDropdown({ className: "repository-root" });+ const input = screen.getByTestId("git-repo-dropdown");++ expect(input).toHaveValue("");+ expect(input).toHaveAttribute(+ "placeholder",+ translated(I18nKey.COMMON$SEARCH_REPOSITORIES_PLACEHOLDER),+ );+ expect(input.parentElement?.parentElement).toHaveClass(+ "relative",+ "repository-root",+ );+ expect(input).toHaveClass(+ "text-inherit",+ "shadow-none",+ "pl-7",+ "pr-16",+ "text-sm",+ "font-normal",+ "leading-5",+ "placeholder:text-[var(--oh-muted)]",+ "disabled:cursor-not-allowed",+ "disabled:opacity-60",+ );+ expect(+ input.previousElementSibling?.querySelector("svg"),+ ).toBeInTheDocument();+ expect(+ input.previousElementSibling?.querySelector(".animate-spin"),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByText(translated(I18nKey.COMMON$MOST_RECENT)),+ ).not.toBeInTheDocument();++ view.rerender(+ <GitRepoDropdown+ provider="github"+ placeholder="Choose a repository"+ className="repository-root"+ onChange={mockOnChange}+ />,+ );++ expect(input).toHaveAttribute("placeholder", "Choose a repository");+ });+it("should open dropdown when input is clicked", async () => {renderDropdown();@@ -156,6 +247,32 @@ describe("GitRepoDropdown", () => {});});+ it("keeps repository options uniquely keyed when results reorder", async () => {+ const user = userEvent.setup();+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ const view = renderDropdown();+ const input = screen.getByTestId("git-repo-dropdown");++ try {+ await user.click(input);+ setupDefaultMocks({+ repositories: [MOCK_REPOSITORIES[2], MOCK_REPOSITORIES[0]],+ });+ view.rerender(+ <GitRepoDropdown provider="github" onChange={mockOnChange} />,+ );++ expect(+ screen.getAllByRole("option").map((option) => option.textContent),+ ).toEqual(["org/feature-repo", "user/repo-one"]);+ expect(consoleError).not.toHaveBeenCalledWith(+ expect.stringContaining('unique "key" prop'),+ );+ } finally {+ consoleError.mockRestore();+ }+ });+it("should preserve typed text when clicking input while typing", async () => {renderDropdown();@@ -173,6 +290,36 @@ describe("GitRepoDropdown", () => {// Text should be preservedexpect(input.value).toBe("repo");});++ it("clears an unselected search when the menu closes", async () => {+ const user = userEvent.setup();+ renderDropdown();+ const input = screen.getByTestId("git-repo-dropdown");++ await user.click(input);+ await user.type(input, "repo");+ await user.keyboard("{Escape}");++ expect(input).toHaveValue("");+ expect(screen.getByTestId("git-repo-dropdown-menu")).toHaveClass(+ "hidden",+ );+ });++ it("preserves keyboard input when typing opens the menu", async () => {+ const user = userEvent.setup();+ renderDropdown();+ const input = screen.getByTestId("git-repo-dropdown");++ await user.tab();+ expect(input).toHaveFocus();+ await user.keyboard("repo");++ expect(input).toHaveValue("repo");+ expect(screen.getByTestId("git-repo-dropdown-menu")).not.toHaveClass(+ "hidden",+ );+ });});describe("cursor position preservation", () => {@@ -200,10 +347,7 @@ describe("GitRepoDropdown", () => {it("should show selected repository name in input when provided", async () => {const selectedRepository = MOCK_REPOSITORIES[0];- renderDropdown(- { value: selectedRepository.id },- { selectedRepository },- );+ renderDropdown({ value: selectedRepository.id }, { selectedRepository });const input = screen.getByTestId("git-repo-dropdown") as HTMLInputElement;@@ -211,6 +355,30 @@ describe("GitRepoDropdown", () => {expect(input.value).toBe(selectedRepository.full_name);});});++ it("preserves an active search when repository data changes", async () => {+ const user = userEvent.setup();+ const view = renderDropdown(+ { value: MOCK_REPOSITORIES[0].id },+ { selectedRepository: MOCK_REPOSITORIES[0] },+ );+ const input = screen.getByTestId("git-repo-dropdown");+ await waitFor(() => expect(input).toHaveValue("user/repo-one"));++ await user.click(input);+ await user.clear(input);+ await user.type(input, "draft-search");+ setupDefaultMocks({ selectedRepository: MOCK_REPOSITORIES[1] });+ view.rerender(+ <GitRepoDropdown+ provider="github"+ value={MOCK_REPOSITORIES[1].id}+ onChange={mockOnChange}+ />,+ );++ expect(input).toHaveValue("draft-search");+ });});describe("repository selection", () => {@@ -229,6 +397,11 @@ describe("GitRepoDropdown", () => {await userEvent.click(screen.getByText("user/repo-two"));expect(mockOnChange).toHaveBeenCalledWith(MOCK_REPOSITORIES[1]);+ await waitFor(() =>+ expect(screen.getByTestId("git-repo-dropdown-menu")).toHaveClass(+ "hidden",+ ),+ );});it("should keep selected repo visible even if it's not in fetched results", async () => {@@ -249,5 +422,334 @@ describe("GitRepoDropdown", () => {expect(input.value).toBe("user/repo-two");});});++ it("clears a locally selected repository and reports an undefined selection", async () => {+ const user = userEvent.setup();+ renderDropdown();+ const input = screen.getByTestId("git-repo-dropdown") as HTMLInputElement;++ await user.click(input);+ await user.click(await screen.findByText("user/repo-two"));+ await user.click(await screen.findByTestId("dropdown-clear"));++ await waitFor(() => expect(input).toHaveValue(""));+ expect(mockOnChange).toHaveBeenLastCalledWith(undefined);+ });++ it("still updates its visible selection when no change callback is provided", async () => {+ const user = userEvent.setup();+ renderDropdown({ onChange: undefined });+ const input = screen.getByTestId("git-repo-dropdown") as HTMLInputElement;++ await user.click(input);+ await user.click(await screen.findByText("user/repo-one"));++ await waitFor(() => expect(input).toHaveValue("user/repo-one"));+ });++ it("clears an externally selected repository when the controlled value becomes null", async () => {+ const selectedRepository = MOCK_REPOSITORIES[0];+ const view = renderDropdown(+ { value: selectedRepository.id },+ { selectedRepository },+ );+ const input = screen.getByTestId("git-repo-dropdown") as HTMLInputElement;+ await waitFor(() => expect(input).toHaveValue("user/repo-one"));++ setupDefaultMocks({ selectedRepository: null });+ view.rerender(+ <GitRepoDropdown+ provider="github"+ value={null}+ onChange={mockOnChange}+ />,+ );++ await waitFor(() => expect(input).toHaveValue(""));+ expect(screen.queryByTestId("dropdown-clear")).not.toBeInTheDocument();+ });++ it("marks an externally selected repository and still lists every repository", async () => {+ const user = userEvent.setup();+ renderDropdown(+ { value: MOCK_REPOSITORIES[0].id },+ { selectedRepository: MOCK_REPOSITORIES[0] },+ );+ const input = screen.getByTestId("git-repo-dropdown");+ await waitFor(() => expect(input).toHaveValue("user/repo-one"));++ await user.click(input);++ const options = screen.getAllByRole("option");+ expect(options).toHaveLength(MOCK_REPOSITORIES.length);+ const selectedOption = within(+ screen.getByTestId("git-repo-dropdown-menu"),+ ).getByRole("option", { name: "user/repo-one" });+ const unselectedOption = within(+ screen.getByTestId("git-repo-dropdown-menu"),+ ).getByRole("option", { name: "user/repo-two" });+ expect(selectedOption).toHaveAttribute("aria-selected", "true");+ expect(selectedOption).toHaveClass("bg-[var(--oh-interactive-selected)]");+ expect(unselectedOption).toHaveAttribute("aria-selected", "false");+ expect(unselectedOption).toHaveClass(+ "hover:bg-[var(--oh-interactive-hover)]",+ );+ });++ it("uses the latest callback when a selected repository is cleared", async () => {+ const user = userEvent.setup();+ const initialOnChange = vi.fn();+ const latestOnChange = vi.fn();+ const view = renderDropdown({ onChange: initialOnChange });+ const input = screen.getByTestId("git-repo-dropdown");++ await user.click(input);+ await user.click(await screen.findByText("user/repo-one"));+ expect(initialOnChange).toHaveBeenCalledWith(MOCK_REPOSITORIES[0]);++ view.rerender(+ <GitRepoDropdown provider="github" onChange={latestOnChange} />,+ );+ await user.click(screen.getByTestId("dropdown-clear"));++ expect(latestOnChange).toHaveBeenCalledWith(undefined);+ expect(initialOnChange).toHaveBeenCalledTimes(1);+ });++ it("keeps a local selection while an external repository is unresolved", async () => {+ const user = userEvent.setup();+ const view = renderDropdown();+ const input = screen.getByTestId("git-repo-dropdown");++ await user.click(input);+ await user.click(await screen.findByText("user/repo-two"));+ await waitFor(() => expect(input).toHaveValue("user/repo-two"));++ view.rerender(+ <GitRepoDropdown+ provider="github"+ value="unresolved-repository"+ onChange={mockOnChange}+ />,+ );++ await waitFor(() => expect(input).toHaveValue("user/repo-two"));+ expect(screen.getByTestId("dropdown-clear")).toBeInTheDocument();+ });+ });++ describe("repository search", () => {+ it.each([+ ["a repository URL", "https://github.com/user/repo-two", "user/repo-two"],+ [+ "an incomplete URL",+ "https://github.com/user",+ "https://github.com/user",+ ],+ ])(+ "passes the processed search for %s",+ async (_label, inputText, search) => {+ const user = userEvent.setup();+ renderDropdown();+ const input = screen.getByTestId("git-repo-dropdown");++ await user.click(input);+ await user.type(input, inputText);++ await waitFor(() => {+ expect(mockUseRepositoryData).toHaveBeenLastCalledWith(+ "github",+ false,+ search,+ [],+ inputText,+ undefined,+ undefined,+ );+ });+ },+ );++ it("filters a repository URL by its owner and repository path", async () => {+ const user = userEvent.setup();+ renderDropdown();+ const input = screen.getByTestId("git-repo-dropdown");++ await user.click(input);+ await user.type(input, "https://github.com/user/repo-two");++ expect(await screen.findByText("user/repo-two")).toBeInTheDocument();+ expect(screen.queryByText("user/repo-one")).not.toBeInTheDocument();+ });++ it("shows repository data directly when URL search supplied a result", async () => {+ const user = userEvent.setup();+ renderDropdown({}, {}, { urlSearchResults: [MOCK_REPOSITORIES[2]] });+ const input = screen.getByTestId("git-repo-dropdown");++ await user.click(input);+ await user.type(input, "does-not-match-any-name");++ expect(await screen.findByText("user/repo-one")).toBeInTheDocument();+ expect(screen.getByText("org/feature-repo")).toBeInTheDocument();+ });++ it("prioritizes matching recent repositories from the active provider", async () => {+ const user = userEvent.setup();+ const otherProviderRepository: GitRepository = {+ id: "gitlab-1",+ full_name: "team/gitlab-repo",+ git_provider: "gitlab",+ is_public: true,+ };+ renderDropdown({}, {}, {}, [+ MOCK_REPOSITORIES[1],+ otherProviderRepository,+ ]);++ await user.click(screen.getByTestId("git-repo-dropdown"));++ expect(+ screen.getByText(translated(I18nKey.COMMON$MOST_RECENT)),+ ).toBeInTheDocument();+ expect(+ screen.getAllByRole("option").map((option) => option.textContent),+ ).toEqual(["user/repo-two", "user/repo-one", "org/feature-repo"]);+ expect(screen.queryByText("team/gitlab-repo")).not.toBeInTheDocument();++ await user.type(screen.getByTestId("git-repo-dropdown"), "repo-two");+ expect(screen.getAllByRole("option")).toHaveLength(1);+ expect(screen.getByText("user/repo-two")).toBeInTheDocument();+ });++ it("updates and case-folds recent repositories as the search changes", async () => {+ const user = userEvent.setup();+ renderDropdown({}, {}, {}, [MOCK_REPOSITORIES[0], MOCK_REPOSITORIES[1]]);+ const input = screen.getByTestId("git-repo-dropdown");++ await user.click(input);+ await user.type(input, "REPO-TWO");++ expect(+ screen.getByText(translated(I18nKey.COMMON$MOST_RECENT)),+ ).toBeInTheDocument();+ expect(+ screen.getAllByRole("option").map((option) => option.textContent),+ ).toEqual(["user/repo-two"]);++ await user.clear(input);+ await user.type(input, "missing-repository");++ expect(+ screen.queryByText(translated(I18nKey.COMMON$MOST_RECENT)),+ ).not.toBeInTheDocument();+ expect(screen.getByTestId("git-repo-dropdown-empty")).toHaveTextContent(+ translated(I18nKey.HOME$NO_REPOSITORY_FOUND),+ );+ });++ it("uses a repository URL to filter recent repositories", async () => {+ const user = userEvent.setup();+ renderDropdown({}, {}, {}, [MOCK_REPOSITORIES[0], MOCK_REPOSITORIES[1]]);+ const input = screen.getByTestId("git-repo-dropdown");++ await user.click(input);+ await user.type(input, "https://github.com/user/repo-two");++ expect(+ screen.getByText(translated(I18nKey.COMMON$MOST_RECENT)),+ ).toBeInTheDocument();+ expect(+ screen.getAllByRole("option").map((option) => option.textContent),+ ).toEqual(["user/repo-two"]);+ });++ it("treats whitespace-only input as an empty search", async () => {+ const user = userEvent.setup();+ renderDropdown({}, {}, {}, [MOCK_REPOSITORIES[0]]);+ const input = screen.getByTestId("git-repo-dropdown");++ await user.click(input);+ await user.type(input, " ");++ expect(+ screen.getAllByRole("option").map((option) => option.textContent),+ ).toEqual(["user/repo-one", "user/repo-two", "org/feature-repo"]);+ expect(+ screen.getByText(translated(I18nKey.COMMON$MOST_RECENT)),+ ).toBeInTheDocument();+ });++ it("shows the localized empty state for an empty repository list", async () => {+ const user = userEvent.setup();+ renderDropdown({}, { repositories: [] });++ await user.click(screen.getByTestId("git-repo-dropdown"));++ expect(screen.getByTestId("git-repo-dropdown-empty")).toHaveTextContent(+ translated(I18nKey.COMMON$NO_REPOSITORY),+ );+ });+ });++ describe("pagination", () => {+ it.each([+ ["near the bottom with another page", 70, true, false, 1],+ ["away from the bottom", 20, true, false, 0],+ ["near the bottom without another page", 70, false, false, 0],+ ["near the bottom during an existing fetch", 70, true, true, 0],+ ])(+ "requests the next page when scrolled %s",+ async (_label, scrollTop, hasNextPage, isFetchingNextPage, callCount) => {+ const fetchNextPage = vi.fn();+ const user = userEvent.setup();+ renderDropdown({}, { fetchNextPage, hasNextPage, isFetchingNextPage });+ await user.click(screen.getByTestId("git-repo-dropdown"));+ const menu = screen.getByTestId("git-repo-dropdown-menu");+ setMenuScrollMetrics(menu, { scrollTop });++ fireEvent.scroll(menu);++ expect(fetchNextPage).toHaveBeenCalledTimes(callCount);+ },+ );++ it("uses updated pagination state after repository data changes", async () => {+ const user = userEvent.setup();+ const initialFetchNextPage = vi.fn();+ const updatedFetchNextPage = vi.fn();+ const view = renderDropdown(+ {},+ { fetchNextPage: initialFetchNextPage, hasNextPage: false },+ );+ await user.click(screen.getByTestId("git-repo-dropdown"));++ setupDefaultMocks({+ fetchNextPage: updatedFetchNextPage,+ hasNextPage: true,+ });+ view.rerender(+ <GitRepoDropdown provider="github" onChange={mockOnChange} />,+ );+ const menu = screen.getByTestId("git-repo-dropdown-menu");+ setMenuScrollMetrics(menu, { scrollTop: 70 });+ fireEvent.scroll(menu);++ expect(updatedFetchNextPage).toHaveBeenCalledTimes(1);+ expect(initialFetchNextPage).not.toHaveBeenCalled();+ });+ });++ describe("loading feedback", () => {+ it.each([+ ["initial repositories", { isLoading: true }, {}],+ ["repository search", { isSearchLoading: true }, {}],+ ["the next page", { isFetchingNextPage: true }, {}],+ ["URL lookup", {}, { isUrlSearchLoading: true }],+ ])("shows a spinner while loading %s", (_label, repository, urlSearch) => {+ const { container } = renderDropdown({}, repository, urlSearch);++ expect(container.querySelector(".animate-spin")).toBeInTheDocument();+ });});});diff --git a/__tests__/components/features/home/home-git-selection-preview.test.tsx b/__tests__/components/features/home/home-git-selection-preview.test.tsxnew file mode 100644index 0000000000..82e23e6d91--- /dev/null+++ b/__tests__/components/features/home/home-git-selection-preview.test.tsx@@ -0,0 +1,212 @@+import type { ComponentProps } from "react";+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import type { GitControlBarRepoButton as RepoButtonComponent } from "#/components/features/chat/git-control-bar-repo-button";+import type { GitControlBarBranchButton as BranchButtonComponent } from "#/components/features/chat/git-control-bar-branch-button";+import type { WorkspaceModeSelector as WorkspaceModeSelectorComponent } from "#/components/features/chat/workspace-mode-selector";+import { HomeGitControlBarPreview } from "#/components/features/home/home-git-control-bar-preview";+import type { Branch, GitRepository } from "#/types/git";+import type { LocalWorkspace } from "#/types/workspace";++type RepoButtonProps = ComponentProps<typeof RepoButtonComponent>;+type BranchButtonProps = ComponentProps<typeof BranchButtonComponent>;+type WorkspaceModeSelectorProps = ComponentProps<+ typeof WorkspaceModeSelectorComponent+>;++vi.mock("#/components/features/chat/git-control-bar-repo-button", () => ({+ GitControlBarRepoButton: ({+ selectedRepository,+ gitProvider,+ workspaceName,+ onClick,+ }: RepoButtonProps) => (+ <button type="button" data-testid="repo-preview" onClick={onClick}>+ <span data-testid="repo-name">{selectedRepository ?? "none"}</span>+ <span data-testid="repo-provider">{gitProvider ?? "none"}</span>+ <span data-testid="workspace-name">{workspaceName ?? "none"}</span>+ </button>+ ),+}));++vi.mock("#/components/features/chat/git-control-bar-branch-button", () => ({+ GitControlBarBranchButton: ({+ selectedBranch,+ selectedRepository,+ gitProvider,+ }: BranchButtonProps) => (+ <div data-testid="branch-preview">+ <span data-testid="branch-name">{selectedBranch ?? "none"}</span>+ <span data-testid="branch-repository">+ {selectedRepository ?? "none"}+ </span>+ <span data-testid="branch-provider">{gitProvider ?? "none"}</span>+ </div>+ ),+}));++vi.mock("#/components/features/chat/workspace-mode-selector", () => ({+ WorkspaceModeSelector: ({+ value,+ backendKind,+ onChange,+ }: WorkspaceModeSelectorProps) => (+ <button+ type="button"+ data-testid="workspace-mode-preview"+ data-value={value}+ data-backend-kind={backendKind}+ onClick={() =>+ onChange(value === "local_repo" ? "new_worktree" : "local_repo")+ }+ >+ Change workspace mode+ </button>+ ),+}));++type PreviewProps = ComponentProps<typeof HomeGitControlBarPreview>;++function createWorkspace(+ overrides: Partial<LocalWorkspace> = {},+): LocalWorkspace {+ return {+ id: "workspace-1",+ name: "Agent Canvas",+ path: "/workspace/agent-canvas",+ ...overrides,+ };+}++function createRepository(+ overrides: Partial<GitRepository> = {},+): GitRepository {+ return {+ id: "repository-1",+ full_name: "OpenHands/agent-canvas",+ git_provider: "github",+ is_public: true,+ ...overrides,+ };+}++function createBranch(overrides: Partial<Branch> = {}): Branch {+ return {+ name: "main",+ commit_sha: "abc123",+ protected: true,+ ...overrides,+ };+}++function createPreviewProps(+ overrides: Partial<PreviewProps> = {},+): PreviewProps {+ return {+ workspace: createWorkspace(),+ repository: createRepository(),+ branch: createBranch(),+ provider: "github",+ workspaceMode: "local_repo",+ backendKind: "local",+ onRepoClick: vi.fn(),+ onWorkspaceModeChange: vi.fn(),+ ...overrides,+ };+}++describe("home git selection preview", () => {+ it("shows a complete selection and forwards both controls", async () => {+ const user = userEvent.setup();+ const props = createPreviewProps({+ workspace: createWorkspace({ path: "/workspace/review-target///" }),+ });++ render(<HomeGitControlBarPreview {...props} />);++ expect(+ screen.getByTestId("home-git-control-bar-preview"),+ ).toBeInTheDocument();+ expect(screen.getByTestId("repo-name")).toHaveTextContent(+ "OpenHands/agent-canvas",+ );+ expect(screen.getByTestId("repo-provider")).toHaveTextContent("github");+ expect(screen.getByTestId("workspace-name")).toHaveTextContent(+ /^review-target$/,+ );+ expect(screen.getByTestId("workspace-mode-preview")).toHaveAttribute(+ "data-value",+ "local_repo",+ );+ expect(screen.getByTestId("workspace-mode-preview")).toHaveAttribute(+ "data-backend-kind",+ "local",+ );+ expect(screen.getByTestId("branch-name")).toHaveTextContent("main");+ expect(screen.getByTestId("branch-repository")).toHaveTextContent(+ "OpenHands/agent-canvas",+ );+ expect(screen.getByTestId("branch-provider")).toHaveTextContent("github");++ await user.click(screen.getByTestId("repo-preview"));+ await user.click(screen.getByTestId("workspace-mode-preview"));++ expect(props.onRepoClick).toHaveBeenCalledOnce();+ expect(props.onWorkspaceModeChange).toHaveBeenCalledWith("new_worktree");+ });++ it("keeps only the repository control when there is no selection", () => {+ render(+ <HomeGitControlBarPreview+ {...createPreviewProps({+ workspace: null,+ repository: null,+ branch: null,+ provider: null,+ })}+ />,+ );++ expect(screen.getByTestId("repo-preview")).toBeInTheDocument();+ expect(screen.getByTestId("repo-name")).toHaveTextContent("none");+ expect(screen.getByTestId("repo-provider")).toHaveTextContent("none");+ expect(screen.getByTestId("workspace-name")).toHaveTextContent("none");+ expect(+ screen.queryByTestId("workspace-mode-preview"),+ ).not.toBeInTheDocument();+ expect(screen.queryByTestId("branch-preview")).not.toBeInTheDocument();+ });++ it("falls back to the full workspace path and shows an unlinked branch", async () => {+ const user = userEvent.setup();+ const props = createPreviewProps({+ workspace: createWorkspace({ path: "/" }),+ repository: null,+ branch: createBranch({ name: "feature/local" }),+ provider: null,+ workspaceMode: "new_worktree",+ backendKind: "cloud",+ });++ render(<HomeGitControlBarPreview {...props} />);++ expect(screen.getByTestId("workspace-name")).toHaveTextContent("/");+ expect(screen.getByTestId("workspace-mode-preview")).toHaveAttribute(+ "data-value",+ "new_worktree",+ );+ expect(screen.getByTestId("workspace-mode-preview")).toHaveAttribute(+ "data-backend-kind",+ "cloud",+ );+ expect(screen.getByTestId("branch-name")).toHaveTextContent(+ "feature/local",+ );+ expect(screen.getByTestId("branch-repository")).toHaveTextContent("none");+ expect(screen.getByTestId("branch-provider")).toHaveTextContent("none");++ await user.click(screen.getByTestId("workspace-mode-preview"));+ expect(props.onWorkspaceModeChange).toHaveBeenCalledWith("local_repo");+ });+});diff --git a/__tests__/components/features/home/provider-selection.test.tsx b/__tests__/components/features/home/provider-selection.test.tsxnew file mode 100644index 0000000000..efed6ce30f--- /dev/null+++ b/__tests__/components/features/home/provider-selection.test.tsx@@ -0,0 +1,403 @@+import React from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { render, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { GitProviderDropdown } from "#/components/features/home/git-provider-dropdown/git-provider-dropdown";+import type { Provider } from "#/types/settings";++const useTranslationMock = vi.hoisted(() => vi.fn());++vi.mock("react-i18next", () => ({+ useTranslation: (namespace?: unknown) => {+ useTranslationMock(namespace);+ return {+ t: (key: string) =>+ ({+ COMMON$SELECT_PROVIDER_PLACEHOLDER: "Select provider",+ COMMON$TOGGLE_MENU: "Toggle menu",+ })[key] ?? key,+ };+ },+}));++const ALL_PROVIDERS: Provider[] = [+ "github",+ "gitlab",+ "bitbucket",+ "bitbucket_data_center",+ "azure_devops",+ "forgejo",+];++type DropdownProps = React.ComponentProps<typeof GitProviderDropdown>;++function createProps(overrides: Partial<DropdownProps> = {}): DropdownProps {+ return {+ providers: ALL_PROVIDERS,+ onChange: vi.fn(),+ ...overrides,+ };+}++function ControlledDropdown({ onChange, value, ...props }: DropdownProps) {+ const [selectedProvider, setSelectedProvider] =+ React.useState<Provider | null>(value ?? null);++ return (+ <GitProviderDropdown+ {...props}+ value={selectedProvider}+ onChange={(provider) => {+ setSelectedProvider(provider);+ onChange?.(provider);+ }}+ />+ );+}++describe("git provider selection", () => {+ it("includes the controlled provider in the initial markup", () => {+ const emptyMarkup = renderToStaticMarkup(+ <GitProviderDropdown providers={ALL_PROVIDERS} />,+ );+ const selectedMarkup = renderToStaticMarkup(+ <GitProviderDropdown providers={ALL_PROVIDERS} value="gitlab" />,+ );++ expect(emptyMarkup).toContain('value=""');+ expect(selectedMarkup).toContain("pl-6");+ expect(selectedMarkup).toContain("min-w-[14px]");+ });++ it("lists every provider with its user-facing name and selects one", async () => {+ const user = userEvent.setup();+ useTranslationMock.mockClear();+ const props = createProps({+ className: "provider-root",+ inputClassName: "provider-input",+ toggleButtonClassName: "provider-toggle-icon",+ itemClassName: "provider-option",+ });++ render(<ControlledDropdown {...props} />);++ const input = screen.getByTestId("git-provider-dropdown");+ expect(useTranslationMock).toHaveBeenNthCalledWith(1, "openhands");+ expect(input).toHaveAttribute("placeholder", "Select provider");+ expect(input).toHaveAttribute("readonly");+ expect(input.parentElement?.parentElement).toHaveClass(+ "relative",+ "provider-root",+ );+ expect(input).toHaveClass(+ "provider-input",+ "w-29.5",+ "border",+ "rounded",+ "text-inherit",+ "bg-tertiary",+ "placeholder:text-[var(--oh-muted)]",+ "focus:outline-none",+ "focus:ring-0",+ "focus:border-[var(--oh-border-input)]",+ "disabled:bg-tertiary",+ "disabled:cursor-not-allowed",+ "disabled:opacity-60",+ "pl-1.5",+ "pr-[1px]",+ "cursor-pointer",+ "text-xs",+ "font-normal",+ "leading-5",+ );+ expect(screen.queryByTestId("dropdown-loading")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Toggle menu" }).querySelector("svg"),+ ).toHaveClass("provider-toggle-icon");++ await user.click(input);++ expect(+ screen.getAllByRole("option").map((option) => option.textContent),+ ).toEqual([+ "GitHub",+ "GitLab",+ "Bitbucket",+ "Bitbucket Data Center",+ "Azure DevOps",+ "Forgejo",+ ]);+ expect(screen.getByRole("option", { name: "GitLab" })).toHaveClass(+ "provider-option",+ );++ await user.click(screen.getByRole("option", { name: "GitLab" }));++ expect(props.onChange).toHaveBeenCalledWith("gitlab");+ expect(props.onChange).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(input).toHaveValue("GitLab"));+ expect(input).toHaveClass("pl-6");+ expect(input.previousElementSibling).toHaveClass(+ "absolute",+ "left-2",+ "z-10",+ );+ expect(input.previousElementSibling?.querySelector("svg")).toHaveClass(+ "min-w-[14px]",+ "h-[14px]",+ );+ expect(screen.queryByRole("option")).not.toBeInTheDocument();+ });++ it("updates the available options when the providers prop changes", async () => {+ const user = userEvent.setup();+ const { rerender } = render(+ <GitProviderDropdown {...createProps({ providers: ["github"] })} />,+ );+ const input = screen.getByTestId("git-provider-dropdown");++ await user.click(input);+ expect(screen.getAllByRole("option")).toHaveLength(1);+ expect(screen.getByRole("option", { name: "GitHub" })).toBeVisible();+ await user.keyboard("{Escape}");++ rerender(+ <GitProviderDropdown+ {...createProps({ providers: ["gitlab", "azure_devops"] })}+ />,+ );+ await user.click(input);++ expect(+ screen.getAllByRole("option").map((option) => option.textContent),+ ).toEqual(["GitLab", "Azure DevOps"]);+ });++ it("keeps provider options uniquely keyed when their order changes", async () => {+ const user = userEvent.setup();+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ const { rerender } = render(+ <GitProviderDropdown+ {...createProps({ providers: ["github", "gitlab"] })}+ />,+ );+ const input = screen.getByTestId("git-provider-dropdown");++ try {+ await user.click(input);+ rerender(+ <GitProviderDropdown+ {...createProps({ providers: ["gitlab", "github"] })}+ />,+ );++ expect(+ screen.getAllByRole("option").map((option) => option.textContent),+ ).toEqual(["GitLab", "GitHub"]);+ expect(consoleError).not.toHaveBeenCalledWith(+ expect.stringContaining('unique "key" prop'),+ );+ } finally {+ consoleError.mockRestore();+ }+ });++ it("allows a different provider to be selected without a callback", async () => {+ const user = userEvent.setup();+ render(<GitProviderDropdown providers={["github", "gitlab"]} />);+ const input = screen.getByTestId("git-provider-dropdown");++ await user.click(input);+ const runtimeErrors: unknown[] = [];+ const preventRuntimeError = (event: ErrorEvent) => {+ event.preventDefault();+ runtimeErrors.push(event.error);+ };+ window.addEventListener("error", preventRuntimeError);+ try {+ await user.click(screen.getByRole("option", { name: "GitLab" }));+ } finally {+ window.removeEventListener("error", preventRuntimeError);+ }++ expect(runtimeErrors).toEqual([]);+ expect(screen.queryByRole("option")).not.toBeInTheDocument();+ await waitFor(() => expect(input).toHaveValue(""));+ });++ it("reopens a selected provider with the complete provider list", async () => {+ const user = userEvent.setup();+ render(<GitProviderDropdown {...createProps({ value: "gitlab" })} />);+ const input = screen.getByTestId("git-provider-dropdown");+ await waitFor(() => expect(input).toHaveValue("GitLab"));++ await user.click(input);++ expect(screen.getAllByRole("option")).toHaveLength(ALL_PROVIDERS.length);+ expect(screen.getByRole("option", { name: "GitHub" })).toBeVisible();+ expect(screen.getByRole("option", { name: "Forgejo" })).toBeVisible();+ });++ it("tracks controlled provider changes and clearing", async () => {+ const props = createProps({ value: "github", isLoading: true });+ const { rerender } = render(<GitProviderDropdown {...props} />);+ const input = screen.getByTestId("git-provider-dropdown");++ await waitFor(() => expect(input).toHaveValue("GitHub"));+ expect(screen.getByTestId("dropdown-loading").parentElement).toHaveClass(+ "right-11",+ );++ rerender(<GitProviderDropdown {...props} value="azure_devops" />);+ await waitFor(() => expect(input).toHaveValue("Azure DevOps"));++ rerender(<GitProviderDropdown {...props} value={null} />);+ await waitFor(() => expect(input).toHaveValue(""));+ expect(input).not.toHaveClass("pl-6");+ expect(screen.getByTestId("dropdown-loading").parentElement).toHaveClass(+ "right-6",+ );+ });++ it("prevents interaction while disabled", async () => {+ const user = userEvent.setup();+ render(<GitProviderDropdown {...createProps({ disabled: true })} />);++ const input = screen.getByTestId("git-provider-dropdown");+ const toggle = screen.getByRole("button", { name: "Toggle menu" });+ expect(input).toBeDisabled();+ expect(toggle).toBeDisabled();++ await user.click(input);+ await user.click(toggle);+ expect(screen.queryByRole("option")).not.toBeInTheDocument();+ });++ it("shows loading and error feedback with a custom placeholder", () => {+ render(+ <GitProviderDropdown+ {...createProps({+ placeholder: "Choose a source",+ isLoading: true,+ errorMessage: "Providers could not be loaded",+ })}+ />,+ );++ expect(screen.getByTestId("git-provider-dropdown")).toHaveAttribute(+ "placeholder",+ "Choose a source",+ );+ expect(screen.getByTestId("dropdown-loading")).toBeVisible();+ expect(screen.getByTestId("dropdown-error")).toHaveTextContent(+ "Providers could not be loaded",+ );+ });++ it("shows an empty state when no providers are available", async () => {+ const user = userEvent.setup();+ render(<GitProviderDropdown {...createProps({ providers: [] })} />);++ await user.click(screen.getByTestId("git-provider-dropdown"));++ expect(screen.getByTestId("git-provider-dropdown-empty")).toHaveTextContent(+ "No providers available",+ );+ expect(screen.queryByRole("option")).not.toBeInTheDocument();+ });++ it("keeps its read-only list intact when the user types", async () => {+ const user = userEvent.setup();+ render(<GitProviderDropdown {...createProps()} />);+ const input = screen.getByTestId("git-provider-dropdown");++ await user.click(input);+ await user.keyboard("git");++ expect(input).toHaveValue("");+ expect(screen.getAllByRole("option")).toHaveLength(ALL_PROVIDERS.length);+ });++ it("dismisses the menu with Escape or an outside click", async () => {+ const user = userEvent.setup();+ render(+ <>+ <button type="button">Outside</button>+ <GitProviderDropdown {...createProps()} />+ </>,+ );+ const input = screen.getByTestId("git-provider-dropdown");++ await user.click(input);+ expect(screen.getAllByRole("option")).toHaveLength(ALL_PROVIDERS.length);+ await user.keyboard("{Escape}");+ expect(screen.queryByRole("option")).not.toBeInTheDocument();++ await user.click(input);+ expect(screen.getAllByRole("option")).toHaveLength(ALL_PROVIDERS.length);+ await user.click(screen.getByRole("button", { name: "Outside" }));+ expect(screen.queryByRole("option")).not.toBeInTheDocument();+ });++ it("clears the selected provider when Escape is pressed while closed", async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <ControlledDropdown {...createProps({ value: "github", onChange })} />,+ );+ const input = screen.getByTestId("git-provider-dropdown");+ await waitFor(() => expect(input).toHaveValue("GitHub"));++ await user.click(input);+ await user.keyboard("{Escape}");+ expect(input).toHaveValue("GitHub");++ await user.keyboard("{Escape}");+ await waitFor(() => expect(input).toHaveValue(""));+ expect(onChange).toHaveBeenCalledWith(null);+ expect(onChange).toHaveBeenCalledTimes(1);+ });++ it("allows the current provider to be reselected without a callback", async () => {+ const user = userEvent.setup();+ render(<GitProviderDropdown providers={["forgejo"]} value="forgejo" />);+ const input = screen.getByTestId("git-provider-dropdown");+ await waitFor(() => expect(input).toHaveValue("Forgejo"));++ await user.click(input);+ await user.click(screen.getByRole("option", { name: "Forgejo" }));++ await waitFor(() => expect(input).toHaveValue("Forgejo"));+ expect(screen.queryByRole("option")).not.toBeInTheDocument();+ });++ it("marks the current provider as selected when the menu opens", async () => {+ const user = userEvent.setup();+ render(<GitProviderDropdown {...createProps({ value: "bitbucket" })} />);+ const input = screen.getByTestId("git-provider-dropdown");+ await waitFor(() => expect(input).toHaveValue("Bitbucket"));++ await user.click(input);++ const listbox = screen.getByRole("listbox");+ const selectedOption = within(listbox).getByRole("option", {+ name: "Bitbucket",+ });+ const unselectedOption = within(listbox).getByRole("option", {+ name: "GitHub",+ });+ expect(selectedOption).toHaveAttribute("aria-selected", "true");+ expect(selectedOption).toHaveClass("bg-[var(--oh-interactive-selected)]");+ expect(selectedOption).not.toHaveClass(+ "hover:bg-[var(--oh-interactive-hover)]",+ );+ expect(unselectedOption).toHaveAttribute("aria-selected", "false");+ expect(unselectedOption).toHaveClass(+ "hover:bg-[var(--oh-interactive-hover)]",+ );+ expect(unselectedOption).not.toHaveClass(+ "bg-[var(--oh-interactive-selected)]",+ );+ });+});