π OpenHands: AI-Driven Development
fix: reduce cloud org and git installation polling (#18128)
Rohit Malhotra3f98684763a4
diff --git a/__tests__/components/features/conversation-panel/cloud-new-conversation-menu.test.tsx b/__tests__/components/features/conversation-panel/cloud-new-conversation-menu.test.tsxnew file mode 100644index 0000000000..c00f8fad4a--- /dev/null+++ b/__tests__/components/features/conversation-panel/cloud-new-conversation-menu.test.tsx@@ -0,0 +1,94 @@+import { screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";++import { renderWithProviders } from "test-utils";+import { CloudNewConversationMenu } from "#/components/features/conversation-panel/cloud-new-conversation-menu";++const mocks = vi.hoisted(() => ({+ useGitRepositories: vi.fn(),+ useSearchRepositories: vi.fn(),+ createConversation: vi.fn(),+}));++vi.mock("#/hooks/query/use-git-repositories", () => ({+ useGitRepositories: (options: unknown) => {+ mocks.useGitRepositories(options);+ return {+ data: { pages: [{ items: [], next_page_id: null }] },+ isLoading: false,+ isError: false,+ hasNextPage: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ };+ },+}));++vi.mock("#/hooks/query/use-search-repositories", () => ({+ useSearchRepositories: (...args: unknown[]) => {+ mocks.useSearchRepositories(...args);+ return { data: [], isLoading: false };+ },+}));++vi.mock("#/hooks/use-user-providers", () => ({+ useUserProviders: () => ({ providers: ["github"], isLoadingSettings: false }),+}));++vi.mock("#/hooks/mutation/use-create-conversation", () => ({+ useCreateConversation: () => ({+ mutate: mocks.createConversation,+ isPending: false,+ }),+}));++vi.mock("#/hooks/use-is-creating-conversation", () => ({+ useIsCreatingConversation: () => false,+}));++describe("CloudNewConversationMenu", () => {+ it("does not enable repository or installation queries while closed", async () => {+ renderWithProviders(+ <CloudNewConversationMenu+ popoverClassName="left-0 right-0"+ trigger={(triggerProps) => (+ <button+ type="button"+ data-testid="new-conversation-button"+ {...triggerProps}+ >+ + New conversation+ </button>+ )}+ />,+ { navigation: { currentPath: "/conversations" } },+ );++ await waitFor(() =>+ expect(mocks.useGitRepositories).toHaveBeenLastCalledWith({+ provider: "github",+ enabled: false,+ }),+ );+ expect(mocks.useSearchRepositories).toHaveBeenLastCalledWith(+ "",+ "github",+ true,+ );++ await userEvent.click(screen.getByTestId("new-conversation-button"));++ await waitFor(() =>+ expect(mocks.useGitRepositories).toHaveBeenLastCalledWith({+ provider: "github",+ enabled: true,+ }),+ );+ expect(mocks.useSearchRepositories).toHaveBeenLastCalledWith(+ "",+ "github",+ false,+ );+ });+});diff --git a/__tests__/hooks/query/use-backends-health.test.tsx b/__tests__/hooks/query/use-backends-health.test.tsxindex 104d844255..6d9c448bf8 100644--- a/__tests__/hooks/query/use-backends-health.test.tsx+++ b/__tests__/hooks/query/use-backends-health.test.tsx@@ -216,6 +216,35 @@ describe("useBackendsHealth", () => {expect(getCurrentCloudApiKeyMock).not.toHaveBeenCalled();});+ it("polls cloud health less frequently than local health", async () => {+ vi.useFakeTimers();+ getCurrentCloudApiKeyMock.mockResolvedValue({+ orgId: "org-1",+ isLegacyKey: false,+ });++ const { result } = renderHook(() => useBackendsHealth([cloudBackend]), {+ wrapper,+ });++ await act(async () => {+ await vi.advanceTimersByTimeAsync(0);+ await Promise.resolve();+ });+ expect(result.current[cloudBackend.id].isConnected).toBe(true);+ expect(getCurrentCloudApiKeyMock).toHaveBeenCalledTimes(1);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(30_000);+ });+ expect(getCurrentCloudApiKeyMock).toHaveBeenCalledTimes(1);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(270_000);+ });+ expect(getCurrentCloudApiKeyMock).toHaveBeenCalledTimes(2);+ });+it("reports disconnected when the cloud probe throws", async () => {getCurrentCloudApiKeyMock.mockRejectedValue(new Error("Network Error"));diff --git a/__tests__/hooks/query/use-git-repositories.test.ts b/__tests__/hooks/query/use-git-repositories.test.tsindex cf7fd77b21..65a7458dc4 100644--- a/__tests__/hooks/query/use-git-repositories.test.ts+++ b/__tests__/hooks/query/use-git-repositories.test.ts@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => ({installations: undefined as string[] | undefined,backend: { id: "local", kind: "local" as "local" | "cloud" },orgId: null as string | null,+ appInstallationsCalls: [] as unknown[][],queryConfig: null as CapturedQueryConfig | null,repos: {data: undefined as unknown,@@ -47,12 +48,15 @@ vi.mock("#/hooks/use-user-providers", () => ({}));vi.mock("#/hooks/query/use-app-installations", () => ({- useAppInstallations: () => ({- data:- mocks.installations === undefined- ? undefined- : { items: mocks.installations, next_page_id: null },- }),+ useAppInstallations: (...args: unknown[]) => {+ mocks.appInstallationsCalls.push(args);+ return {+ data:+ mocks.installations === undefined+ ? undefined+ : { items: mocks.installations, next_page_id: null },+ };+ },}));vi.mock("#/contexts/active-backend-context", () => ({@@ -85,6 +89,7 @@ describe("useGitRepositories", () => {mocks.installations = undefined;mocks.backend = { id: "local", kind: "local" };mocks.orgId = null;+ mocks.appInstallationsCalls = [];mocks.queryConfig = null;mocks.repos.data = undefined;mocks.repos.isLoading = false;@@ -252,6 +257,22 @@ describe("useGitRepositories", () => {},);+ it("passes the enabled flag through to app installation fetching", () => {+ setupMocks();+ mocks.backend = { id: "cloud", kind: "cloud" };+ mocks.providers = ["github"];++ renderHook(() =>+ useGitRepositories({ provider: "github", enabled: false }),+ );++ expect(mocks.appInstallationsCalls.at(-1)).toEqual([+ "github",+ { enabled: false },+ ]);+ expect(config().enabled).toBe(false);+ });+it("stays disabled while connected providers are unresolved", () => {setupMocks();mocks.providers = undefined;diff --git a/src/components/features/conversation-panel/cloud-new-conversation-menu.tsx b/src/components/features/conversation-panel/cloud-new-conversation-menu.tsxindex ad9d7068a8..5dd0aa439f 100644--- a/src/components/features/conversation-panel/cloud-new-conversation-menu.tsx+++ b/src/components/features/conversation-panel/cloud-new-conversation-menu.tsx@@ -116,6 +116,7 @@ export function CloudNewConversationMenu({setSelectedProvider(fallback);}, [providers, selectedProvider, lastSelectedProvider]);+ const repositoryQueriesEnabled = open && !!selectedProvider;const {data: repoPages,isLoading,@@ -123,10 +124,17 @@ export function CloudNewConversationMenu({hasNextPage,isFetchingNextPage,fetchNextPage,- } = useGitRepositories({ provider: selectedProvider });+ } = useGitRepositories({+ provider: selectedProvider,+ enabled: repositoryQueriesEnabled,+ });const { data: searchResults, isLoading: isSearchLoading } =- useSearchRepositories(debouncedQuery, selectedProvider);+ useSearchRepositories(+ debouncedQuery,+ selectedProvider,+ !repositoryQueriesEnabled,+ );const allRepositories = React.useMemo(() => repoPages?.pages.flatMap((page) => page.items) ?? [],diff --git a/src/hooks/query/use-app-installations.ts b/src/hooks/query/use-app-installations.tsindex d20065af0a..a5d6f40b96 100644--- a/src/hooks/query/use-app-installations.ts+++ b/src/hooks/query/use-app-installations.ts@@ -13,7 +13,15 @@ import { shouldUseInstallationRepos } from "#/utils/utils";* between backends (Local β Cloud, Cloud A β Cloud B) naturally produces* a fresh query β no `clear()`/`invalidate` orchestration required.*/-export const useAppInstallations = (selectedProvider: Provider | null) => {+interface UseAppInstallationsOptions {+ enabled?: boolean;+}++export const useAppInstallations = (+ selectedProvider: Provider | null,+ options: UseAppInstallationsOptions = {},+) => {+ const { enabled = true } = options;const { data: userIsAuthenticated } = useIsAuthed();const { providers } = useUserProviders();const active = useActiveBackend();@@ -32,6 +40,7 @@ export const useAppInstallations = (selectedProvider: Provider | null) => {],queryFn: () => GitService.getUserInstallations(selectedProvider!),enabled:+ enabled &&userIsAuthenticated &&!!selectedProvider &&// Gate on providers length too: when settings haven't yet tolddiff --git a/src/hooks/query/use-backends-health.ts b/src/hooks/query/use-backends-health.tsindex d495830b19..508a07e54f 100644--- a/src/hooks/query/use-backends-health.ts+++ b/src/hooks/query/use-backends-health.ts@@ -23,10 +23,14 @@ import {} from "#/api/backend-registry/health-store";import { MAX_CONSECUTIVE_FAILURES } from "#/api/backend-registry/health-storage";-// 30s: each tick costs two sequential requests per backend (settings ++// 30s: each local tick costs two sequential requests per backend (settings +// server_info), which on slow links measurably competes with conversation// traffic for the browser's per-origin HTTP/1.1 connection pool.const REFRESH_INTERVAL_MS = 30000;+// Cloud health probes hit app-server auth/org endpoints that are shared with the+// main UI. They do not need local-runtime-level freshness, and a slower cadence+// avoids competing with conversation, sandbox, and repository requests.+const CLOUD_REFRESH_INTERVAL_MS = 5 * 60 * 1000;const PROBE_TIMEOUT_MS = 4000;export { INVALID_BACKEND_API_KEY_ERROR } from "#/api/agent-server-compatibility";export const MISSING_BACKEND_API_KEY_ERROR = "API key required";@@ -221,6 +225,8 @@ export function useBackendsHealth(const entry = healthMap[b.id];const hasMissingCloudApiKey = hasMissingBackendApiKey(b);const isDisabled = entry?.disabled === true;+ const refreshInterval =+ b.kind === "cloud" ? CLOUD_REFRESH_INTERVAL_MS : REFRESH_INTERVAL_MS;const shouldReprobeStaleCloudNetworkError =isDisabled &&b.kind === "cloud" &&@@ -252,15 +258,17 @@ export function useBackendsHealth(refetchInterval:isDisabled || hasMissingCloudApiKey? (false as const)- : REFRESH_INTERVAL_MS,+ : refreshInterval,refetchIntervalInBackground: false,refetchOnMount: isDisabled && probeDisabledOnce ? "always" : true,- refetchOnReconnect: !isDisabled && !hasMissingCloudApiKey,- refetchOnWindowFocus: !isDisabled && !hasMissingCloudApiKey,+ refetchOnReconnect:+ b.kind !== "cloud" && !isDisabled && !hasMissingCloudApiKey,+ refetchOnWindowFocus:+ b.kind !== "cloud" && !isDisabled && !hasMissingCloudApiKey,retry: false,// Keep the previous verdict visible while the next probe is in// flight so the indicator doesn't flicker on routine polling.- staleTime: isDisabled ? 0 : REFRESH_INTERVAL_MS,+ staleTime: isDisabled ? 0 : refreshInterval,meta: { disableToast: true },};}),diff --git a/src/hooks/query/use-git-repositories.ts b/src/hooks/query/use-git-repositories.tsindex 6567768653..aad07c1f58 100644--- a/src/hooks/query/use-git-repositories.ts+++ b/src/hooks/query/use-git-repositories.ts@@ -20,7 +20,7 @@ type Cursor = InstallationCursor | UserCursor;export function useGitRepositories(options: UseGitRepositoriesOptions) {const { provider, pageSize = 30, enabled = true } = options;const { providers } = useUserProviders();- const { data: page } = useAppInstallations(provider);+ const { data: page } = useAppInstallations(provider, { enabled });const installations = page?.items;const active = useActiveBackend();