Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Route agent-server calls through TypeScript client (#278)

Graham Neubig1cd45306dfc0
diff --git a/.pr/pr-278/agent-run.gif b/.pr/pr-278/agent-run.gif
new file mode 100644
index 0000000000..081097b934
Binary files /dev/null and b/.pr/pr-278/agent-run.gif differ
diff --git a/AGENTS.md b/AGENTS.md
index 5fc675707e..b599fd817f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,10 +2,9 @@
- This repository is a near-direct port of the OpenHands frontend, adapted to talk straight to `software-agent-sdk` / `agent_server` without the usual OpenHands app backend.
- Frontend API adaptation lives mainly in `src/api/`:
- - `option-service` fabricates an OSS web-client config and reads models/providers from `agent_server` LLM endpoints.
- - `settings-service` uses agent server `/api/settings` endpoints for persistence; reads schemas from `/api/settings/agent-schema` and `/api/settings/conversation-schema`, fetches settings with optional `X-Expose-Secrets: encrypted` header for conversation start payloads, and saves settings via PATCH with diffs.
- - `agent-server-conversation-service`, `event-service`, `agent-server-git-service`, and `skills-service` are mapped directly to `agent_server` REST endpoints.
- - Shared REST calls should use `createHttpClient()` / typed adapters from `src/api/typescript-client.ts`, which handle backend URL and optional `X-Session-API-Key` resolution.
+ - `option-service` fabricates an OSS web-client config and reads models/providers through `@openhands/typescript-client` LLM endpoints.
+ - `settings-service` uses `@openhands/typescript-client` settings APIs for persistence; reads schemas from `/api/settings/agent-schema` and `/api/settings/conversation-schema`, fetches settings with optional `X-Expose-Secrets: encrypted` header for conversation start payloads, and saves settings via PATCH with diffs.
+ - `agent-server-conversation-service`, `event-service`, `agent-server-git-service`, and `skills-service` route local agent-server access through `@openhands/typescript-client` rather than direct HTTP calls.
- Supported env vars for deployment:
- `VITE_BACKEND_BASE_URL` for the agent server base URL.
- `VITE_SESSION_API_KEY` for optional session auth.
@@ -29,8 +28,8 @@
- `src/components/shared/buttons/styled-tooltip.tsx` should keep HeroUI tooltip animations disabled in Vitest (`disableAnimation` when `import.meta.env.MODE === "test"`); otherwise full-suite runs can end with unhandled `window is not defined` rejections from `framer-motion` after jsdom teardown (seen via `recent-conversation` tests in CI).
- `__tests__/i18n/library-namespace.test.ts` imports the full library entry and can exceed Vitest's default 5s timeout under full-suite load; keep an explicit higher timeout on that case unless the test is substantially narrowed.
-- `@openhands/typescript-client` is consumed directly from `github:OpenHands/typescript-client#6b9603f`; that package ships the needed subpath exports for `client/http-client`, `events/remote-events-list`, and `workspace/remote-workspace`. `RemoteWorkspace.gitChanges`/`gitDiff` accept an optional `{ ref }` option; agent-canvas passes `'HEAD'` so the changes panel reflects working-tree + index versus the latest commit (i.e. staged + unstaged) instead of a diff against the upstream/default branch.
-- Shared TypeScript-client adapters live in `src/api/typescript-client.ts`; prefer those helpers for agent-server-backed REST/workspace/event/VS Code calls instead of adding new bespoke axios clients.
+- `@openhands/typescript-client` is currently pinned to commit `ef62e82fc3dfb03991a1c8025429caf354427263` because the package metadata needed by this PR has not been published as a consistent npm/tagged release yet. That commit ships the needed typed clients plus subpath exports for `client/http-client`, `events/remote-events-list`, and `workspace/remote-workspace`. `RemoteWorkspace.gitChanges`/`gitDiff` accept an optional `{ ref }` option; agent-canvas passes `'HEAD'` so the changes panel reflects working-tree + index versus the latest commit (i.e. staged + unstaged) instead of a diff against the upstream/default branch.
+- Use `@openhands/typescript-client` classes directly for agent-server-backed REST/workspace/event/VS Code calls. Centralize host/session API key/working-directory option assembly through `src/api/agent-server-client-options.ts`; the backend fallback policy itself lives in `src/api/backend-registry/active-store.ts`.
- Local verification/build gotchas:
- `npm run typecheck` assumes generated translation types exist; run `npm run make-i18n` first if `src/i18n/declaration.ts` is missing.
- Merge note: `main` removed the old project-management integration subcomponents/hooks and their related feature-flag/i18n surface. If a feature branch still keeps the top-level `/integrations` git-token page, retain `src/routes/git-settings.tsx` plus the git-provider token inputs/hooks, but do **not** blindly restore `src/components/features/settings/project-management/*` or the old integration mutation/query hooks unless the corresponding option types and i18n keys are also reintroduced.
diff --git a/__tests__/api/agent-server-compatibility-bundled-pin.test.ts b/__tests__/api/agent-server-compatibility-bundled-pin.test.ts
index cc9b0b58fc..ed04220418 100644
--- a/__tests__/api/agent-server-compatibility-bundled-pin.test.ts
+++ b/__tests__/api/agent-server-compatibility-bundled-pin.test.ts
@@ -1,3 +1,4 @@
+import { ServerClient } from "@openhands/typescript-client/clients";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
__resetActiveStoreForTests,
@@ -7,21 +8,17 @@ import {
import type { Backend } from "#/api/backend-registry/types";
import { loadAgentServerInfo } from "#/api/agent-server-compatibility";
-const getServerInfoMock = vi.fn();
-const createServerClientMock = vi.fn(() => ({
- getServerInfo: getServerInfoMock,
+const { getServerInfoMock } = vi.hoisted(() => ({
+ getServerInfoMock: vi.fn(),
}));
-vi.mock("#/api/typescript-client", async () => {
- const actual = await vi.importActual<
- typeof import("#/api/typescript-client")
- >("#/api/typescript-client");
- return {
- ...actual,
- createServerClient: (...args: unknown[]) =>
- createServerClientMock(...(args as [])),
- };
-});
+vi.mock("@openhands/typescript-client/clients", () => ({
+ ServerClient: vi.fn(function ServerClientMock() {
+ return {
+ getServerInfo: getServerInfoMock,
+ };
+ }),
+}));
const cloudBackend: Backend = {
id: "prod",
@@ -35,7 +32,7 @@ beforeEach(() => {
window.localStorage.clear();
__resetActiveStoreForTests();
getServerInfoMock.mockReset();
- createServerClientMock.mockClear();
+ vi.mocked(ServerClient).mockClear();
getServerInfoMock.mockResolvedValue({ version: "1.0.0" });
});
@@ -51,9 +48,9 @@ describe("loadAgentServerInfo", () => {
await loadAgentServerInfo();
- expect(createServerClientMock).toHaveBeenCalledOnce();
- const callArgs = createServerClientMock.mock.calls[0] as unknown as [
- { host?: string; sessionApiKey?: string | null },
+ expect(ServerClient).toHaveBeenCalledOnce();
+ const callArgs = vi.mocked(ServerClient).mock.calls[0] as unknown as [
+ { host?: string; apiKey?: string | null },
];
const overrides = callArgs[0];
diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.ts
index 573c2eb578..e7852a11ec 100644
--- a/__tests__/api/agent-server-conversation-service.test.ts
+++ b/__tests__/api/agent-server-conversation-service.test.ts
@@ -1,3 +1,8 @@
+import {
+ ConversationClient,
+ FileClient,
+ SettingsClient,
+} from "@openhands/typescript-client/clients";
import axios from "axios";
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import {
@@ -14,27 +19,42 @@ const {
mockHttpGet,
mockHttpPost,
mockHttpDelete,
- mockFileUpload,
- mockCreateHttpClient,
- mockCreateRemoteWorkspace,
+ mockConversationClient,
+ mockFileClient,
+ mockSettingsClient,
mockGetSettings,
mockGetSettingsForConversation,
} = vi.hoisted(() => ({
mockHttpGet: vi.fn(),
mockHttpPost: vi.fn(),
mockHttpDelete: vi.fn(),
- mockFileUpload: vi.fn(),
- mockCreateHttpClient: vi.fn(),
- mockCreateRemoteWorkspace: vi.fn(),
+ mockConversationClient: vi.fn(),
+ mockFileClient: vi.fn(),
+ mockSettingsClient: vi.fn(),
mockGetSettings: vi.fn(),
mockGetSettingsForConversation: vi.fn(),
}));
-vi.mock("#/api/typescript-client", () => ({
- createHttpClient: mockCreateHttpClient,
- createRemoteWorkspace: mockCreateRemoteWorkspace,
- createVSCodeClient: vi.fn(),
-}));
+vi.mock("@openhands/typescript-client/clients", async () => {
+ const actual = await vi.importActual<
+ typeof import("@openhands/typescript-client/clients")
+ >("@openhands/typescript-client/clients");
+ return {
+ ...actual,
+ ConversationClient: vi.fn(function ConversationClientMock() {
+ return mockConversationClient();
+ }),
+ FileClient: vi.fn(function FileClientMock() {
+ return mockFileClient();
+ }),
+ SettingsClient: vi.fn(function SettingsClientMock() {
+ return mockSettingsClient();
+ }),
+ VSCodeClient: vi.fn(function VSCodeClientMock() {
+ return { getUrl: vi.fn() };
+ }),
+ };
+});
vi.mock("#/api/agent-server-config", () => ({
DEFAULT_WORKING_DIR: "workspace/project",
@@ -61,16 +81,50 @@ describe("AgentServerConversationService", () => {
mockHttpGet.mockReset();
mockHttpPost.mockReset();
mockHttpDelete.mockReset();
- mockFileUpload.mockReset();
-
- mockCreateHttpClient.mockReturnValue({
- get: mockHttpGet,
- post: mockHttpPost,
- patch: vi.fn(),
- delete: mockHttpDelete,
+ vi.mocked(ConversationClient).mockClear();
+ vi.mocked(FileClient).mockClear();
+ vi.mocked(SettingsClient).mockClear();
+
+ mockConversationClient.mockReturnValue({
+ createConversation: async (payload: unknown) => {
+ const response = await mockHttpPost("/api/conversations", payload);
+ return response.data;
+ },
+ getConversations: async (conversationIds: string[]) => {
+ const response = await mockHttpGet("/api/conversations", {
+ params: { ids: conversationIds },
+ });
+ return response.data;
+ },
+ deleteConversation: async (conversationId: string) => {
+ const response = await mockHttpDelete(
+ `/api/conversations/${conversationId}`,
+ );
+ return response.data;
+ },
+ searchConversations: vi.fn(),
+ getConversation: vi.fn(),
+ sendEvent: vi.fn(),
+ updateConversation: vi.fn(),
+ });
+ mockFileClient.mockReturnValue({
+ downloadTextFile: async (path: string) => {
+ const response = await mockHttpGet("/api/file/download", {
+ params: { path },
+ responseType: "arrayBuffer",
+ });
+ return new TextDecoder().decode(response.data);
+ },
+ downloadTrajectory: async (conversationId: string) => {
+ const response = await mockHttpGet(
+ `/api/file/download-trajectory/${conversationId}`,
+ { responseType: "blob" },
+ );
+ return response.data;
+ },
});
- mockCreateRemoteWorkspace.mockReturnValue({
- fileUpload: mockFileUpload,
+ mockSettingsClient.mockReturnValue({
+ listSecrets: vi.fn().mockResolvedValue({ secrets: [] }),
});
});
@@ -99,6 +153,16 @@ describe("AgentServerConversationService", () => {
await AgentServerConversationService.readConversationFile("conv-123");
expect(content).toBe("# PLAN content");
+ expect(ConversationClient).toHaveBeenCalledWith({
+ host: "http://localhost:54928",
+ apiKey: "test-api-key",
+ workingDir: "/workspace/project/agent-canvas",
+ });
+ expect(FileClient).toHaveBeenCalledWith({
+ host: "http://localhost:54928",
+ apiKey: "test-api-key",
+ workingDir: "/workspace/project/agent-canvas",
+ });
expect(mockHttpGet).toHaveBeenCalledWith(
"/api/file/download",
expect.objectContaining({
@@ -109,6 +173,39 @@ describe("AgentServerConversationService", () => {
}),
);
});
+
+ it("rejects explicit file paths outside the conversation workspace", async () => {
+ mockHttpGet.mockImplementation((url: string) => {
+ if (url === "/api/conversations") {
+ return Promise.resolve({
+ data: [
+ {
+ id: "conv-123",
+ created_at: "2024-01-01",
+ updated_at: "2024-01-01",
+ workspace: {
+ working_dir: "/workspace/project/agent-canvas/conv-123",
+ },
+ },
+ ],
+ });
+ }
+ return Promise.resolve({ data: new ArrayBuffer(0) });
+ });
+
+ await expect(
+ AgentServerConversationService.readConversationFile(
+ "conv-123",
+ "/workspace/project/agent-canvas/other/PLAN.md",
+ ),
+ ).rejects.toThrow(
+ "Conversation file path must stay inside the workspace",
+ );
+ expect(mockHttpGet).not.toHaveBeenCalledWith(
+ "/api/file/download",
+ expect.anything(),
+ );
+ });
});
describe("createConversation", () => {
@@ -133,6 +230,11 @@ describe("AgentServerConversationService", () => {
await AgentServerConversationService.createConversation();
await AgentServerConversationService.createConversation();
+ expect(ConversationClient).toHaveBeenCalledWith({
+ host: "http://localhost:54928",
+ apiKey: "test-api-key",
+ workingDir: "/workspace/project/agent-canvas",
+ });
expect(mockHttpPost).toHaveBeenCalledTimes(2);
const [firstCall, secondCall] = mockHttpPost.mock.calls;
const firstPayload = firstCall[1] as {
@@ -208,6 +310,105 @@ describe("AgentServerConversationService", () => {
});
});
+ describe("conversation update fallbacks", () => {
+ it("throws a useful error when repository update cannot reload the conversation", async () => {
+ mockHttpGet.mockResolvedValue({ data: [] });
+
+ await expect(
+ AgentServerConversationService.updateConversationRepository(
+ "missing-conv",
+ "OpenHands/agent-canvas",
+ ),
+ ).rejects.toThrow("Conversation missing-conv was not found");
+ });
+
+ it("throws a useful error when title update cannot reload the conversation", async () => {
+ mockHttpGet.mockResolvedValue({ data: [] });
+
+ await expect(
+ AgentServerConversationService.updateConversationTitle(
+ "missing-conv",
+ "New title",
+ ),
+ ).rejects.toThrow("Conversation missing-conv was not found");
+ });
+
+ it("normalizes conversation list items with missing timestamps", async () => {
+ mockHttpGet.mockResolvedValue({
+ data: [
+ {
+ id: "conv-no-timestamps",
+ title: "Conversation without timestamps",
+ },
+ ],
+ });
+
+ const [conversation] =
+ await AgentServerConversationService.batchGetAppConversations([
+ "conv-no-timestamps",
+ ]);
+
+ expect(conversation).toMatchObject({
+ id: "conv-no-timestamps",
+ created_at: "1970-01-01T00:00:00.000Z",
+ updated_at: "1970-01-01T00:00:00.000Z",
+ });
+ });
+
+ it("throws a user-friendly error for unusable conversation list responses", async () => {
+ mockHttpGet.mockResolvedValue({ data: [{ title: "missing id" }] });
+
+ await expect(
+ AgentServerConversationService.batchGetAppConversations(["missing-id"]),
+ ).rejects.toThrow(
+ "Unable to load conversations because the selected agent server returned",
+ );
+ });
+
+ it("sanitizes malformed optional conversation fields", async () => {
+ mockHttpGet.mockResolvedValue({
+ data: [
+ {
+ id: "conv-malformed-fields",
+ title: "Conversation with malformed fields",
+ metrics: {
+ accumulated_cost: "1.23",
+ max_budget_per_task: 10,
+ accumulated_token_usage: {
+ prompt_tokens: "123",
+ completion_tokens: 4,
+ },
+ },
+ agent: "not an agent object",
+ workspace: "not a workspace object",
+ },
+ ],
+ });
+
+ const [conversation] =
+ await AgentServerConversationService.batchGetAppConversations([
+ "conv-malformed-fields",
+ ]);
+
+ expect(conversation?.metrics).toEqual({
+ accumulated_cost: null,
+ max_budget_per_task: 10,
+ accumulated_token_usage: {
+ prompt_tokens: 0,
+ completion_tokens: 4,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ context_window: 0,
+ per_turn_token: 0,
+ },
+ });
+ expect(conversation?.llm_model).toBeTruthy();
+ expect(conversation?.workspace?.working_dir).toBe(
+ "/workspace/project/agent-canvas",
+ );
+ });
+ });
+
describe("cloud branches", () => {
const cloudBackend: Backend = {
id: "prod",
@@ -276,7 +477,9 @@ describe("AgentServerConversationService", () => {
// Act
const content =
- await AgentServerConversationService.readConversationFile("conv-cloud-1");
+ await AgentServerConversationService.readConversationFile(
+ "conv-cloud-1",
+ );
// Assert
expect(content).toBe("# PLAN content");
@@ -288,58 +491,4 @@ describe("AgentServerConversationService", () => {
);
});
});
-
- describe("uploadFile", () => {
- it("uses query params for file upload path", async () => {
- const file = new File(["test content"], "test.txt", {
- type: "text/plain",
- });
- const uploadPath = "/workspace/custom/path.txt";
-
- await AgentServerConversationService.uploadFile(
- "http://localhost:54928/api/conversations/conv-123",
- "test-api-key",
- file,
- uploadPath,
- );
-
- expect(mockCreateRemoteWorkspace).toHaveBeenCalledWith({
- sessionApiKey: "test-api-key",
- });
- expect(mockFileUpload).toHaveBeenCalledWith(file, uploadPath);
- });
-
- it("uses default workspace path when no path provided", async () => {
- const file = new File(["test content"], "myfile.txt", {
- type: "text/plain",
- });
-
- await AgentServerConversationService.uploadFile(
- "http://localhost:54928/api/conversations/conv-123",
- "test-api-key",
- file,
- );
-
- expect(mockFileUpload).toHaveBeenCalledWith(
- file,
- "/workspace/myfile.txt",
- );
- });
-
- it("passes through the selected session key for uploads", async () => {
- const file = new File(["test content"], "test.txt", {
- type: "text/plain",
- });
-
- await AgentServerConversationService.uploadFile(
- "http://localhost:54928/api/conversations/conv-123",
- "my-session-key",
- file,
- );
-
- expect(mockCreateRemoteWorkspace).toHaveBeenCalledWith({
- sessionApiKey: "my-session-key",
- });
- });
- });
});
diff --git a/__tests__/api/agent-server-git-service.test.ts b/__tests__/api/agent-server-git-service.test.ts
index 847814e9b3..04bd949d21 100644
--- a/__tests__/api/agent-server-git-service.test.ts
+++ b/__tests__/api/agent-server-git-service.test.ts
@@ -1,14 +1,19 @@
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
import { describe, test, expect, vi, beforeEach } from "vitest";
import AgentServerGitService from "../../src/api/git-service/agent-server-git-service.api";
-const { mockGitChanges, mockGitDiff, mockCreateRemoteWorkspace } = vi.hoisted(() => ({
+const { mockGitChanges, mockGitDiff } = vi.hoisted(() => ({
mockGitChanges: vi.fn(),
mockGitDiff: vi.fn(),
- mockCreateRemoteWorkspace: vi.fn(),
}));
-vi.mock("../../src/api/typescript-client", () => ({
- createRemoteWorkspace: mockCreateRemoteWorkspace,
+vi.mock("@openhands/typescript-client/workspace/remote-workspace", () => ({
+ RemoteWorkspace: vi.fn(function RemoteWorkspaceMock() {
+ return {
+ gitChanges: mockGitChanges,
+ gitDiff: mockGitDiff,
+ };
+ }),
}));
describe("AgentServerGitService", () => {
@@ -16,10 +21,7 @@ describe("AgentServerGitService", () => {
vi.clearAllMocks();
mockGitChanges.mockReset();
mockGitDiff.mockReset();
- mockCreateRemoteWorkspace.mockReturnValue({
- gitChanges: mockGitChanges,
- gitDiff: mockGitDiff,
- });
+ vi.mocked(RemoteWorkspace).mockClear();
});
describe("getGitChanges", () => {
@@ -44,11 +46,14 @@ describe("AgentServerGitService", () => {
"/workspace/project",
);
- expect(mockCreateRemoteWorkspace).toHaveBeenCalledWith({
- conversationUrl: "http://localhost:3000/api/conversations/123",
- sessionApiKey: "my-session-key",
+ expect(RemoteWorkspace).toHaveBeenCalledWith({
+ host: "http://localhost:3000",
+ apiKey: "my-session-key",
+ workingDir: "workspace/project",
+ });
+ expect(mockGitChanges).toHaveBeenCalledWith("/workspace/project", {
+ ref: "HEAD",
});
- expect(mockGitChanges).toHaveBeenCalledWith("/workspace/project", { ref: "HEAD" });
});
test("preserves slashes in path when using workspace helper", async () => {
@@ -61,7 +66,9 @@ describe("AgentServerGitService", () => {
pathWithSlashes,
);
- expect(mockGitChanges).toHaveBeenCalledWith(pathWithSlashes, { ref: "HEAD" });
+ expect(mockGitChanges).toHaveBeenCalledWith(pathWithSlashes, {
+ ref: "HEAD",
+ });
});
test("maps V1 git statuses to V0 format", async () => {
@@ -89,7 +96,9 @@ describe("AgentServerGitService", () => {
describe("getGitChangeDiff", () => {
test("passes conversation URL and path to runtime workspace diff helper", async () => {
- mockGitDiff.mockResolvedValue({ diff: "--- a/file.ts\n+++ b/file.ts\n..." });
+ mockGitDiff.mockResolvedValue({
+ diff: "--- a/file.ts\n+++ b/file.ts\n...",
+ });
await AgentServerGitService.getGitChangeDiff(
"http://localhost:3000/api/conversations/123",
@@ -97,11 +106,14 @@ describe("AgentServerGitService", () => {
"/workspace/project/file.ts",
);
- expect(mockCreateRemoteWorkspace).toHaveBeenCalledWith({
- conversationUrl: "http://localhost:3000/api/conversations/123",
- sessionApiKey: "test-api-key",
+ expect(RemoteWorkspace).toHaveBeenCalledWith({
+ host: "http://localhost:3000",
+ apiKey: "test-api-key",
+ workingDir: "workspace/project",
+ });
+ expect(mockGitDiff).toHaveBeenCalledWith("/workspace/project/file.ts", {
+ ref: "HEAD",
});
- expect(mockGitDiff).toHaveBeenCalledWith("/workspace/project/file.ts", { ref: "HEAD" });
});
test("preserves slashes in file path when using workspace helper", async () => {
diff --git a/__tests__/api/conversation-service.test.ts b/__tests__/api/conversation-service.test.ts
new file mode 100644
index 0000000000..608abea7cc
--- /dev/null
+++ b/__tests__/api/conversation-service.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
+
+import ConversationService from "#/api/conversation-service/conversation-service.api";
+
+const fileUploadMock = vi.fn();
+
+vi.mock("@openhands/typescript-client/workspace/remote-workspace", () => ({
+ RemoteWorkspace: vi.fn(function RemoteWorkspaceMock() {
+ return { fileUpload: fileUploadMock };
+ }),
+}));
+
+function makeFile(name: string) {
+ return new File(["content"], name, { type: "text/plain" });
+}
+
+describe("ConversationService", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ ConversationService.setCurrentConversation(null);
+ });
+
+ describe("uploadFiles", () => {
+ it("uploads files through RemoteWorkspace and reports successes", async () => {
+ fileUploadMock.mockResolvedValue(undefined);
+
+ const result = await ConversationService.uploadFiles("conv-1", [
+ makeFile("a.txt"),
+ makeFile("b.txt"),
+ ]);
+
+ expect(RemoteWorkspace).toHaveBeenCalledWith(
+ expect.objectContaining({
+ host: expect.any(String),
+ workingDir: expect.any(String),
+ }),
+ );
+ expect(fileUploadMock).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "a.txt" }),
+ "/workspace/a.txt",
+ );
+ expect(fileUploadMock).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "b.txt" }),
+ "/workspace/b.txt",
+ );
+ expect(result).toEqual({
+ uploaded_files: ["a.txt", "b.txt"],
+ skipped_files: [],
+ });
+ });
+
+ it("uploads using only the basename of user-provided file names", async () => {
+ fileUploadMock.mockResolvedValue(undefined);
+
+ const result = await ConversationService.uploadFiles("conv-1", [
+ makeFile("../../evil.txt"),
+ ]);
+
+ expect(fileUploadMock).toHaveBeenCalledWith(
+ expect.objectContaining({ name: "../../evil.txt" }),
+ "/workspace/evil.txt",
+ );
+ expect(result).toEqual({
+ uploaded_files: ["evil.txt"],
+ skipped_files: [],
+ });
+ });
+
+ it("uses the current conversation session key and reports per-file failures", async () => {
+ ConversationService.setCurrentConversation({
+ id: "conv-1",
+ session_api_key: "session-key",
+ } as never);
+ fileUploadMock
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new Error("too large"));
+
+ const result = await ConversationService.uploadFiles("conv-1", [
+ makeFile("ok.txt"),
+ makeFile("bad.txt"),
+ ]);
+
+ expect(RemoteWorkspace).toHaveBeenCalledWith(
+ expect.objectContaining({ apiKey: "session-key" }),
+ );
+ expect(result).toEqual({
+ uploaded_files: ["ok.txt"],
+ skipped_files: [{ name: "bad.txt", reason: "too large" }],
+ });
+ });
+
+ it("uploads files in bounded batches", async () => {
+ let activeUploads = 0;
+ let maxActiveUploads = 0;
+ fileUploadMock.mockImplementation(async () => {
+ activeUploads += 1;
+ maxActiveUploads = Math.max(maxActiveUploads, activeUploads);
+ await Promise.resolve();
+ activeUploads -= 1;
+ });
+
+ const files = Array.from({ length: 7 }, (_, index) =>
+ makeFile(`file-${String(index)}.txt`),
+ );
+
+ const result = await ConversationService.uploadFiles("conv-1", files);
+
+ expect(fileUploadMock).toHaveBeenCalledTimes(7);
+ expect(maxActiveUploads).toBe(5);
+ expect(result.uploaded_files).toEqual(files.map((file) => file.name));
+ expect(result.skipped_files).toEqual([]);
+ });
+ });
+});
diff --git a/__tests__/api/skills-service.test.ts b/__tests__/api/skills-service.test.ts
index f2f8da1759..d778b577c3 100644
--- a/__tests__/api/skills-service.test.ts
+++ b/__tests__/api/skills-service.test.ts
@@ -1,3 +1,4 @@
+import { SkillsClient } from "@openhands/typescript-client/clients";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
__resetActiveStoreForTests,
@@ -7,13 +8,14 @@ import {
import type { Backend } from "#/api/backend-registry/types";
import SkillsService from "#/api/skills-service";
-const { mockGetSkills, mockCreateSkillsClient } = vi.hoisted(() => ({
+const { mockGetSkills } = vi.hoisted(() => ({
mockGetSkills: vi.fn(),
- mockCreateSkillsClient: vi.fn(),
}));
-vi.mock("#/api/typescript-client", () => ({
- createSkillsClient: mockCreateSkillsClient,
+vi.mock("@openhands/typescript-client/clients", () => ({
+ SkillsClient: vi.fn(function SkillsClientMock() {
+ return { getSkills: mockGetSkills };
+ }),
}));
const localBackend: Backend = {
@@ -30,8 +32,7 @@ beforeEach(() => {
setRegisteredBackends([localBackend]);
setActiveSelection({ backendId: localBackend.id });
mockGetSkills.mockReset();
- mockCreateSkillsClient.mockReset();
- mockCreateSkillsClient.mockReturnValue({ getSkills: mockGetSkills });
+ vi.mocked(SkillsClient).mockClear();
});
afterEach(() => {
diff --git a/__tests__/api/use-create-conversation-metadata.test.ts b/__tests__/api/use-create-conversation-metadata.test.ts
index 8b34e9414a..029e11aec1 100644
--- a/__tests__/api/use-create-conversation-metadata.test.ts
+++ b/__tests__/api/use-create-conversation-metadata.test.ts
@@ -1,3 +1,7 @@
+import {
+ ConversationClient,
+ SettingsClient,
+} from "@openhands/typescript-client/clients";
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -7,21 +11,35 @@ import { getStoredConversationMetadata } from "#/api/conversation-metadata-store
const {
mockHttpPost,
- mockCreateHttpClient,
+ mockConversationClient,
+ mockSettingsClient,
mockGetSettings,
mockGetSettingsForConversation,
} = vi.hoisted(() => ({
mockHttpPost: vi.fn(),
- mockCreateHttpClient: vi.fn(),
+ mockConversationClient: vi.fn(),
+ mockSettingsClient: vi.fn(),
mockGetSettings: vi.fn(),
mockGetSettingsForConversation: vi.fn(),
}));
-vi.mock("#/api/typescript-client", () => ({
- createHttpClient: mockCreateHttpClient,
- createRemoteWorkspace: vi.fn(),
- createVSCodeClient: vi.fn(),
-}));
+vi.mock("@openhands/typescript-client/clients", async () => {
+ const actual = await vi.importActual<
+ typeof import("@openhands/typescript-client/clients")
+ >("@openhands/typescript-client/clients");
+ return {
+ ...actual,
+ ConversationClient: vi.fn(function ConversationClientMock() {
+ return mockConversationClient();
+ }),
+ SettingsClient: vi.fn(function SettingsClientMock() {
+ return mockSettingsClient();
+ }),
+ VSCodeClient: vi.fn(function VSCodeClientMock() {
+ return { getUrl: vi.fn() };
+ }),
+ };
+});
vi.mock("#/api/agent-server-config", () => ({
DEFAULT_WORKING_DIR: "workspace/project",
@@ -57,7 +75,6 @@ describe("useCreateConversation persists selected repository metadata", () => {
beforeEach(() => {
window.localStorage.clear();
mockHttpPost.mockReset();
- mockCreateHttpClient.mockReset();
mockGetSettings.mockReset();
mockGetSettingsForConversation.mockReset();
mockGetSettings.mockResolvedValue({
@@ -69,11 +86,17 @@ describe("useCreateConversation persists selected repository metadata", () => {
conversationSettings: {},
secretsEncrypted: true,
});
- mockCreateHttpClient.mockReturnValue({
- get: vi.fn(),
- post: mockHttpPost,
- patch: vi.fn(),
- delete: vi.fn(),
+ mockConversationClient.mockReset();
+ vi.mocked(ConversationClient).mockClear();
+ vi.mocked(SettingsClient).mockClear();
+ mockConversationClient.mockReturnValue({
+ createConversation: async (payload: unknown) => {
+ const response = await mockHttpPost("/api/conversations", payload);
+ return response.data;
+ },
+ });
+ mockSettingsClient.mockReturnValue({
+ listSecrets: vi.fn().mockResolvedValue({ secrets: [] }),
});
mockHttpPost.mockResolvedValue({
data: {
diff --git a/__tests__/components/backends/backend-selector.test.tsx b/__tests__/components/backends/backend-selector.test.tsx
index b98e5a83eb..a2559d4482 100644
--- a/__tests__/components/backends/backend-selector.test.tsx
+++ b/__tests__/components/backends/backend-selector.test.tsx
@@ -22,12 +22,12 @@ import {
} from "#/components/features/backends/environment-switch-overlay";
import { ENVIRONMENT_SWITCH_SETACTIVE_DELAY_MS } from "#/components/features/backends/environment-switch-store";
+import { ServerClient } from "@openhands/typescript-client/clients";
import {
getCloudOrganizations,
getCloudOrganizationMe,
getCurrentCloudApiKey,
} from "#/api/cloud/organization-service.api";
-import { createServerClient } from "#/api/typescript-client";
vi.mock("#/api/cloud/organization-service.api", () => ({
getCloudOrganizations: vi.fn(),
@@ -35,8 +35,8 @@ vi.mock("#/api/cloud/organization-service.api", () => ({
getCurrentCloudApiKey: vi.fn(),
}));
-vi.mock("#/api/typescript-client", () => ({
- createServerClient: vi.fn(),
+vi.mock("@openhands/typescript-client/clients", () => ({
+ ServerClient: vi.fn(),
}));
function renderWithProviders(ui: React.ReactElement) {
@@ -94,13 +94,15 @@ beforeEach(() => {
// Default the local-server health probe to "connected" so the
// existing label-focused tests aren't surprised by a red indicator;
// tests that assert on the disconnected state override this.
- vi.mocked(createServerClient).mockReset();
- vi.mocked(createServerClient).mockReturnValue({
- getServerInfo: vi.fn().mockResolvedValue({ version: "1.18.0" }),
- // The dropdown only invokes getServerInfo on the returned client;
- // the rest of the ServerClient surface is unused here, so a
- // partial cast is sufficient.
- } as unknown as ReturnType<typeof createServerClient>);
+ vi.mocked(ServerClient).mockReset();
+ vi.mocked(ServerClient).mockImplementation(function ServerClientMock() {
+ return {
+ getServerInfo: vi.fn().mockResolvedValue({ version: "1.18.0" }),
+ // The dropdown only invokes getServerInfo on the returned client;
+ // the rest of the ServerClient surface is unused here, so a
+ // partial cast is sufficient.
+ } as unknown as ServerClient;
+ });
});
afterEach(async () => {
@@ -811,9 +813,11 @@ describe("BackendSelector", () => {
describe("connection indicator", () => {
it("renders one status dot per option, green when the probe succeeds", async () => {
- vi.mocked(createServerClient).mockReturnValue({
- getServerInfo: vi.fn().mockResolvedValue({ version: "1.18.0" }),
- } as unknown as ReturnType<typeof createServerClient>);
+ vi.mocked(ServerClient).mockImplementation(function ServerClientMock() {
+ return {
+ getServerInfo: vi.fn().mockResolvedValue({ version: "1.18.0" }),
+ } as unknown as ServerClient;
+ });
renderWithProviders(
<TestSeed
@@ -845,9 +849,11 @@ describe("BackendSelector", () => {
});
it("flips the status dot to red when the local probe fails", async () => {
- vi.mocked(createServerClient).mockReturnValue({
- getServerInfo: vi.fn().mockRejectedValue(new Error("ECONNREFUSED")),
- } as unknown as ReturnType<typeof createServerClient>);
+ vi.mocked(ServerClient).mockImplementation(function ServerClientMock() {
+ return {
+ getServerInfo: vi.fn().mockRejectedValue(new Error("ECONNREFUSED")),
+ } as unknown as ServerClient;
+ });
renderWithProviders(<BackendSelector />);
diff --git a/__tests__/components/backends/manage-backends-modal.test.tsx b/__tests__/components/backends/manage-backends-modal.test.tsx
index b8692944b8..70f6d062f4 100644
--- a/__tests__/components/backends/manage-backends-modal.test.tsx
+++ b/__tests__/components/backends/manage-backends-modal.test.tsx
@@ -11,8 +11,8 @@ import {
} from "#/contexts/active-backend-context";
import { ManageBackendsModal } from "#/components/features/backends/manage-backends-modal";
-vi.mock("#/api/typescript-client", () => ({
- createServerClient: vi.fn(() => ({
+vi.mock("@openhands/typescript-client/clients", () => ({
+ ServerClient: vi.fn(() => ({
getServerInfo: vi.fn().mockResolvedValue({ version: "1.18.0" }),
})),
}));
@@ -80,9 +80,7 @@ describe("ManageBackendsModal", () => {
await user.click(screen.getByTestId("manage-backends-add"));
- expect(
- await screen.findByTestId("add-backend-modal"),
- ).toBeInTheDocument();
+ expect(await screen.findByTestId("add-backend-modal")).toBeInTheDocument();
});
it("opens an edit form pre-filled with the row's backend, and persists changes via updateBackend", async () => {
@@ -109,11 +107,15 @@ describe("ManageBackendsModal", () => {
);
await screen.findByTestId("edit-backend-modal");
- const nameInput = screen.getByTestId("edit-backend-name") as HTMLInputElement;
+ const nameInput = screen.getByTestId(
+ "edit-backend-name",
+ ) as HTMLInputElement;
expect(nameInput.value).toBe("Acme Local");
// Update the host and save.
- const hostInput = screen.getByTestId("edit-backend-host") as HTMLInputElement;
+ const hostInput = screen.getByTestId(
+ "edit-backend-host",
+ ) as HTMLInputElement;
await user.clear(hostInput);
await user.type(hostInput, "http://localhost:9999");
diff --git a/__tests__/components/features/home/workspace-selection-form.test.tsx b/__tests__/components/features/home/workspace-selection-form.test.tsx
index 738139c765..a68227d468 100644
--- a/__tests__/components/features/home/workspace-selection-form.test.tsx
+++ b/__tests__/components/features/home/workspace-selection-form.test.tsx
@@ -2,16 +2,19 @@ import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, vi, beforeEach, it } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-
import { WorkspaceSelectionForm } from "../../../../src/components/features/home/workspace-selection-form";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
-import FilesService from "#/api/files-service/files-service.api";
import { useWorkspacesStore } from "#/stores/workspaces-store";
import { LocalWorkspace } from "#/types/workspace";
const mockNavigate = vi.fn();
const mockUseIsCreatingConversation = vi.fn();
+const { mockSearchSubdirectories, mockGetHome } = vi.hoisted(() => ({
+ mockSearchSubdirectories: vi.fn(),
+ mockGetHome: vi.fn(),
+}));
+
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
@@ -36,6 +39,21 @@ vi.mock("#/hooks/use-tracking", () => ({
}),
}));
+vi.mock("@openhands/typescript-client/clients", async () => {
+ const actual = await vi.importActual<
+ typeof import("@openhands/typescript-client/clients")
+ >("@openhands/typescript-client/clients");
+ return {
+ ...actual,
+ FileClient: vi.fn(function FileClientMock() {
+ return {
+ searchSubdirectories: mockSearchSubdirectories,
+ getHome: mockGetHome,
+ };
+ }),
+ };
+});
+
mockUseIsCreatingConversation.mockReturnValue(false);
function makeStartTask(overrides: Record<string, unknown> = {}) {
@@ -82,46 +100,46 @@ function renderForm(
describe("WorkspaceSelectionForm", () => {
beforeEach(() => {
vi.clearAllMocks();
- vi.restoreAllMocks();
+ mockSearchSubdirectories.mockReset();
+ mockGetHome.mockReset();
mockUseIsCreatingConversation.mockReturnValue(false);
+ mockGetHome.mockResolvedValue({ home: "/Users/me" });
useWorkspacesStore.setState({ workspaces: [], workspaceParents: [] });
// `useResolvedWorkspaces` always queries an implicit `/projects` parent
// (the dev:docker mount point). Default it to empty so tests that don't
// care about it don't hit a real network call. Tests that need specific
// behavior can replace this with their own spy.
- vi.spyOn(FilesService, "searchSubdirs").mockResolvedValue({
+ mockSearchSubdirectories.mockResolvedValue({
items: [],
next_page_id: null,
});
});
it("Add Workspace adds only the chosen folder (not its subfolders) and dedupes on repeat", async () => {
- vi.spyOn(FilesService, "getHome").mockResolvedValue({
- home: "/Users/me",
- favorites: [],
- locations: [{ label: "/", path: "/" }],
+
+ mockGetHome.mockResolvedValue({ home: "/Users/me" });
+ const searchSpy = mockSearchSubdirectories;
+
+ mockSearchSubdirectories.mockImplementation(async (path: string) => {
+ if (path === "/Users/me") {
+ return {
+ items: [{ name: "dev", path: "/Users/me/dev" }],
+ next_page_id: null,
+ };
+ }
+ if (path === "/Users/me/dev") {
+ return {
+ items: [
+ { name: "repo1", path: "/Users/me/dev/repo1" },
+ { name: "repo2", path: "/Users/me/dev/repo2" },
+ { name: "repo3", path: "/Users/me/dev/repo3" },
+ ],
+ next_page_id: null,
+ };
+ }
+ throw new Error(`unexpected path ${path}`);
});
- const searchSpy = vi
- .spyOn(FilesService, "searchSubdirs")
- .mockImplementation(async (path: string) => {
- if (path === "/Users/me") {
- return {
- items: [{ name: "dev", path: "/Users/me/dev" }],
- next_page_id: null,
- };
- }
- if (path === "/Users/me/dev") {
- return {
- items: [
- { name: "repo1", path: "/Users/me/dev/repo1" },
- { name: "repo2", path: "/Users/me/dev/repo2" },
- { name: "repo3", path: "/Users/me/dev/repo3" },
- ],
- next_page_id: null,
- };
- }
- throw new Error(`unexpected path ${path}`);
- });
+
// Pre-seed one workspace to verify dedup
renderForm([{ id: "/Users/me/dev", name: "dev", path: "/Users/me/dev" }]);
@@ -231,20 +249,20 @@ describe("WorkspaceSelectionForm", () => {
});
it("Implicit /projects parent surfaces workspaces automatically", async () => {
- const searchSpy = vi
- .spyOn(FilesService, "searchSubdirs")
- .mockImplementation(async (path: string) => {
- if (path === "/projects") {
- return {
- items: [
- { name: "agent-canvas", path: "/projects/agent-canvas" },
- { name: "sdk", path: "/projects/sdk" },
- ],
- next_page_id: null,
- };
- }
- return { items: [], next_page_id: null };
- });
+ const searchSpy = mockSearchSubdirectories;
+
+ mockSearchSubdirectories.mockImplementation(async (path: string) => {
+ if (path === "/projects") {
+ return {
+ items: [
+ { name: "agent-canvas", path: "/projects/agent-canvas" },
+ { name: "sdk", path: "/projects/sdk" },
+ ],
+ next_page_id: null,
+ };
+ }
+ return { items: [], next_page_id: null };
+ });
renderForm();
const user = userEvent.setup();
@@ -258,9 +276,10 @@ describe("WorkspaceSelectionForm", () => {
});
it("A stored /projects parent suppresses the implicit duplicate query", async () => {
- const searchSpy = vi
- .spyOn(FilesService, "searchSubdirs")
- .mockResolvedValue({ items: [], next_page_id: null });
+ const searchSpy = mockSearchSubdirectories.mockResolvedValue({
+ items: [],
+ next_page_id: null,
+ });
renderForm(
[],
@@ -319,9 +338,7 @@ describe("WorkspaceSelectionForm", () => {
});
it("disables the workspace dropdown while parent workspaces are loading", async () => {
- vi.spyOn(FilesService, "searchSubdirs").mockReturnValue(
- new Promise(() => {}) as never,
- );
+ mockSearchSubdirectories.mockReturnValue(new Promise(() => {}) as never);
renderForm(
[],
@@ -335,31 +352,29 @@ describe("WorkspaceSelectionForm", () => {
});
it("Add all subdirectories saves a workspace parent and lists its children dynamically", async () => {
- vi.spyOn(FilesService, "getHome").mockResolvedValue({
- home: "/Users/me",
- favorites: [],
- locations: [{ label: "/", path: "/" }],
+
+ mockGetHome.mockResolvedValue({ home: "/Users/me" });
+ const searchSpy = mockSearchSubdirectories;
+
+ mockSearchSubdirectories.mockImplementation(async (path: string) => {
+ if (path === "/Users/me") {
+ return {
+ items: [{ name: "dev", path: "/Users/me/dev" }],
+ next_page_id: null,
+ };
+ }
+ if (path === "/Users/me/dev") {
+ return {
+ items: [
+ { name: "repo1", path: "/Users/me/dev/repo1" },
+ { name: "repo2", path: "/Users/me/dev/repo2" },
+ ],
+ next_page_id: null,
+ };
+ }
+ throw new Error(`unexpected path ${path}`);
});
- const searchSpy = vi
- .spyOn(FilesService, "searchSubdirs")
- .mockImplementation(async (path: string) => {
- if (path === "/Users/me") {
- return {
- items: [{ name: "dev", path: "/Users/me/dev" }],
- next_page_id: null,
- };
- }
- if (path === "/Users/me/dev") {
- return {
- items: [
- { name: "repo1", path: "/Users/me/dev/repo1" },
- { name: "repo2", path: "/Users/me/dev/repo2" },
- ],
- next_page_id: null,
- };
- }
- throw new Error(`unexpected path ${path}`);
- });
+
renderForm();
const user = userEvent.setup();
@@ -401,20 +416,20 @@ describe("WorkspaceSelectionForm", () => {
// Scope the mock to the user-added parent so the implicit `/projects`
// parent (always queried by `useResolvedWorkspaces`) doesn't also get
// these entries.
- const searchSpy = vi
- .spyOn(FilesService, "searchSubdirs")
- .mockImplementation(async (path: string) => {
- if (path === "/Users/me/dev") {
- return {
- items: [
- { name: "repoA", path: "/Users/me/dev/repoA" },
- { name: "repoB", path: "/Users/me/dev/repoB" },
- ],
- next_page_id: null,
- };
- }
- return { items: [], next_page_id: null };
- });
+ const searchSpy = mockSearchSubdirectories;
+
+ mockSearchSubdirectories.mockImplementation(async (path: string) => {
+ if (path === "/Users/me/dev") {
+ return {
+ items: [
+ { name: "repoA", path: "/Users/me/dev/repoA" },
+ { name: "repoB", path: "/Users/me/dev/repoB" },
+ ],
+ next_page_id: null,
+ };
+ }
+ return { items: [], next_page_id: null };
+ });
renderForm(
[],
@@ -471,22 +486,21 @@ describe("WorkspaceSelectionForm", () => {
// Arrange: backend reports a home with a custom favorite that did NOT
// exist in the old hardcoded list (Documents / Desktop / Downloads).
// This is the regression guard for the original 404-on-navigate bug.
- vi.spyOn(FilesService, "getHome").mockResolvedValue({
+ mockGetHome.mockResolvedValue({
home: "/Users/me",
favorites: [{ label: "projects", path: "/Users/me/projects" }],
locations: [{ label: "/", path: "/" }],
});
- const searchSpy = vi
- .spyOn(FilesService, "searchSubdirs")
- .mockImplementation(async (path: string) => {
- if (path === "/Users/me/projects") {
- return {
- items: [{ name: "repo1", path: "/Users/me/projects/repo1" }],
- next_page_id: null,
- };
- }
- return { items: [], next_page_id: null };
- });
+ const searchSpy = mockSearchSubdirectories;
+ mockSearchSubdirectories.mockImplementation(async (path: string) => {
+ if (path === "/Users/me/projects") {
+ return {
+ items: [{ name: "repo1", path: "/Users/me/projects/repo1" }],
+ next_page_id: null,
+ };
+ }
+ return { items: [], next_page_id: null };
+ });
renderForm();
const user = userEvent.setup();
diff --git a/__tests__/components/modals/skills/skill-modal.test.tsx b/__tests__/components/modals/skills/skill-modal.test.tsx
index 78853f2506..a7f61bf748 100644
--- a/__tests__/components/modals/skills/skill-modal.test.tsx
+++ b/__tests__/components/modals/skills/skill-modal.test.tsx
@@ -3,10 +3,14 @@ import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderWithProviders } from "test-utils";
import { SkillsModal } from "#/components/features/conversation-panel/skills-modal";
-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { loadSkillsForConversation } from "#/api/agent-server-adapter";
import { AgentState } from "#/types/agent-state";
import { useAgentState } from "#/hooks/use-agent-state";
+vi.mock("#/api/agent-server-adapter", () => ({
+ loadSkillsForConversation: vi.fn(),
+}));
+
// Mock the agent state hook
vi.mock("#/hooks/use-agent-state", () => ({
useAgentState: vi.fn(),
@@ -54,8 +58,8 @@ describe("SkillsModal", () => {
// Reset all mocks before each test
vi.clearAllMocks();
- // Setup default mock for getSkills (agent-server)
- vi.spyOn(AgentServerConversationService, "getSkills").mockResolvedValue({
+ // Setup default mock for skills loading
+ vi.mocked(loadSkillsForConversation).mockResolvedValue({
skills: mockSkills,
});
@@ -83,7 +87,7 @@ describe("SkillsModal", () => {
describe("Refresh Button Functionality", () => {
it("should call refetch when refresh button is clicked", async () => {
const user = userEvent.setup();
- const refreshSpy = vi.spyOn(AgentServerConversationService, "getSkills");
+ const refreshSpy = vi.mocked(loadSkillsForConversation);
renderWithProviders(<SkillsModal {...defaultProps} />);
@@ -102,7 +106,7 @@ describe("SkillsModal", () => {
describe("Skills Display", () => {
it("should display skills correctly", async () => {
- vi.spyOn(AgentServerConversationService, "getSkills").mockResolvedValue({
+ vi.mocked(loadSkillsForConversation).mockResolvedValue({
skills: mockSkills,
});
diff --git a/__tests__/components/onboarding/onboarding-modal.test.tsx b/__tests__/components/onboarding/onboarding-modal.test.tsx
index 22e5d89831..a83c96042f 100644
--- a/__tests__/components/onboarding/onboarding-modal.test.tsx
+++ b/__tests__/components/onboarding/onboarding-modal.test.tsx
@@ -12,10 +12,12 @@ import { NavigationProvider } from "#/context/navigation-context";
// Both the backend status badge in the embedded edit form and the
// step-1 health probe ride on `useBackendsHealth`, which itself
// resolves through these two clients.
-vi.mock("#/api/typescript-client", () => ({
- createServerClient: vi.fn(() => ({
- getServerInfo: vi.fn().mockResolvedValue({ version: "1.18.0" }),
- })),
+vi.mock("@openhands/typescript-client/clients", () => ({
+ ServerClient: vi.fn(function ServerClientMock() {
+ return {
+ getServerInfo: vi.fn().mockResolvedValue({ version: "1.18.0" }),
+ };
+ }),
}));
vi.mock("#/api/cloud/organization-service.api", () => ({
@@ -96,26 +98,28 @@ describe("OnboardingModal", () => {
"data-active",
"true",
);
- expect(
- screen.getByTestId("onboarding-slide-0").style.transform,
- ).toBe("translateX(0%)");
- expect(
- screen.getByTestId("onboarding-slide-1").style.transform,
- ).toBe("translateX(100%)");
- expect(
- screen.getByTestId("onboarding-slide-2").style.transform,
- ).toBe("translateX(200%)");
- expect(
- screen.getByTestId("onboarding-slide-3").style.transform,
- ).toBe("translateX(300%)");
+ expect(screen.getByTestId("onboarding-slide-0").style.transform).toBe(
+ "translateX(0%)",
+ );
+ expect(screen.getByTestId("onboarding-slide-1").style.transform).toBe(
+ "translateX(100%)",
+ );
+ expect(screen.getByTestId("onboarding-slide-2").style.transform).toBe(
+ "translateX(200%)",
+ );
+ expect(screen.getByTestId("onboarding-slide-3").style.transform).toBe(
+ "translateX(300%)",
+ );
// Progress bar reflects step 1 of 4.
- expect(
- screen.getByTestId("onboarding-progress-step-0"),
- ).toHaveAttribute("data-state", "current");
- expect(
- screen.getByTestId("onboarding-progress-step-1"),
- ).toHaveAttribute("data-state", "upcoming");
+ expect(screen.getByTestId("onboarding-progress-step-0")).toHaveAttribute(
+ "data-state",
+ "current",
+ );
+ expect(screen.getByTestId("onboarding-progress-step-1")).toHaveAttribute(
+ "data-state",
+ "upcoming",
+ );
});
it("advances each step via the per-step Next button and reframes slide offsets", async () => {
@@ -134,21 +138,19 @@ describe("OnboardingModal", () => {
"data-active",
"true",
);
- expect(
- screen.getByTestId("onboarding-slide-0").style.transform,
- ).toBe("translateX(-100%)");
- expect(
- screen.getByTestId("onboarding-slide-1").style.transform,
- ).toBe("translateX(0%)");
- expect(
- screen.getByTestId("onboarding-slide-2").style.transform,
- ).toBe("translateX(100%)");
+ expect(screen.getByTestId("onboarding-slide-0").style.transform).toBe(
+ "translateX(-100%)",
+ );
+ expect(screen.getByTestId("onboarding-slide-1").style.transform).toBe(
+ "translateX(0%)",
+ );
+ expect(screen.getByTestId("onboarding-slide-2").style.transform).toBe(
+ "translateX(100%)",
+ );
// Once the backend health probe resolves, step 1's Next is enabled.
await waitFor(() =>
- expect(
- screen.getByTestId("onboarding-backend-next"),
- ).not.toBeDisabled(),
+ expect(screen.getByTestId("onboarding-backend-next")).not.toBeDisabled(),
);
await user.click(screen.getByTestId("onboarding-backend-next"));
expect(screen.getByTestId("onboarding-modal")).toHaveAttribute(
@@ -170,9 +172,9 @@ describe("OnboardingModal", () => {
"data-active",
"true",
);
- expect(
- screen.getByTestId("onboarding-slide-3").style.transform,
- ).toBe("translateX(0%)");
+ expect(screen.getByTestId("onboarding-slide-3").style.transform).toBe(
+ "translateX(0%)",
+ );
});
it("Skip immediately closes the modal", async () => {
@@ -230,9 +232,7 @@ describe("OnboardingModal", () => {
await user.click(screen.getByTestId("onboarding-agent-next"));
await waitFor(() =>
- expect(
- screen.getByTestId("onboarding-backend-next"),
- ).not.toBeDisabled(),
+ expect(screen.getByTestId("onboarding-backend-next")).not.toBeDisabled(),
);
await user.click(screen.getByTestId("onboarding-backend-next"));
await user.click(screen.getByTestId("onboarding-llm-next"));
diff --git a/__tests__/hooks/mutation/use-resume-conversation.test.tsx b/__tests__/hooks/mutation/use-resume-conversation.test.tsx
index 07ef2b5957..af76faabdd 100644
--- a/__tests__/hooks/mutation/use-resume-conversation.test.tsx
+++ b/__tests__/hooks/mutation/use-resume-conversation.test.tsx
@@ -1,10 +1,21 @@
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { ConversationClient } from "@openhands/typescript-client/clients";
import { describe, expect, it, vi, beforeEach } from "vitest";
import React from "react";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import { useResumeConversation } from "#/hooks/mutation/use-resume-conversation";
+const { runConversationMock } = vi.hoisted(() => ({
+ runConversationMock: vi.fn(),
+}));
+
+vi.mock("@openhands/typescript-client/clients", () => ({
+ ConversationClient: vi.fn(function ConversationClientMock() {
+ return { runConversation: runConversationMock };
+ }),
+}));
+
describe("useResumeConversation", () => {
let queryClient: QueryClient;
@@ -16,6 +27,8 @@ describe("useResumeConversation", () => {
},
});
vi.restoreAllMocks();
+ runConversationMock.mockReset().mockResolvedValue({ success: true });
+ vi.mocked(ConversationClient).mockClear();
});
const wrapper = ({ children }: { children: React.ReactNode }) => (
@@ -48,10 +61,6 @@ describe("useResumeConversation", () => {
updated_at: new Date().toISOString(),
},
]);
- vi.spyOn(AgentServerConversationService, "resumeConversation").mockResolvedValue({
- success: true,
- });
-
const invalidateSpy = vi.spyOn(queryClient, "invalidateQueries");
const { result } = renderHook(() => useResumeConversation(), { wrapper });
diff --git a/__tests__/hooks/query/use-backends-health.test.tsx b/__tests__/hooks/query/use-backends-health.test.tsx
index cf16705966..4b0922287d 100644
--- a/__tests__/hooks/query/use-backends-health.test.tsx
+++ b/__tests__/hooks/query/use-backends-health.test.tsx
@@ -1,3 +1,4 @@
+import { ServerClient } from "@openhands/typescript-client/clients";
import React from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { renderHook, waitFor } from "@testing-library/react";
@@ -9,8 +10,10 @@ import { useBackendsHealth } from "#/hooks/query/use-backends-health";
const getServerInfoMock = vi.fn();
const getCurrentCloudApiKeyMock = vi.fn();
-vi.mock("#/api/typescript-client", () => ({
- createServerClient: () => ({ getServerInfo: getServerInfoMock }),
+vi.mock("@openhands/typescript-client/clients", () => ({
+ ServerClient: vi.fn(function ServerClientMock() {
+ return { getServerInfo: getServerInfoMock };
+ }),
}));
vi.mock("#/api/cloud/organization-service.api", () => ({
@@ -38,14 +41,13 @@ function wrapper({ children }: { children: React.ReactNode }) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
- return (
- <QueryClientProvider client={client}>{children}</QueryClientProvider>
- );
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
}
beforeEach(() => {
getServerInfoMock.mockReset();
getCurrentCloudApiKeyMock.mockReset();
+ vi.mocked(ServerClient).mockClear();
});
afterEach(() => {
diff --git a/__tests__/hooks/query/use-workspace-file-content.test.tsx b/__tests__/hooks/query/use-workspace-file-content.test.tsx
new file mode 100644
index 0000000000..a731403a85
--- /dev/null
+++ b/__tests__/hooks/query/use-workspace-file-content.test.tsx
@@ -0,0 +1,147 @@
+import React from "react";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { useWorkspaceFileContent } from "#/hooks/query/use-workspace-file-content";
+import { useWorkspaceMutationCounter } from "#/stores/use-workspace-mutation-counter";
+
+const { downloadFileMock, fileClientMock } = vi.hoisted(() => {
+ const downloadFile = vi.fn();
+ return {
+ downloadFileMock: downloadFile,
+ fileClientMock: vi.fn(function FileClientMock() {
+ return { downloadFile };
+ }),
+ };
+});
+
+vi.mock("@openhands/typescript-client/clients", () => ({
+ FileClient: fileClientMock,
+}));
+
+vi.mock("#/api/agent-server-client-options", () => ({
+ getAgentServerClientOptions: vi.fn(() => ({
+ host: "https://agent.example.com",
+ apiKey: "session-key",
+ workingDir: "/workspace/project",
+ })),
+}));
+
+const useActiveConversationMock = vi.fn();
+vi.mock("#/hooks/query/use-active-conversation", () => ({
+ useActiveConversation: () => useActiveConversationMock(),
+}));
+
+const useRuntimeIsReadyMock = vi.fn();
+vi.mock("#/hooks/use-runtime-is-ready", () => ({
+ useRuntimeIsReady: () => useRuntimeIsReadyMock(),
+}));
+
+function makeWrapper() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const Wrapper = function WorkspaceFileContentTestWrapper({
+ children,
+ }: {
+ children: React.ReactNode;
+ }) {
+ return (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ };
+ return Wrapper;
+}
+
+describe("useWorkspaceFileContent", () => {
+ beforeEach(() => {
+ Object.defineProperty(URL, "createObjectURL", {
+ configurable: true,
+ value: vi.fn(() => "blob:preview-url"),
+ });
+ useWorkspaceMutationCounter.setState({ count: 0 });
+ fileClientMock.mockClear();
+ downloadFileMock.mockReset();
+ useActiveConversationMock.mockReset();
+ useRuntimeIsReadyMock.mockReset();
+ useRuntimeIsReadyMock.mockReturnValue(true);
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ id: "conv-1",
+ conversation_url: "https://agent.example.com/api/conversations/conv-1",
+ session_api_key: "session-key",
+ workspace: { working_dir: "/workspace/project/agent-canvas" },
+ },
+ });
+ });
+
+ it("downloads selected files through the typed file API", async () => {
+ downloadFileMock.mockResolvedValue(
+ new TextEncoder().encode("# Hello").buffer,
+ );
+
+ const { result } = renderHook(
+ () => useWorkspaceFileContent("docs/readme.md"),
+ { wrapper: makeWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(downloadFileMock).toHaveBeenCalledWith(
+ "/workspace/project/agent-canvas/docs/readme.md",
+ );
+ expect(result.current.data).toMatchObject({
+ kind: "text",
+ text: "# Hello",
+ staticUrl: "blob:preview-url",
+ mimeType: "text/markdown",
+ });
+ });
+
+ it("refetches selected file content after workspace mutations", async () => {
+ downloadFileMock
+ .mockResolvedValueOnce(new TextEncoder().encode("first").buffer)
+ .mockResolvedValueOnce(new TextEncoder().encode("second").buffer);
+
+ const { result } = renderHook(
+ () => useWorkspaceFileContent("docs/readme.md"),
+ { wrapper: makeWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.data?.text).toBe("first"));
+
+ act(() => {
+ useWorkspaceMutationCounter.getState().bump();
+ });
+
+ await waitFor(() => expect(result.current.data?.text).toBe("second"));
+ expect(downloadFileMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not start a file request before a path is selected", async () => {
+ renderHook(() => useWorkspaceFileContent(null), { wrapper: makeWrapper() });
+
+ await new Promise((resolve) => {
+ setTimeout(resolve, 10);
+ });
+
+ expect(fileClientMock).not.toHaveBeenCalled();
+ expect(downloadFileMock).not.toHaveBeenCalled();
+ });
+
+ it("rejects traversal outside the workspace", async () => {
+ const { result } = renderHook(() => useWorkspaceFileContent("../.env"), {
+ wrapper: makeWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+
+ expect(downloadFileMock).not.toHaveBeenCalled();
+ expect(result.current.error).toEqual(
+ expect.objectContaining({
+ message: "Workspace file path must stay inside the workspace",
+ }),
+ );
+ });
+});
diff --git a/__tests__/hooks/query/use-workspace-session.test.tsx b/__tests__/hooks/query/use-workspace-session.test.tsx
index 88dae68702..751f193159 100644
--- a/__tests__/hooks/query/use-workspace-session.test.tsx
+++ b/__tests__/hooks/query/use-workspace-session.test.tsx
@@ -1,4 +1,5 @@
import React from "react";
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -8,24 +9,18 @@ import {
useWorkspaceSession,
} from "#/hooks/query/use-workspace-session";
-// We mock the workspace factory rather than the lower-level HttpClient:
+// We mock the SDK workspace rather than the lower-level HttpClient:
// that's where our wiring contract lives (we hand the typescript-client a
// conversation id and trust it to do the right POST + return a base URL).
const startWorkspaceSessionMock = vi.fn();
-const createRemoteWorkspaceMock = vi.fn();
-
-vi.mock("#/api/typescript-client", async (importOriginal) => {
- const real = await importOriginal<typeof import("#/api/typescript-client")>();
- return {
- ...real,
- createRemoteWorkspace: (...args: unknown[]) => {
- createRemoteWorkspaceMock(...args);
- return {
- startWorkspaceSession: startWorkspaceSessionMock,
- };
- },
- };
-});
+
+vi.mock("@openhands/typescript-client/workspace/remote-workspace", () => ({
+ RemoteWorkspace: vi.fn(function RemoteWorkspaceMock() {
+ return {
+ startWorkspaceSession: startWorkspaceSessionMock,
+ };
+ }),
+}));
const useActiveConversationMock = vi.fn();
vi.mock("#/hooks/query/use-active-conversation", () => ({
@@ -65,7 +60,7 @@ function flushScheduler(ms = 10): Promise<void> {
beforeEach(() => {
startWorkspaceSessionMock.mockReset();
- createRemoteWorkspaceMock.mockReset();
+ vi.mocked(RemoteWorkspace).mockClear();
useActiveConversationMock.mockReset();
useRuntimeIsReadyMock.mockReset();
useRuntimeIsReadyMock.mockReturnValue(true);
@@ -98,10 +93,11 @@ describe("useWorkspaceSession", () => {
);
});
- expect(createRemoteWorkspaceMock).toHaveBeenCalledTimes(1);
- expect(createRemoteWorkspaceMock).toHaveBeenCalledWith({
- conversationUrl: "https://agent.example.com/api/conversations/conv-1",
- sessionApiKey: "key-abc",
+ expect(RemoteWorkspace).toHaveBeenCalledTimes(1);
+ expect(RemoteWorkspace).toHaveBeenCalledWith({
+ host: "http://agent.example.com",
+ apiKey: "key-abc",
+ workingDir: "workspace/project",
});
expect(startWorkspaceSessionMock).toHaveBeenCalledTimes(1);
expect(startWorkspaceSessionMock).toHaveBeenCalledWith("conv-1");
diff --git a/__tests__/routes/files-tab.test.tsx b/__tests__/routes/files-tab.test.tsx
index 272885a0f2..4f96e403b2 100644
--- a/__tests__/routes/files-tab.test.tsx
+++ b/__tests__/routes/files-tab.test.tsx
@@ -360,7 +360,7 @@ describe("FilesTab", () => {
).not.toBeInTheDocument();
});
- it("uses the static workspace URL as the iframe src for HTML files", async () => {
+ it("uses the browser preview URL as the iframe src for HTML files", async () => {
useHasAttachedSourceMock.mockReturnValue({
hasAttachedSource: false,
isLoading: false,
@@ -369,8 +369,7 @@ describe("FilesTab", () => {
data: ["index.html"],
isLoading: false,
});
- const staticUrl =
- "http://localhost:3000/api/conversations/abc/workspace/index.html";
+ const staticUrl = "blob:preview-url";
useWorkspaceFileContentMock.mockReturnValue({
data: {
path: "index.html",
@@ -387,18 +386,14 @@ describe("FilesTab", () => {
const iframe = await screen.findByTestId("file-content-viewer-iframe");
expect(iframe).toBeInTheDocument();
- // The iframe src starts with the workspace static URL and carries the
- // mutation-counter cache-buster (`?v=<n>`) so browser-cached responses
- // are invalidated whenever the agent edits a file.
- expect(iframe.getAttribute("src")).toMatch(
- new RegExp(`^${staticUrl.replace(/[/.]/g, "\\$&")}\\?v=\\d+$`),
- );
- // The iframe is sandboxed with `allow-same-origin` only: relative
- // asset refs (CSS, images) load from the workspace fileserver
- // origin, but `<script>` / inline event handlers inside the
- // previewed file are inert. We deliberately do NOT add
- // `allow-scripts` β€” a workspace HTML file's scripts must not run in
- // the canvas's context.
+ // The iframe src uses the hook-provided browser preview URL directly;
+ // mutation freshness is handled by the hook's query key, not by mutating
+ // Blob URLs with cache-buster query params.
+ expect(iframe).toHaveAttribute("src", staticUrl);
+ // The iframe is sandboxed with `allow-same-origin` only: `<script>` /
+ // inline event handlers inside the previewed file are inert. We deliberately
+ // do NOT add `allow-scripts` β€” a workspace HTML file's scripts must not run
+ // in the canvas's context.
expect(iframe).toHaveAttribute("sandbox", "allow-same-origin");
});
diff --git a/src/api/README.md b/src/api/README.md
index 08cfd983d4..0c4a44d6c1 100644
--- a/src/api/README.md
+++ b/src/api/README.md
@@ -2,7 +2,9 @@
## Overview
-Services are the abstraction layer between frontend components and backend APIs. They encapsulate HTTP requests using `createHttpClient()` from `@openhands/typescript-client` (wrapped in `src/api/typescript-client.ts`, which resolves the active backend's host + `X-Session-API-Key`) and provide typed methods for each endpoint.
+Services are the abstraction layer between frontend components and backend APIs. Local agent-server API access should use `@openhands/typescript-client` classes directly, with shared connection options from `src/api/agent-server-client-options.ts` for the active local backend host, session API key, and workspace defaults.
+
+Cloud-specific APIs should use the cloud service modules/proxy helpers instead of local agent-server clients.
Each service is a plain object with async methods.
@@ -12,42 +14,35 @@ Each service lives in its own directory:
```
src/api/
-β”œβ”€β”€ feature-service/
-β”‚ β”œβ”€β”€ feature-service.api.ts # Service methods
-β”‚ └── feature.types.ts # Types and interfaces
-└── typescript-client.ts # `createHttpClient` + typed SDK clients
+└── feature-service/
+ β”œβ”€β”€ feature-service.api.ts # Service methods
+ └── feature.types.ts # Types and interfaces
```
## Creating a Service
-Use an object literal with named export. Use object destructuring for parameters to make calls self-documenting.
+Use an object literal with named export. Use object destructuring for parameters to make calls self-documenting. Prefer typed `@openhands/typescript-client` classes over generic HTTP calls. If a needed endpoint is missing, add it to `@openhands/typescript-client` first.
```typescript
// feature-service/feature-service.api.ts
-import { createHttpClient } from "../typescript-client";
+import { FeatureClient } from "@openhands/typescript-client/clients";
+import { getAgentServerClientOptions } from "../agent-server-client-options";
import { Feature, CreateFeatureParams } from "./feature.types";
export const featureService = {
- getFeature: async ({ id }: { id: string }) => {
- const response = await createHttpClient().get<Feature>(
- `/api/features/${id}`,
- );
- return response.data;
+ getFeature: async ({ id }: { id: string }): Promise<Feature> => {
+ return new FeatureClient(getAgentServerClientOptions()).getFeature(id);
},
- createFeature: async ({ name, description }: CreateFeatureParams) => {
- const response = await createHttpClient().post<Feature>("/api/features", {
- name,
- description,
- });
- return response.data;
+ createFeature: async (params: CreateFeatureParams): Promise<Feature> => {
+ return new FeatureClient(getAgentServerClientOptions()).createFeature(params);
},
};
```
### Types
-Define types in a separate file within the same directory:
+Define app-specific types in a separate file within the same directory when the TypeScript client models are not sufficient:
```typescript
// feature-service/feature.types.ts
@@ -69,12 +64,14 @@ export interface CreateFeatureParams {
> **Don't call services directly in components.** Wrap them in TanStack Query hooks.
>
> Why? TanStack Query provides:
+>
> - **Caching** - Avoid redundant network requests
> - **Deduplication** - Multiple components requesting the same data share one request
> - **Loading/error states** - Built-in `isLoading`, `isError`, `data` states
> - **Background refetching** - Data stays fresh automatically
>
> Hooks location:
+>
> - `src/hooks/query/` for data fetching (`useQuery`)
> - `src/hooks/mutation/` for writes/updates (`useMutation`)
@@ -93,9 +90,9 @@ export const useFeature = (id: string) => {
## Naming Conventions
-| Item | Convention | Example |
-|------|------------|---------|
-| Directory | `feature-service/` | `secrets-service/` |
+| Item | Convention | Example |
+| ------------ | ------------------------ | ------------------------ |
+| Directory | `feature-service/` | `secrets-service/` |
| Service file | `feature-service.api.ts` | `secrets-service.api.ts` |
-| Types file | `feature.types.ts` | `secrets.types.ts` |
-| Export name | `featureService` | `secretsService` |
+| Types file | `feature.types.ts` | `secrets.types.ts` |
+| Export name | `featureService` | `secretsService` |
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index 5429a40de1..c596db0883 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -1,3 +1,4 @@
+import { SkillsClient } from "@openhands/typescript-client/clients";
import { DEFAULT_SETTINGS } from "#/services/settings";
import { ExecutionStatus } from "#/types/agent-server/core";
import { Settings, SettingsValue } from "#/types/settings";
@@ -9,13 +10,12 @@ import {
import { getEffectiveLocalBackend } from "./backend-registry/active-store";
import { buildAuthHeaders } from "./backend-registry/auth";
import {
- GetHooksResponse,
GetSkillsResponse,
PluginSpec,
AppConversation,
AppConversationPage,
} from "./conversation-service/agent-server-conversation-service.types";
-import { createHttpClient, createSkillsClient } from "./typescript-client";
+import { getAgentServerClientOptions } from "./agent-server-client-options";
import SettingsService from "./settings-service/settings-service.api";
import { getStoredConversationMetadata } from "./conversation-metadata-store";
@@ -520,25 +520,15 @@ export async function buildStartConversationRequestWithEncryptedSettings(options
});
}
-export async function downloadTextFile(path: string): Promise<string> {
- const response = await createHttpClient().get<ArrayBuffer>(
- "/api/file/download",
- {
- params: { path },
- responseType: "arrayBuffer",
- },
- );
-
- return new TextDecoder().decode(response.data);
-}
-
export async function loadSkillsForConversation(
conversation: AppConversation | null | undefined,
): Promise<GetSkillsResponse> {
const projectDir =
conversation?.workspace?.working_dir ?? getAgentServerWorkingDir();
- const response = await createSkillsClient().getSkills({
+ const response = await new SkillsClient(
+ getAgentServerClientOptions(),
+ ).getSkills({
load_public: shouldLoadPublicSkills(),
load_user: true,
load_project: true,
@@ -548,7 +538,3 @@ export async function loadSkillsForConversation(
return { skills: response.skills ?? [] };
}
-
-export function emptyHooksResponse(): GetHooksResponse {
- return { hooks: [] };
-}
diff --git a/src/api/agent-server-client-options.ts b/src/api/agent-server-client-options.ts
new file mode 100644
index 0000000000..f6dd2c3d01
--- /dev/null
+++ b/src/api/agent-server-client-options.ts
@@ -0,0 +1,60 @@
+import { buildHttpBaseUrl } from "#/utils/websocket-url";
+import { getAgentServerWorkingDir } from "./agent-server-config";
+import { getEffectiveLocalBackend } from "./backend-registry/active-store";
+import type { Backend } from "./backend-registry/types";
+
+export interface AgentServerClientOverrides {
+ host?: string;
+ apiKey?: string | null;
+ sessionApiKey?: string | null;
+ workingDir?: string;
+ conversationUrl?: string | null;
+ timeout?: number;
+}
+
+export interface AgentServerClientOptions {
+ host: string;
+ apiKey?: string;
+ workingDir: string;
+ timeout?: number;
+}
+
+function normalizeHost(host: string): string {
+ return host.replace(/\/+$/, "");
+}
+
+function resolveHost(
+ overrides: AgentServerClientOverrides,
+ backend: Backend,
+): string {
+ if (overrides.host) return normalizeHost(overrides.host);
+ if (overrides.conversationUrl)
+ return normalizeHost(buildHttpBaseUrl(overrides.conversationUrl));
+ return normalizeHost(backend.host);
+}
+
+export function getAgentServerClientOptions(
+ overrides: AgentServerClientOverrides = {},
+): AgentServerClientOptions {
+ const backend = getEffectiveLocalBackend();
+ const apiKey =
+ overrides.sessionApiKey ?? overrides.apiKey ?? backend.apiKey ?? undefined;
+
+ return {
+ host: resolveHost(overrides, backend),
+ ...(apiKey ? { apiKey } : {}),
+ workingDir: overrides.workingDir ?? getAgentServerWorkingDir(),
+ ...(overrides.timeout !== undefined ? { timeout: overrides.timeout } : {}),
+ };
+}
+
+export function getAgentServerHttpClientOptions(
+ overrides?: AgentServerClientOverrides,
+) {
+ const { host, apiKey, timeout } = getAgentServerClientOptions(overrides);
+ return {
+ baseUrl: host,
+ ...(apiKey ? { apiKey } : {}),
+ timeout: timeout ?? 60000,
+ };
+}
diff --git a/src/api/agent-server-compatibility.ts b/src/api/agent-server-compatibility.ts
index e3ee6b1e0d..fa7f20ff27 100644
--- a/src/api/agent-server-compatibility.ts
+++ b/src/api/agent-server-compatibility.ts
@@ -1,9 +1,8 @@
+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";
-import {
- createServerClient,
- type ServerInfo as BaseServerInfo,
-} from "#/api/typescript-client";
const AGENT_SERVER_INFO_TIMEOUT_MS = 5000;
@@ -62,11 +61,13 @@ export async function loadAgentServerInfo() {
let serverInfo: AgentServerInfo;
try {
- serverInfo = (await createServerClient({
- host: local.host,
- sessionApiKey: local.apiKey || null,
- timeout: AGENT_SERVER_INFO_TIMEOUT_MS,
- }).getServerInfo()) as AgentServerInfo;
+ serverInfo = (await new ServerClient(
+ getAgentServerClientOptions({
+ host: local.host,
+ sessionApiKey: local.apiKey || null,
+ timeout: AGENT_SERVER_INFO_TIMEOUT_MS,
+ }),
+ ).getServerInfo()) as AgentServerInfo;
} catch (error) {
clearCachedAgentServerInfo();
if (error instanceof HttpError) {
diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.ts
index 10e771e58b..fcb999eedf 100644
--- a/src/api/automation-service/automation-service.api.ts
+++ b/src/api/automation-service/automation-service.api.ts
@@ -21,7 +21,7 @@ export interface AutomationHealthResponse {
// `scripts/dev-with-automation.mjs` mounts behind the local agent-server.
// That sidecar authenticates via its own `VITE_AUTOMATION_API_KEY` Bearer
// token β€” NOT the agent-server's `X-Session-API-Key` β€” so we cannot reuse
-// the shared `createHttpClient()` instance for these calls.
+// the default local agent-server client for these calls.
const localAutomationAxios = axios.create();
localAutomationAxios.interceptors.request.use((config) => {
diff --git a/src/api/cloud/proxy.ts b/src/api/cloud/proxy.ts
index 4fc84ff984..76ba6a37dd 100644
--- a/src/api/cloud/proxy.ts
+++ b/src/api/cloud/proxy.ts
@@ -92,8 +92,8 @@ export async function callCloudProxy<TResponse = unknown>(
};
const upstreamHost = req.hostOverride ?? req.backend.host;
- // Talk directly to the local agent-server, bypassing the shared
- // `createHttpClient()` resolver (which would otherwise read host + auth
+ // Talk directly to the local agent-server, bypassing the global
+ // local agent-server client configuration (which would otherwise read host + auth
// from the active backend β€” wrong for this call: we need the local
// backend's host and session key explicitly, not the active one).
const response = await axios.post<TResponse>(
diff --git a/src/api/config-service/config-service.api.ts b/src/api/config-service/config-service.api.ts
index fed54c4a9e..0aefa0490c 100644
--- a/src/api/config-service/config-service.api.ts
+++ b/src/api/config-service/config-service.api.ts
@@ -1,4 +1,5 @@
-import { createLlmMetadataClient } from "../typescript-client";
+import { LLMMetadataClient } from "@openhands/typescript-client/clients";
+import { getAgentServerClientOptions } from "../agent-server-client-options";
import type {
LLMModel,
LLMModelPage,
@@ -46,7 +47,7 @@ class ConfigService {
params: SearchModelsParams = {},
verifiedByProvider?: Record<string, string[]>,
): Promise<LLMModelPage> {
- const llmClient = createLlmMetadataClient();
+ const llmClient = new LLMMetadataClient(getAgentServerClientOptions());
const verifiedFetch =
verifiedByProvider !== undefined
? Promise.resolve(verifiedByProvider)
@@ -96,7 +97,7 @@ class ConfigService {
params: SearchProvidersParams = {},
verifiedByProvider?: Record<string, string[]>,
): Promise<ProviderPage> {
- const llmClient = createLlmMetadataClient();
+ const llmClient = new LLMMetadataClient(getAgentServerClientOptions());
const verifiedFetch =
verifiedByProvider !== undefined
? Promise.resolve(verifiedByProvider)
diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.ts
index 9b75b82492..ef2c78870a 100644
--- a/src/api/conversation-service/agent-server-conversation-service.api.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts
@@ -1,3 +1,9 @@
+import { ConversationSortOrder } from "@openhands/typescript-client";
+import {
+ ConversationClient,
+ FileClient,
+ VSCodeClient,
+} from "@openhands/typescript-client/clients";
import { v4 as uuidv4 } from "uuid";
import { Provider } from "#/types/settings";
import { buildHttpBaseUrl } from "#/utils/websocket-url";
@@ -23,19 +29,12 @@ import {
import {
DirectConversationInfo,
buildStartConversationRequestWithEncryptedSettings,
- downloadTextFile,
- emptyHooksResponse,
getDefaultConversationTitle,
- loadSkillsForConversation,
toAppConversation,
toConversationPage,
} from "../agent-server-adapter";
import { GetVSCodeUrlResponse } from "../open-hands.types";
-import {
- createHttpClient,
- createRemoteWorkspace,
- createVSCodeClient,
-} from "../typescript-client";
+import { getAgentServerClientOptions } from "../agent-server-client-options";
import SettingsService from "../settings-service/settings-service.api";
import {
ConversationMetadata,
@@ -43,27 +42,214 @@ import {
setStoredConversationMetadata,
} from "../conversation-metadata-store";
import type {
- GetHooksResponse,
- GetSkillsResponse,
PluginSpec,
AppConversation,
AppConversationPage,
AppConversationStartRequest,
AppConversationStartTask,
+ MetricsSnapshot,
RuntimeConversationInfo,
SendMessageRequest,
SendMessageResponse,
} from "./agent-server-conversation-service.types";
+const DEFAULT_CONVERSATION_TIMESTAMP = "1970-01-01T00:00:00.000Z";
+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.";
+
+function invalidConversationResponse(): Error {
+ return new Error(INVALID_CONVERSATION_RESPONSE_MESSAGE);
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function numberOrNull(value: unknown): number | null {
+ return typeof value === "number" ? value : null;
+}
+
+function numberOrZero(value: unknown): number {
+ return typeof value === "number" ? value : 0;
+}
+
+function stringOrNull(value: unknown): string | null {
+ return typeof value === "string" ? value : null;
+}
+
+function readTimestamp(
+ item: Record<string, unknown>,
+ snakeKey: "created_at" | "updated_at",
+ camelKey: "createdAt" | "updatedAt",
+): string {
+ const value = item[snakeKey] ?? item[camelKey];
+ return typeof value === "string" && value.trim()
+ ? value
+ : DEFAULT_CONVERSATION_TIMESTAMP;
+}
+
+function normalizeTokenUsage(
+ value: unknown,
+): NonNullable<MetricsSnapshot["accumulated_token_usage"]> | null {
+ if (!isRecord(value)) return null;
+
+ return {
+ prompt_tokens: numberOrZero(value.prompt_tokens),
+ completion_tokens: numberOrZero(value.completion_tokens),
+ cache_read_tokens: numberOrZero(value.cache_read_tokens),
+ cache_write_tokens: numberOrZero(value.cache_write_tokens),
+ context_window: numberOrZero(value.context_window),
+ per_turn_token: numberOrZero(value.per_turn_token),
+ };
+}
+
+function normalizeMetrics(value: unknown): MetricsSnapshot | null {
+ if (!isRecord(value)) return null;
+
+ return {
+ accumulated_cost: numberOrNull(value.accumulated_cost),
+ max_budget_per_task: numberOrNull(value.max_budget_per_task),
+ accumulated_token_usage: normalizeTokenUsage(value.accumulated_token_usage),
+ };
+}
+
+function normalizeAgent(value: unknown): DirectConversationInfo["agent"] {
+ if (!isRecord(value)) return null;
+ const llm = isRecord(value.llm)
+ ? { model: stringOrNull(value.llm.model) }
+ : null;
+ return { llm };
+}
+
+function normalizeWorkspace(
+ value: unknown,
+): DirectConversationInfo["workspace"] {
+ if (!isRecord(value)) return null;
+ return { working_dir: stringOrNull(value.working_dir) };
+}
+
+function normalizeAbsolutePath(path: string): string | null {
+ if (!path.startsWith("/")) return null;
+
+ const segments: string[] = [];
+ for (const segment of path.split("/")) {
+ if (segment && segment !== ".") {
+ if (segment === "..") {
+ if (!segments.length) return null;
+ segments.pop();
+ } else {
+ segments.push(segment);
+ }
+ }
+ }
+
+ return `/${segments.join("/")}`;
+}
+
+function requirePathInsideDirectory(path: string, directory: string): string {
+ const normalizedPath = normalizeAbsolutePath(path);
+ const normalizedDirectory = normalizeAbsolutePath(directory);
+
+ if (
+ !normalizedPath ||
+ !normalizedDirectory ||
+ (normalizedPath !== normalizedDirectory &&
+ !normalizedPath.startsWith(`${normalizedDirectory}/`))
+ ) {
+ throw new Error("Conversation file path must stay inside the workspace");
+ }
+
+ return normalizedPath;
+}
+
+function requireDirectConversationInfo(item: unknown): DirectConversationInfo {
+ if (!isRecord(item) || typeof item.id !== "string" || !item.id.trim()) {
+ throw invalidConversationResponse();
+ }
+
+ return {
+ id: item.id.trim(),
+ title: stringOrNull(item.title),
+ created_at: readTimestamp(item, "created_at", "createdAt"),
+ updated_at: readTimestamp(item, "updated_at", "updatedAt"),
+ execution_status: stringOrNull(item.execution_status),
+ metrics: normalizeMetrics(item.metrics),
+ agent: normalizeAgent(item.agent),
+ workspace: normalizeWorkspace(item.workspace),
+ };
+}
+
+function requireDirectConversationItems(
+ items: unknown,
+): DirectConversationInfo[] {
+ if (!Array.isArray(items)) {
+ throw invalidConversationResponse();
+ }
+ return items.map(requireDirectConversationInfo);
+}
+
+function requireConversationSearchPage(page: unknown): {
+ items: DirectConversationInfo[];
+ next_page_id: string | null;
+} {
+ if (Array.isArray(page)) {
+ return {
+ items: requireDirectConversationItems(page),
+ next_page_id: null,
+ };
+ }
+
+ if (!isRecord(page)) {
+ throw invalidConversationResponse();
+ }
+
+ return {
+ items: requireDirectConversationItems(page.items),
+ next_page_id:
+ typeof page.next_page_id === "string" ? page.next_page_id : null,
+ };
+}
+
+const RUNTIME_STATUSES = new Set<string>([
+ "idle",
+ "running",
+ "paused",
+ "waiting_for_confirmation",
+ "finished",
+ "error",
+ "stuck",
+]);
+
+function toRuntimeStatus(
+ status: DirectConversationInfo["execution_status"],
+): RuntimeConversationInfo["status"] {
+ const nextStatus = status ?? "idle";
+ return (
+ RUNTIME_STATUSES.has(nextStatus) ? nextStatus : "idle"
+ ) as RuntimeConversationInfo["status"];
+}
+
+function requireAppConversation(
+ conversation: AppConversation | null | undefined,
+ conversationId: string,
+): AppConversation {
+ if (!conversation) {
+ throw new Error(`Conversation ${conversationId} was not found`);
+ }
+ return conversation;
+}
+
class AgentServerConversationService {
static async sendMessage(
conversationId: string,
message: SendMessageRequest,
): Promise<SendMessageResponse> {
- await createHttpClient().post(
- `/api/conversations/${conversationId}/events`,
+ await new ConversationClient(getAgentServerClientOptions()).sendEvent(
+ conversationId,
+ message,
{
- ...message,
run: true,
},
);
@@ -121,11 +307,9 @@ class AgentServerConversationService {
workingDir,
});
- const response = await createHttpClient().post<DirectConversationInfo>(
- "/api/conversations",
- payload,
- );
- const { data } = response;
+ const data = await new ConversationClient(
+ getAgentServerClientOptions(),
+ ).createConversation<DirectConversationInfo>(payload);
if (metadata?.selected_repository || workingDirOverride) {
// The agent-server runtime has no concept of selected repo/branch/
@@ -172,15 +356,6 @@ class AgentServerConversationService {
return null;
}
- static async searchStartTasks(
- limit: number = 100,
- ): Promise<AppConversationStartTask[]> {
- if (limit < 0) {
- return [];
- }
- return [];
- }
-
static async getVSCodeUrl(
conversationId: string,
conversationUrl: string | null | undefined,
@@ -193,10 +368,14 @@ class AgentServerConversationService {
// the user's browser can't reach.
const workspaceDir =
await this.resolveConversationWorkingDir(conversationId);
- const vscodeUrl = await createVSCodeClient({
- conversationUrl,
- sessionApiKey,
- }).getUrl({
+ // Local mode: the typescript-client targets the local agent-server
+ // directly via the conversationUrl override.
+ const vscodeUrl = await new VSCodeClient(
+ getAgentServerClientOptions({
+ conversationUrl,
+ sessionApiKey,
+ }),
+ ).getUrl({
baseUrl:
typeof window !== "undefined" ? window.location.origin : undefined,
workspaceDir,
@@ -214,43 +393,6 @@ class AgentServerConversationService {
return conversation?.workspace?.working_dir ?? getAgentServerWorkingDir();
}
- static async pauseConversation(
- conversationId: string,
- _conversationUrl: string | null | undefined,
- sessionApiKey?: string | null,
- ): Promise<{ success: boolean }> {
- const response = await createHttpClient({ sessionApiKey }).post<{
- success: boolean;
- }>(`/api/conversations/${conversationId}/pause`, {});
-
- return response.data;
- }
-
- static async askAgent(
- conversationId: string,
- _conversationUrl: string | null | undefined,
- question: string,
- sessionApiKey?: string | null,
- ): Promise<{ response: string }> {
- const response = await createHttpClient({ sessionApiKey }).post<{
- response: string;
- }>(`/api/conversations/${conversationId}/ask_agent`, { question });
-
- return response.data;
- }
-
- static async resumeConversation(
- conversationId: string,
- _conversationUrl: string | null | undefined,
- sessionApiKey?: string | null,
- ): Promise<{ success: boolean }> {
- const response = await createHttpClient({ sessionApiKey }).post<{
- success: boolean;
- }>(`/api/conversations/${conversationId}/run`, {});
-
- return response.data;
- }
-
static async batchGetAppConversations(
ids: string[],
): Promise<(AppConversation | null)[]> {
@@ -260,27 +402,13 @@ class AgentServerConversationService {
return batchGetCloudConversations(ids);
}
- const response = await createHttpClient().get<
- (DirectConversationInfo | null)[]
- >("/api/conversations", { params: { ids } });
-
- return response.data.map((item) => (item ? toAppConversation(item) : null));
- }
+ const data = await new ConversationClient(
+ getAgentServerClientOptions(),
+ ).getConversations<DirectConversationInfo>(ids);
- static async uploadFile(
- _conversationUrl: string | null | undefined,
- sessionApiKey: string | null | undefined,
- file: File,
- path?: string,
- ): Promise<void> {
- const uploadPath = path || `/workspace/${file.name}`;
- await createRemoteWorkspace({ sessionApiKey }).fileUpload(file, uploadPath);
- }
-
- static async getConversationConfig(
- conversationId: string,
- ): Promise<{ runtime_id: string }> {
- return { runtime_id: conversationId };
+ return requireDirectConversationItems(data).map((item) =>
+ toAppConversation(item),
+ );
}
static async updateConversationPublicFlag(
@@ -308,8 +436,10 @@ class AgentServerConversationService {
} else {
removeStoredConversationMetadata(conversationId);
}
- const results = await this.batchGetAppConversations([conversationId]);
- return results[0] as AppConversation;
+ const [conversation] = await this.batchGetAppConversations([
+ conversationId,
+ ]);
+ return requireAppConversation(conversation, conversationId);
}
static async readConversationFile(
@@ -320,18 +450,19 @@ class AgentServerConversationService {
// Cloud SaaS exposes a per-conversation file endpoint; the sandbox
// working dir is fixed (`/workspace/project`), so PLAN.md lives at
// a known absolute path. Mirrors OpenHands' readConversationFile.
- return readCloudConversationFile(
- conversationId,
+ const path = requirePathInsideDirectory(
filePath ?? "/workspace/project/.agents_tmp/PLAN.md",
+ "/workspace/project",
);
- }
-
- if (filePath) {
- return downloadTextFile(filePath);
+ return readCloudConversationFile(conversationId, path);
}
const workingDir = await this.resolveConversationWorkingDir(conversationId);
- return downloadTextFile(`${workingDir}/.agents_tmp/PLAN.md`);
+ const path = requirePathInsideDirectory(
+ filePath ?? `${workingDir}/.agents_tmp/PLAN.md`,
+ workingDir,
+ );
+ return new FileClient(getAgentServerClientOptions()).downloadTextFile(path);
}
static async downloadConversation(conversationId: string): Promise<Blob> {
@@ -339,28 +470,9 @@ class AgentServerConversationService {
return downloadCloudConversation(conversationId);
}
- const response = await createHttpClient().get<Blob>(
- `/api/file/download-trajectory/${conversationId}`,
- {
- responseType: "blob",
- },
- );
-
- return response.data;
- }
-
- static async getSkills(conversationId: string): Promise<GetSkillsResponse> {
- const [conversation] = await this.batchGetAppConversations([
+ return new FileClient(getAgentServerClientOptions()).downloadTrajectory(
conversationId,
- ]);
- return loadSkillsForConversation(conversation);
- }
-
- static async getHooks(conversationId: string): Promise<GetHooksResponse> {
- if (!conversationId) {
- return emptyHooksResponse();
- }
- return emptyHooksResponse();
+ );
}
static async getRuntimeConversation(
@@ -378,7 +490,7 @@ class AgentServerConversationService {
// the conversation's runtime URL β€” same pattern as getVSCodeUrl. Local
// mode forwards conversationUrl so the host explicitly resolves to the
// conversation's runtime instead of falling back to the active backend.
- const data: RawRuntime =
+ const response =
active.kind === "cloud" && conversationUrl
? await callCloudProxy<RawRuntime>({
backend: active,
@@ -388,46 +500,25 @@ class AgentServerConversationService {
authMode: "session-api-key",
sessionApiKey,
})
- : (
- await createHttpClient({
+ : await new ConversationClient(
+ getAgentServerClientOptions({
conversationUrl,
sessionApiKey,
- }).get<RawRuntime>(`/api/conversations/${conversationId}`)
- ).data;
+ }),
+ ).getConversation<RawRuntime>(conversationId);
+ const data = requireDirectConversationInfo(response);
+ const stats = isRecord(response) ? response.stats : null;
return {
id: data.id,
title: data.title?.trim()
? data.title
: getDefaultConversationTitle(data.id),
- metrics: data.metrics
- ? {
- accumulated_cost: data.metrics.accumulated_cost ?? null,
- max_budget_per_task: data.metrics.max_budget_per_task ?? null,
- accumulated_token_usage: data.metrics.accumulated_token_usage
- ? {
- prompt_tokens:
- data.metrics.accumulated_token_usage.prompt_tokens ?? 0,
- completion_tokens:
- data.metrics.accumulated_token_usage.completion_tokens ?? 0,
- cache_read_tokens:
- data.metrics.accumulated_token_usage.cache_read_tokens ?? 0,
- cache_write_tokens:
- data.metrics.accumulated_token_usage.cache_write_tokens ??
- 0,
- context_window:
- data.metrics.accumulated_token_usage.context_window ?? 0,
- per_turn_token:
- data.metrics.accumulated_token_usage.per_turn_token ?? 0,
- }
- : null,
- }
- : null,
+ metrics: normalizeMetrics(data.metrics),
created_at: data.created_at,
updated_at: data.updated_at,
- status:
- (data.execution_status as RuntimeConversationInfo["status"]) ?? "idle",
- stats: data.stats ?? { usage_to_metrics: {} },
+ status: toRuntimeStatus(data.execution_status),
+ stats: isRecord(stats) ? stats : { usage_to_metrics: {} },
};
}
@@ -439,25 +530,24 @@ class AgentServerConversationService {
return searchCloudConversations(limit, pageId);
}
- const response = await createHttpClient().get<{
- items: DirectConversationInfo[];
- next_page_id: string | null;
- }>("/api/conversations/search", {
- params: {
- limit,
- page_id: pageId,
- sort_order: "UPDATED_AT_DESC",
- },
+ const data = await new ConversationClient(
+ getAgentServerClientOptions(),
+ ).searchConversations({
+ limit,
+ page_id: pageId,
+ sort_order: ConversationSortOrder.UPDATED_AT_DESC,
});
- return toConversationPage(response.data);
+ return toConversationPage(requireConversationSearchPage(data));
}
static async deleteConversation(conversationId: string): Promise<void> {
if (getActiveBackend().backend.kind === "cloud") {
await deleteCloudConversation(conversationId);
} else {
- await createHttpClient().delete(`/api/conversations/${conversationId}`);
+ await new ConversationClient(
+ getAgentServerClientOptions(),
+ ).deleteConversation(conversationId);
}
removeStoredConversationMetadata(conversationId);
}
@@ -466,13 +556,15 @@ class AgentServerConversationService {
conversationId: string,
title: string,
): Promise<AppConversation> {
- await createHttpClient().patch(`/api/conversations/${conversationId}`, {
+ await new ConversationClient(
+ getAgentServerClientOptions(),
+ ).updateConversation(conversationId, {
title,
});
const [conversation] = await this.batchGetAppConversations([
conversationId,
]);
- return conversation as AppConversation;
+ return requireAppConversation(conversation, conversationId);
}
}
diff --git a/src/api/conversation-service/conversation-service.api.ts b/src/api/conversation-service/conversation-service.api.ts
index 9b161da5e0..10df6b4599 100644
--- a/src/api/conversation-service/conversation-service.api.ts
+++ b/src/api/conversation-service/conversation-service.api.ts
@@ -1,40 +1,41 @@
-import { getAgentServerWorkingDir } from "../agent-server-config";
+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 {
GetVSCodeUrlResponse,
GetTrajectoryResponse,
FileUploadSuccessResponse,
} from "../open-hands.types";
+import { getAgentServerWorkingDir } from "../agent-server-config";
import {
- createRemoteEventsList,
- createRemoteWorkspace,
- createVSCodeClient,
-} from "../typescript-client";
+ getAgentServerClientOptions,
+ getAgentServerHttpClientOptions,
+} from "../agent-server-client-options";
import { AppConversation } from "./agent-server-conversation-service.types";
const FILE_UPLOAD_CONCURRENCY = 5;
-class ConversationService {
- private static currentConversation: AppConversation | null = null;
+function getSafeUploadFileName(fileName: string): string {
+ const parts = fileName.split(/[\\/]+/).filter(Boolean);
+ const safeName = parts[parts.length - 1];
- static getCurrentConversation(): AppConversation | null {
- return this.currentConversation;
+ if (!safeName || safeName === "." || safeName === "..") {
+ throw new Error("Invalid file name");
}
+ return safeName;
+}
+
+class ConversationService {
+ private static currentConversation: AppConversation | null = null;
+
static setCurrentConversation(
currentConversation: AppConversation | null,
): void {
this.currentConversation = currentConversation;
}
- static getConversationUrl(conversationId: string): string {
- if (this.currentConversation?.id === conversationId) {
- if (this.currentConversation.conversation_url) {
- return this.currentConversation.conversation_url;
- }
- }
- return `/api/conversations/${conversationId}`;
- }
-
private static getClientOverrides() {
return {
sessionApiKey: this.currentConversation?.session_api_key,
@@ -49,8 +50,8 @@ class ConversationService {
? (this.currentConversation?.workspace?.working_dir ??
getAgentServerWorkingDir())
: getAgentServerWorkingDir();
- const vscodeUrl = await createVSCodeClient(
- this.getClientOverrides(),
+ const vscodeUrl = await new VSCodeClient(
+ getAgentServerClientOptions(this.getClientOverrides()),
).getUrl({
baseUrl:
typeof window !== "undefined" ? window.location.origin : undefined,
@@ -63,9 +64,11 @@ class ConversationService {
static async getTrajectory(
conversationId: string,
): Promise<GetTrajectoryResponse> {
- const page = await createRemoteEventsList(
+ const page = await new RemoteEventsList(
+ new HttpClient(
+ getAgentServerHttpClientOptions(this.getClientOverrides()),
+ ),
conversationId,
- this.getClientOverrides(),
).search({ limit: 10000 });
return { trajectory: page.items ?? [] };
@@ -75,11 +78,14 @@ class ConversationService {
_conversationId: string,
files: File[],
): Promise<FileUploadSuccessResponse> {
- const workspace = createRemoteWorkspace(this.getClientOverrides());
+ const workspace = new RemoteWorkspace(
+ getAgentServerClientOptions(this.getClientOverrides()),
+ );
const uploadFile = async (file: File) => {
try {
- await workspace.fileUpload(file, `/workspace/${file.name}`);
- return { uploadedFile: file.name, skippedFile: null };
+ const safeName = getSafeUploadFileName(file.name);
+ await workspace.fileUpload(file, `/workspace/${safeName}`);
+ return { uploadedFile: safeName, skippedFile: null };
} catch (error) {
return {
uploadedFile: null,
diff --git a/src/api/conversation.utils.ts b/src/api/conversation.utils.ts
deleted file mode 100644
index a0a9acd4ad..0000000000
--- a/src/api/conversation.utils.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import ConversationService from "#/api/conversation-service/conversation-service.api";
-
-/**
- * Returns a URL compatible for the file service
- * @param conversationId ID of the conversation
- * @returns URL of the conversation
- */
-export const getConversationUrl = (conversationId: string) =>
- ConversationService.getConversationUrl(conversationId);
diff --git a/src/api/event-service/event-service.api.ts b/src/api/event-service/event-service.api.ts
index f2a1f294cc..82c584470d 100644
--- a/src/api/event-service/event-service.api.ts
+++ b/src/api/event-service/event-service.api.ts
@@ -1,8 +1,14 @@
+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";
import { getActiveBackend } from "../backend-registry/active-store";
import { callCloudProxy } from "../cloud/proxy";
-import { createHttpClient, createRemoteEventsList } from "../typescript-client";
+import {
+ getAgentServerClientOptions,
+ getAgentServerHttpClientOptions,
+} from "../agent-server-client-options";
import type {
ConfirmationResponseRequest,
ConfirmationResponseResponse,
@@ -29,7 +35,7 @@ import type {
* `localhost` from talking directly to either the SaaS or the runtime.
*
* Local mode keeps the existing typescript-client path: it targets the
- * conversation's host directly via `createRemoteEventsList`/`createHttpClient`.
+ * conversation's host directly via typed client classes.
*/
class EventService {
static async respondToConfirmation(
@@ -52,15 +58,15 @@ class EventService {
});
}
- const response = await createHttpClient({
- conversationUrl,
- sessionApiKey,
- }).post<ConfirmationResponseResponse>(
- `/api/conversations/${conversationId}/events/respond_to_confirmation`,
+ return new ConversationClient(
+ getAgentServerClientOptions({
+ conversationUrl,
+ sessionApiKey,
+ }),
+ ).respondToConfirmation<ConfirmationResponseResponse>(
+ conversationId,
request,
);
-
- return response.data;
}
static async getEventCount(
@@ -81,10 +87,12 @@ class EventService {
});
}
- return createRemoteEventsList(conversationId, {
- conversationUrl,
- sessionApiKey,
- }).count();
+ return new ConversationClient(
+ getAgentServerClientOptions({
+ conversationUrl,
+ sessionApiKey,
+ }),
+ ).getEventCount(conversationId);
}
/**
@@ -131,10 +139,12 @@ class EventService {
};
}
- const page = await createRemoteEventsList(conversationId, {
- conversationUrl,
- sessionApiKey,
- }).search({
+ const page = await new RemoteEventsList(
+ new HttpClient(
+ getAgentServerHttpClientOptions({ conversationUrl, sessionApiKey }),
+ ),
+ conversationId,
+ ).search({
limit,
...(options.pageId ? { page_id: options.pageId } : {}),
...(options.sortOrder ? { sort_order: options.sortOrder } : {}),
@@ -143,8 +153,8 @@ class EventService {
});
return {
- items: (page.items ?? []) as OpenHandsEvent[],
- next_page_id: page.next_page_id ?? null,
+ items: (page?.items ?? []) as OpenHandsEvent[],
+ next_page_id: page?.next_page_id ?? null,
};
}
}
diff --git a/src/api/files-service/files-service.api.ts b/src/api/files-service/files-service.api.ts
deleted file mode 100644
index 4de54e9284..0000000000
--- a/src/api/files-service/files-service.api.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { createHttpClient } from "../typescript-client";
-
-export interface SubdirectoryEntry {
- name: string;
- path: string;
-}
-
-export interface SubdirectoryPage {
- items: SubdirectoryEntry[];
- next_page_id: string | null;
-}
-
-export interface FileBrowserEntry {
- label: string;
- path: string;
-}
-
-export interface HomeResponse {
- home: string;
- favorites: FileBrowserEntry[];
- locations: FileBrowserEntry[];
-}
-
-export interface SearchSubdirsOptions {
- pageId?: string | null;
- limit?: number;
-}
-
-const FilesService = {
- async searchSubdirs(
- path: string,
- options: SearchSubdirsOptions = {},
- ): Promise<SubdirectoryPage> {
- const params: Record<string, string | number> = { path };
- if (options.pageId) params.page_id = options.pageId;
- if (typeof options.limit === "number") params.limit = options.limit;
-
- const response = await createHttpClient().get<SubdirectoryPage>(
- "/api/file/search_subdirs",
- { params },
- );
- return response.data;
- },
-
- async getHome(): Promise<HomeResponse> {
- const response =
- await createHttpClient().get<HomeResponse>("/api/file/home");
- return response.data;
- },
-};
-
-export default FilesService;
diff --git a/src/api/git-service/agent-server-git-service.api.ts b/src/api/git-service/agent-server-git-service.api.ts
index 1649f55846..49d0bdcbbd 100644
--- a/src/api/git-service/agent-server-git-service.api.ts
+++ b/src/api/git-service/agent-server-git-service.api.ts
@@ -1,9 +1,10 @@
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
import { mapAnyGitStatusToClientStatus } from "#/utils/git-status-mapper";
import { buildHttpBaseUrl } from "#/utils/websocket-url";
import type { GitChange, GitChangeDiff } from "../open-hands.types";
import { getActiveBackend } from "../backend-registry/active-store";
import { callCloudProxy } from "../cloud/proxy";
-import { createRemoteWorkspace } from "../typescript-client";
+import { getAgentServerClientOptions } from "../agent-server-client-options";
interface AgentServerGitChange {
status: string;
@@ -68,10 +69,9 @@ class AgentServerGitService {
}));
}
- const changes = await createRemoteWorkspace({
- conversationUrl,
- sessionApiKey,
- }).gitChanges(path, { ref: "HEAD" });
+ const changes = await new RemoteWorkspace(
+ getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ ).gitChanges(path, { ref: "HEAD" });
if (!Array.isArray(changes)) {
throw new Error(
@@ -114,10 +114,9 @@ class AgentServerGitService {
} as GitChangeDiff;
}
- const diff = (await createRemoteWorkspace({
- conversationUrl,
- sessionApiKey,
- }).gitDiff(path, { ref: "HEAD" })) as GitChangeDiff & { diff?: string };
+ const diff = (await new RemoteWorkspace(
+ getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ ).gitDiff(path, { ref: "HEAD" })) as GitChangeDiff & { diff?: string };
return {
modified: diff.modified ?? "",
diff --git a/src/api/git-service/git-service.api.ts b/src/api/git-service/git-service.api.ts
index 2721cce006..55081eb60e 100644
--- a/src/api/git-service/git-service.api.ts
+++ b/src/api/git-service/git-service.api.ts
@@ -1,8 +1,9 @@
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
import { RepositoryPage, BranchPage, InstallationPage } from "#/types/git";
import { Provider } from "#/types/settings";
import { GitChange, GitChangeDiff } from "../open-hands.types";
import AgentServerConversationService from "../conversation-service/agent-server-conversation-service.api";
-import { createRemoteWorkspace } from "../typescript-client";
+import { getAgentServerClientOptions } from "../agent-server-client-options";
import { mapAnyGitStatusToClientStatus } from "#/utils/git-status-mapper";
import { getActiveBackend } from "../backend-registry/active-store";
import {
@@ -145,10 +146,9 @@ class GitService {
await AgentServerConversationService.resolveConversationWorkingDir(
conversationId,
);
- const changes = await createRemoteWorkspace({ workingDir }).gitChanges(
- workingDir,
- { ref: "HEAD" },
- );
+ const changes = await new RemoteWorkspace(
+ getAgentServerClientOptions({ workingDir }),
+ ).gitChanges(workingDir, { ref: "HEAD" });
return changes.map((change) => ({
path: change.path,
@@ -164,7 +164,9 @@ class GitService {
_conversationId: string,
path: string,
): Promise<GitChangeDiff> {
- const diff = await createRemoteWorkspace().gitDiff(path, { ref: "HEAD" });
+ const diff = await new RemoteWorkspace(
+ getAgentServerClientOptions(),
+ ).gitDiff(path, { ref: "HEAD" });
return {
modified: diff.modified ?? "",
diff --git a/src/api/no-direct-agent-server-calls.test.ts b/src/api/no-direct-agent-server-calls.test.ts
new file mode 100644
index 0000000000..480efba95c
--- /dev/null
+++ b/src/api/no-direct-agent-server-calls.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+import { readdirSync, readFileSync } from "node:fs";
+import { join, relative } from "node:path";
+
+const SRC_ROOT = join(process.cwd(), "src");
+const EXCLUDED_SEGMENTS = new Set(["mocks", "routeTree.gen.ts"]);
+const ALLOWED_AD_HOC_HTTP_FILES = new Set([
+ "api/automation-service/automation-service.api.ts",
+ "api/cloud/proxy.ts",
+]);
+
+function collectSourceFiles(dir: string): string[] {
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ const fullPath = join(dir, entry.name);
+ const relPath = relative(SRC_ROOT, fullPath);
+
+ if (entry.isDirectory()) {
+ if (EXCLUDED_SEGMENTS.has(entry.name)) return [];
+ return collectSourceFiles(fullPath);
+ }
+
+ if (EXCLUDED_SEGMENTS.has(entry.name)) return [];
+ if (!/\.(ts|tsx)$/.test(entry.name)) return [];
+ if (/\.(test|spec)\.(ts|tsx)$/.test(entry.name)) return [];
+ return [relPath];
+ });
+}
+
+describe("agent-server API access", () => {
+ it("uses typed @openhands/typescript-client access instead of ad-hoc HTTP", () => {
+ const violations = collectSourceFiles(SRC_ROOT).flatMap((relPath) => {
+ const source = readFileSync(join(SRC_ROOT, relPath), "utf8");
+ const fileViolations: string[] = [];
+
+ if (/openHands\s*\./.test(source)) {
+ fileViolations.push("uses the shared axios instance directly");
+ }
+
+ if (/\bcreateHttpClient\s*\(/.test(source)) {
+ fileViolations.push("uses createHttpClient directly");
+ }
+
+ if (
+ (/\baxios\s*\(/.test(source) ||
+ /\baxios\s*\.\s*(?:create|get|post|put|patch|delete|request)\s*\(/.test(
+ source,
+ )) &&
+ !ALLOWED_AD_HOC_HTTP_FILES.has(relPath)
+ ) {
+ fileViolations.push("uses axios directly for HTTP calls");
+ }
+
+ if (/\bfetch\s*\([\s\S]{0,200}['"`]\/api\//.test(source)) {
+ fileViolations.push("calls an /api path with fetch directly");
+ }
+
+ return fileViolations.map((violation) => `${relPath}: ${violation}`);
+ });
+
+ expect(violations).toEqual([]);
+ });
+});
diff --git a/src/api/option-service/option-service.api.ts b/src/api/option-service/option-service.api.ts
index 5da71e7a0f..80ee208a63 100644
--- a/src/api/option-service/option-service.api.ts
+++ b/src/api/option-service/option-service.api.ts
@@ -1,10 +1,11 @@
+import { LLMMetadataClient } from "@openhands/typescript-client/clients";
import { loadAgentServerInfo } from "../agent-server-compatibility";
-import { createLlmMetadataClient } from "../typescript-client";
+import { getAgentServerClientOptions } from "../agent-server-client-options";
import { ModelsResponse, WebClientConfig } from "./option.types";
class OptionService {
static async getModels(): Promise<ModelsResponse> {
- const llmClient = createLlmMetadataClient();
+ const llmClient = new LLMMetadataClient(getAgentServerClientOptions());
const [models, verifiedByProvider, providers] = await Promise.all([
llmClient.getModels(),
llmClient.getVerifiedModels(),
@@ -26,10 +27,6 @@ class OptionService {
};
}
- static async getSecurityAnalyzers(): Promise<string[]> {
- return ["llm", "pattern", "policy_rail"];
- }
-
static async getConfig(): Promise<WebClientConfig> {
await loadAgentServerInfo();
diff --git a/src/api/pending-message-service/pending-message-service.api.ts b/src/api/pending-message-service/pending-message-service.api.ts
deleted file mode 100644
index 3efbc01532..0000000000
--- a/src/api/pending-message-service/pending-message-service.api.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { createHttpClient } from "../typescript-client";
-import type {
- PendingMessageResponse,
- QueuePendingMessageRequest,
-} from "./pending-message-service.types";
-
-class PendingMessageService {
- static async queueMessage(
- conversationId: string,
- message: QueuePendingMessageRequest,
- ): Promise<PendingMessageResponse> {
- await createHttpClient().post(
- `/api/conversations/${conversationId}/events`,
- {
- ...message,
- role: "user",
- run: true,
- },
- );
-
- return {
- id: `${conversationId}:${Date.now()}`,
- queued: true,
- position: 1,
- };
- }
-}
-
-export default PendingMessageService;
diff --git a/src/api/pending-message-service/pending-message-service.types.ts b/src/api/pending-message-service/pending-message-service.types.ts
deleted file mode 100644
index e838a52a45..0000000000
--- a/src/api/pending-message-service/pending-message-service.types.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/**
- * Types for the pending message service
- */
-
-import type { MessageContent } from "../conversation-service/agent-server-conversation-service.types";
-
-/**
- * Response when queueing a pending message
- */
-export interface PendingMessageResponse {
- id: string;
- queued: boolean;
- position: number;
-}
-
-/**
- * Request to queue a pending message
- */
-export interface QueuePendingMessageRequest {
- role?: "user";
- content: MessageContent[];
-}
diff --git a/src/api/secrets-service.ts b/src/api/secrets-service.ts
index cb51051386..b5574e123e 100644
--- a/src/api/secrets-service.ts
+++ b/src/api/secrets-service.ts
@@ -1,3 +1,4 @@
+import { SettingsClient } from "@openhands/typescript-client/clients";
import { getActiveBackend } from "./backend-registry/active-store";
import {
createCloudSecret,
@@ -5,37 +6,9 @@ import {
fetchCloudSecrets,
updateCloudSecret,
} from "./cloud/secrets-service.api";
-import { createHttpClient } from "./typescript-client";
+import { getAgentServerClientOptions } from "./agent-server-client-options";
import { CustomSecretWithoutValue } from "./secrets-service.types";
-/**
- * Response from GET /api/settings/secrets (agent-server API)
- */
-interface SecretsListResponse {
- secrets: Array<{
- name: string;
- description?: string;
- }>;
-}
-
-/**
- * Request for PUT /api/settings/secrets (agent-server API)
- * This is an upsert operation - creates or updates by name.
- */
-interface CreateSecretRequest {
- name: string;
- value: string;
- description?: string;
-}
-
-/**
- * Response from PUT /api/settings/secrets (agent-server API)
- */
-interface CreateSecretResponse {
- name: string;
- description?: string;
-}
-
/**
* Retry helper for API calls with exponential backoff.
*/
@@ -78,9 +51,9 @@ export class SecretsService {
return await withRetry(() => fetchCloudSecrets());
}
const response = await withRetry(() =>
- createHttpClient().get<SecretsListResponse>("/api/settings/secrets"),
+ new SettingsClient(getAgentServerClientOptions()).listSecrets(),
);
- return response.data.secrets.map((s) => ({
+ return response.secrets.map((s) => ({
name: s.name,
description: s.description,
}));
@@ -109,11 +82,11 @@ export class SecretsService {
return;
}
await withRetry(() =>
- createHttpClient().put<CreateSecretResponse>("/api/settings/secrets", {
+ new SettingsClient(getAgentServerClientOptions()).upsertSecret({
name,
value,
description,
- } satisfies CreateSecretRequest),
+ }),
);
}
@@ -157,9 +130,7 @@ export class SecretsService {
return;
}
await withRetry(() =>
- createHttpClient().delete<{ deleted: boolean }>(
- `/api/settings/secrets/${encodeURIComponent(name)}`,
- ),
+ new SettingsClient(getAgentServerClientOptions()).deleteSecret(name),
);
} catch (error) {
// 404 means secret doesn't exist - treat as successful deletion
diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.ts
index f4c3b1fb4c..5551d03f5a 100644
--- a/src/api/settings-service/settings-service.api.ts
+++ b/src/api/settings-service/settings-service.api.ts
@@ -1,3 +1,4 @@
+import { SettingsClient } from "@openhands/typescript-client/clients";
import { DEFAULT_SETTINGS } from "#/services/settings";
import { Settings, SettingsSchema, SettingsValue } from "#/types/settings";
import {
@@ -12,7 +13,7 @@ import {
fetchCloudSettingsSchema,
saveCloudSettings,
} from "../cloud/settings-service.api";
-import { createHttpClient, createSettingsClient } from "../typescript-client";
+import { getAgentServerClientOptions } from "../agent-server-client-options";
/**
* Response from GET /api/settings
@@ -207,16 +208,11 @@ class SettingsService {
static async fetchSettingsFromApi(
exposeSecrets?: ExposeSecretsMode,
): Promise<SettingsApiResponse> {
- const headers: Record<string, string> = {};
- if (exposeSecrets) {
- headers["X-Expose-Secrets"] = exposeSecrets;
- }
-
- const response = await withRetry(() =>
- createHttpClient().get<SettingsApiResponse>("/api/settings", { headers }),
- );
-
- return response.data;
+ return withRetry(() =>
+ new SettingsClient(getAgentServerClientOptions()).getSettings({
+ exposeSecrets,
+ }),
+ ) as Promise<SettingsApiResponse>;
}
/**
@@ -297,14 +293,18 @@ class SettingsService {
if (getActiveBackend().backend.kind === "cloud") {
return (await fetchCloudSettingsSchema()) as SettingsSchema;
}
- return (await createSettingsClient().getAgentSchema()) as SettingsSchema;
+ return (await new SettingsClient(
+ getAgentServerClientOptions(),
+ ).getAgentSchema()) as SettingsSchema;
}
static async getConversationSettingsSchema(): Promise<SettingsSchema> {
if (getActiveBackend().backend.kind === "cloud") {
return (await fetchCloudConversationSettingsSchema()) as SettingsSchema;
}
- return (await createSettingsClient().getConversationSchema()) as SettingsSchema;
+ return (await new SettingsClient(
+ getAgentServerClientOptions(),
+ ).getConversationSchema()) as SettingsSchema;
}
/**
@@ -390,8 +390,7 @@ class SettingsService {
return true;
}
await withRetry(() =>
- createHttpClient().patch<SettingsApiResponse>(
- "/api/settings",
+ new SettingsClient(getAgentServerClientOptions()).updateSettings(
localPayload,
),
);
diff --git a/src/api/shared-conversation-service.api.ts b/src/api/shared-conversation-service.api.ts
deleted file mode 100644
index 4d812f86ee..0000000000
--- a/src/api/shared-conversation-service.api.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { OpenHandsEvent } from "#/types/agent-server/core";
-import { createHttpClient } from "./typescript-client";
-
-export interface SharedConversation {
- id: string;
- created_by_user_id: string | null;
- selected_repository: string | null;
- selected_branch: string | null;
- git_provider: string | null;
- title: string | null;
- pr_number: number[];
- llm_model: string | null;
- metrics: unknown | null;
- parent_conversation_id: string | null;
- sub_conversation_ids: string[];
- created_at: string;
- updated_at: string;
-}
-
-export interface EventPage {
- items: OpenHandsEvent[];
- next_page_id: string | null;
-}
-
-export const sharedConversationService = {
- async getSharedConversation(
- conversationId: string,
- ): Promise<SharedConversation | null> {
- const response = await createHttpClient().get<
- (SharedConversation | null)[]
- >("/api/shared-conversations", { params: { ids: conversationId } });
-
- return response.data[0] || null;
- },
-
- async getSharedConversationEvents(
- conversationId: string,
- limit: number = 100,
- pageId?: string,
- ): Promise<EventPage> {
- const response = await createHttpClient().get<EventPage>(
- "/api/shared-events/search",
- {
- params: {
- conversation_id: conversationId,
- limit,
- ...(pageId ? { page_id: pageId } : {}),
- },
- },
- );
-
- return response.data;
- },
-};
diff --git a/src/api/skills-service.ts b/src/api/skills-service.ts
index 4f89e044a1..0f91511c10 100644
--- a/src/api/skills-service.ts
+++ b/src/api/skills-service.ts
@@ -1,8 +1,9 @@
+import { SkillsClient } from "@openhands/typescript-client/clients";
import { SkillInfo } from "#/types/settings";
import { getAgentServerWorkingDir } from "./agent-server-config";
import { getActiveBackend } from "./backend-registry/active-store";
import { fetchCloudSkills } from "./cloud/skills-service.api";
-import { createSkillsClient } from "./typescript-client";
+import { getAgentServerClientOptions } from "./agent-server-client-options";
class SkillsService {
static async getSkills(): Promise<SkillInfo[]> {
@@ -14,7 +15,9 @@ class SkillsService {
// sees the available catalog even on a fresh dev environment with no local
// user/project skills. Conversation creation paths still gate on
// shouldLoadPublicSkills() to keep new-conversation latency low.
- const response = await createSkillsClient().getSkills({
+ const response = await new SkillsClient(
+ getAgentServerClientOptions(),
+ ).getSkills({
load_public: true,
load_user: true,
load_project: true,
diff --git a/src/api/typescript-client.ts b/src/api/typescript-client.ts
deleted file mode 100644
index a3a0e4b20b..0000000000
--- a/src/api/typescript-client.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import {
- LLMMetadataClient,
- ServerClient,
- SettingsClient,
- SkillsClient,
- 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 { buildHttpBaseUrl } from "#/utils/websocket-url";
-import {
- getActiveBackend,
- getEffectiveLocalBackend,
-} from "./backend-registry/active-store";
-import { getAgentServerWorkingDir } from "./agent-server-config";
-
-export type { ServerInfo } from "@openhands/typescript-client";
-
-interface TypeScriptClientOverrides {
- host?: string;
- apiKey?: string | null;
- sessionApiKey?: string | null;
- workingDir?: string;
- conversationUrl?: string | null;
- timeout?: number;
-}
-
-interface ResolvedClientOptions {
- host: string;
- apiKey?: string;
- workingDir: string;
-}
-
-/**
- * Pick the backend whose host + API key the typescript-client should use
- * by default. The typescript-client clients (createHttpClient and friends)
- * speak the *local agent-server's* protocol β€” `X-Session-API-Key` auth and
- * paths like `/api/conversations`, `/api/skills`, etc. The cloud SaaS
- * exposes neither, so when the active backend is cloud, fall back to the
- * first registered local backend for these calls. Cloud-specific calls go
- * through `callCloudProxy` separately and never touch this resolver.
- */
-function resolveDefaultBackend() {
- const active = getActiveBackend().backend;
- if (active.kind === "cloud") return getEffectiveLocalBackend();
- return active;
-}
-
-function resolveHost(overrides: TypeScriptClientOverrides): string {
- if (overrides.host) return overrides.host.replace(/\/$/, "");
- if (overrides.conversationUrl)
- return buildHttpBaseUrl(overrides.conversationUrl);
- return resolveDefaultBackend().host;
-}
-
-function resolveClientOptions(
- overrides: TypeScriptClientOverrides = {},
-): ResolvedClientOptions {
- const backend = resolveDefaultBackend();
-
- const host = resolveHost(overrides);
- const apiKey =
- overrides.sessionApiKey ?? overrides.apiKey ?? backend.apiKey ?? undefined;
-
- return {
- host,
- ...(apiKey ? { apiKey } : {}),
- workingDir: overrides.workingDir ?? getAgentServerWorkingDir(),
- };
-}
-
-export function createServerClient(
- overrides?: TypeScriptClientOverrides,
-): ServerClient {
- const { host, apiKey } = resolveClientOptions(overrides);
- return new ServerClient({
- host,
- ...(apiKey ? { apiKey } : {}),
- ...(overrides?.timeout ? { timeout: overrides.timeout } : {}),
- });
-}
-
-export function createLlmMetadataClient(
- overrides?: TypeScriptClientOverrides,
-): LLMMetadataClient {
- const { host, apiKey } = resolveClientOptions(overrides);
- return new LLMMetadataClient({ host, ...(apiKey ? { apiKey } : {}) });
-}
-
-export function createSettingsClient(
- overrides?: TypeScriptClientOverrides,
-): SettingsClient {
- const { host, apiKey } = resolveClientOptions(overrides);
- return new SettingsClient({ host, ...(apiKey ? { apiKey } : {}) });
-}
-
-export function createSkillsClient(
- overrides?: TypeScriptClientOverrides,
-): SkillsClient {
- const { host, apiKey } = resolveClientOptions(overrides);
- return new SkillsClient({ host, ...(apiKey ? { apiKey } : {}) });
-}
-
-export function createVSCodeClient(
- overrides?: TypeScriptClientOverrides,
-): VSCodeClient {
- const { host, apiKey } = resolveClientOptions(overrides);
- return new VSCodeClient({ host, ...(apiKey ? { apiKey } : {}) });
-}
-
-export function createHttpClient(
- overrides?: TypeScriptClientOverrides,
-): HttpClient {
- const { host, apiKey } = resolveClientOptions(overrides);
- return new HttpClient({
- baseUrl: host,
- ...(apiKey ? { apiKey } : {}),
- timeout: 60000,
- });
-}
-
-export function createRemoteEventsList(
- conversationId: string,
- overrides?: TypeScriptClientOverrides,
-): RemoteEventsList {
- return new RemoteEventsList(createHttpClient(overrides), conversationId);
-}
-
-export function createRemoteWorkspace(
- overrides?: TypeScriptClientOverrides,
-): RemoteWorkspace {
- const { host, apiKey, workingDir } = resolveClientOptions(overrides);
- return new RemoteWorkspace({
- host,
- workingDir,
- ...(apiKey ? { apiKey } : {}),
- });
-}
diff --git a/src/components/features/backends/backend-form-modal.tsx b/src/components/features/backends/backend-form-modal.tsx
index 7057d4b466..45270f7426 100644
--- a/src/components/features/backends/backend-form-modal.tsx
+++ b/src/components/features/backends/backend-form-modal.tsx
@@ -1,12 +1,13 @@
import React from "react";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
+import { ServerClient } from "@openhands/typescript-client/clients";
import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
import { BrandButton } from "#/components/features/settings/brand-button";
import { SettingsInput } from "#/components/features/settings/settings-input";
import { useActiveBackendContext } from "#/contexts/active-backend-context";
import { useBackendsHealth } from "#/hooks/query/use-backends-health";
-import { createServerClient } from "#/api/typescript-client";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { I18nKey } from "#/i18n/declaration";
import type { Backend, BackendKind } from "#/api/backend-registry/types";
import { BackendStatusDot } from "./backend-status-dot";
@@ -55,11 +56,13 @@ function BackendStatusBadge({
const { data: version } = useQuery({
queryKey: ["backend-version", backend.host, backend.apiKey],
queryFn: async () => {
- const info = await createServerClient({
- host: backend.host,
- sessionApiKey: backend.apiKey || null,
- timeout: 5000,
- }).getServerInfo();
+ const info = await new ServerClient(
+ getAgentServerClientOptions({
+ host: backend.host,
+ sessionApiKey: backend.apiKey || null,
+ timeout: 5000,
+ }),
+ ).getServerInfo();
return info.version ?? null;
},
retry: false,
diff --git a/src/components/features/backends/manage-backends-modal.tsx b/src/components/features/backends/manage-backends-modal.tsx
index c7988457db..50ea099066 100644
--- a/src/components/features/backends/manage-backends-modal.tsx
+++ b/src/components/features/backends/manage-backends-modal.tsx
@@ -3,8 +3,9 @@ import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { Plus } from "lucide-react";
+import { ServerClient } from "@openhands/typescript-client/clients";
import { type Backend } from "#/api/backend-registry/types";
-import { createServerClient } from "#/api/typescript-client";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { BrandButton } from "#/components/features/settings/brand-button";
import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";
import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
@@ -24,11 +25,13 @@ function BackendVersion({ backend }: { backend: Backend }) {
const { data: version } = useQuery({
queryKey: ["backend-version", backend.host, backend.apiKey],
queryFn: async () => {
- const info = await createServerClient({
- host: backend.host,
- sessionApiKey: backend.apiKey || null,
- timeout: 5000,
- }).getServerInfo();
+ const info = await new ServerClient(
+ getAgentServerClientOptions({
+ host: backend.host,
+ sessionApiKey: backend.apiKey || null,
+ timeout: 5000,
+ }),
+ ).getServerInfo();
return info.version ?? null;
},
retry: false,
diff --git a/src/components/features/files-tab/file-content-viewer.tsx b/src/components/features/files-tab/file-content-viewer.tsx
index 98aa308a89..f18d9381dc 100644
--- a/src/components/features/files-tab/file-content-viewer.tsx
+++ b/src/components/features/files-tab/file-content-viewer.tsx
@@ -2,10 +2,6 @@ import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
import { useWorkspaceFileContent } from "#/hooks/query/use-workspace-file-content";
-import {
- useWorkspaceMutationCounter,
- withWorkspaceCacheBuster,
-} from "#/stores/use-workspace-mutation-counter";
import { MarkdownRenderer } from "#/components/features/markdown/markdown-renderer";
import { HighlightedSourceView } from "./highlighted-source-view";
import type { ViewMode } from "./view-mode";
@@ -24,20 +20,14 @@ function getExtension(path: string): string {
}
/**
- * Renders the contents of a single workspace file. In `rich` mode we point
- * an iframe / <img> straight at the agent server's static workspace
- * fileserver for HTML / SVG / images / PDFs, so relative asset references
- * load naturally. In `plain` mode we always show the raw bytes as text (or
+ * Renders the contents of a single workspace file. In `rich` mode we render
+ * HTML / SVG / images / PDFs from the browser-renderable URL produced by the
+ * file-content hook. In `plain` mode we always show the raw bytes as text (or
* a fallback message for binaries).
*/
export function FileContentViewer({ path, viewMode }: FileContentViewerProps) {
const { t } = useTranslation("openhands");
const query = useWorkspaceFileContent(path);
- // Subscribe to the workspace mutation counter so the iframe / <img> src
- // changes after every agent-side edit, forcing a fresh fetch even when
- // the *path* hasn't moved (e.g. agent rewrote `style.css` referenced by
- // the currently-displayed `index.html`).
- const mutationCounter = useWorkspaceMutationCounter((state) => state.count);
if (query.isLoading) {
return (
@@ -66,7 +56,6 @@ export function FileContentViewer({ path, viewMode }: FileContentViewerProps) {
}
const { kind, text, staticUrl, mimeType } = query.data;
- const bustedStaticUrl = withWorkspaceCacheBuster(staticUrl, mutationCounter);
// ----- Plain mode: raw source bytes, syntax-highlighted when we can
// recognize the grammar (falls through to a `<pre>` otherwise). This
@@ -100,7 +89,7 @@ export function FileContentViewer({ path, viewMode }: FileContentViewerProps) {
data-testid="file-content-viewer-image"
>
<img
- src={bustedStaticUrl}
+ src={staticUrl}
alt={path}
className="max-h-full max-w-full object-contain"
/>
@@ -120,7 +109,7 @@ export function FileContentViewer({ path, viewMode }: FileContentViewerProps) {
return (
<iframe
title={path}
- src={bustedStaticUrl}
+ src={staticUrl}
sandbox="allow-same-origin"
data-testid="file-content-viewer-iframe"
className="h-full w-full bg-white"
@@ -141,17 +130,15 @@ export function FileContentViewer({ path, viewMode }: FileContentViewerProps) {
// Text-like content.
if (mimeType === "text/html" || HTML_LIKE_EXTS.has(getExtension(path))) {
- // Sandbox the preview iframe: `allow-same-origin` keeps the frame on
- // the workspace fileserver's origin so relative `<link href="…">`,
- // `<img src="…">`, etc. continue to resolve, while the absence of
- // `allow-scripts` means any `<script>` (or `onerror=…`, inline event
- // handler, …) inside the previewed file is inert. This is exactly
- // the safe-preview posture we want β€” users can look at their HTML
- // without it executing in the canvas's context.
+ // Sandbox the preview iframe. The absence of `allow-scripts` means any
+ // `<script>` (or `onerror=…`, inline event handler, …) inside the
+ // previewed file is inert. This is exactly the safe-preview posture we
+ // want β€” users can look at their HTML without it executing in the
+ // canvas's context.
return (
<iframe
title={path}
- src={bustedStaticUrl}
+ src={staticUrl}
sandbox="allow-same-origin"
data-testid="file-content-viewer-iframe"
className="h-full w-full bg-white"
diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsx
index ce2d636510..85370e105f 100644
--- a/src/contexts/conversation-websocket-context.tsx
+++ b/src/contexts/conversation-websocket-context.tsx
@@ -7,6 +7,8 @@ import React, {
useMemo,
useRef,
} from "react";
+import { ConversationClient } from "@openhands/typescript-client/clients";
+
import { useQueryClient } from "@tanstack/react-query";
import { usePostHog } from "posthog-js/react";
import { useWebSocket, WebSocketHookOptions } from "#/hooks/use-websocket";
@@ -44,7 +46,7 @@ import type {
SendMessageRequest,
} from "#/api/conversation-service/agent-server-conversation-service.types";
import EventService from "#/api/event-service/event-service.api";
-import PendingMessageService from "#/api/pending-message-service/pending-message-service.api";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { useConversationStore } from "#/stores/conversation-store";
import { trackError } from "#/utils/error-handler";
import { useReadConversationFile } from "#/hooks/mutation/use-read-conversation-file";
@@ -834,10 +836,14 @@ export function ConversationWebSocketProvider({
}
try {
- await PendingMessageService.queueMessage(conversationId, {
- role: "user",
- content: message.content,
- });
+ await new ConversationClient(getAgentServerClientOptions()).sendEvent(
+ conversationId,
+ {
+ role: "user",
+ content: message.content,
+ },
+ { run: true },
+ );
// Message queued successfully - it will be delivered when ready
// Return queued: true so caller knows not to show optimistic UI
return { queued: true };
diff --git a/src/hooks/mutation/conversation-mutation-utils.ts b/src/hooks/mutation/conversation-mutation-utils.ts
index e2fd3afd8b..5a28e12f33 100644
--- a/src/hooks/mutation/conversation-mutation-utils.ts
+++ b/src/hooks/mutation/conversation-mutation-utils.ts
@@ -1,6 +1,8 @@
import { QueryClient } from "@tanstack/react-query";
+import { ConversationClient } from "@openhands/typescript-client/clients";
import { getActiveBackend } from "#/api/backend-registry/active-store";
import { pauseCloudSandbox } from "#/api/cloud/conversation-service.api";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
@@ -44,11 +46,9 @@ export const pauseConversation = async (conversationId: string) => {
return { success: true };
}
- return AgentServerConversationService.pauseConversation(
- conversationId,
- conversationUrl,
- sessionApiKey,
- );
+ return new ConversationClient(
+ getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ ).pauseConversation(conversationId);
};
/**
@@ -60,22 +60,17 @@ export const askAgent = async (
): Promise<{ response: string }> => {
const { conversationUrl, sessionApiKey } =
await fetchConversationData(conversationId);
- return AgentServerConversationService.askAgent(
- conversationId,
- conversationUrl,
- question,
- sessionApiKey,
- );
+ return new ConversationClient(
+ getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ ).askAgent(conversationId, question);
};
export const resumeConversation = async (conversationId: string) => {
const { conversationUrl, sessionApiKey } =
await fetchConversationData(conversationId);
- return AgentServerConversationService.resumeConversation(
- conversationId,
- conversationUrl,
- sessionApiKey,
- );
+ return new ConversationClient(
+ getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ ).runConversation(conversationId);
};
export const updateConversationExecutionStatusInCache = (
diff --git a/src/hooks/mutation/use-conversation-upload-files.ts b/src/hooks/mutation/use-conversation-upload-files.ts
index fba7b5d552..7145797bfe 100644
--- a/src/hooks/mutation/use-conversation-upload-files.ts
+++ b/src/hooks/mutation/use-conversation-upload-files.ts
@@ -1,5 +1,6 @@
import { useMutation } from "@tanstack/react-query";
-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { FileUploadSuccessResponse } from "#/api/open-hands.types";
interface UploadFilesVariables {
@@ -27,12 +28,9 @@ export const useConversationUploadFiles = () =>
try {
// Upload to /workspace/{filename}
const filePath = `/workspace/${file.name}`;
- await AgentServerConversationService.uploadFile(
- conversationUrl,
- sessionApiKey,
- file,
- filePath,
- );
+ await new RemoteWorkspace(
+ getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ ).fileUpload(file, filePath);
return { success: true as const, fileName: file.name, filePath };
} catch (error) {
return {
diff --git a/src/hooks/query/use-ai-config-options.ts b/src/hooks/query/use-ai-config-options.ts
index a9d33984f1..c431a56fd1 100644
--- a/src/hooks/query/use-ai-config-options.ts
+++ b/src/hooks/query/use-ai-config-options.ts
@@ -1,10 +1,9 @@
import { useQuery } from "@tanstack/react-query";
-import OptionService from "#/api/option-service/option-service.api";
export const useAIConfigOptions = () =>
useQuery({
queryKey: ["ai-config-options"],
- queryFn: OptionService.getSecurityAnalyzers,
+ queryFn: () => ["llm", "pattern", "policy_rail"],
staleTime: 1000 * 60 * 5,
gcTime: 1000 * 60 * 15,
});
diff --git a/src/hooks/query/use-backends-health.ts b/src/hooks/query/use-backends-health.ts
index 6ff5a125ea..e9b6c9dc30 100644
--- a/src/hooks/query/use-backends-health.ts
+++ b/src/hooks/query/use-backends-health.ts
@@ -1,7 +1,8 @@
import { useQueries } from "@tanstack/react-query";
+import { ServerClient } from "@openhands/typescript-client/clients";
import { getCurrentCloudApiKey } from "#/api/cloud/organization-service.api";
import type { Backend } from "#/api/backend-registry/types";
-import { createServerClient } from "#/api/typescript-client";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
const REFRESH_INTERVAL_MS = 10000;
const PROBE_TIMEOUT_MS = 4000;
@@ -29,11 +30,13 @@ async function probeBackend(backend: Backend): Promise<true> {
return true;
}
- await createServerClient({
- host: backend.host,
- sessionApiKey: backend.apiKey || null,
- timeout: PROBE_TIMEOUT_MS,
- }).getServerInfo();
+ await new ServerClient(
+ getAgentServerClientOptions({
+ host: backend.host,
+ sessionApiKey: backend.apiKey || null,
+ timeout: PROBE_TIMEOUT_MS,
+ }),
+ ).getServerInfo();
return true;
}
diff --git a/src/hooks/query/use-conversation-hooks.ts b/src/hooks/query/use-conversation-hooks.ts
index 16fe4583e3..a69486518c 100644
--- a/src/hooks/query/use-conversation-hooks.ts
+++ b/src/hooks/query/use-conversation-hooks.ts
@@ -1,5 +1,5 @@
import { useQuery } from "@tanstack/react-query";
-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import type { HookEvent } from "#/api/conversation-service/agent-server-conversation-service.types";
import { useConversationId } from "../use-conversation-id";
import { AgentState } from "#/types/agent-state";
import { useAgentState } from "#/hooks/use-agent-state";
@@ -14,9 +14,7 @@ export const useConversationHooks = () => {
throw new Error("No conversation ID provided");
}
- const data =
- await AgentServerConversationService.getHooks(conversationId);
- return data.hooks;
+ return [] as HookEvent[];
},
enabled:
!!conversationId &&
diff --git a/src/hooks/query/use-conversation-skills.ts b/src/hooks/query/use-conversation-skills.ts
index 7c3655ad0d..4d8822fdd2 100644
--- a/src/hooks/query/use-conversation-skills.ts
+++ b/src/hooks/query/use-conversation-skills.ts
@@ -1,22 +1,21 @@
import { useQuery } from "@tanstack/react-query";
-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { loadSkillsForConversation } from "#/api/agent-server-adapter";
import { useConversationId } from "../use-conversation-id";
import { useActiveConversation } from "./use-active-conversation";
export const useConversationSkills = () => {
const { conversationId } = useConversationId();
- const executionStatus = useActiveConversation().data?.execution_status;
+ const activeConversation = useActiveConversation().data;
+ const executionStatus = activeConversation?.execution_status;
return useQuery({
- queryKey: ["conversation", conversationId, "skills"],
+ queryKey: ["conversation", conversationId, "skills", activeConversation],
queryFn: async () => {
if (!conversationId) {
throw new Error("No conversation ID provided");
}
- // Check if V1 is enabled and use the appropriate API
- const data =
- await AgentServerConversationService.getSkills(conversationId);
+ const data = await loadSkillsForConversation(activeConversation);
return data.skills;
},
enabled: !!executionStatus,
diff --git a/src/hooks/query/use-has-git-commits.ts b/src/hooks/query/use-has-git-commits.ts
index 18f74fd186..575f8b464a 100644
--- a/src/hooks/query/use-has-git-commits.ts
+++ b/src/hooks/query/use-has-git-commits.ts
@@ -1,6 +1,7 @@
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
import { useQuery } from "@tanstack/react-query";
-import { createRemoteWorkspace } from "#/api/typescript-client";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
@@ -44,10 +45,12 @@ export function useHasGitCommits(options?: { enabled?: boolean }): {
workingDir,
],
queryFn: async () => {
- const workspace = createRemoteWorkspace({
- conversationUrl,
- sessionApiKey,
- });
+ const workspace = new RemoteWorkspace(
+ getAgentServerClientOptions({
+ conversationUrl,
+ sessionApiKey,
+ }),
+ );
// `git rev-parse --verify HEAD` exits 0 iff HEAD resolves to a
// real commit. Returns non-zero in three cases that all collapse
diff --git a/src/hooks/query/use-local-git-info.ts b/src/hooks/query/use-local-git-info.ts
index 1b91fdd776..411433c5b2 100644
--- a/src/hooks/query/use-local-git-info.ts
+++ b/src/hooks/query/use-local-git-info.ts
@@ -1,6 +1,7 @@
import { useQuery } from "@tanstack/react-query";
-import { createRemoteWorkspace } from "#/api/typescript-client";
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
import { Provider } from "#/types/settings";
@@ -48,10 +49,12 @@ export const useLocalGitInfo = () => {
workingDir,
],
queryFn: async () => {
- const workspace = createRemoteWorkspace({
- conversationUrl,
- sessionApiKey,
- });
+ const workspace = new RemoteWorkspace(
+ getAgentServerClientOptions({
+ conversationUrl,
+ sessionApiKey,
+ }),
+ );
const [remoteResult, branchResult] = await Promise.all([
workspace.executeCommand("git remote get-url origin", workingDir, 10),
diff --git a/src/hooks/query/use-resolved-workspaces.ts b/src/hooks/query/use-resolved-workspaces.ts
index de8874dbe7..8be0d09c36 100644
--- a/src/hooks/query/use-resolved-workspaces.ts
+++ b/src/hooks/query/use-resolved-workspaces.ts
@@ -1,7 +1,8 @@
import { useMemo } from "react";
import { useQueries } from "@tanstack/react-query";
+import { FileClient } from "@openhands/typescript-client/clients";
-import FilesService from "#/api/files-service/files-service.api";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { useWorkspacesStore } from "#/stores/workspaces-store";
import { LocalWorkspace, LocalWorkspaceParent } from "#/types/workspace";
@@ -18,11 +19,13 @@ interface UseResolvedWorkspacesResult {
* effectively the user's projects root in the dockerized dev stack. We
* surface its immediate subdirectories as workspaces automatically.
*
- * In environments where `/projects` doesn't exist (e.g. dockerless dev),
- * the `searchSubdirs` call will fail and the implicit parent contributes
- * no entries. This is safe and intentional β€” the implicit parent stays
- * silent rather than user-visible.
+ * This is a development convenience only. Production previews may point at
+ * arbitrary remote agent servers that do not expose the file-browser endpoint;
+ * probing `/projects` there creates noisy 404s before the user has added any
+ * workspace parent explicitly.
*/
+const INCLUDE_IMPLICIT_WORKSPACE_PARENTS = import.meta.env.DEV;
+
const IMPLICIT_WORKSPACE_PARENTS: LocalWorkspaceParent[] = [
{ id: "implicit:/projects", name: "/projects", path: "/projects" },
];
@@ -48,14 +51,20 @@ export function useResolvedWorkspaces(): UseResolvedWorkspacesResult {
const seen = new Set(storedParents.map((p) => p.path));
// Filter out implicit parents that conflict with user-added ones (by path)
// so custom names/ids are preserved.
- const extras = IMPLICIT_WORKSPACE_PARENTS.filter((p) => !seen.has(p.path));
+ const implicitParents = INCLUDE_IMPLICIT_WORKSPACE_PARENTS
+ ? IMPLICIT_WORKSPACE_PARENTS
+ : [];
+ const extras = implicitParents.filter((p) => !seen.has(p.path));
return extras.length === 0 ? storedParents : [...storedParents, ...extras];
}, [storedParents]);
const parentQueries = useQueries({
queries: workspaceParents.map((parent) => ({
queryKey: ["file", "search_subdirs", parent.path],
- queryFn: () => FilesService.searchSubdirs(parent.path),
+ queryFn: () =>
+ new FileClient(getAgentServerClientOptions()).searchSubdirectories(
+ parent.path,
+ ),
retry: false,
meta: { disableToast: true },
})),
diff --git a/src/hooks/query/use-search-subdirs.ts b/src/hooks/query/use-search-subdirs.ts
index 21ad08add1..6fe5c11484 100644
--- a/src/hooks/query/use-search-subdirs.ts
+++ b/src/hooks/query/use-search-subdirs.ts
@@ -1,12 +1,28 @@
import { useQuery } from "@tanstack/react-query";
-import FilesService from "#/api/files-service/files-service.api";
+import { FileClient } from "@openhands/typescript-client/clients";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { useActiveBackend } from "#/contexts/active-backend-context";
+export interface FileBrowserEntry {
+ label: string;
+ path: string;
+}
+
+export interface HomeDirectoryResponse {
+ home: string;
+ favorites?: FileBrowserEntry[];
+ locations?: FileBrowserEntry[];
+}
+
+function getFileClient() {
+ return new FileClient(getAgentServerClientOptions());
+}
+
export const useSearchSubdirs = (path: string | null) => {
const active = useActiveBackend();
return useQuery({
queryKey: ["file", "search_subdirs", path, active.backend.id, active.orgId],
- queryFn: () => FilesService.searchSubdirs(path as string),
+ queryFn: () => getFileClient().searchSubdirectories(path as string),
enabled: !!path,
retry: false,
meta: { disableToast: true },
@@ -17,7 +33,8 @@ export const useHomeDirectory = () => {
const active = useActiveBackend();
return useQuery({
queryKey: ["file", "home", active.backend.id, active.orgId],
- queryFn: () => FilesService.getHome(),
+ queryFn: async (): Promise<HomeDirectoryResponse> =>
+ getFileClient().getHome(),
retry: false,
meta: { disableToast: true },
staleTime: Infinity,
diff --git a/src/hooks/query/use-shared-conversation-events.ts b/src/hooks/query/use-shared-conversation-events.ts
index 9adcc15ce1..92aa5782d8 100644
--- a/src/hooks/query/use-shared-conversation-events.ts
+++ b/src/hooks/query/use-shared-conversation-events.ts
@@ -1,5 +1,12 @@
import { useInfiniteQuery } from "@tanstack/react-query";
-import { sharedConversationService } from "#/api/shared-conversation-service.api";
+import { SharedClient } from "@openhands/typescript-client/clients";
+import type { OpenHandsEvent } from "#/types/agent-server/core";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
+
+interface SharedEventPage {
+ items: OpenHandsEvent[];
+ next_page_id: string | null;
+}
export const useSharedConversationEvents = (conversationId?: string) =>
useInfiniteQuery({
@@ -8,11 +15,13 @@ export const useSharedConversationEvents = (conversationId?: string) =>
if (!conversationId) {
throw new Error("Conversation ID is required");
}
- return sharedConversationService.getSharedConversationEvents(
- conversationId,
- 100,
- pageParam,
- );
+ return new SharedClient(getAgentServerClientOptions()).searchSharedEvents(
+ {
+ conversationId,
+ limit: 100,
+ pageId: pageParam,
+ },
+ ) as Promise<SharedEventPage>;
},
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) => lastPage.next_page_id ?? undefined,
diff --git a/src/hooks/query/use-shared-conversation.ts b/src/hooks/query/use-shared-conversation.ts
index 9fd6b51ce3..bb99eaddab 100644
--- a/src/hooks/query/use-shared-conversation.ts
+++ b/src/hooks/query/use-shared-conversation.ts
@@ -1,5 +1,6 @@
import { useQuery } from "@tanstack/react-query";
-import { sharedConversationService } from "#/api/shared-conversation-service.api";
+import { SharedClient } from "@openhands/typescript-client/clients";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
export const useSharedConversation = (conversationId?: string) =>
useQuery({
@@ -8,7 +9,9 @@ export const useSharedConversation = (conversationId?: string) =>
if (!conversationId) {
throw new Error("Conversation ID is required");
}
- return sharedConversationService.getSharedConversation(conversationId);
+ return new SharedClient(
+ getAgentServerClientOptions(),
+ ).getSharedConversation(conversationId);
},
enabled: !!conversationId,
retry: false, // Don't retry for shared conversations
diff --git a/src/hooks/query/use-start-tasks.ts b/src/hooks/query/use-start-tasks.ts
index 9a3f2e88ab..4090cf5896 100644
--- a/src/hooks/query/use-start-tasks.ts
+++ b/src/hooks/query/use-start-tasks.ts
@@ -1,5 +1,5 @@
import { useQuery } from "@tanstack/react-query";
-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import type { AppConversationStartTask } from "#/api/conversation-service/agent-server-conversation-service.types";
/**
* Hook to fetch in-progress conversation start tasks
@@ -15,7 +15,7 @@ import AgentServerConversationService from "#/api/conversation-service/agent-ser
export const useStartTasks = (limit = 10) =>
useQuery({
queryKey: ["start-tasks", "search", limit],
- queryFn: () => AgentServerConversationService.searchStartTasks(limit),
+ queryFn: (): AppConversationStartTask[] => [],
select: (tasks) =>
tasks.filter(
(task) => task.status !== "READY" && task.status !== "ERROR",
diff --git a/src/hooks/query/use-verified-models.ts b/src/hooks/query/use-verified-models.ts
index 55958aeaf2..e8c9e7a214 100644
--- a/src/hooks/query/use-verified-models.ts
+++ b/src/hooks/query/use-verified-models.ts
@@ -1,5 +1,6 @@
import { useQuery } from "@tanstack/react-query";
-import { createLlmMetadataClient } from "#/api/typescript-client";
+import { LLMMetadataClient } from "@openhands/typescript-client/clients";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
export const VERIFIED_MODELS_QUERY_KEY = ["config", "verified-models"] as const;
export const VERIFIED_MODELS_STALE_TIME = 1000 * 60 * 5;
@@ -8,7 +9,7 @@ export const VERIFIED_MODELS_GC_TIME = 1000 * 60 * 15;
export async function fetchVerifiedModelsByProvider(): Promise<
Record<string, string[]>
> {
- const client = createLlmMetadataClient();
+ const client = new LLMMetadataClient(getAgentServerClientOptions());
return (await client.getVerifiedModels()) ?? {};
}
diff --git a/src/hooks/query/use-workspace-file-content.ts b/src/hooks/query/use-workspace-file-content.ts
index a6524b7562..32018e7ef6 100644
--- a/src/hooks/query/use-workspace-file-content.ts
+++ b/src/hooks/query/use-workspace-file-content.ts
@@ -1,11 +1,10 @@
import { useQuery } from "@tanstack/react-query";
+import { FileClient } from "@openhands/typescript-client/clients";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
-import {
- joinWorkspaceUrl,
- useWorkspaceSession,
-} from "#/hooks/query/use-workspace-session";
+import { useWorkspaceMutationCounter } from "#/stores/use-workspace-mutation-counter";
// Magic-number sniff for common binary formats we can render via iframe.
const IMAGE_EXTENSIONS = new Set([
@@ -30,10 +29,8 @@ export interface WorkspaceFileContent {
/** Decoded text contents β€” only populated when kind === "text". */
text: string | null;
/**
- * URL pointing at the file on the agent server's static workspace
- * fileserver (the `/api/conversations/{id}/workspace/...` route added in
- * software-agent-sdk PR #3192). Suitable to use as an `<iframe src>` or
- * `<img src>` against unauthenticated agent servers. Always populated.
+ * Browser-renderable URL for rich previews and "open in new window".
+ * Usually a local Blob URL derived from `/api/file/download` bytes.
*/
staticUrl: string;
/** MIME type guessed from the file extension. */
@@ -105,15 +102,38 @@ function isLikelyBinary(buffer: ArrayBuffer): boolean {
return false;
}
+function resolveWorkspacePath(
+ workingDir: string,
+ relativePath: string,
+): string {
+ const normalizedWorkingDir = workingDir.replace(/\/+$/, "");
+ const segments: string[] = [];
+
+ for (const segment of relativePath.replace(/^\/+/, "").split("/")) {
+ if (!segment || segment === ".") continue;
+ if (segment === "..") {
+ throw new Error("Workspace file path must stay inside the workspace");
+ }
+ segments.push(segment);
+ }
+
+ if (!normalizedWorkingDir.startsWith("/") || segments.length === 0) {
+ throw new Error("Invalid workspace file path");
+ }
+
+ return `${normalizedWorkingDir}/${segments.join("/")}`;
+}
+
+function makePreviewUrl(buffer: ArrayBuffer, mimeType: string): string {
+ return URL.createObjectURL(new Blob([buffer], { type: mimeType }));
+}
+
/**
- * Reads a single file out of the active conversation's workspace via the
- * agent server's static workspace fileserver and classifies it as
- * text/image/pdf/binary so the UI can pick a renderer.
- *
- * Image and PDF kinds are rendered directly from `staticUrl` (no fetch
- * here). Text/binary classification still requires reading the body so
- * we can run a NUL-byte sniff and decode UTF-8 for the plain/markdown
- * renderers.
+ * Reads a single file out of the active conversation's workspace through the
+ * typed file API and classifies it as text/image/pdf/binary so the UI can pick
+ * a renderer. We intentionally avoid the cookie-based workspace-session route
+ * here: older live agent-server previews may not expose it yet, and credentialed
+ * cross-origin requests fail when those backends return wildcard CORS headers.
*
* Pass a falsy `relativePath` to disable the query (e.g. when no file is
* selected yet).
@@ -121,63 +141,55 @@ function isLikelyBinary(buffer: ArrayBuffer): boolean {
export function useWorkspaceFileContent(relativePath: string | null) {
const { data: conversation } = useActiveConversation();
const runtimeIsReady = useRuntimeIsReady();
- const { data: workspaceSession } = useWorkspaceSession();
+ const workspaceMutationCount = useWorkspaceMutationCounter(
+ (state) => state.count,
+ );
const conversationId = conversation?.id;
const conversationUrl = conversation?.conversation_url;
- const baseUrl = workspaceSession?.baseUrl;
+ const sessionApiKey = conversation?.session_api_key;
+ const workingDir = conversation?.workspace?.working_dir?.trim();
return useQuery<WorkspaceFileContent>({
queryKey: [
"workspace-file-content",
conversationId,
conversationUrl,
- baseUrl,
+ sessionApiKey,
+ workingDir,
relativePath,
+ workspaceMutationCount,
],
queryFn: async () => {
if (!relativePath) throw new Error("No path");
- if (!baseUrl) throw new Error("No workspace session");
+ if (!workingDir) throw new Error("No workspace directory");
- const staticUrl = joinWorkspaceUrl(baseUrl, relativePath);
const kind = classifyKind(relativePath);
const mimeType = guessMimeType(relativePath);
+ const filePath = resolveWorkspacePath(workingDir, relativePath);
+ const fileClient = new FileClient(
+ getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ );
+ const buffer = await fileClient.downloadFile(filePath);
- // Image / PDF: don't fetch the bytes β€” the consumer renders them
- // directly via `staticUrl` in an iframe or <img>. The browser
- // will attach the `oh_workspace_session_key` cookie minted by
- // `useWorkspaceSession` so the request authenticates without us
- // having to set any headers (which a top-level <iframe src> can't
- // do anyway).
if (kind !== "text") {
return {
path: relativePath,
kind,
text: null,
- staticUrl,
+ staticUrl: makePreviewUrl(buffer, mimeType),
mimeType,
};
}
- // For our own fetch we also rely on the workspace-session cookie
- // (it travels because we opt in to credentialed requests). This
- // replaces the previous `X-Session-API-Key` header: same auth
- // path the iframe/img uses, no CORS preflight for a custom header.
- const response = await fetch(staticUrl, {
- credentials: "include",
- });
- if (!response.ok) {
- throw new Error(`Failed to read ${relativePath}: ${response.status}`);
- }
-
- const buffer = await response.arrayBuffer();
if (isLikelyBinary(buffer)) {
+ const binaryMimeType = "application/octet-stream";
return {
path: relativePath,
kind: "binary",
text: null,
- staticUrl,
- mimeType: "application/octet-stream",
+ staticUrl: makePreviewUrl(buffer, binaryMimeType),
+ mimeType: binaryMimeType,
};
}
@@ -186,15 +198,12 @@ export function useWorkspaceFileContent(relativePath: string | null) {
path: relativePath,
kind: "text",
text,
- staticUrl,
+ staticUrl: makePreviewUrl(buffer, mimeType),
mimeType,
};
},
- // Gate on `baseUrl`: until `useWorkspaceSession` has minted the
- // workspace cookie, we cannot fetch `staticUrl` (would 401) and
- // we'd hand `<iframe src>` a URL that doesn't authenticate. Once
- // the session resolves the query unblocks automatically.
- enabled: runtimeIsReady && !!baseUrl && !!relativePath,
+ enabled:
+ runtimeIsReady && !!conversationId && !!workingDir && !!relativePath,
retry: false,
staleTime: 1000 * 5,
gcTime: 1000 * 60,
diff --git a/src/hooks/query/use-workspace-files.ts b/src/hooks/query/use-workspace-files.ts
index 674eb16af1..d4b1759001 100644
--- a/src/hooks/query/use-workspace-files.ts
+++ b/src/hooks/query/use-workspace-files.ts
@@ -1,6 +1,7 @@
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
import { useQuery } from "@tanstack/react-query";
-import { createRemoteWorkspace } from "#/api/typescript-client";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
@@ -61,10 +62,12 @@ export function useWorkspaceFiles() {
workingDir,
],
queryFn: async () => {
- const workspace = createRemoteWorkspace({
- conversationUrl,
- sessionApiKey,
- });
+ const workspace = new RemoteWorkspace(
+ getAgentServerClientOptions({
+ conversationUrl,
+ sessionApiKey,
+ }),
+ );
const result = await workspace.executeCommand(
buildListCommand(),
diff --git a/src/hooks/query/use-workspace-session.ts b/src/hooks/query/use-workspace-session.ts
index a197dccbc2..524e7c01d2 100644
--- a/src/hooks/query/use-workspace-session.ts
+++ b/src/hooks/query/use-workspace-session.ts
@@ -1,6 +1,7 @@
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
import { useQuery } from "@tanstack/react-query";
-import { createRemoteWorkspace } from "#/api/typescript-client";
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
@@ -56,10 +57,12 @@ export function useWorkspaceSession(): {
sessionApiKey,
],
queryFn: async () => {
- const workspace = createRemoteWorkspace({
- conversationUrl,
- sessionApiKey,
- });
+ const workspace = new RemoteWorkspace(
+ getAgentServerClientOptions({
+ conversationUrl,
+ sessionApiKey,
+ }),
+ );
const baseUrl = await workspace.startWorkspaceSession(conversationId!);
return { baseUrl };
},
diff --git a/src/routes/files-tab.tsx b/src/routes/files-tab.tsx
index 2ef9886610..a03d7a7be4 100644
--- a/src/routes/files-tab.tsx
+++ b/src/routes/files-tab.tsx
@@ -11,10 +11,6 @@ import { useAutoRefreshFilesOnEdit } from "#/hooks/use-auto-refresh-files-on-edi
import { useUnifiedGetGitChanges } from "#/hooks/query/use-unified-get-git-changes";
import { useOptionalConversationId } from "#/hooks/use-conversation-id";
import { useConversationLocalStorageState } from "#/utils/conversation-local-storage";
-import {
- useWorkspaceMutationCounter,
- withWorkspaceCacheBuster,
-} from "#/stores/use-workspace-mutation-counter";
import { sortFilesByPriority } from "#/utils/file-priority";
import { FileQuickRow } from "#/components/features/files-tab/file-quick-row";
import { FileTreeView } from "#/components/features/files-tab/file-tree-view";
@@ -75,11 +71,7 @@ function FilesTab() {
// dedupes against `FileContentViewer`'s identical call, so this costs
// nothing extra.
const selectedFileContent = useWorkspaceFileContent(selectedPath);
- const mutationCounter = useWorkspaceMutationCounter((state) => state.count);
- const selectedFileStaticUrl = withWorkspaceCacheBuster(
- selectedFileContent.data?.staticUrl ?? null,
- mutationCounter,
- );
+ const selectedFileStaticUrl = selectedFileContent.data?.staticUrl ?? null;
// Auto-select the highest-priority file the first time we load the list,
// so users see something useful immediately.
@@ -137,7 +129,7 @@ function FilesTab() {
<div className="ml-auto flex items-center gap-1">
{/* Open the currently-selected file in a new browser tab. Only
meaningful while we're showing a file (not the diff view) and
- we've resolved its staticUrl from the workspace fileserver. */}
+ we've resolved its browser-renderable preview URL. */}
{!diffViewEnabled && selectedFileStaticUrl && (
<a
href={selectedFileStaticUrl}
diff --git a/src/stores/use-workspace-mutation-counter.ts b/src/stores/use-workspace-mutation-counter.ts
index 5a570ce437..b2f409bd05 100644
--- a/src/stores/use-workspace-mutation-counter.ts
+++ b/src/stores/use-workspace-mutation-counter.ts
@@ -2,18 +2,14 @@ import { create } from "zustand";
/**
* Monotonic counter that ticks every time the agent commits a file-editor
- * mutation in the workspace. Used as a cache-buster for resources we serve
- * via the agent server's static workspace fileserver (iframes, images, PDFs):
- * appending `?v=<count>` to those URLs forces the browser to re-request a
- * fresh copy after each edit instead of reusing the previously-fetched
- * response β€” important because the rendered HTML may reference other
- * assets (CSS, images) that the user can't see directly but expects to
- * reflect the latest version of the workspace.
+ * mutation in the workspace. The file-content query includes this counter in
+ * its query key, so the selected file is refetched after each edit even when
+ * the selected path has not changed.
*
* Consumers:
* - {@link useAutoRefreshFilesOnEdit} bumps this on each mutation event.
- * - {@link FileContentViewer} reads the count and appends it to its
- * `<iframe>` / `<img>` src.
+ * - {@link useWorkspaceFileContent} reads the count and refreshes its Blob
+ * preview URL and decoded text.
*/
interface WorkspaceMutationCounterState {
count: number;
@@ -25,22 +21,3 @@ export const useWorkspaceMutationCounter =
count: 0,
bump: () => set((state) => ({ count: state.count + 1 })),
}));
-
-/**
- * Append the current mutation counter as a `v=<n>` query parameter so the
- * browser refetches the URL after every agent-side edit. Returns `null` if
- * the input is `null` so callers can pass through optional URLs untouched.
- */
-export function withWorkspaceCacheBuster(url: string, version: number): string;
-export function withWorkspaceCacheBuster(
- url: string | null,
- version: number,
-): string | null;
-export function withWorkspaceCacheBuster(
- url: string | null,
- version: number,
-): string | null {
- if (url === null) return null;
- const sep = url.includes("?") ? "&" : "?";
- return `${url}${sep}v=${version}`;
-}