π OpenHands: AI-Driven Development
refactor: use React Query for automation SDK version (#16982)
Engel Nyst7ef4da5f2dac
diff --git a/.github/pr-assets/pr-16982-validation.png b/.github/pr-assets/pr-16982-validation.pngnew file mode 100644index 0000000000..95f0eed403Binary files /dev/null and b/.github/pr-assets/pr-16982-validation.png differdiff --git a/__tests__/hooks/query/use-automation-sdk-version.test.tsx b/__tests__/hooks/query/use-automation-sdk-version.test.tsxindex 7d0cb77476..3a12139894 100644--- a/__tests__/hooks/query/use-automation-sdk-version.test.tsx+++ b/__tests__/hooks/query/use-automation-sdk-version.test.tsx@@ -1,11 +1,10 @@import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient } from "@tanstack/react-query";import { beforeEach, describe, expect, it, vi } from "vitest";import AutomationService from "#/api/automation-service/automation-service.api";import type { ResolvedActiveBackend } from "#/api/backend-registry/types";-import {- __resetAutomationSdkVersionCacheForTests,- useAutomationSdkVersion,-} from "#/hooks/query/use-automation-sdk-version";+import { useAutomationSdkVersion } from "#/hooks/query/use-automation-sdk-version";+import { setQueryClient } from "#/query-client-config";vi.mock("#/api/automation-service/automation-service.api", () => ({default: {@@ -33,7 +32,11 @@ vi.mock("#/contexts/active-backend-context", () => ({describe("useAutomationSdkVersion", () => {beforeEach(() => {vi.clearAllMocks();- __resetAutomationSdkVersionCacheForTests();+ setQueryClient(+ new QueryClient({+ defaultOptions: { queries: { retry: false } },+ }),+ );activeBackendMock.active = {backend: {id: "local-1",@@ -46,7 +49,7 @@ describe("useAutomationSdkVersion", () => {};});- it("shares one SDK version request across multiple hook consumers", async () => {+ it("shares one request across consumers without a QueryClientProvider", async () => {vi.mocked(AutomationService.getSdkVersion).mockResolvedValue("1.36.3");const { result } = renderHook(() => ({diff --git a/__tests__/routes/automation-git-sync.test.tsx b/__tests__/routes/automation-git-sync.test.tsxindex 45da6f69d4..7438c3f1fb 100644--- a/__tests__/routes/automation-git-sync.test.tsx+++ b/__tests__/routes/automation-git-sync.test.tsx@@ -1,11 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import {- act,- fireEvent,- render,- screen,- waitFor,-} from "@testing-library/react";+import { act, fireEvent, render, screen } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { MemoryRouter, Route, Routes } from "react-router";import { HttpError } from "@openhands/typescript-client";@@ -128,7 +122,7 @@ describe("AutomationGitSync β failed background refetch", () => {vi.useFakeTimers();renderGitSync();await act(async () => {- await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(1);});expect(screen.getByTestId("git-sync-repo-url-input")).toBeInTheDocument();@@ -155,7 +149,7 @@ describe("AutomationGitSync β sync progress", () => {vi.useFakeTimers();renderGitSync();await act(async () => {- await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(1);});return screen.getByTestId("git-sync-now-button");}diff --git a/src/hooks/query/use-automation-sdk-version.ts b/src/hooks/query/use-automation-sdk-version.tsindex 3f5a64a7c3..d17c4c6ded 100644--- a/src/hooks/query/use-automation-sdk-version.ts+++ b/src/hooks/query/use-automation-sdk-version.ts@@ -1,112 +1,49 @@import React from "react";+import { QueryClientContext, useQuery } from "@tanstack/react-query";import AutomationService from "#/api/automation-service/automation-service.api";import { isNoBackend } from "#/api/backend-registry/active-store";import { useActiveBackend } from "#/contexts/active-backend-context";+import { getQueryClient } from "#/query-client-config";export const AUTOMATION_SDK_VERSION_CACHE_NAMESPACE = "automation-sdk-version";const AUTOMATION_SDK_VERSION_CACHE_TIME_MS = 60 * 60 * 1000;-const CACHE_KEY_SEPARATOR = "\u0000";--interface AutomationSdkVersionCacheEntry {- expiresAt: number;- version: string | null;-}--const sdkVersionCache = new Map<string, AutomationSdkVersionCacheEntry>();-const sdkVersionRequests = new Map<string, Promise<string | null>>();--export function __resetAutomationSdkVersionCacheForTests() {- sdkVersionCache.clear();- sdkVersionRequests.clear();-}--function readCachedSdkVersion(cacheKey: string): string | null | undefined {- const cached = sdkVersionCache.get(cacheKey);- if (!cached) return undefined;-- if (cached.expiresAt <= Date.now()) {- sdkVersionCache.delete(cacheKey);- return undefined;- }-- return cached.version;-}--function writeCachedSdkVersion(cacheKey: string, version: string | null) {- sdkVersionCache.set(cacheKey, {- expiresAt: Date.now() + AUTOMATION_SDK_VERSION_CACHE_TIME_MS,- version,- });-}--function getCachedOrFetchSdkVersion(cacheKey: string) {- const cached = readCachedSdkVersion(cacheKey);- if (cached !== undefined) return Promise.resolve(cached);-- const existingRequest = sdkVersionRequests.get(cacheKey);- if (existingRequest) return existingRequest;-+async function fetchAutomationSdkVersion(): Promise<string | null> {if (typeof AutomationService.getSdkVersion !== "function") {- writeCachedSdkVersion(cacheKey, null);- return Promise.resolve(null);+ return null;}- const request = AutomationService.getSdkVersion()- .then((version) => {- writeCachedSdkVersion(cacheKey, version);- return version;- })- .catch(() => {- writeCachedSdkVersion(cacheKey, null);- return null;- })- .finally(() => {- sdkVersionRequests.delete(cacheKey);- });- sdkVersionRequests.set(cacheKey, request);- return request;+ try {+ return await AutomationService.getSdkVersion();+ } catch {+ return null;+ }}export function useAutomationSdkVersion() {const active = useActiveBackend();const { backend } = active;- const cacheKey = [- AUTOMATION_SDK_VERSION_CACHE_NAMESPACE,- backend.id,- backend.kind,- backend.host,- active.orgId ?? "",- ].join(CACHE_KEY_SEPARATOR);-- const [automationSdkVersion, setAutomationSdkVersion] = React.useState<- string | null- >(() => readCachedSdkVersion(cacheKey) ?? null);-- React.useEffect(() => {- if (isNoBackend(backend)) {- setAutomationSdkVersion(null);- return undefined;- }-- const cached = readCachedSdkVersion(cacheKey);- if (cached !== undefined) {- setAutomationSdkVersion(cached);- return undefined;- }-- let isMounted = true;- setAutomationSdkVersion(null);- void getCachedOrFetchSdkVersion(cacheKey).then((version) => {- if (isMounted) {- setAutomationSdkVersion(version);- }- });-- return () => {- isMounted = false;- };- }, [backend, cacheKey]);-- return automationSdkVersion;+ const providerQueryClient = React.useContext(QueryClientContext);+ const canFetchSdkVersion =+ !isNoBackend(backend) &&+ typeof AutomationService.getSdkVersion === "function";+ const { data } = useQuery(+ {+ queryKey: [+ AUTOMATION_SDK_VERSION_CACHE_NAMESPACE,+ backend.id,+ backend.kind,+ backend.host,+ active.orgId ?? "",+ ],+ queryFn: fetchAutomationSdkVersion,+ enabled: canFetchSdkVersion,+ initialData: canFetchSdkVersion ? undefined : null,+ staleTime: AUTOMATION_SDK_VERSION_CACHE_TIME_MS,+ gcTime: AUTOMATION_SDK_VERSION_CACHE_TIME_MS,+ },+ providerQueryClient ?? getQueryClient(),+ );++ return data ?? null;}