Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: show full workspace file tree in Files tab on cloud backends (OHE-3053) (#16344)

Lila Garciac36754604357
diff --git a/__tests__/hooks/query/use-workspace-files.test.tsx b/__tests__/hooks/query/use-workspace-files.test.tsx
index a25a37e7b5..b9358811d2 100644
--- a/__tests__/hooks/query/use-workspace-files.test.tsx
+++ b/__tests__/hooks/query/use-workspace-files.test.tsx
@@ -5,11 +5,42 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import AgentServerRuntimeService from "#/api/runtime-service/agent-server-runtime-service";
import { useWorkspaceFiles } from "#/hooks/query/use-workspace-files";
-import type { GitChange } from "#/api/open-hands.types";
-
-const useActiveBackendMock = vi.fn();
-vi.mock("#/contexts/active-backend-context", () => ({
- useActiveBackend: () => useActiveBackendMock(),
+import { listCloudConversationFiles } from "#/api/cloud/conversation-service.api";
+
+// The hook reads cloud/local from the backend-registry store (the same source
+// the transport layer branches on), so drive the store snapshot in tests.
+// `getSnapshot` must return a STABLE reference per state or `useSyncExternalStore`
+// re-renders forever β€” precompute one frozen snapshot per kind.
+const STORE_SNAPSHOTS = {
+ local: {
+ active: {
+ backend: {
+ id: "backend-id",
+ name: "Local",
+ host: "http://127.0.0.1:8000",
+ apiKey: "test-key",
+ kind: "local",
+ },
+ orgId: null,
+ },
+ },
+ cloud: {
+ active: {
+ backend: {
+ id: "backend-id",
+ name: "Production",
+ host: "https://app.all-hands.dev",
+ apiKey: "test-key",
+ kind: "cloud",
+ },
+ orgId: null,
+ },
+ },
+} as const;
+let storeBackendKind: "local" | "cloud" = "local";
+vi.mock("#/api/backend-registry/active-store", () => ({
+ subscribeActiveBackend: () => () => {},
+ getSnapshot: () => STORE_SNAPSHOTS[storeBackendKind],
}));
const useActiveConversationMock = vi.fn();
@@ -22,12 +53,17 @@ vi.mock("#/hooks/use-runtime-is-ready", () => ({
useRuntimeIsReady: () => useRuntimeIsReadyMock(),
}));
-const useUnifiedGetGitChangesMock = vi.fn();
-vi.mock("#/hooks/query/use-unified-get-git-changes", () => ({
- useUnifiedGetGitChanges: () => useUnifiedGetGitChangesMock(),
+const useOptionalConversationIdMock = vi.fn();
+vi.mock("#/hooks/use-conversation-id", () => ({
+ useOptionalConversationId: () => useOptionalConversationIdMock(),
+}));
+
+vi.mock("#/api/cloud/conversation-service.api", () => ({
+ listCloudConversationFiles: vi.fn(),
}));
const executeCommandSpy = vi.spyOn(AgentServerRuntimeService, "executeCommand");
+const listCloudFilesMock = vi.mocked(listCloudConversationFiles);
function makeWrapper() {
const client = new QueryClient({
@@ -51,48 +87,28 @@ const conversation = {
workspace: { working_dir: "/workspace/project" },
};
-function gitChangesResult(data: GitChange[], isLoading = false) {
- return {
- data,
- isLoading,
- isFetching: false,
- isSuccess: true,
- isError: false,
- error: null,
- refetch: vi.fn(),
- };
-}
-
beforeEach(() => {
- useActiveBackendMock.mockReset();
+ storeBackendKind = "local";
useActiveConversationMock.mockReset();
useRuntimeIsReadyMock.mockReset();
- useUnifiedGetGitChangesMock.mockReset();
+ useOptionalConversationIdMock.mockReset();
executeCommandSpy.mockReset();
+ listCloudFilesMock.mockReset();
useRuntimeIsReadyMock.mockReturnValue(true);
useActiveConversationMock.mockReturnValue({ data: conversation });
- useUnifiedGetGitChangesMock.mockReturnValue(gitChangesResult([]));
+ useOptionalConversationIdMock.mockReturnValue({ conversationId: "conv-1" });
+ listCloudFilesMock.mockResolvedValue([]);
});
afterEach(() => {
vi.clearAllMocks();
});
-const makeBackend = (kind: "local" | "cloud") => ({
- backend: {
- id: "backend-id",
- name: kind === "local" ? "Local" : "Production",
- host:
- kind === "local" ? "http://127.0.0.1:8000" : "https://app.all-hands.dev",
- apiKey: "test-key",
- kind,
- },
- orgId: null,
-});
-
describe("useWorkspaceFiles β€” local backend", () => {
- beforeEach(() => useActiveBackendMock.mockReturnValue(makeBackend("local")));
+ beforeEach(() => {
+ storeBackendKind = "local";
+ });
it("lists files via bash find and does not touch git changes", async () => {
executeCommandSpy.mockResolvedValue({
@@ -113,51 +129,72 @@ describe("useWorkspaceFiles β€” local backend", () => {
});
describe("useWorkspaceFiles β€” cloud backend", () => {
- beforeEach(() => useActiveBackendMock.mockReturnValue(makeBackend("cloud")));
+ beforeEach(() => {
+ storeBackendKind = "cloud";
+ });
- it("derives the file list from git changes without running bash", async () => {
- useUnifiedGetGitChangesMock.mockReturnValue(
- gitChangesResult([
- { status: "A", path: "hello.txt" },
- { status: "M", path: "src/index.ts" },
- ]),
- );
+ it("lists the full tree via the cloud files endpoint without running bash", async () => {
+ listCloudFilesMock.mockResolvedValue([
+ "hello.txt",
+ "src/index.ts",
+ "src/untouched.ts",
+ ]);
const { result } = renderHook(() => useWorkspaceFiles(), {
wrapper: makeWrapper(),
});
await waitFor(() =>
- expect(result.current.data).toEqual(["hello.txt", "src/index.ts"]),
+ expect(result.current.data).toEqual([
+ "hello.txt",
+ "src/index.ts",
+ "src/untouched.ts",
+ ]),
+ );
+ // The cloud path uses the first-class listing endpoint, anchored at the
+ // conversation's absolute working dir.
+ expect(listCloudFilesMock).toHaveBeenCalledWith(
+ "conv-1",
+ "/workspace/project",
);
// Cloud must never drive the removed bash/cloud-proxy path.
expect(executeCommandSpy).not.toHaveBeenCalled();
});
- it("drops deleted files (they can't be opened) and de-dupes", async () => {
- useUnifiedGetGitChangesMock.mockReturnValue(
- gitChangesResult([
- { status: "A", path: "hello.txt" },
- { status: "D", path: "gone.txt" },
- { status: "M", path: "hello.txt" },
- ]),
- );
+ it("normalizes leading ./ and de-dupes the returned paths", async () => {
+ listCloudFilesMock.mockResolvedValue([
+ "./hello.txt",
+ "hello.txt",
+ "./src/index.ts",
+ ]);
const { result } = renderHook(() => useWorkspaceFiles(), {
wrapper: makeWrapper(),
});
- await waitFor(() => expect(result.current.data).toEqual(["hello.txt"]));
+ await waitFor(() =>
+ expect(result.current.data).toEqual(["hello.txt", "src/index.ts"]),
+ );
});
- it("surfaces the git-changes loading state", async () => {
- useUnifiedGetGitChangesMock.mockReturnValue(gitChangesResult([], true));
+ it("fires using the route id even when the active-conversation query has no data yet", async () => {
+ // Regression: the query id must come from the route, not from
+ // `useActiveConversation().data.id`. If the batch-get query is still
+ // loading (data === undefined) the listing must still fire β€” otherwise the
+ // Files tab makes no `/files` call at all on cloud.
+ useActiveConversationMock.mockReturnValue({ data: undefined });
+ listCloudFilesMock.mockResolvedValue(["hello.txt"]);
const { result } = renderHook(() => useWorkspaceFiles(), {
wrapper: makeWrapper(),
});
- expect(result.current.isLoading).toBe(true);
- expect(executeCommandSpy).not.toHaveBeenCalled();
+ await waitFor(() => expect(result.current.data).toEqual(["hello.txt"]));
+ // Falls back to the default working dir when the conversation metadata
+ // (and thus its working_dir) isn't available yet.
+ expect(listCloudFilesMock).toHaveBeenCalledWith(
+ "conv-1",
+ "/workspace/project",
+ );
});
});
diff --git a/src/api/cloud/conversation-service.api.ts b/src/api/cloud/conversation-service.api.ts
index 74dfc53e32..2c16777d7d 100644
--- a/src/api/cloud/conversation-service.api.ts
+++ b/src/api/cloud/conversation-service.api.ts
@@ -274,6 +274,29 @@ export async function readCloudConversationFile(
return data ?? "";
}
+/**
+ * List every file in a cloud conversation's sandbox workspace. Hits
+ * `GET /api/v1/app-conversations/{id}/files?path=...` on the cloud backend,
+ * which resolves the conversation's runtime and runs a bounded `find`
+ * server-side (see enterprise `list_conversation_files`). Unlike the
+ * git-changes source, this returns the full tree so the Files tab matches the
+ * local-backend experience. Paths come back relative to `path`.
+ */
+export async function listCloudConversationFiles(
+ conversationId: string,
+ path: string,
+): Promise<string[]> {
+ const backend = getActiveCloudBackend();
+ const params = new URLSearchParams();
+ params.append("path", path);
+ const data = await callCloudProxy<string[]>({
+ backend,
+ method: "GET",
+ path: `/api/v1/app-conversations/${conversationId}/files?${params.toString()}`,
+ });
+ return Array.isArray(data) ? data : [];
+}
+
/**
* Fetch a single v1 app-conversation start task. Mirrors OpenHands'
* `AgentServerConversationService.getStartTask` β€” uses the batch search endpoint
diff --git a/src/hooks/query/use-workspace-files.ts b/src/hooks/query/use-workspace-files.ts
index 47ec1ccd43..d43b05cc53 100644
--- a/src/hooks/query/use-workspace-files.ts
+++ b/src/hooks/query/use-workspace-files.ts
@@ -1,11 +1,16 @@
-import { useMemo } from "react";
+import { useSyncExternalStore } from "react";
import { useQuery } from "@tanstack/react-query";
import AgentServerRuntimeService from "#/api/runtime-service/agent-server-runtime-service";
-import { useActiveBackend } from "#/contexts/active-backend-context";
+import { listCloudConversationFiles } from "#/api/cloud/conversation-service.api";
+import {
+ getSnapshot,
+ subscribeActiveBackend,
+} from "#/api/backend-registry/active-store";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useOptionalConversationId } from "#/hooks/use-conversation-id";
import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
-import { useUnifiedGetGitChanges } from "#/hooks/query/use-unified-get-git-changes";
+import { getGitPath } from "#/utils/get-git-path";
// Cap the number of files we render so a giant repo doesn't freeze the UI.
const MAX_FILES = 2000;
@@ -52,9 +57,10 @@ function normalizePath(path: string): string {
* `/api/bash/execute_bash_command`, excluding common heavy/build directories.
* Returns paths relative to the working dir (e.g. `src/index.html`).
*
- * Local only: the cloud API exposes no bash-exec / file-listing endpoint,
- * and the old cross-origin `/api/cloud-proxy` hop these calls relied on was
- * removed from the agent-server. See `useWorkspaceFiles` for the cloud path.
+ * Local only: the browser can't drive `/api/bash/execute_bash_command` on a
+ * cloud runtime (no CORS, and the `/api/cloud-proxy` hop was removed). Cloud
+ * backends hit a first-class cloud API listing endpoint instead β€” see
+ * `useCloudWorkspaceFiles`.
*/
function useLocalWorkspaceFiles(enabled: boolean): WorkspaceFilesResult {
const { data: conversation } = useActiveConversation();
@@ -108,44 +114,81 @@ function useLocalWorkspaceFiles(enabled: boolean): WorkspaceFilesResult {
}
/**
- * Cloud-backend listing: derive the file list from the conversation's git
- * changes β€” the same data source the diff view uses (and the only
- * runtime-workspace transport the cloud API proxies, alongside git diff and
- * single-file read). `git status` reports created/modified/untracked files,
- * which covers the common Agent Canvas case (a fresh or agent-authored
- * workspace). It intentionally does NOT enumerate unchanged tracked files β€”
- * the cloud API has no full-workspace listing endpoint β€” so a conversation
- * attached to a large existing repo shows changed files rather than the whole
- * tree. Deleted files are dropped since they can't be opened.
+ * Cloud-backend listing: enumerate the full workspace tree via the cloud API's
+ * first-class `GET /api/v1/app-conversations/{id}/files` endpoint, which
+ * resolves the conversation's runtime and runs the same bounded `find`
+ * server-side (see enterprise `list_conversation_files`). This is the same
+ * server-side runtime-hop transport the git-changes/diff and single-file read
+ * already use, so it works without CORS or the removed `/api/cloud-proxy` hop.
+ *
+ * Unlike the previous git-changes-based approach, this returns unchanged
+ * tracked files too, so a conversation attached to a large existing repo shows
+ * the whole tree β€” matching the local-backend experience. Paths come back
+ * relative to the working dir (e.g. `src/index.html`).
*/
function useCloudWorkspaceFiles(enabled: boolean): WorkspaceFilesResult {
- const gitChanges = useUnifiedGetGitChanges();
-
- const data = useMemo(() => {
- if (!enabled) return undefined;
- const paths = gitChanges.data
- .filter((change) => change.status !== "D")
- .map((change) => change.path);
- return Array.from(new Set(paths)).slice(0, MAX_FILES);
- }, [enabled, gitChanges.data]);
-
- return {
- data: enabled ? data : undefined,
- isLoading: enabled ? gitChanges.isLoading : false,
- };
+ // Source the id from the route (like the diff/commits cloud hooks), NOT from
+ // `useActiveConversation().data.id`: the cloud API listing call only needs
+ // the id, and gating on the batch-get query's data would keep the query
+ // disabled β€” and never fire β€” whenever that data is null or still loading.
+ const { conversationId } = useOptionalConversationId();
+ const { data: conversation } = useActiveConversation();
+ const runtimeIsReady = useRuntimeIsReady();
+
+ const selectedRepository = conversation?.selected_repository;
+ const workingDir = conversation?.workspace?.working_dir?.trim();
+
+ // Anchor against an absolute workspace path the same way the diff view and
+ // single-file read do (`getGitPath` defaults to a relative convention; the
+ // cloud runtime needs an absolute path).
+ const gitPath = getGitPath(selectedRepository, workingDir);
+ const absolutePath = gitPath.startsWith("/") ? gitPath : `/${gitPath}`;
+
+ const query = useQuery<string[]>({
+ queryKey: ["workspace-files-cloud", conversationId, absolutePath],
+ queryFn: async () => {
+ const files = await listCloudConversationFiles(
+ conversationId!,
+ absolutePath,
+ );
+ const normalized = files.map(normalizePath).filter(Boolean);
+ return Array.from(new Set(normalized)).slice(0, MAX_FILES);
+ },
+ enabled: enabled && runtimeIsReady && !!conversationId,
+ retry: false,
+ staleTime: 1000 * 30,
+ gcTime: 1000 * 60 * 5,
+ meta: { disableToast: true },
+ });
+
+ return { data: query.data, isLoading: query.isLoading };
}
/**
* Lists the files shown in the Files tab for the active conversation.
*
- * Local backends enumerate the full workspace tree via bash `find`. Cloud
- * backends derive the list from git changes (see `useCloudWorkspaceFiles`
- * for the rationale and its limitation), because the cloud API exposes no
- * bash-exec or file-listing endpoint.
+ * Both backends enumerate the full workspace tree. Local backends run bash
+ * `find` directly against the agent-server; cloud backends call the cloud
+ * API's first-class file-listing endpoint, which runs the same `find`
+ * server-side on the conversation's runtime (see `useCloudWorkspaceFiles`).
+ *
+ * Cloud detection reads the backend-registry store (via `useSyncExternalStore`)
+ * rather than the `ActiveBackendProvider` context. The transport layer that
+ * actually issues the requests β€” `executeCommand`, `getGitChanges`, the cloud
+ * file-read β€” all branch on the *store* (`getActiveBackend()`), so the Files
+ * tab must use the same source. Reading the context here can disagree with the
+ * store (its `useActiveBackend` fallback synthesizes a *local* backend when the
+ * provider isn't in scope), which would run the local bash path against a cloud
+ * backend: `executeCommand` then POSTs to the removed `/api/cloud-proxy` (405)
+ * and the cloud `/files` call never fires.
*/
export function useWorkspaceFiles(): WorkspaceFilesResult {
- const { backend } = useActiveBackend();
- const isCloud = backend.kind === "cloud";
+ const snapshot = useSyncExternalStore(
+ subscribeActiveBackend,
+ getSnapshot,
+ getSnapshot,
+ );
+ const isCloud = snapshot.active.backend.kind === "cloud";
const local = useLocalWorkspaceFiles(!isCloud);
const cloud = useCloudWorkspaceFiles(isCloud);