Skip to content

🙌 OpenHands: AI-Driven Development

fix(files-tab): restore static fileserver for rich file preview (#632)

Robert Brennanc9fc3219b5bd
diff --git a/__tests__/hooks/query/use-workspace-file-content.test.tsx b/__tests__/hooks/query/use-workspace-file-content.test.tsx
index 12786f8cbb..ef751604a1 100644
--- a/__tests__/hooks/query/use-workspace-file-content.test.tsx
+++ b/__tests__/hooks/query/use-workspace-file-content.test.tsx
@@ -3,50 +3,23 @@ import { act, renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- __resetActiveStoreForTests,
- setActiveSelection,
- setRegisteredBackends,
-} from "#/api/backend-registry/active-store";
-import { callCloudProxy } from "#/api/cloud/proxy";
-import type { Backend } from "#/api/backend-registry/types";
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();
+const useWorkspaceSessionMock = vi.fn();
+vi.mock("#/hooks/query/use-workspace-session", async (importOriginal) => {
+ const real =
+ await importOriginal<
+ typeof import("#/hooks/query/use-workspace-session")
+ >();
return {
- downloadFileMock: downloadFile,
- fileClientMock: vi.fn(function FileClientMock() {
- return { downloadFile };
- }),
+ ...real,
+ // Keep the real joinWorkspaceUrl so we assert against URLs assembled
+ // by the hook the same way the production code assembles them.
+ useWorkspaceSession: () => useWorkspaceSessionMock(),
};
});
-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",
- })),
-}));
-
-vi.mock("#/api/cloud/proxy", () => ({
- callCloudProxy: vi.fn(),
-}));
-
-const cloudBackend: Backend = {
- id: "cloud-1",
- name: "Production",
- host: "https://app.all-hands.dev",
- apiKey: "cloud-api-key",
- kind: "cloud",
-};
-
const useActiveConversationMock = vi.fn();
vi.mock("#/hooks/query/use-active-conversation", () => ({
useActiveConversation: () => useActiveConversationMock(),
@@ -57,6 +30,8 @@ vi.mock("#/hooks/use-runtime-is-ready", () => ({
useRuntimeIsReady: () => useRuntimeIsReadyMock(),
}));
+const fetchMock = vi.fn();
+
function makeWrapper() {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -73,18 +48,14 @@ function makeWrapper() {
return Wrapper;
}
+const BASE_URL =
+ "https://agent.example.com/api/conversations/conv-1/workspace/";
+
describe("useWorkspaceFileContent", () => {
beforeEach(() => {
- Object.defineProperty(URL, "createObjectURL", {
- configurable: true,
- value: vi.fn(() => "blob:preview-url"),
- });
- window.localStorage.clear();
- __resetActiveStoreForTests();
- useWorkspaceMutationCounter.setState({ count: 0 });
- fileClientMock.mockClear();
- downloadFileMock.mockReset();
- vi.mocked(callCloudProxy).mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+ fetchMock.mockReset();
+ useWorkspaceSessionMock.mockReset();
useActiveConversationMock.mockReset();
useRuntimeIsReadyMock.mockReset();
useRuntimeIsReadyMock.mockReturnValue(true);
@@ -93,20 +64,31 @@ describe("useWorkspaceFileContent", () => {
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" },
},
});
+ useWorkspaceSessionMock.mockReturnValue({
+ data: { baseUrl: BASE_URL },
+ isLoading: false,
+ isError: false,
+ error: null,
+ });
+ useWorkspaceMutationCounter.setState({ count: 0 });
});
afterEach(() => {
- window.localStorage.clear();
- __resetActiveStoreForTests();
+ vi.unstubAllGlobals();
});
- it("downloads selected files through the typed file API", async () => {
- downloadFileMock.mockResolvedValue(
- new TextEncoder().encode("# Hello").buffer,
- );
+ function arrayBufferFromString(value: string): ArrayBuffer {
+ return new TextEncoder().encode(value).buffer as ArrayBuffer;
+ }
+
+ it("returns a static URL on the workspace fileserver for text content", async () => {
+ fetchMock.mockResolvedValue({
+ ok: true,
+ status: 200,
+ arrayBuffer: () => Promise.resolve(arrayBufferFromString("# Hello")),
+ });
const { result } = renderHook(
() => useWorkspaceFileContent("docs/readme.md"),
@@ -115,21 +97,89 @@ describe("useWorkspaceFileContent", () => {
await waitFor(() => expect(result.current.isSuccess).toBe(true));
- expect(downloadFileMock).toHaveBeenCalledWith(
- "/workspace/project/agent-canvas/docs/readme.md",
+ expect(fetchMock).toHaveBeenCalledWith(
+ `${BASE_URL}docs/readme.md`,
+ expect.objectContaining({ credentials: "include" }),
);
- expect(result.current.data).toMatchObject({
+ expect(result.current.data).toEqual({
+ path: "docs/readme.md",
kind: "text",
text: "# Hello",
- staticUrl: "blob:preview-url",
+ staticUrl: `${BASE_URL}docs/readme.md`,
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);
+ it("does not fetch image bytes — image staticUrl is rendered directly", async () => {
+ 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: `${BASE_URL}assets/logo.png`,
+ mimeType: "image/png",
+ });
+ });
+
+ it("does not fetch PDF bytes — PDF staticUrl is rendered directly", async () => {
+ const { result } = renderHook(() => useWorkspaceFileContent("report.pdf"), {
+ wrapper: makeWrapper(),
+ });
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(result.current.data).toEqual({
+ path: "report.pdf",
+ kind: "pdf",
+ text: null,
+ staticUrl: `${BASE_URL}report.pdf`,
+ mimeType: "application/pdf",
+ });
+ });
+
+ it("flips text → binary when the fetched bytes contain a NUL", async () => {
+ const binary = new Uint8Array([0x01, 0x00, 0x02]).buffer;
+ fetchMock.mockResolvedValue({
+ ok: true,
+ status: 200,
+ arrayBuffer: () => Promise.resolve(binary),
+ });
+
+ const { result } = renderHook(
+ () => useWorkspaceFileContent("data/blob.bin"),
+ { wrapper: makeWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+
+ expect(result.current.data).toMatchObject({
+ kind: "binary",
+ text: null,
+ mimeType: "application/octet-stream",
+ staticUrl: `${BASE_URL}data/blob.bin`,
+ });
+ });
+
+ it("refetches text content after a workspace mutation tick", async () => {
+ fetchMock
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ arrayBuffer: () => Promise.resolve(arrayBufferFromString("first")),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ arrayBuffer: () => Promise.resolve(arrayBufferFromString("second")),
+ });
const { result } = renderHook(
() => useWorkspaceFileContent("docs/readme.md"),
@@ -143,7 +193,7 @@ describe("useWorkspaceFileContent", () => {
});
await waitFor(() => expect(result.current.data?.text).toBe("second"));
- expect(downloadFileMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
});
it("does not start a file request before a path is selected", async () => {
@@ -153,67 +203,46 @@ describe("useWorkspaceFileContent", () => {
setTimeout(resolve, 10);
});
- expect(fileClientMock).not.toHaveBeenCalled();
- expect(downloadFileMock).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
});
- it("rejects traversal outside the workspace", async () => {
- const { result } = renderHook(() => useWorkspaceFileContent("../.env"), {
+ it("does not start a file request before the workspace session is minted", async () => {
+ useWorkspaceSessionMock.mockReturnValue({
+ data: null,
+ isLoading: true,
+ isError: false,
+ error: null,
+ });
+
+ renderHook(() => useWorkspaceFileContent("docs/readme.md"), {
wrapper: makeWrapper(),
});
+ await new Promise((resolve) => {
+ setTimeout(resolve, 10);
+ });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("surfaces a non-OK response as an error", async () => {
+ fetchMock.mockResolvedValue({
+ ok: false,
+ status: 404,
+ arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)),
+ });
+
+ const { result } = renderHook(
+ () => useWorkspaceFileContent("missing.txt"),
+ { 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",
+ message: "Failed to read missing.txt: 404",
}),
);
});
-
- describe("cloud backend", () => {
- beforeEach(() => {
- setRegisteredBackends([cloudBackend]);
- setActiveSelection({ backendId: cloudBackend.id, orgId: null });
- useActiveConversationMock.mockReturnValue({
- data: {
- id: "conv-cloud",
- conversation_url:
- "https://runtime.example.com/api/conversations/conv-cloud",
- session_api_key: "cloud-session-key",
- workspace: { working_dir: "/workspace/project" },
- },
- });
- });
-
- it("fetches file content through callCloudProxy instead of FileClient", async () => {
- vi.mocked(callCloudProxy).mockResolvedValue(
- new Blob([new TextEncoder().encode("cloud file content")]),
- );
-
- const { result } = renderHook(
- () => useWorkspaceFileContent("src/app.ts"),
- { wrapper: makeWrapper() },
- );
-
- await waitFor(() => expect(result.current.isSuccess).toBe(true));
-
- // FileClient must never be called directly for cloud conversations.
- expect(fileClientMock).not.toHaveBeenCalled();
- expect(downloadFileMock).not.toHaveBeenCalled();
-
- const proxyCall = vi.mocked(callCloudProxy).mock.calls[0][0];
- expect(proxyCall.method).toBe("GET");
- expect(proxyCall.path).toContain("/api/file/download");
- expect(proxyCall.path).toContain(
- encodeURIComponent("/workspace/project/src/app.ts"),
- );
- expect(proxyCall.authMode).toBe("session-api-key");
- expect(proxyCall.sessionApiKey).toBe("cloud-session-key");
- expect(proxyCall.responseType).toBe("blob");
-
- expect(result.current.data?.text).toBe("cloud file content");
- });
- });
});
diff --git a/__tests__/hooks/query/use-workspace-session.test.tsx b/__tests__/hooks/query/use-workspace-session.test.tsx
new file mode 100644
index 0000000000..751f193159
--- /dev/null
+++ b/__tests__/hooks/query/use-workspace-session.test.tsx
@@ -0,0 +1,189 @@
+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";
+
+import {
+ joinWorkspaceUrl,
+ useWorkspaceSession,
+} from "#/hooks/query/use-workspace-session";
+
+// 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();
+
+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", () => ({
+ 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 WorkspaceSessionTestWrapper({
+ children,
+ }: {
+ children: React.ReactNode;
+ }) {
+ return (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ };
+ return Wrapper;
+}
+
+// Yields back to the event loop a few microtasks deep so react-query has a
+// chance to schedule (and, in the negative-path tests, to NOT schedule) the
+// query. ESLint forbids returning the timer id from `new Promise(...)`, so
+// we wrap setTimeout in a void callback.
+function flushScheduler(ms = 10): Promise<void> {
+ return new Promise((resolve) => {
+ setTimeout(resolve, ms);
+ });
+}
+
+beforeEach(() => {
+ startWorkspaceSessionMock.mockReset();
+ vi.mocked(RemoteWorkspace).mockClear();
+ useActiveConversationMock.mockReset();
+ useRuntimeIsReadyMock.mockReset();
+ useRuntimeIsReadyMock.mockReturnValue(true);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("useWorkspaceSession", () => {
+ it("calls startWorkspaceSession and exposes the returned baseUrl", async () => {
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ id: "conv-1",
+ conversation_url: "https://agent.example.com/api/conversations/conv-1",
+ session_api_key: "key-abc",
+ },
+ });
+ startWorkspaceSessionMock.mockResolvedValue(
+ "https://agent.example.com/api/conversations/conv-1/workspace/",
+ );
+
+ const { result } = renderHook(() => useWorkspaceSession(), {
+ wrapper: makeWrapper(),
+ });
+
+ await waitFor(() => {
+ expect(result.current.data?.baseUrl).toBe(
+ "https://agent.example.com/api/conversations/conv-1/workspace/",
+ );
+ });
+
+ 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");
+ });
+
+ it("does not call startWorkspaceSession until the runtime is ready", async () => {
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ id: "conv-1",
+ conversation_url: "https://agent.example.com/api/conversations/conv-1",
+ session_api_key: "key-abc",
+ },
+ });
+ useRuntimeIsReadyMock.mockReturnValue(false);
+
+ const { result } = renderHook(() => useWorkspaceSession(), {
+ wrapper: makeWrapper(),
+ });
+
+ // Give react-query a tick to schedule (it shouldn't).
+ await flushScheduler();
+ expect(startWorkspaceSessionMock).not.toHaveBeenCalled();
+ expect(result.current.data).toBeNull();
+ });
+
+ it("does not call startWorkspaceSession without a conversation id", async () => {
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+
+ renderHook(() => useWorkspaceSession(), { wrapper: makeWrapper() });
+
+ await flushScheduler();
+ expect(startWorkspaceSessionMock).not.toHaveBeenCalled();
+ });
+
+ it("surfaces the error when the workspace-session POST fails", async () => {
+ useActiveConversationMock.mockReturnValue({
+ data: {
+ id: "conv-1",
+ conversation_url: "https://agent.example.com/api/conversations/conv-1",
+ session_api_key: "bad-key",
+ },
+ });
+ startWorkspaceSessionMock.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/);
+ expect(result.current.data).toBeNull();
+ });
+});
+
+describe("joinWorkspaceUrl", () => {
+ const base = "https://agent.example.com/api/conversations/c1/workspace/";
+
+ it("returns the base URL when no relative path is supplied", () => {
+ expect(joinWorkspaceUrl(base)).toBe(base);
+ expect(joinWorkspaceUrl(base, "")).toBe(base);
+ expect(joinWorkspaceUrl(base, null)).toBe(base);
+ });
+
+ it("appends a single-segment path", () => {
+ expect(joinWorkspaceUrl(base, "index.html")).toBe(`${base}index.html`);
+ });
+
+ it("appends nested paths preserving separators", () => {
+ expect(joinWorkspaceUrl(base, "src/components/App.tsx")).toBe(
+ `${base}src/components/App.tsx`,
+ );
+ });
+
+ it("strips leading slashes on the relative path", () => {
+ expect(joinWorkspaceUrl(base, "/index.html")).toBe(`${base}index.html`);
+ expect(joinWorkspaceUrl(base, "///deep/path.md")).toBe(
+ `${base}deep/path.md`,
+ );
+ });
+
+ it("URL-encodes individual segments but not the separators", () => {
+ expect(joinWorkspaceUrl(base, "my files/has spaces.txt")).toBe(
+ `${base}my%20files/has%20spaces.txt`,
+ );
+ expect(joinWorkspaceUrl(base, "tëst/résumé.pdf")).toBe(
+ `${base}t%C3%ABst/r%C3%A9sum%C3%A9.pdf`,
+ );
+ });
+});
diff --git a/__tests__/routes/files-tab.test.tsx b/__tests__/routes/files-tab.test.tsx
index 758ed26ef1..cb0ae5ec14 100644
--- a/__tests__/routes/files-tab.test.tsx
+++ b/__tests__/routes/files-tab.test.tsx
@@ -367,7 +367,7 @@ describe("FilesTab", () => {
).not.toBeInTheDocument();
});
- it("uses the browser preview URL as the iframe src for HTML files", async () => {
+ it("uses the workspace fileserver URL as the iframe src for HTML files", async () => {
useHasAttachedSourceMock.mockReturnValue({
hasAttachedSource: false,
isLoading: false,
@@ -376,7 +376,8 @@ describe("FilesTab", () => {
data: ["index.html"],
isLoading: false,
});
- const staticUrl = "blob:preview-url";
+ const staticUrl =
+ "https://agent.example.com/api/conversations/conv-1/workspace/index.html";
useWorkspaceFileContentMock.mockReturnValue({
data: {
path: "index.html",
@@ -393,10 +394,12 @@ describe("FilesTab", () => {
const iframe = await screen.findByTestId("file-content-viewer-iframe");
expect(iframe).toBeInTheDocument();
- // 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 src points at the workspace fileserver so relative
+ // asset references (`<link href="style.css">` etc.) resolve to
+ // sibling files. The `?v=<mutation-counter>` suffix is the
+ // cache-buster appended by the viewer so the browser re-fetches
+ // after each agent-side edit.
+ expect(iframe).toHaveAttribute("src", `${staticUrl}?v=0`);
// 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
diff --git a/src/components/features/files-tab/file-content-viewer.tsx b/src/components/features/files-tab/file-content-viewer.tsx
index bc0322ddb7..147218bb1f 100644
--- a/src/components/features/files-tab/file-content-viewer.tsx
+++ b/src/components/features/files-tab/file-content-viewer.tsx
@@ -2,6 +2,10 @@ 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";
@@ -20,14 +24,20 @@ function getExtension(path: string): string {
}
/**
- * 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
+ * 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
* 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 (
@@ -56,6 +66,7 @@ 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
@@ -89,7 +100,7 @@ export function FileContentViewer({ path, viewMode }: FileContentViewerProps) {
data-testid="file-content-viewer-image"
>
<img
- src={staticUrl}
+ src={bustedStaticUrl}
alt={path}
className="max-h-full max-w-full object-contain"
/>
@@ -109,7 +120,7 @@ export function FileContentViewer({ path, viewMode }: FileContentViewerProps) {
return (
<iframe
title={path}
- src={staticUrl}
+ src={bustedStaticUrl}
sandbox="allow-same-origin"
data-testid="file-content-viewer-iframe"
className="h-full w-full bg-white"
@@ -130,15 +141,17 @@ export function FileContentViewer({ path, viewMode }: FileContentViewerProps) {
// Text-like content.
if (mimeType === "text/html" || HTML_LIKE_EXTS.has(getExtension(path))) {
- // 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.
+ // 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.
return (
<iframe
title={path}
- src={staticUrl}
+ src={bustedStaticUrl}
sandbox="allow-same-origin"
data-testid="file-content-viewer-iframe"
className="h-full w-full bg-white"
diff --git a/src/hooks/query/use-workspace-file-content.ts b/src/hooks/query/use-workspace-file-content.ts
index f1ef457d30..57bc039611 100644
--- a/src/hooks/query/use-workspace-file-content.ts
+++ b/src/hooks/query/use-workspace-file-content.ts
@@ -1,8 +1,11 @@
import { useQuery } from "@tanstack/react-query";
-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 {
+ 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.
@@ -28,8 +31,12 @@ export interface WorkspaceFileContent {
/** Decoded text contents — only populated when kind === "text". */
text: string | null;
/**
- * Browser-renderable URL for rich previews and "open in new window".
- * Usually a local Blob URL derived from `/api/file/download` bytes.
+ * URL pointing at the file on the agent server's static workspace
+ * fileserver (the `/api/conversations/{id}/workspace/...` route minted
+ * by `RemoteWorkspace.startWorkspaceSession`). Suitable to use as an
+ * `<iframe src>` or `<img src>` — the workspace-session cookie
+ * authenticates the browser request, and relative asset references
+ * inside an HTML preview resolve naturally against this URL.
*/
staticUrl: string;
/** MIME type guessed from the file extension. */
@@ -101,38 +108,15 @@ 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 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.
+ * 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.
*
* Pass a falsy `relativePath` to disable the query (e.g. when no file is
* selected yet).
@@ -140,56 +124,73 @@ function makePreviewUrl(buffer: ArrayBuffer, mimeType: string): string {
export function useWorkspaceFileContent(relativePath: string | null) {
const { data: conversation } = useActiveConversation();
const runtimeIsReady = useRuntimeIsReady();
+ const { data: workspaceSession } = useWorkspaceSession();
+ // Bump on every agent-side file mutation so the query refetches the
+ // currently-selected file's body even when the *path* hasn't changed.
+ // The iframe / <img> cache-busting for the rich preview is handled at
+ // the consumer (FileContentViewer / files-tab) by appending the same
+ // counter to the staticUrl, so a single tick refreshes both the
+ // decoded text and the iframe-rendered HTML's sibling assets.
const workspaceMutationCount = useWorkspaceMutationCounter(
(state) => state.count,
);
const conversationId = conversation?.id;
const conversationUrl = conversation?.conversation_url;
- const sessionApiKey = conversation?.session_api_key;
- const workingDir = conversation?.workspace?.working_dir?.trim();
+ const baseUrl = workspaceSession?.baseUrl;
return useQuery<WorkspaceFileContent>({
queryKey: [
"workspace-file-content",
conversationId,
conversationUrl,
- sessionApiKey,
- workingDir,
+ baseUrl,
relativePath,
workspaceMutationCount,
],
queryFn: async () => {
if (!relativePath) throw new Error("No path");
- if (!workingDir) throw new Error("No workspace directory");
+ if (!baseUrl) throw new Error("No workspace session");
+ const staticUrl = joinWorkspaceUrl(baseUrl, relativePath);
const kind = classifyKind(relativePath);
const mimeType = guessMimeType(relativePath);
- const filePath = resolveWorkspacePath(workingDir, relativePath);
- const buffer = await AgentServerRuntimeService.downloadFile(
- conversationUrl,
- sessionApiKey,
- 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: makePreviewUrl(buffer, mimeType),
+ staticUrl,
mimeType,
};
}
+ // For our own fetch we also rely on the workspace-session cookie
+ // (it travels because we opt in to credentialed requests). This
+ // matches the auth path the iframe / <img> uses, and avoids a 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: makePreviewUrl(buffer, binaryMimeType),
- mimeType: binaryMimeType,
+ staticUrl,
+ mimeType: "application/octet-stream",
};
}
@@ -198,12 +199,11 @@ export function useWorkspaceFileContent(relativePath: string | null) {
path: relativePath,
kind: "text",
text,
- staticUrl: makePreviewUrl(buffer, mimeType),
+ staticUrl,
mimeType,
};
},
- enabled:
- runtimeIsReady && !!conversationId && !!workingDir && !!relativePath,
+ enabled: runtimeIsReady && !!conversationId && !!baseUrl && !!relativePath,
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
new file mode 100644
index 0000000000..524e7c01d2
--- /dev/null
+++ b/src/hooks/query/use-workspace-session.ts
@@ -0,0 +1,106 @@
+import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
+import { useQuery } from "@tanstack/react-query";
+
+import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
+
+export interface WorkspaceSession {
+ /**
+ * Absolute URL prefix for the conversation's static workspace fileserver,
+ * always ending in a `/`. Append a relative path to address a single file
+ * (e.g. `${baseUrl}index.html`).
+ */
+ baseUrl: string;
+}
+
+/**
+ * Mint a workspace static-asset session for the active conversation.
+ *
+ * Calling `POST /api/auth/workspace-session` exchanges the conversation's
+ * `X-Session-API-Key` for an `oh_workspace_session_key` cookie scoped to
+ * `/api/conversations`. Once that cookie is set the browser can embed
+ * workspace artifacts directly as `<iframe src>` / `<img src>` / top-level
+ * navigations — which it cannot do when the only credential is a custom
+ * request header.
+ *
+ * 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
+ * for the lifetime of the conversation; only switching conversations (a
+ * different `conversationId` in the query key) re-runs it.
+ *
+ * Returns `null` from `data` until the session has been minted, so
+ * callers can gate iframe / img rendering on a definite "the cookie is
+ * set" signal rather than guessing.
+ */
+export function useWorkspaceSession(): {
+ data: WorkspaceSession | null;
+ isLoading: boolean;
+ isError: boolean;
+ error: Error | null;
+} {
+ const { data: conversation } = useActiveConversation();
+ const runtimeIsReady = useRuntimeIsReady();
+
+ const conversationId = conversation?.id;
+ const conversationUrl = conversation?.conversation_url;
+ const sessionApiKey = conversation?.session_api_key;
+
+ const enabled = runtimeIsReady && !!conversationId;
+
+ const query = useQuery<WorkspaceSession>({
+ queryKey: [
+ "workspace-session",
+ conversationId,
+ conversationUrl,
+ sessionApiKey,
+ ],
+ queryFn: async () => {
+ const workspace = new RemoteWorkspace(
+ getAgentServerClientOptions({
+ conversationUrl,
+ sessionApiKey,
+ }),
+ );
+ const baseUrl = await workspace.startWorkspaceSession(conversationId!);
+ return { baseUrl };
+ },
+ enabled,
+ // The cookie is sticky; minting it once per page-load is plenty.
+ staleTime: Infinity,
+ gcTime: Infinity,
+ // No auto-retry: a 401 here means the session API key isn't valid for
+ // this conversation, which won't fix itself on a second POST. The
+ // user can re-trigger by reloading or switching conversation.
+ retry: false,
+ });
+
+ return {
+ data: query.data ?? null,
+ isLoading: query.isLoading,
+ isError: query.isError,
+ error: (query.error as Error | null) ?? null,
+ };
+}
+
+/**
+ * Append a workspace-relative path to a base URL produced by
+ * {@link useWorkspaceSession}, URL-encoding each segment but preserving
+ * `/` separators. Pass an empty / undefined `relativePath` to get the
+ * directory base back (server then falls back to its `index.html`).
+ */
+export function joinWorkspaceUrl(
+ baseUrl: string,
+ relativePath?: string | null,
+): string {
+ const cleaned = (relativePath ?? "").replace(/^\/+/, "");
+ if (!cleaned) return baseUrl;
+ const encoded = cleaned
+ .split("/")
+ .map((segment) => encodeURIComponent(segment))
+ .join("/");
+ // baseUrl is guaranteed to end with a single trailing slash by the
+ // server's contract (startWorkspaceSession returns `${host}/api/.../workspace/`).
+ return `${baseUrl}${encoded}`;
+}
diff --git a/src/routes/files-tab.tsx b/src/routes/files-tab.tsx
index f19f698ddc..8a3faeea50 100644
--- a/src/routes/files-tab.tsx
+++ b/src/routes/files-tab.tsx
@@ -12,6 +12,10 @@ 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";
@@ -73,7 +77,11 @@ function FilesTab() {
// dedupes against `FileContentViewer`'s identical call, so this costs
// nothing extra.
const selectedFileContent = useWorkspaceFileContent(selectedPath);
- const selectedFileStaticUrl = selectedFileContent.data?.staticUrl ?? null;
+ const mutationCounter = useWorkspaceMutationCounter((state) => state.count);
+ const selectedFileStaticUrl = withWorkspaceCacheBuster(
+ selectedFileContent.data?.staticUrl ?? null,
+ mutationCounter,
+ );
// Auto-select the highest-priority file the first time we load the list,
// so users see something useful immediately.
@@ -131,7 +139,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 browser-renderable preview URL. */}
+ we've resolved its staticUrl from the workspace fileserver. */}
{!diffViewEnabled && selectedFileStaticUrl && (
<a
href={selectedFileStaticUrl}
diff --git a/src/stores/use-workspace-mutation-counter.ts b/src/stores/use-workspace-mutation-counter.ts
index b2f409bd05..9ecb3ee1e1 100644
--- a/src/stores/use-workspace-mutation-counter.ts
+++ b/src/stores/use-workspace-mutation-counter.ts
@@ -2,14 +2,25 @@ import { create } from "zustand";
/**
* Monotonic counter that ticks every time the agent commits a file-editor
- * 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.
+ * mutation in the workspace. Serves two purposes:
+ *
+ * 1. It's part of the {@link useWorkspaceFileContent} query key, so the
+ * hook refetches the selected file's body (used for text decoding /
+ * binary classification) after each edit even when the selected path
+ * hasn't moved.
+ * 2. It's appended as a `?v=<count>` cache-buster to the static
+ * workspace fileserver URLs used by `<iframe src>` / `<img src>` for
+ * the rich preview, so the browser re-requests a fresh copy after
+ * each edit — important because the rendered HTML may reference
+ * sibling assets (CSS, images) that the user can't see directly but
+ * expects to reflect the latest version of the workspace.
*
* Consumers:
* - {@link useAutoRefreshFilesOnEdit} bumps this on each mutation event.
- * - {@link useWorkspaceFileContent} reads the count and refreshes its Blob
- * preview URL and decoded text.
+ * - {@link useWorkspaceFileContent} reads the count via its query key so
+ * the hook refetches after each edit.
+ * - `FileContentViewer` / files-tab "open in new tab" link append the
+ * count to the static URL via {@link withWorkspaceCacheBuster}.
*/
interface WorkspaceMutationCounterState {
count: number;
@@ -21,3 +32,22 @@ 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}`;
+}