Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: stop calling /api/auth/workspace-session on cloud backends (#763)

Hiep Lebf5b9e4390e7
diff --git a/__tests__/hooks/query/use-workspace-file-content.test.tsx b/__tests__/hooks/query/use-workspace-file-content.test.tsx
index ef751604a1..de3c66a330 100644
--- a/__tests__/hooks/query/use-workspace-file-content.test.tsx
+++ b/__tests__/hooks/query/use-workspace-file-content.test.tsx
@@ -30,6 +30,18 @@ vi.mock("#/hooks/use-runtime-is-ready", () => ({
useRuntimeIsReady: () => useRuntimeIsReadyMock(),
}));
+const getActiveBackendMock = vi.fn();
+vi.mock("#/api/backend-registry/active-store", () => ({
+ getActiveBackend: () => getActiveBackendMock(),
+}));
+
+const downloadFileMock = vi.fn();
+vi.mock("#/api/runtime-service/agent-server-runtime-service", () => ({
+ default: {
+ downloadFile: (...args: unknown[]) => downloadFileMock(...args),
+ },
+}));
+
const fetchMock = vi.fn();
function makeWrapper() {
@@ -58,6 +70,8 @@ describe("useWorkspaceFileContent", () => {
useWorkspaceSessionMock.mockReset();
useActiveConversationMock.mockReset();
useRuntimeIsReadyMock.mockReset();
+ getActiveBackendMock.mockReset();
+ downloadFileMock.mockReset();
useRuntimeIsReadyMock.mockReturnValue(true);
useActiveConversationMock.mockReturnValue({
data: {
@@ -72,6 +86,10 @@ describe("useWorkspaceFileContent", () => {
isError: false,
error: null,
});
+ getActiveBackendMock.mockReturnValue({
+ backend: { id: "local-1", kind: "local", host: "http://localhost:8000" },
+ orgId: null,
+ });
useWorkspaceMutationCounter.setState({ count: 0 });
});
@@ -245,4 +263,70 @@ describe("useWorkspaceFileContent", () => {
}),
);
});
+
+ describe("cloud backend", () => {
+ beforeEach(() => {
+ getActiveBackendMock.mockReturnValue({
+ backend: {
+ id: "cloud-1",
+ kind: "cloud",
+ host: "https://app.all-hands.dev",
+ },
+ orgId: "org-1",
+ });
+ // useWorkspaceSession self-disables on cloud β€” its data is null.
+ useWorkspaceSessionMock.mockReturnValue({
+ data: null,
+ isLoading: false,
+ isError: false,
+ error: null,
+ });
+ });
+
+ it("fetches text via downloadFile and exposes a data: URI staticUrl", async () => {
+ downloadFileMock.mockResolvedValue(arrayBufferFromString("# Hello"));
+
+ const { result } = renderHook(
+ () => useWorkspaceFileContent("docs/readme.md"),
+ { wrapper: makeWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(downloadFileMock).toHaveBeenCalledWith(
+ "https://agent.example.com/api/conversations/conv-1",
+ "session-key",
+ "docs/readme.md",
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(result.current.data).toEqual({
+ path: "docs/readme.md",
+ kind: "text",
+ text: "# Hello",
+ staticUrl: `data:text/markdown;charset=utf-8;base64,${btoa("# Hello")}`,
+ mimeType: "text/markdown",
+ });
+ });
+
+ it("renders images via base64 data URI bytes from downloadFile", async () => {
+ const imageBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]).buffer;
+ downloadFileMock.mockResolvedValue(imageBytes);
+
+ const { result } = renderHook(
+ () => useWorkspaceFileContent("assets/logo.png"),
+ { wrapper: makeWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(result.current.data).toEqual({
+ path: "assets/logo.png",
+ kind: "image",
+ text: null,
+ staticUrl: `data:image/png;base64,${btoa("\x89PNG")}`,
+ mimeType: "image/png",
+ });
+ });
+ });
});
diff --git a/__tests__/hooks/query/use-workspace-session.test.tsx b/__tests__/hooks/query/use-workspace-session.test.tsx
index 70f3fac413..03615e5aca 100644
--- a/__tests__/hooks/query/use-workspace-session.test.tsx
+++ b/__tests__/hooks/query/use-workspace-session.test.tsx
@@ -142,7 +142,7 @@ describe("useWorkspaceSession", () => {
});
describe("cloud backend", () => {
- it("routes through callCloudProxy with correct path and auth", async () => {
+ it("does not fire any request β€” workspace-session is local-only", async () => {
getActiveBackendMock.mockReturnValue({
backend: {
id: "cloud-1",
@@ -158,59 +158,14 @@ describe("useWorkspaceSession", () => {
session_api_key: "cloud-key-xyz",
},
});
- callCloudProxyMock.mockResolvedValue({
- base_url: "https://abc123.prod-runtime.all-hands.dev/api/conversations/conv-cloud/workspace/",
- });
const { result } = renderHook(() => useWorkspaceSession(), {
wrapper: makeWrapper(),
});
- await waitFor(() => {
- expect(result.current.data?.baseUrl).toBe(
- "https://abc123.prod-runtime.all-hands.dev/api/conversations/conv-cloud/workspace/",
- );
- });
-
- expect(callCloudProxyMock).toHaveBeenCalledTimes(1);
- const proxyCall = callCloudProxyMock.mock.calls[0][0];
- expect(proxyCall.backend.id).toBe("cloud-1");
- expect(proxyCall.method).toBe("POST");
- expect(proxyCall.path).toBe("/api/auth/workspace-session");
- expect(proxyCall.body).toEqual({ conversation_id: "conv-cloud" });
- expect(proxyCall.authMode).toBe("session-api-key");
- expect(proxyCall.sessionApiKey).toBe("cloud-key-xyz");
- // buildHttpBaseUrl uses the browser's protocol, which in jsdom is http:
- expect(proxyCall.hostOverride).toBe(
- "http://abc123.prod-runtime.all-hands.dev",
- );
- expect(RemoteWorkspace).not.toHaveBeenCalled();
- });
-
- it("surfaces the error when the cloud workspace-session POST fails", async () => {
- getActiveBackendMock.mockReturnValue({
- backend: {
- id: "cloud-1",
- kind: "cloud",
- host: "https://app.all-hands.dev",
- },
- });
- useActiveConversationMock.mockReturnValue({
- data: {
- id: "conv-cloud",
- conversation_url:
- "https://abc123.prod-runtime.all-hands.dev/api/conversations/conv-cloud",
- session_api_key: "bad-key",
- },
- });
- callCloudProxyMock.mockRejectedValue(new Error("401 Unauthorized"));
-
- const { result } = renderHook(() => useWorkspaceSession(), {
- wrapper: makeWrapper(),
- });
-
- await waitFor(() => expect(result.current.isError).toBe(true));
- expect(result.current.error?.message).toMatch(/401/);
+ await flushScheduler();
+ expect(callCloudProxyMock).not.toHaveBeenCalled();
+ expect(startWorkspaceSessionMock).not.toHaveBeenCalled();
expect(result.current.data).toBeNull();
});
});
diff --git a/src/hooks/query/use-workspace-file-content.ts b/src/hooks/query/use-workspace-file-content.ts
index 57bc039611..134805596c 100644
--- a/src/hooks/query/use-workspace-file-content.ts
+++ b/src/hooks/query/use-workspace-file-content.ts
@@ -1,5 +1,7 @@
import { useQuery } from "@tanstack/react-query";
+import { getActiveBackend } from "#/api/backend-registry/active-store";
+import AgentServerRuntimeService from "#/api/runtime-service/agent-server-runtime-service";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
import {
@@ -108,6 +110,21 @@ function isLikelyBinary(buffer: ArrayBuffer): boolean {
return false;
}
+function arrayBufferToBase64(buffer: ArrayBuffer): string {
+ const bytes = new Uint8Array(buffer);
+ // Chunk to stay under the call-stack limit of `String.fromCharCode(...arr)`
+ // for larger files (>~100KB) while avoiding per-byte allocation.
+ const CHUNK = 0x8000;
+ let binary = "";
+ for (let i = 0; i < bytes.length; i += CHUNK) {
+ binary += String.fromCharCode.apply(
+ null,
+ bytes.subarray(i, i + CHUNK) as unknown as number[],
+ );
+ }
+ return btoa(binary);
+}
+
/**
* Reads a single file out of the active conversation's workspace via the
* agent server's static workspace fileserver and classifies it as
@@ -137,25 +154,73 @@ export function useWorkspaceFileContent(relativePath: string | null) {
const conversationId = conversation?.id;
const conversationUrl = conversation?.conversation_url;
+ const sessionApiKey = conversation?.session_api_key;
const baseUrl = workspaceSession?.baseUrl;
+ const isCloud = getActiveBackend().backend.kind === "cloud";
return useQuery<WorkspaceFileContent>({
queryKey: [
"workspace-file-content",
conversationId,
conversationUrl,
- baseUrl,
+ sessionApiKey,
+ isCloud ? "cloud" : baseUrl,
relativePath,
workspaceMutationCount,
],
queryFn: async () => {
if (!relativePath) throw new Error("No path");
- if (!baseUrl) throw new Error("No workspace session");
- const staticUrl = joinWorkspaceUrl(baseUrl, relativePath);
const kind = classifyKind(relativePath);
const mimeType = guessMimeType(relativePath);
+ if (isCloud) {
+ // Cloud: no static fileserver cookie path is reachable from the
+ // browser. Fetch bytes server-side through callCloudProxy and
+ // hand the consumer a self-contained `data:` URI for iframe /
+ // <img> rendering.
+ const buffer = await AgentServerRuntimeService.downloadFile(
+ conversationUrl,
+ sessionApiKey,
+ relativePath,
+ );
+ if (kind === "text") {
+ if (isLikelyBinary(buffer)) {
+ return {
+ path: relativePath,
+ kind: "binary",
+ text: null,
+ staticUrl: `data:application/octet-stream;base64,${arrayBufferToBase64(buffer)}`,
+ mimeType: "application/octet-stream",
+ };
+ }
+ const text = new TextDecoder("utf-8", { fatal: false }).decode(
+ buffer,
+ );
+ return {
+ path: relativePath,
+ kind: "text",
+ text,
+ staticUrl: `data:${mimeType};charset=utf-8;base64,${arrayBufferToBase64(buffer)}`,
+ mimeType,
+ };
+ }
+ return {
+ path: relativePath,
+ kind,
+ text: null,
+ staticUrl: `data:${mimeType};base64,${arrayBufferToBase64(buffer)}`,
+ mimeType,
+ };
+ }
+
+ // Local: rely on the workspace-session cookie minted by
+ // useWorkspaceSession to authenticate the same-origin static
+ // fileserver fetch.
+ if (!baseUrl) throw new Error("No workspace session");
+
+ const staticUrl = joinWorkspaceUrl(baseUrl, relativePath);
+
// 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
@@ -203,7 +268,11 @@ export function useWorkspaceFileContent(relativePath: string | null) {
mimeType,
};
},
- enabled: runtimeIsReady && !!conversationId && !!baseUrl && !!relativePath,
+ enabled:
+ runtimeIsReady &&
+ !!conversationId &&
+ !!relativePath &&
+ (isCloud || !!baseUrl),
retry: false,
staleTime: 1000 * 5,
gcTime: 1000 * 60,
diff --git a/src/hooks/query/use-workspace-session.ts b/src/hooks/query/use-workspace-session.ts
index c4a9a954c5..fd5be818a8 100644
--- a/src/hooks/query/use-workspace-session.ts
+++ b/src/hooks/query/use-workspace-session.ts
@@ -2,8 +2,6 @@ import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-w
import { useQuery } from "@tanstack/react-query";
import { getActiveBackend } from "#/api/backend-registry/active-store";
-import { callCloudProxy } from "#/api/cloud/proxy";
-import { buildHttpBaseUrl } from "#/utils/websocket-url";
import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
@@ -27,6 +25,14 @@ export interface WorkspaceSession {
* navigations β€” which it cannot do when the only credential is a custom
* request header.
*
+ * Local-only. The cookie flow is useless on cloud: the POST would be a
+ * server-side hop through `callCloudProxy` (so the `Set-Cookie` never
+ * reaches the browser jar), and the runtime sandbox is cross-origin with
+ * the GUI (so `fetch(staticUrl, { credentials: "include" })` couldn't
+ * attach the cookie anyway). On cloud, `useWorkspaceFileContent` fetches
+ * bytes through `callCloudProxy` directly and renders binary kinds as
+ * `data:` URIs, so this hook stays disabled and returns `data: null`.
+ *
* We treat the call as cache-once-per-conversation: the cookie lives in
* the browser jar, so re-issuing the POST on every component remount is
* wasted work. `staleTime: Infinity` keeps the cached `baseUrl` in place
@@ -49,8 +55,9 @@ export function useWorkspaceSession(): {
const conversationId = conversation?.id;
const conversationUrl = conversation?.conversation_url;
const sessionApiKey = conversation?.session_api_key;
+ const isLocal = getActiveBackend().backend.kind === "local";
- const enabled = runtimeIsReady && !!conversationId;
+ const enabled = runtimeIsReady && !!conversationId && isLocal;
const query = useQuery<WorkspaceSession>({
queryKey: [
@@ -60,24 +67,6 @@ export function useWorkspaceSession(): {
sessionApiKey,
],
queryFn: async () => {
- const active = getActiveBackend().backend;
-
- if (active.kind === "cloud" && conversationUrl) {
- // Cloud conversations: route through callCloudProxy to avoid CORS
- // restrictions on direct browser β†’ runtime sandbox calls.
- const response = await callCloudProxy<{ base_url: string }>({
- backend: active,
- method: "POST",
- hostOverride: buildHttpBaseUrl(conversationUrl),
- path: "/api/auth/workspace-session",
- body: { conversation_id: conversationId },
- authMode: "session-api-key",
- sessionApiKey,
- });
- return { baseUrl: response.base_url };
- }
-
- // Local conversations: use the SDK client directly.
const workspace = new RemoteWorkspace(
getAgentServerClientOptions({
conversationUrl,