Skip to content

🙌 OpenHands: AI-Driven Development

Extract composable provider stack (#46)

Graham Neubigf62063e41304
diff --git a/AGENTS.md b/AGENTS.md
index aaec495d4d..0d02d7316a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -20,6 +20,8 @@
- `npm test` now runs `npm run make-i18n` first so clean environments generate `src/i18n/declaration.ts` before Vitest loads aliased imports.
- `__tests__/vite-config.test.ts` should import `vite.config` directly under `// @vitest-environment node`; spawning plain `node -e 'import ./vite.config.ts'` is not portable across Node patch releases in CI.
- `vitest.setup.ts` must guard DOM-specific globals (`HTMLCanvasElement`, `HTMLElement`, `window`) because some suites run in the Node environment instead of jsdom.
+- `__tests__/components/providers/posthog-wrapper.test.tsx` must wrap `PostHogWrapper` in a `QueryClientProvider`; the wrapper now reads its client from React Query context instead of importing the global singleton.
+
- `@openhands/typescript-client` is consumed directly from `github:OpenHands/typescript-client#4716d2e`; that package ships the needed subpath exports for `client/http-client`, `events/remote-events-list`, and `workspace/remote-workspace`.
- Shared TypeScript-client adapters live in `src/api/typescript-client.ts`; prefer those helpers for agent-server-backed REST/workspace/event/VS Code calls before falling back to `open-hands-axios`.
- Local verification/build gotchas:
diff --git a/__tests__/agent-server-ui-providers.test.tsx b/__tests__/agent-server-ui-providers.test.tsx
new file mode 100644
index 0000000000..4ae940ddbf
--- /dev/null
+++ b/__tests__/agent-server-ui-providers.test.tsx
@@ -0,0 +1,187 @@
+import React from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, useQueryClient } from "@tanstack/react-query";
+import { createInstance } from "i18next";
+import { initReactI18next, useTranslation } from "react-i18next";
+
+vi.mock("react-i18next", async (importOriginal) =>
+ importOriginal<typeof import("react-i18next")>(),
+);
+
+import OptionService from "#/api/option-service/option-service.api";
+import {
+ AgentServerUIProviders,
+ DEFAULT_AGENT_SERVER_ANALYTICS,
+ getDefaultI18n,
+ getDefaultQueryClient,
+ getI18n,
+ getQueryClient,
+ queryClient,
+ setI18n,
+ setQueryClient,
+} from "#/index";
+
+vi.mock("posthog-js/react", () => ({
+ PostHogProvider: ({ children }: { children: React.ReactNode }) => children,
+}));
+
+const BaseProbe = ({ translation }: { translation?: string }) => {
+ const currentQueryClient = useQueryClient();
+
+ return (
+ <div>
+ <div data-testid="query-client-kind">
+ {currentQueryClient === getDefaultQueryClient() ? "default" : "custom"}
+ </div>
+ <div data-testid="query-client-value">
+ {String(queryClient.getQueryData(["provider-probe"]))}
+ </div>
+ {translation && <div data-testid="translation-value">{translation}</div>}
+ <div data-testid="imperative-translation-value">
+ {getI18n().t("PROVIDER$LABEL")}
+ </div>
+ </div>
+ );
+};
+
+const DefaultProbe = () => <BaseProbe />;
+
+const CustomProbe = () => {
+ const { t } = useTranslation();
+
+ return <BaseProbe translation={t("PROVIDER$LABEL")} />;
+};
+
+const createTestI18n = async (value: string) => {
+ const instance = createInstance();
+
+ await instance.use(initReactI18next).init({
+ lng: "en",
+ fallbackLng: "en",
+ ns: ["translation"],
+ defaultNS: "translation",
+ interpolation: { escapeValue: false },
+ resources: {
+ en: {
+ translation: {
+ PROVIDER$LABEL: value,
+ },
+ },
+ },
+ });
+
+ return instance;
+};
+
+afterEach(() => {
+ cleanup();
+ getDefaultQueryClient().removeQueries({ queryKey: ["provider-probe"] });
+ setQueryClient();
+ setI18n();
+ vi.restoreAllMocks();
+});
+
+describe("AgentServerUIProviders", () => {
+ it("exports and uses the default query client and i18n instances when props are omitted", async () => {
+ const defaultI18n = getDefaultI18n();
+
+ defaultI18n.addResourceBundle(
+ "en",
+ "translation",
+ { PROVIDER$LABEL: "Default provider" },
+ true,
+ true,
+ );
+ await defaultI18n.changeLanguage("en");
+
+ getDefaultQueryClient().setQueryData(["provider-probe"], "default-client");
+
+ render(
+ <AgentServerUIProviders>
+ <DefaultProbe />
+ </AgentServerUIProviders>,
+ );
+
+ expect(screen.getByTestId("query-client-kind")).toHaveTextContent(
+ "default",
+ );
+ expect(screen.getByTestId("query-client-value")).toHaveTextContent(
+ "default-client",
+ );
+
+ await waitFor(() => {
+ expect(
+ screen.getByTestId("imperative-translation-value"),
+ ).toHaveTextContent("Default provider");
+ });
+
+ expect(getQueryClient()).toBe(getDefaultQueryClient());
+ });
+
+ it("injects a custom query client and i18n instance without conflicting with imperative callers", async () => {
+ const customQueryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ },
+ });
+ const customI18n = await createTestI18n("Custom provider");
+
+ customQueryClient.setQueryData(["provider-probe"], "custom-client");
+
+ const view = render(
+ <AgentServerUIProviders queryClient={customQueryClient} i18n={customI18n}>
+ <CustomProbe />
+ </AgentServerUIProviders>,
+ );
+
+ expect(screen.getByTestId("query-client-kind")).toHaveTextContent("custom");
+ expect(screen.getByTestId("query-client-value")).toHaveTextContent(
+ "custom-client",
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId("translation-value")).toHaveTextContent(
+ "Custom provider",
+ );
+ expect(
+ screen.getByTestId("imperative-translation-value"),
+ ).toHaveTextContent("Custom provider");
+ });
+
+ expect(getQueryClient()).toBe(customQueryClient);
+ expect(getI18n()).toBe(customI18n);
+
+ view.unmount();
+
+ expect(getQueryClient()).toBe(getDefaultQueryClient());
+ expect(getI18n()).toBe(getDefaultI18n());
+ });
+
+ it("only mounts PostHog analytics when the host app opts in", async () => {
+ const getConfigSpy = vi
+ .spyOn(OptionService, "getConfig")
+ .mockResolvedValue({ posthog_client_key: "phc_test_key" } as never);
+
+ const noAnalyticsView = render(
+ <AgentServerUIProviders>
+ <div data-testid="child">child</div>
+ </AgentServerUIProviders>,
+ );
+
+ expect(screen.getByTestId("child")).toHaveTextContent("child");
+ expect(getConfigSpy).not.toHaveBeenCalled();
+
+ noAnalyticsView.unmount();
+
+ render(
+ <AgentServerUIProviders analytics={DEFAULT_AGENT_SERVER_ANALYTICS}>
+ <div data-testid="child-with-analytics">child</div>
+ </AgentServerUIProviders>,
+ );
+
+ await waitFor(() => {
+ expect(getConfigSpy).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/__tests__/components/providers/posthog-wrapper.test.tsx b/__tests__/components/providers/posthog-wrapper.test.tsx
index 4d61f34935..5167c9d27c 100644
--- a/__tests__/components/providers/posthog-wrapper.test.tsx
+++ b/__tests__/components/providers/posthog-wrapper.test.tsx
@@ -1,5 +1,7 @@
+import { type ReactNode } from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { PostHogWrapper } from "#/components/providers/posthog-wrapper";
import OptionService from "#/api/option-service/option-service.api";
@@ -12,6 +14,21 @@ vi.mock("posthog-js/react", () => ({
},
}));
+const renderWithQueryClient = (children: ReactNode) =>
+ render(
+ <QueryClientProvider
+ client={
+ new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ },
+ })
+ }
+ >
+ {children}
+ </QueryClientProvider>,
+ );
+
describe("PostHogWrapper", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -30,7 +47,7 @@ describe("PostHogWrapper", () => {
// Webflow sends distinct_id and session_id without the ph_ prefix
window.location.hash = "distinct_id=user-123&session_id=session-456";
- render(
+ renderWithQueryClient(
<PostHogWrapper>
<div data-testid="child" />
</PostHogWrapper>,
@@ -53,7 +70,7 @@ describe("PostHogWrapper", () => {
it("should clean up URL hash after extracting bootstrap IDs", async () => {
window.location.hash = "distinct_id=user-123&session_id=session-456";
- render(
+ renderWithQueryClient(
<PostHogWrapper>
<div data-testid="child" />
</PostHogWrapper>,
@@ -67,7 +84,7 @@ describe("PostHogWrapper", () => {
it("should persist bootstrap IDs to sessionStorage for OAuth survival", async () => {
window.location.hash = "distinct_id=user-123&session_id=session-456";
- render(
+ renderWithQueryClient(
<PostHogWrapper>
<div data-testid="child" />
</PostHogWrapper>,
@@ -99,7 +116,7 @@ describe("PostHogWrapper", () => {
JSON.stringify({ distinctID: "user-123", sessionID: "session-456" }),
);
- render(
+ renderWithQueryClient(
<PostHogWrapper>
<div data-testid="child" />
</PostHogWrapper>,
@@ -125,7 +142,7 @@ describe("PostHogWrapper", () => {
JSON.stringify({ distinctID: "user-123", sessionID: "session-456" }),
);
- render(
+ renderWithQueryClient(
<PostHogWrapper>
<div data-testid="child" />
</PostHogWrapper>,
@@ -137,7 +154,7 @@ describe("PostHogWrapper", () => {
});
it("should initialize without bootstrap when neither hash nor sessionStorage has IDs", async () => {
- render(
+ renderWithQueryClient(
<PostHogWrapper>
<div data-testid="child" />
</PostHogWrapper>,
diff --git a/src/components/providers/agent-server-ui-providers.tsx b/src/components/providers/agent-server-ui-providers.tsx
new file mode 100644
index 0000000000..782f8ed341
--- /dev/null
+++ b/src/components/providers/agent-server-ui-providers.tsx
@@ -0,0 +1,81 @@
+import React from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nextProvider } from "react-i18next";
+import { type i18n as I18nInstance } from "i18next";
+import {
+ getDefaultQueryClient,
+ getQueryClient,
+ setQueryClient,
+} from "#/query-client-config";
+import { getDefaultI18n, getI18n, setI18n } from "#/i18n";
+import { PostHogWrapper } from "./posthog-wrapper";
+
+export type AgentServerUIAnalyticsConfig =
+ | {
+ provider: "posthog";
+ }
+ | false
+ | null;
+
+export const DEFAULT_AGENT_SERVER_ANALYTICS: AgentServerUIAnalyticsConfig = {
+ provider: "posthog",
+};
+
+export interface AgentServerUIProvidersProps {
+ children: React.ReactNode;
+ queryClient?: QueryClient;
+ analytics?: AgentServerUIAnalyticsConfig;
+ i18n?: I18nInstance;
+}
+
+export function AgentServerUIProviders({
+ children,
+ queryClient,
+ analytics,
+ i18n,
+}: AgentServerUIProvidersProps) {
+ const resolvedQueryClient = React.useMemo(
+ () => queryClient ?? getDefaultQueryClient(),
+ [queryClient],
+ );
+ const resolvedI18n = React.useMemo(() => i18n ?? getDefaultI18n(), [i18n]);
+ const previousProvidersRef = React.useRef<{
+ queryClient: QueryClient;
+ i18n: I18nInstance;
+ } | null>(null);
+
+ if (!previousProvidersRef.current) {
+ previousProvidersRef.current = {
+ queryClient: getQueryClient(),
+ i18n: getI18n(),
+ };
+ }
+
+ setQueryClient(resolvedQueryClient);
+ setI18n(resolvedI18n);
+
+ React.useEffect(
+ () => () => {
+ if (previousProvidersRef.current) {
+ setQueryClient(previousProvidersRef.current.queryClient);
+ setI18n(previousProvidersRef.current.i18n);
+ }
+ },
+ [],
+ );
+
+ const content =
+ analytics && analytics.provider === "posthog" ? (
+ <PostHogWrapper>{children}</PostHogWrapper>
+ ) : (
+ children
+ );
+
+ return (
+ <I18nextProvider i18n={resolvedI18n} defaultNS="translation">
+ <QueryClientProvider client={resolvedQueryClient}>
+ {content}
+ </QueryClientProvider>
+ </I18nextProvider>
+ );
+}
diff --git a/src/components/providers/index.ts b/src/components/providers/index.ts
new file mode 100644
index 0000000000..3fee4c1cae
--- /dev/null
+++ b/src/components/providers/index.ts
@@ -0,0 +1,7 @@
+export {
+ AgentServerUIProviders,
+ DEFAULT_AGENT_SERVER_ANALYTICS,
+ type AgentServerUIAnalyticsConfig,
+ type AgentServerUIProvidersProps,
+} from "./agent-server-ui-providers";
+export { PostHogWrapper } from "./posthog-wrapper";
diff --git a/src/components/providers/posthog-wrapper.tsx b/src/components/providers/posthog-wrapper.tsx
index 7a66fff311..3a058dc72e 100644
--- a/src/components/providers/posthog-wrapper.tsx
+++ b/src/components/providers/posthog-wrapper.tsx
@@ -1,6 +1,6 @@
import React from "react";
+import { useQueryClient } from "@tanstack/react-query";
import { PostHogProvider } from "posthog-js/react";
-import { queryClient } from "#/query-client-config";
import OptionService from "#/api/option-service/option-service.api";
import { QUERY_KEYS, CONFIG_CACHE_OPTIONS } from "#/hooks/query/query-keys";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
@@ -40,6 +40,7 @@ function getBootstrapIds() {
}
export function PostHogWrapper({ children }: { children: React.ReactNode }) {
+ const queryClient = useQueryClient();
const [posthogClientKey, setPosthogClientKey] = React.useState<string | null>(
null,
);
@@ -62,7 +63,7 @@ export function PostHogWrapper({ children }: { children: React.ReactNode }) {
setIsLoading(false);
}
})();
- }, []);
+ }, [queryClient]);
if (isLoading || !posthogClientKey) {
return children;
diff --git a/src/entry.client.tsx b/src/entry.client.tsx
index f8e8e9f808..4597ac12d8 100644
--- a/src/entry.client.tsx
+++ b/src/entry.client.tsx
@@ -8,10 +8,10 @@
import { HydratedRouter } from "react-router/dom";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
-import "./i18n";
-import { QueryClientProvider } from "@tanstack/react-query";
-import { queryClient } from "./query-client-config";
-import { PostHogWrapper } from "./components/providers/posthog-wrapper";
+import {
+ AgentServerUIProviders,
+ DEFAULT_AGENT_SERVER_ANALYTICS,
+} from "./components/providers";
import { shouldStartMockWorker } from "./mocks/should-start-mock-worker";
async function prepareApp() {
@@ -29,11 +29,9 @@ prepareApp().then(() =>
hydrateRoot(
document,
<StrictMode>
- <QueryClientProvider client={queryClient}>
- <PostHogWrapper>
- <HydratedRouter />
- </PostHogWrapper>
- </QueryClientProvider>
+ <AgentServerUIProviders analytics={DEFAULT_AGENT_SERVER_ANALYTICS}>
+ <HydratedRouter />
+ </AgentServerUIProviders>
</StrictMode>,
);
}),
diff --git a/src/i18n/index.ts b/src/i18n/index.ts
index 3234f41c11..21b5222fd3 100644
--- a/src/i18n/index.ts
+++ b/src/i18n/index.ts
@@ -1,4 +1,4 @@
-import i18n from "i18next";
+import { createInstance, type i18n as I18nInstance } from "i18next";
import Backend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
@@ -21,22 +21,52 @@ export const AvailableLanguages = [
{ label: "Українська", value: "uk" },
];
-i18n
- .use(Backend)
- .use(LanguageDetector)
- .use(initReactI18next)
- .init({
- fallbackLng: "en",
- debug: import.meta.env.NODE_ENV === "development",
-
- // Define supported languages explicitly to prevent 404 errors
- // According to i18next documentation, this is the recommended way to prevent
- // 404 requests for unsupported language codes like 'en-US@posix'
- supportedLngs: AvailableLanguages.map((lang) => lang.value),
-
- // Do NOT set nonExplicitSupportedLngs: true as it causes 404 errors
- // for region-specific codes not in supportedLngs (per i18next developer)
- nonExplicitSupportedLngs: false,
- });
+const initializeI18n = (instance: I18nInstance) => {
+ instance
+ .use(Backend)
+ .use(LanguageDetector)
+ .use(initReactI18next)
+ .init({
+ fallbackLng: "en",
+ debug: import.meta.env.NODE_ENV === "development",
+
+ supportedLngs: AvailableLanguages.map((lang) => lang.value),
+ nonExplicitSupportedLngs: false,
+ });
+
+ return instance;
+};
+
+export const createAgentServerI18n = () => initializeI18n(createInstance());
+
+let defaultI18n: I18nInstance | null = null;
+let activeI18n: I18nInstance | null = null;
+
+export const getDefaultI18n = () => {
+ if (!defaultI18n) {
+ defaultI18n = createAgentServerI18n();
+ }
+
+ return defaultI18n;
+};
+
+export const getI18n = () => activeI18n ?? getDefaultI18n();
+
+export const setI18n = (instance?: I18nInstance | null) => {
+ activeI18n = instance ?? getDefaultI18n();
+ return activeI18n;
+};
+
+const i18n = new Proxy({} as I18nInstance, {
+ get: (_target, prop) => {
+ const instance = getI18n();
+ const value = Reflect.get(instance, prop, instance);
+ return typeof value === "function" ? value.bind(instance) : value;
+ },
+ set: (_target, prop, value) => {
+ const instance = getI18n();
+ return Reflect.set(instance, prop, value, instance);
+ },
+}) as I18nInstance;
export default i18n;
diff --git a/src/index.ts b/src/index.ts
new file mode 100644
index 0000000000..8d99c61c00
--- /dev/null
+++ b/src/index.ts
@@ -0,0 +1,20 @@
+export {
+ AgentServerUIProviders,
+ DEFAULT_AGENT_SERVER_ANALYTICS,
+ type AgentServerUIAnalyticsConfig,
+ type AgentServerUIProvidersProps,
+} from "./components/providers";
+export {
+ createAgentServerQueryClient,
+ getDefaultQueryClient,
+ getQueryClient,
+ queryClient,
+ setQueryClient,
+} from "./query-client-config";
+export {
+ AvailableLanguages,
+ createAgentServerI18n,
+ getDefaultI18n,
+ getI18n,
+ setI18n,
+} from "./i18n";
diff --git a/src/query-client-config.ts b/src/query-client-config.ts
index 8b30c10de0..0547c5c407 100644
--- a/src/query-client-config.ts
+++ b/src/query-client-config.ts
@@ -1,48 +1,86 @@
import { QueryCache, MutationCache, QueryClient } from "@tanstack/react-query";
-import i18next from "i18next";
import { AxiosError } from "axios";
+import i18n from "#/i18n";
import { I18nKey } from "./i18n/declaration";
import { retrieveAxiosErrorMessage } from "./utils/retrieve-axios-error-message";
import { displayErrorToast } from "./utils/custom-toast-handlers";
-const handle401Error = (error: AxiosError, queryClient: QueryClient) => {
+const handle401Error = (error: AxiosError, client: QueryClient) => {
if (error?.response?.status === 401 || error?.status === 401) {
- queryClient.invalidateQueries({ queryKey: ["user", "authenticated"] });
+ client.invalidateQueries({ queryKey: ["user", "authenticated"] });
}
};
const shownErrors = new Set<string>();
-export const queryClient = new QueryClient({
- queryCache: new QueryCache({
- onError: (error, query) => {
- const isAuthQuery =
- query.queryKey[0] === "user" && query.queryKey[1] === "authenticated";
- if (!isAuthQuery) {
- handle401Error(error, queryClient);
- }
-
- if (!query.meta?.disableToast) {
- const errorMessage = retrieveAxiosErrorMessage(error);
-
- if (!shownErrors.has(errorMessage || "")) {
- displayErrorToast(errorMessage || i18next.t(I18nKey.ERROR$GENERIC));
- shownErrors.add(errorMessage);
-
- setTimeout(() => {
- shownErrors.delete(errorMessage);
- }, 3000);
+
+export const createAgentServerQueryClient = () => {
+ let client: QueryClient;
+
+ client = new QueryClient({
+ queryCache: new QueryCache({
+ onError: (error, query) => {
+ const isAuthQuery =
+ query.queryKey[0] === "user" && query.queryKey[1] === "authenticated";
+ if (!isAuthQuery) {
+ handle401Error(error, client);
+ }
+
+ if (!query.meta?.disableToast) {
+ const errorMessage = retrieveAxiosErrorMessage(error);
+
+ if (!shownErrors.has(errorMessage || "")) {
+ displayErrorToast(errorMessage || i18n.t(I18nKey.ERROR$GENERIC));
+ shownErrors.add(errorMessage || "");
+
+ setTimeout(() => {
+ shownErrors.delete(errorMessage || "");
+ }, 3000);
+ }
+ }
+ },
+ }),
+ mutationCache: new MutationCache({
+ onError: (error, _, __, mutation) => {
+ handle401Error(error, client);
+
+ if (!mutation?.meta?.disableToast) {
+ const message = retrieveAxiosErrorMessage(error);
+ displayErrorToast(message || i18n.t(I18nKey.ERROR$GENERIC));
}
- }
- },
- }),
- mutationCache: new MutationCache({
- onError: (error, _, __, mutation) => {
- handle401Error(error, queryClient);
-
- if (!mutation?.meta?.disableToast) {
- const message = retrieveAxiosErrorMessage(error);
- displayErrorToast(message || i18next.t(I18nKey.ERROR$GENERIC));
- }
- },
- }),
-});
+ },
+ }),
+ });
+
+ return client;
+};
+
+let defaultQueryClient: QueryClient | null = null;
+let activeQueryClient: QueryClient | null = null;
+
+export const getDefaultQueryClient = () => {
+ if (!defaultQueryClient) {
+ defaultQueryClient = createAgentServerQueryClient();
+ }
+
+ return defaultQueryClient;
+};
+
+export const getQueryClient = () =>
+ activeQueryClient ?? getDefaultQueryClient();
+
+export const setQueryClient = (client?: QueryClient | null) => {
+ activeQueryClient = client ?? getDefaultQueryClient();
+ return activeQueryClient;
+};
+
+export const queryClient = new Proxy({} as QueryClient, {
+ get: (_target, prop) => {
+ const client = getQueryClient();
+ const value = Reflect.get(client, prop, client);
+ return typeof value === "function" ? value.bind(client) : value;
+ },
+ set: (_target, prop, value) => {
+ const client = getQueryClient();
+ return Reflect.set(client, prop, value, client);
+ },
+}) as QueryClient;