π OpenHands: AI-Driven Development
Remove direct HttpClient usage from agent-server APIs (#743)
Graham Neubig56fcdc6b2eac
diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.tsindex 14b460a3a0..04772e8817 100644--- a/__tests__/api/agent-server-conversation-service.test.ts+++ b/__tests__/api/agent-server-conversation-service.test.ts@@ -24,11 +24,11 @@ const {mockFileClient,mockSettingsClient,mockSwitchProfile,+ mockSwitchLLM,mockGetSettings,mockGetSettingsForConversation,mockGetProfile,mockActivateProfile,- mockSdkHttpPost,} = vi.hoisted(() => ({mockHttpGet: vi.fn(),mockHttpPost: vi.fn(),@@ -37,11 +37,11 @@ const {mockFileClient: vi.fn(),mockSettingsClient: vi.fn(),mockSwitchProfile: vi.fn(),+ mockSwitchLLM: vi.fn(),mockGetSettings: vi.fn(),mockGetSettingsForConversation: vi.fn(),mockGetProfile: vi.fn(),mockActivateProfile: vi.fn(),- mockSdkHttpPost: vi.fn(),}));vi.mock("@openhands/typescript-client/clients", async () => {@@ -71,16 +71,6 @@ vi.mock("@openhands/typescript-client/clients", async () => {};});-vi.mock("@openhands/typescript-client/client/http-client", async (importOriginal) => {- const actual = await importOriginal<typeof import("@openhands/typescript-client/client/http-client")>();- return {- ...actual,- HttpClient: vi.fn(function HttpClientMock() {- return { post: mockSdkHttpPost };- }),- };-});-vi.mock("#/api/agent-server-config", () => ({DEFAULT_WORKING_DIR: "workspace/project",getAgentServerBaseUrl: vi.fn(() => "http://localhost:54928"),@@ -109,7 +99,7 @@ describe("AgentServerConversationService", () => {mockHttpDelete.mockReset();mockGetProfile.mockReset();mockActivateProfile.mockReset();- mockSdkHttpPost.mockReset();+ mockSwitchLLM.mockReset();vi.mocked(ConversationClient).mockClear();vi.mocked(FileClient).mockClear();vi.mocked(ProfilesClient).mockClear();@@ -137,6 +127,7 @@ describe("AgentServerConversationService", () => {sendEvent: vi.fn(),updateConversation: vi.fn(),switchProfile: mockSwitchProfile,+ switchLLM: mockSwitchLLM,});mockFileClient.mockReturnValue({downloadTextFile: async (path: string) => {@@ -585,17 +576,14 @@ describe("AgentServerConversationService", () => {config: llmConfig,api_key_set: true,});- mockSdkHttpPost.mockResolvedValue({ data: undefined });+ mockSwitchLLM.mockResolvedValue(undefined);await AgentServerConversationService.switchProfile("conv-1", "haiku");expect(mockGetProfile).toHaveBeenCalledWith("haiku", {exposeSecrets: "encrypted",});- expect(mockSdkHttpPost).toHaveBeenCalledWith(- "/api/conversations/conv-1/switch_llm",- { llm: llmConfig },- );+ expect(mockSwitchLLM).toHaveBeenCalledWith("conv-1", llmConfig);// Per-convo path: global default is left untouched.expect(mockActivateProfile).not.toHaveBeenCalled();});@@ -612,7 +600,7 @@ describe("AgentServerConversationService", () => {expect(mockActivateProfile).toHaveBeenCalledWith("haiku");// Home-page path: don't touch any conversation's LLM.expect(mockGetProfile).not.toHaveBeenCalled();- expect(mockSdkHttpPost).not.toHaveBeenCalled();+ expect(mockSwitchLLM).not.toHaveBeenCalled();});it("rejects profile switching on cloud backends before any network call", async () => {@@ -633,7 +621,7 @@ describe("AgentServerConversationService", () => {);expect(mockActivateProfile).not.toHaveBeenCalled();expect(mockGetProfile).not.toHaveBeenCalled();- expect(mockSdkHttpPost).not.toHaveBeenCalled();+ expect(mockSwitchLLM).not.toHaveBeenCalled();});});diff --git a/__tests__/api/workspaces-service.test.ts b/__tests__/api/workspaces-service.test.tsindex 53f65e74f2..b445cf2571 100644--- a/__tests__/api/workspaces-service.test.ts+++ b/__tests__/api/workspaces-service.test.ts@@ -8,29 +8,30 @@ import {import type { Backend } from "#/api/backend-registry/types";import WorkspacesService from "#/api/workspaces-service/workspaces-service.api";-const { mockGet, mockPost, mockDelete, mockAssertAgentServerSupports } =- vi.hoisted(() => ({- mockGet: vi.fn(),- mockPost: vi.fn(),- mockDelete: vi.fn(),- mockAssertAgentServerSupports: vi.fn(),- }));--vi.mock("@openhands/typescript-client/client/http-client", () => ({- HttpClient: vi.fn(function HttpClientMock() {- return { get: mockGet, post: mockPost, delete: mockDelete };- }),+const {+ mockListWorkspaces,+ mockAddWorkspaces,+ mockDeleteWorkspace,+ mockAddWorkspaceParents,+ mockDeleteWorkspaceParent,+} = vi.hoisted(() => ({+ mockListWorkspaces: vi.fn(),+ mockAddWorkspaces: vi.fn(),+ mockDeleteWorkspace: vi.fn(),+ mockAddWorkspaceParents: vi.fn(),+ mockDeleteWorkspaceParent: vi.fn(),}));vi.mock("@openhands/typescript-client/clients", () => ({- AgentServerFeatureRequirements: {- workspaces: {- feature: "workspaces",- displayName: "Workspaces",- minVersion: "1.23.0",- },- },- assertAgentServerSupports: mockAssertAgentServerSupports,+ WorkspacesClient: vi.fn(function WorkspacesClientMock() {+ return {+ listWorkspaces: mockListWorkspaces,+ addWorkspaces: mockAddWorkspaces,+ deleteWorkspace: mockDeleteWorkspace,+ addWorkspaceParents: mockAddWorkspaceParents,+ deleteWorkspaceParent: mockDeleteWorkspaceParent,+ };+ }),}));const localBackend: Backend = {@@ -46,15 +47,11 @@ beforeEach(() => {__resetActiveStoreForTests();setRegisteredBackends([localBackend]);setActiveSelection({ backendId: localBackend.id });- mockGet.mockReset();- mockPost.mockReset();- mockDelete.mockReset();- mockAssertAgentServerSupports.mockReset();- mockAssertAgentServerSupports.mockResolvedValue({- version: "1.23.0",- uptime: 1,- idle_time: 0,- });+ mockListWorkspaces.mockReset();+ mockAddWorkspaces.mockReset();+ mockDeleteWorkspace.mockReset();+ mockAddWorkspaceParents.mockReset();+ mockDeleteWorkspaceParent.mockReset();});afterEach(() => {@@ -62,23 +59,23 @@ afterEach(() => {});describe("WorkspacesService", () => {- it("listWorkspaces unwraps the response body returned by HttpClient.get", async () => {+ it("listWorkspaces delegates to WorkspacesClient", async () => {// Arrangeconst body = {workspaces: [{ id: "/a", name: "a", path: "/a" }],workspaceParents: [{ id: "/p", name: "p", path: "/p" }],};- mockGet.mockResolvedValue({ data: body, status: 200 });+ mockListWorkspaces.mockResolvedValue(body);// Actconst result = await WorkspacesService.listWorkspaces();// Assert- expect(mockGet).toHaveBeenCalledWith("/api/workspaces");+ expect(mockListWorkspaces).toHaveBeenCalledWith();expect(result).toEqual(body);});- it("propagates the typed old-server error before calling /api/workspaces", async () => {+ it("propagates the typed old-server error from WorkspacesClient", async () => {// Arrangeconst error = {code: "AGENT_SERVER_VERSION_TOO_OLD",@@ -86,17 +83,17 @@ describe("WorkspacesService", () => {requiredVersion: "1.23.0",actualVersion: "1.22.1",};- mockAssertAgentServerSupports.mockRejectedValue(error);+ mockListWorkspaces.mockRejectedValue(error);// Act + Assertawait expect(WorkspacesService.listWorkspaces()).rejects.toBe(error);- expect(mockGet).not.toHaveBeenCalled();});- it("addWorkspaces POSTs the items wrapped in a workspaces envelope", async () => {+ it("addWorkspaces delegates to WorkspacesClient", async () => {// Arrange- mockPost.mockResolvedValue({- data: { workspaces: [], workspaceParents: [] },+ mockAddWorkspaces.mockResolvedValue({+ workspaces: [],+ workspaceParents: [],});const items = [{ id: "/a", name: "a", path: "/a", parentPath: "/p" }];@@ -104,15 +101,14 @@ describe("WorkspacesService", () => {await WorkspacesService.addWorkspaces(items);// Assert- expect(mockPost).toHaveBeenCalledWith("/api/workspaces", {- workspaces: items,- });+ expect(mockAddWorkspaces).toHaveBeenCalledWith(items);});- it("addWorkspaceParents POSTs the items wrapped in a parents envelope", async () => {+ it("addWorkspaceParents delegates to WorkspacesClient", async () => {// Arrange- mockPost.mockResolvedValue({- data: { workspaces: [], workspaceParents: [] },+ mockAddWorkspaceParents.mockResolvedValue({+ workspaces: [],+ workspaceParents: [],});const parents = [{ id: "/p", name: "p", path: "/p" }];@@ -120,34 +116,28 @@ describe("WorkspacesService", () => {await WorkspacesService.addWorkspaceParents(parents);// Assert- expect(mockPost).toHaveBeenCalledWith("/api/workspaces/parents", {- parents,- });+ expect(mockAddWorkspaceParents).toHaveBeenCalledWith(parents);});- it("removeWorkspace URL-encodes the path so slashes survive the query string", async () => {+ it("removeWorkspace delegates to WorkspacesClient", async () => {// Arrange- mockDelete.mockResolvedValue({ data: { deleted: true } });+ mockDeleteWorkspace.mockResolvedValue({ deleted: true });// Actawait WorkspacesService.removeWorkspace("/Users/me/dev/repo 1");// Assert- expect(mockDelete).toHaveBeenCalledWith(- "/api/workspaces?path=%2FUsers%2Fme%2Fdev%2Frepo%201",- );+ expect(mockDeleteWorkspace).toHaveBeenCalledWith("/Users/me/dev/repo 1");});- it("removeWorkspaceParent targets the parents endpoint", async () => {+ it("removeWorkspaceParent delegates to WorkspacesClient", async () => {// Arrange- mockDelete.mockResolvedValue({ data: { deleted: true } });+ mockDeleteWorkspaceParent.mockResolvedValue({ deleted: true });// Actawait WorkspacesService.removeWorkspaceParent("/parents/root");// Assert- expect(mockDelete).toHaveBeenCalledWith(- "/api/workspaces/parents?path=%2Fparents%2Froot",- );+ expect(mockDeleteWorkspaceParent).toHaveBeenCalledWith("/parents/root");});});diff --git a/eslint.config.js b/eslint.config.jsindex 32d8c7d291..2c179563d8 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -143,6 +143,18 @@ export default ["i18next/no-literal-string": "error","unused-imports/no-unused-imports": "error","@typescript-eslint/prefer-optional-chain": "error",+ "no-restricted-imports": [+ "error",+ {+ paths: [+ {+ name: "@openhands/typescript-client/client/http-client",+ message:+ "Use typed @openhands/typescript-client clients instead of constructing HttpClient directly.",+ },+ ],+ },+ ],// Allow `interface Foo extends Bar<"foo"> {}` β the codebase uses this// discriminated-union pattern in `src/types/agent-server/**` and thediff --git a/src/api/agent-server-compatibility.ts b/src/api/agent-server-compatibility.tsindex 7c03d5cef9..57d1606b4b 100644--- a/src/api/agent-server-compatibility.ts+++ b/src/api/agent-server-compatibility.ts@@ -1,5 +1,4 @@import { ServerClient } from "@openhands/typescript-client/clients";-import { HttpError } from "@openhands/typescript-client/client/http-client";import type { ServerInfo as BaseServerInfo } from "@openhands/typescript-client";import { getAgentServerClientOptions } from "#/api/agent-server-client-options";import { getEffectiveLocalBackend } from "#/api/backend-registry/active-store";@@ -52,6 +51,15 @@ export function isAgentServerToolAvailable(toolName: string) {return availableTools.includes(toolName);}+function isSdkHttpError(error: unknown) {+ return (+ error instanceof Error &&+ error.name === "HttpError" &&+ "status" in error &&+ typeof error.status === "number"+ );+}+export async function loadAgentServerInfo() {// The probe is a *local* agent-server concern β it verifies the runtime// hosting the GUI is reachable. It must NEVER run against the active@@ -70,7 +78,7 @@ export async function loadAgentServerInfo() {).getServerInfo()) as AgentServerInfo;} catch (error) {clearCachedAgentServerInfo();- if (error instanceof HttpError) {+ if (isSdkHttpError(error)) {throw error;}diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.tsindex fe463c99fd..5fe8a66e14 100644--- a/src/api/conversation-service/agent-server-conversation-service.api.ts+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts@@ -1,11 +1,13 @@-import { ConversationSortOrder } from "@openhands/typescript-client";+import {+ ConversationSortOrder,+ type LLMConfig,+} from "@openhands/typescript-client";import {ConversationClient,FileClient,ProfilesClient,VSCodeClient,} from "@openhands/typescript-client/clients";-import { HttpClient } from "@openhands/typescript-client/client/http-client";import { v4 as uuidv4 } from "uuid";import { Provider } from "#/types/settings";import { buildHttpBaseUrl } from "#/utils/websocket-url";@@ -37,10 +39,7 @@ import {toConversationPage,} from "../agent-server-adapter";import { GetVSCodeUrlResponse } from "../open-hands.types";-import {- getAgentServerClientOptions,- getAgentServerHttpClientOptions,-} from "../agent-server-client-options";+import { getAgentServerClientOptions } from "../agent-server-client-options";import SettingsService from "../settings-service/settings-service.api";import {ConversationMetadata,@@ -66,6 +65,10 @@ const INVALID_CONVERSATION_RESPONSE_MESSAGE ="Unable to load conversations because the selected agent server returned " +"data this UI does not understand. Check the backend URL/session key and " +"update the agent server if needed.";+const INVALID_PROFILE_CONFIG_MESSAGE =+ "Unable to switch LLM profiles because the selected agent server returned " ++ "profile data this UI does not understand. Check the backend URL/session " ++ "key and update the agent server if needed.";function invalidConversationResponse(): Error {return new Error(INVALID_CONVERSATION_RESPONSE_MESSAGE);@@ -75,6 +78,10 @@ function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === "object" && value !== null && !Array.isArray(value);}+function isLLMConfig(value: unknown): value is LLMConfig {+ return isRecord(value) && typeof value.model === "string";+}+function numberOrNull(value: unknown): number | null {return typeof value === "number" ? value : null;}@@ -642,10 +649,13 @@ class AgentServerConversationService {const profile = await profilesClient.getProfile(profileName, {exposeSecrets: "encrypted",});+ if (!isLLMConfig(profile.config)) {+ throw new Error(INVALID_PROFILE_CONFIG_MESSAGE);+ }- await new HttpClient(getAgentServerHttpClientOptions()).post(- `/api/conversations/${conversationId}/switch_llm`,- { llm: profile.config },+ await new ConversationClient(getAgentServerClientOptions()).switchLLM(+ conversationId,+ profile.config,);}}diff --git a/src/api/conversation-service/conversation-service.api.ts b/src/api/conversation-service/conversation-service.api.tsindex e26ad714a5..44e34025e8 100644--- a/src/api/conversation-service/conversation-service.api.ts+++ b/src/api/conversation-service/conversation-service.api.ts@@ -1,5 +1,4 @@import { VSCodeClient } from "@openhands/typescript-client/clients";-import { HttpClient } from "@openhands/typescript-client/client/http-client";import { RemoteEventsList } from "@openhands/typescript-client/events/remote-events-list";import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";import {@@ -65,9 +64,7 @@ class ConversationService {conversationId: string,): Promise<GetTrajectoryResponse> {const page = await new RemoteEventsList(- new HttpClient(- getAgentServerHttpClientOptions(this.getClientOverrides()),- ),+ getAgentServerHttpClientOptions(this.getClientOverrides()),conversationId,).search({ limit: 10000 });diff --git a/src/api/event-service/event-service.api.ts b/src/api/event-service/event-service.api.tsindex 348197b639..71d50a2b61 100644--- a/src/api/event-service/event-service.api.ts+++ b/src/api/event-service/event-service.api.ts@@ -1,5 +1,4 @@import { ConversationClient } from "@openhands/typescript-client/clients";-import { HttpClient } from "@openhands/typescript-client/client/http-client";import { RemoteEventsList } from "@openhands/typescript-client/events/remote-events-list";import { OpenHandsEvent } from "#/types/agent-server/core";import { buildHttpBaseUrl } from "#/utils/websocket-url";@@ -164,9 +163,7 @@ class EventService {}const page = await new RemoteEventsList(- new HttpClient(- getAgentServerHttpClientOptions({ conversationUrl, sessionApiKey }),- ),+ getAgentServerHttpClientOptions({ conversationUrl, sessionApiKey }),conversationId,).search({limit,diff --git a/src/api/no-direct-agent-server-calls.test.ts b/src/api/no-direct-agent-server-calls.test.tsindex 329bc92030..d640e898f2 100644--- a/src/api/no-direct-agent-server-calls.test.ts+++ b/src/api/no-direct-agent-server-calls.test.ts@@ -42,6 +42,18 @@ describe("agent-server API access", () => {fileViolations.push("uses createHttpClient directly");}+ if (+ /from\s+["']@openhands\/typescript-client\/client\/http-client["']/.test(+ source,+ )+ ) {+ fileViolations.push("imports the low-level SDK HttpClient directly");+ }++ if (/\bnew\s+HttpClient\s*\(/.test(source)) {+ fileViolations.push("constructs HttpClient directly");+ }+if ((/\baxios\s*\(/.test(source) ||/\baxios\s*\.\s*(?:create|get|post|put|patch|delete|request)\s*\(/.test(diff --git a/src/api/workspaces-service/workspaces-service.api.ts b/src/api/workspaces-service/workspaces-service.api.tsindex f9f013a9a0..174b5d7f39 100644--- a/src/api/workspaces-service/workspaces-service.api.ts+++ b/src/api/workspaces-service/workspaces-service.api.ts@@ -4,72 +4,63 @@* server (workspace/.openhands/workspaces.json). All clients pointed at* the same agent-server see the same list.*- * This service preflights workspace support through the SDK compatibility- * helper so old agent-server backends fail with a typed version error instead- * of surfacing a generic 404 from /api/workspaces.+ * The SDK WorkspacesClient owns compatibility preflight behavior, so old+ * agent-server backends surface the same typed version error without this+ * frontend constructing a raw HttpClient.*/import {- AgentServerFeatureRequirements,- assertAgentServerSupports,+ WorkspacesClient,+ type WorkspacesListResponse as SdkWorkspacesListResponse,} from "@openhands/typescript-client/clients";-import { HttpClient } from "@openhands/typescript-client/client/http-client";import { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";-import { getAgentServerHttpClientOptions } from "../agent-server-client-options";+import { getAgentServerClientOptions } from "../agent-server-client-options";export interface WorkspacesListResponse {workspaces: LocalWorkspace[];workspaceParents: LocalWorkspaceParent[];}-async function supportedClient() {- const httpClient = new HttpClient(getAgentServerHttpClientOptions());- await assertAgentServerSupports(- httpClient,- AgentServerFeatureRequirements.workspaces,- );- return httpClient;+function client() {+ return new WorkspacesClient(getAgentServerClientOptions());+}++function toLocalWorkspacesResponse(+ response: SdkWorkspacesListResponse,+): WorkspacesListResponse {+ return {+ workspaces: response.workspaces.map(({ parentPath, ...workspace }) => ({+ ...workspace,+ ...(parentPath ? { parentPath } : {}),+ })),+ workspaceParents: response.workspaceParents,+ };}class WorkspacesService {static async listWorkspaces(): Promise<WorkspacesListResponse> {- const client = await supportedClient();- const res = await client.get<WorkspacesListResponse>("/api/workspaces");- return res.data;+ return toLocalWorkspacesResponse(await client().listWorkspaces());}static async addWorkspaces(items: LocalWorkspace[],): Promise<WorkspacesListResponse> {- const client = await supportedClient();- const res = await client.post<WorkspacesListResponse>("/api/workspaces", {- workspaces: items,- });- return res.data;+ return toLocalWorkspacesResponse(await client().addWorkspaces(items));}static async removeWorkspace(path: string): Promise<void> {- const client = await supportedClient();- await client.delete(`/api/workspaces?path=${encodeURIComponent(path)}`);+ await client().deleteWorkspace(path);}static async addWorkspaceParents(items: LocalWorkspaceParent[],): Promise<WorkspacesListResponse> {- const client = await supportedClient();- const res = await client.post<WorkspacesListResponse>(- "/api/workspaces/parents",- { parents: items },- );- return res.data;+ return toLocalWorkspacesResponse(await client().addWorkspaceParents(items));}static async removeWorkspaceParent(path: string): Promise<void> {- const client = await supportedClient();- await client.delete(- `/api/workspaces/parents?path=${encodeURIComponent(path)}`,- );+ await client().deleteWorkspaceParent(path);}}