Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(files): show the current file body after Refresh and reload (#18032)

Engel Nyst230028ac57dc
diff --git a/__tests__/hooks/query/use-workspace-file-content.test.tsx b/__tests__/hooks/query/use-workspace-file-content.test.tsx
index 34f77d5dec..36cad33145 100644
--- a/__tests__/hooks/query/use-workspace-file-content.test.tsx
+++ b/__tests__/hooks/query/use-workspace-file-content.test.tsx
@@ -146,9 +146,12 @@ describe("useWorkspaceFileContent", () => {
await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ // Revalidate instead of trusting the browser HTTP cache: the fileserver
+ // sends no Cache-Control, so an old file's body stays heuristically
+ // fresh and a Refresh would otherwise keep showing it (#17921).
expect(fetchMock).toHaveBeenCalledWith(
`${BASE_URL}docs/readme.md`,
- expect.objectContaining({ credentials: "include" }),
+ expect.objectContaining({ credentials: "include", cache: "no-cache" }),
);
expect(result.current.data).toEqual({
path: "docs/readme.md",
diff --git a/__tests__/routes/files-tab.test.tsx b/__tests__/routes/files-tab.test.tsx
index ab294eaed5..9bafa067ec 100644
--- a/__tests__/routes/files-tab.test.tsx
+++ b/__tests__/routes/files-tab.test.tsx
@@ -6,6 +6,7 @@ import { MemoryRouter } from "react-router";
import FilesTab from "#/routes/files-tab";
import { useFilesTabStore } from "#/stores/files-tab-store";
+import { useWorkspaceMutationCounter } from "#/stores/use-workspace-mutation-counter";
import { NavigationProvider } from "#/context/navigation-context";
import {
LOCAL_STORAGE_KEYS,
@@ -63,6 +64,7 @@ describe("FilesTab", () => {
selectedConversationId: null,
openPaths: [],
});
+ useWorkspaceMutationCounter.setState({ count: 0 });
localStorage.clear();
useWorkspaceFilesMock.mockReset();
@@ -349,6 +351,47 @@ describe("FilesTab", () => {
expect(iframe).toHaveAttribute("sandbox", "allow-same-origin");
});
+ it("re-requests the rich preview and the new-window link on Refresh", async () => {
+ useWorkspaceFilesMock.mockReturnValue({
+ data: ["index.html"],
+ isLoading: false,
+ });
+ const staticUrl =
+ "https://agent.example.com/api/conversations/conv-1/workspace/index.html";
+ useWorkspaceFileContentMock.mockReturnValue({
+ data: {
+ path: "index.html",
+ kind: "text",
+ text: "<!doctype html><body>hi</body>",
+ staticUrl,
+ mimeType: "text/html",
+ },
+ isLoading: false,
+ isError: false,
+ });
+ const user = userEvent.setup();
+
+ openFile("index.html");
+ renderTab();
+ const iframe = await screen.findByTestId("file-content-viewer-iframe");
+ const srcBefore = iframe.getAttribute("src");
+
+ await user.click(screen.getByTestId("files-tab-refresh"));
+
+ // A new URL is the only way to make an <iframe>/<img> skip a cached
+ // response, so Refresh must change it (#17921).
+ await waitFor(() => {
+ expect(
+ screen.getByTestId("file-content-viewer-iframe").getAttribute("src"),
+ ).not.toBe(srcBefore);
+ });
+ expect(
+ screen.getByTestId("files-tab-open-in-new-window").getAttribute("href"),
+ ).toBe(
+ screen.getByTestId("file-content-viewer-iframe").getAttribute("src"),
+ );
+ });
+
it("switches between rich and plain content modes", async () => {
useWorkspaceFilesMock.mockReturnValue({
data: ["src/main.ts"],
diff --git a/__tests__/stores/use-workspace-mutation-counter.test.ts b/__tests__/stores/use-workspace-mutation-counter.test.ts
new file mode 100644
index 0000000000..82672a332a
--- /dev/null
+++ b/__tests__/stores/use-workspace-mutation-counter.test.ts
@@ -0,0 +1,34 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+async function loadFreshCounterStore() {
+ vi.resetModules();
+ return (await import("#/stores/use-workspace-mutation-counter"))
+ .useWorkspaceMutationCounter;
+}
+
+describe("workspace mutation counter", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("starts each page load at a cache-buster no earlier load used", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
+ const firstLoad = await loadFreshCounterStore();
+ vi.setSystemTime(new Date("2026-01-01T00:00:05Z"));
+ const secondLoad = await loadFreshCounterStore();
+
+ // A reload must not rebuild the `?v=` URL the previous load used, or the
+ // rich preview can be answered from the browser HTTP cache (#17921).
+ expect(secondLoad.getState().count).not.toBe(firstLoad.getState().count);
+ });
+
+ it("ticks forward on every bump", async () => {
+ const useWorkspaceMutationCounter = await loadFreshCounterStore();
+ const initial = useWorkspaceMutationCounter.getState().count;
+
+ useWorkspaceMutationCounter.getState().bump();
+
+ expect(useWorkspaceMutationCounter.getState().count).toBe(initial + 1);
+ });
+});
diff --git a/src/components/features/files-tab/file-content-viewer.tsx b/src/components/features/files-tab/file-content-viewer.tsx
index a558c354b0..300af8d5b7 100644
--- a/src/components/features/files-tab/file-content-viewer.tsx
+++ b/src/components/features/files-tab/file-content-viewer.tsx
@@ -75,9 +75,10 @@ export function FileContentViewer({ path, viewMode }: FileContentViewerProps) {
const isLightTheme = COLOR_THEMES[colorTheme].appearance === "light";
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`).
+ // changes after every agent file-editor edit and every Files tab Refresh,
+ // forcing a fresh fetch of the displayed file even when the *path* hasn't
+ // moved. Assets it references (e.g. a `style.css` used by `index.html`)
+ // keep their own URLs, so they are not cache-busted by this.
const mutationCounter = useWorkspaceMutationCounter((state) => state.count);
if (query.isLoading) {
diff --git a/src/hooks/query/use-workspace-file-content.ts b/src/hooks/query/use-workspace-file-content.ts
index c8a5809b35..3d5b6b863c 100644
--- a/src/hooks/query/use-workspace-file-content.ts
+++ b/src/hooks/query/use-workspace-file-content.ts
@@ -143,12 +143,14 @@ export function useWorkspaceFileContent(relativePath: string | null) {
const { data: conversation } = useActiveConversation();
const runtimeIsReady = useRuntimeIsReady({ allowAgentError: true });
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.
+ // Bumped on every agent file-editor mutation (not shell commands) and on
+ // the Files tab Refresh, 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.
+ // decoded text and the top-level file the iframe / <img> renders (its
+ // sibling assets keep their own URLs and are not cache-busted).
const workspaceMutationCount = useWorkspaceMutationCounter(
(state) => state.count,
);
@@ -263,8 +265,15 @@ export function useWorkspaceFileContent(relativePath: string | null) {
// (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.
+ //
+ // `cache: "no-cache"` makes the browser revalidate (ETag /
+ // Last-Modified) on every read. The fileserver sends no
+ // Cache-Control, so with the default mode an old file's cached body
+ // stays heuristically fresh and Refresh, an agent edit or even a page
+ // reload keeps showing it (#17921).
const response = await fetch(staticUrl, {
credentials: "include",
+ cache: "no-cache",
});
if (!response.ok) {
throw new Error(`Failed to read ${relativePath}: ${response.status}`);
diff --git a/src/routes/files-tab.tsx b/src/routes/files-tab.tsx
index 32d53ca817..40be66089e 100644
--- a/src/routes/files-tab.tsx
+++ b/src/routes/files-tab.tsx
@@ -112,6 +112,9 @@ function FilesTab() {
// nothing extra.
const selectedFileContent = useWorkspaceFileContent(selectedPath);
const mutationCounter = useWorkspaceMutationCounter((state) => state.count);
+ const bumpWorkspaceMutationCounter = useWorkspaceMutationCounter(
+ (state) => state.bump,
+ );
const selectedFileStaticUrl = withWorkspaceCacheBuster(
selectedFileContent.data?.staticUrl ?? null,
mutationCounter,
@@ -136,11 +139,12 @@ function FilesTab() {
const [isRefreshing, setIsRefreshing] = useState(false);
const refreshFiles = async () => {
setIsRefreshing(true);
+ // Bumping the counter re-keys every `workspace-file-content` query, so
+ // the open file refetches, and gives the rich preview's <iframe>/<img> a
+ // new `?v=` URL: the only way to make them skip a cached response.
+ bumpWorkspaceMutationCounter();
try {
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: ["workspace-files"] }),
- queryClient.invalidateQueries({ queryKey: ["workspace-file-content"] }),
- ]);
+ await queryClient.invalidateQueries({ queryKey: ["workspace-files"] });
} finally {
setIsRefreshing(false);
}
diff --git a/src/stores/use-workspace-mutation-counter.ts b/src/stores/use-workspace-mutation-counter.ts
index 9ecb3ee1e1..14e61bd456 100644
--- a/src/stores/use-workspace-mutation-counter.ts
+++ b/src/stores/use-workspace-mutation-counter.ts
@@ -2,23 +2,31 @@ import { create } from "zustand";
/**
* Monotonic counter that ticks every time the agent commits a file-editor
- * mutation in the workspace. Serves two purposes:
+ * mutation in the workspace and every time the user clicks Refresh in the
+ * Files tab. 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.
+ * binary classification) after each edit or Refresh 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.
+ * the rich preview, so the browser re-requests a fresh copy of that
+ * top-level file after each edit or Refresh. Only the top-level URL
+ * changes: sibling assets the rendered HTML references (CSS, images)
+ * keep their own URLs and can still come from the browser cache.
+ *
+ * The count is seeded from `Date.now()` at page load rather than 0, so the
+ * first `?v=` URL of a page load never matches one the browser cached
+ * during an earlier load (the fileserver sends no Cache-Control, so a
+ * reload would otherwise show the old bytes).
*
* Consumers:
* - {@link useAutoRefreshFilesOnEdit} bumps this on each mutation event.
+ * - The Files tab Refresh button bumps it so the open file refetches and
+ * the rich preview re-requests.
* - {@link useWorkspaceFileContent} reads the count via its query key so
- * the hook refetches after each edit.
+ * the hook refetches after each bump.
* - `FileContentViewer` / files-tab "open in new tab" link append the
* count to the static URL via {@link withWorkspaceCacheBuster}.
*/
@@ -29,14 +37,17 @@ interface WorkspaceMutationCounterState {
export const useWorkspaceMutationCounter =
create<WorkspaceMutationCounterState>((set) => ({
- count: 0,
+ count: Date.now(),
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.
+ * browser refetches the URL after every agent file-editor edit and every
+ * Files tab Refresh. The counter is seeded from `Date.now()`, so a page
+ * reload never rebuilds a URL the browser cached during an earlier load.
+ * 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(