π OpenHands: AI-Driven Development
fix(frontend): stop frontend bash probes on cloud runtimes (#761)
Hiep Le0d3783b422cf
diff --git a/__tests__/hooks/query/use-has-git-commits.test.tsx b/__tests__/hooks/query/use-has-git-commits.test.tsxnew file mode 100644index 0000000000..95a551aa03--- /dev/null+++ b/__tests__/hooks/query/use-has-git-commits.test.tsx@@ -0,0 +1,117 @@+import React from "react";+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import AgentServerRuntimeService from "#/api/runtime-service/agent-server-runtime-service";+import { useHasGitCommits } from "#/hooks/query/use-has-git-commits";++const useActiveBackendMock = vi.fn();+vi.mock("#/contexts/active-backend-context", () => ({+ useActiveBackend: () => useActiveBackendMock(),+}));++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(),+}));++const executeCommandSpy = vi.spyOn(AgentServerRuntimeService, "executeCommand");++function makeWrapper() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return function HasGitCommitsTestWrapper({+ children,+ }: {+ children: React.ReactNode;+ }) {+ return (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ };+}++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,+});++const conversation = {+ id: "conv-1",+ conversation_url: "https://runtime.example.com/api/conversations/conv-1",+ session_api_key: "session-key",+ workspace: { working_dir: "/workspace/project" },+};++describe("useHasGitCommits", () => {+ beforeEach(() => {+ useActiveBackendMock.mockReset();+ useActiveConversationMock.mockReset();+ useRuntimeIsReadyMock.mockReset();+ executeCommandSpy.mockReset();++ useRuntimeIsReadyMock.mockReturnValue(true);+ useActiveConversationMock.mockReturnValue({ data: conversation });+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("does not call executeCommand on a cloud backend", async () => {+ // Arrange+ useActiveBackendMock.mockReturnValue(makeBackend("cloud"));++ // Act+ const { result } = renderHook(() => useHasGitCommits(), {+ wrapper: makeWrapper(),+ });++ // Assert: probe stays disabled; hasCommits remains null.+ await new Promise((resolve) => {+ setTimeout(resolve, 20);+ });+ expect(executeCommandSpy).not.toHaveBeenCalled();+ expect(result.current.hasCommits).toBeNull();+ });++ it("probes HEAD via executeCommand on a local backend and returns true when the repo has commits", async () => {+ // Arrange+ useActiveBackendMock.mockReturnValue(makeBackend("local"));+ executeCommandSpy.mockResolvedValue({+ exit_code: 0,+ stdout: "abcdef0\n",+ stderr: "",+ });++ // Act+ const { result } = renderHook(() => useHasGitCommits(), {+ wrapper: makeWrapper(),+ });++ // Assert+ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(executeCommandSpy).toHaveBeenCalledWith(+ conversation.conversation_url,+ conversation.session_api_key,+ "git rev-parse --verify HEAD",+ "/workspace/project",+ 10,+ );+ expect(result.current.hasCommits).toBe(true);+ });+});diff --git a/__tests__/hooks/query/use-local-git-info.test.tsx b/__tests__/hooks/query/use-local-git-info.test.tsxnew file mode 100644index 0000000000..6447278d88--- /dev/null+++ b/__tests__/hooks/query/use-local-git-info.test.tsx@@ -0,0 +1,154 @@+import React from "react";+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useLocalGitInfo } from "#/hooks/query/use-local-git-info";++const useActiveBackendMock = vi.fn();+vi.mock("#/contexts/active-backend-context", () => ({+ useActiveBackend: () => useActiveBackendMock(),+}));++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(),+}));++const runCommandMock = vi.fn();+const useBashCommandRunnerMock = vi.fn();+vi.mock("#/hooks/use-bash-command-runner", () => ({+ useBashCommandRunner: (+ conversationUrl: string | null | undefined,+ sessionApiKey: string | null | undefined,+ enabled: boolean,+ ) => useBashCommandRunnerMock(conversationUrl, sessionApiKey, enabled),+}));++function makeWrapper() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return function LocalGitInfoTestWrapper({+ children,+ }: {+ children: React.ReactNode;+ }) {+ return (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+ };+}++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,+});++const conversationWithoutRepo = {+ id: "conv-1",+ conversation_url: "https://runtime.example.com/api/conversations/conv-1",+ session_api_key: "session-key",+ workspace: { working_dir: "/workspace/project" },+ selected_repository: null,+ git_provider: null,+ selected_branch: null,+};++describe("useLocalGitInfo", () => {+ beforeEach(() => {+ useActiveBackendMock.mockReset();+ useActiveConversationMock.mockReset();+ useRuntimeIsReadyMock.mockReset();+ runCommandMock.mockReset();+ useBashCommandRunnerMock.mockReset();+ useBashCommandRunnerMock.mockImplementation(() => runCommandMock);++ useRuntimeIsReadyMock.mockReturnValue(true);+ useActiveConversationMock.mockReturnValue({+ data: conversationWithoutRepo,+ });+ runCommandMock.mockResolvedValue({+ exit_code: 0,+ stdout: "[email protected]:acme/widgets.git\n",+ stderr: "",+ });+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("does not call the bash runner on a cloud backend even when conversation metadata is incomplete", async () => {+ // Arrange+ useActiveBackendMock.mockReturnValue(makeBackend("cloud"));++ // Act+ const { result } = renderHook(() => useLocalGitInfo(), {+ wrapper: makeWrapper(),+ });++ // Assert: query stays disabled (no fetch, no data); bash endpoint not driven.+ await new Promise((resolve) => {+ setTimeout(resolve, 20);+ });+ expect(result.current.fetchStatus).toBe("idle");+ expect(runCommandMock).not.toHaveBeenCalled();+ // The bash command runner should be created in a disabled state on cloud.+ expect(useBashCommandRunnerMock).toHaveBeenCalledWith(+ conversationWithoutRepo.conversation_url,+ conversationWithoutRepo.session_api_key,+ false,+ );+ });++ it("probes git metadata via the bash runner on a local backend when conversation metadata is incomplete", async () => {+ // Arrange+ useActiveBackendMock.mockReturnValue(makeBackend("local"));+ runCommandMock+ .mockResolvedValueOnce({+ exit_code: 0,+ stdout: "[email protected]:acme/widgets.git\n",+ stderr: "",+ })+ .mockResolvedValueOnce({+ exit_code: 0,+ stdout: "main\n",+ stderr: "",+ });++ // Act+ const { result } = renderHook(() => useLocalGitInfo(), {+ wrapper: makeWrapper(),+ });++ // Assert+ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(useBashCommandRunnerMock).toHaveBeenCalledWith(+ conversationWithoutRepo.conversation_url,+ conversationWithoutRepo.session_api_key,+ true,+ );+ expect(runCommandMock).toHaveBeenCalledWith(+ "git remote get-url origin",+ "/workspace/project",+ 10,+ );+ expect(result.current.data).toMatchObject({+ repository: "acme/widgets",+ branch: "main",+ });+ });+});diff --git a/src/hooks/query/use-has-git-commits.ts b/src/hooks/query/use-has-git-commits.tsindex 6a42e2a044..0400369a89 100644--- a/src/hooks/query/use-has-git-commits.ts+++ b/src/hooks/query/use-has-git-commits.ts@@ -1,6 +1,7 @@import { useQuery } from "@tanstack/react-query";import AgentServerRuntimeService from "#/api/runtime-service/agent-server-runtime-service";+import { useActiveBackend } from "#/contexts/active-backend-context";import { useActiveConversation } from "#/hooks/query/use-active-conversation";import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";@@ -8,6 +9,12 @@ import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";* Probes whether the conversation's working-directory git repository has* at least one commit reachable from HEAD.*+ * Local-only by design: we deliberately avoid driving+ * `/api/bash/execute_bash_command` from the frontend on cloud backends.+ * On cloud, `hasCommits` stays `null` and the Files tab keeps its+ * optimistic diff-view default β fine in practice since cloud+ * conversations almost always have an attached repo with commits.+ ** Used by the Files tab to decide whether the diff view is a sensible* default: an attached source (repo or local workspace) with no commits* β e.g. a brand-new empty GitHub repo, a freshly `git init`-ed@@ -23,6 +30,8 @@ export function useHasGitCommits(options?: { enabled?: boolean }): {} {const { data: conversation } = useActiveConversation();const runtimeIsReady = useRuntimeIsReady();+ const { backend } = useActiveBackend();+ const isLocalBackend = backend.kind === "local";const conversationId = conversation?.id;const conversationUrl = conversation?.conversation_url;@@ -31,6 +40,7 @@ export function useHasGitCommits(options?: { enabled?: boolean }): {const enabled =(options?.enabled ?? true) &&+ isLocalBackend &&runtimeIsReady &&!!conversationId &&!!workingDir;diff --git a/src/hooks/query/use-local-git-info.ts b/src/hooks/query/use-local-git-info.tsindex f7657c644f..d56b90a3cf 100644--- a/src/hooks/query/use-local-git-info.ts+++ b/src/hooks/query/use-local-git-info.ts@@ -3,6 +3,7 @@ import { useRef } from "react";import type { CommandResult } from "#/api/runtime-service/agent-server-runtime-service";import { getAgentServerWorkingDir } from "#/api/agent-server-config";+import { useActiveBackend } from "#/contexts/active-backend-context";import { useActiveConversation } from "#/hooks/query/use-active-conversation";import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";import { useBashCommandRunner } from "#/hooks/use-bash-command-runner";@@ -83,25 +84,29 @@ async function probeNestedRepoInDir(}/**- * Probe git metadata directly from the workspace checkout via the agent- * server's bash-events WebSocket (`git remote get-url origin`,+ * Probe git metadata for a **local** backend's workspace checkout by+ * shelling out via the agent server (`git remote get-url origin`,* `git rev-parse --abbrev-ref HEAD`).*- * We intentionally keep this probe enabled until the active conversation has- * a complete repo tuple (`selected_repository`, `git_provider`,- * `selected_branch`) so the control bar can recover from partial metadata- * hydration after connect/clone flows.+ * Local-only by design. On cloud backends the conversation metadata+ * (`selected_repository`, `git_provider`, `selected_branch`) is the+ * source of truth, and probing via `/api/bash/execute_bash_command`+ * would (a) leak the user's local `getAgentServerWorkingDir()` path to+ * the cloud runtime when `workspace.working_dir` is missing, and+ * (b) hit a bash endpoint we don't want the frontend driving on cloud.*- * Commands are executed over a persistent WebSocket connection- * (`/sockets/bash-events`) rather than individual REST calls, which avoids- * the per-request HTTP overhead of the previous polling approach.+ * On local, we keep the probe enabled until the active conversation+ * has a complete repo tuple so the control bar can recover from+ * partial metadata hydration after connect/clone flows.*- * Returns `null` fields when the working dir is not a git checkout β callers- * should treat that the same as "no repo detected".+ * Returns `null` fields when the working dir is not a git checkout β+ * callers should treat that the same as "no repo detected".*/export const useLocalGitInfo = () => {const { data: conversation } = useActiveConversation();const runtimeIsReady = useRuntimeIsReady();+ const { backend } = useActiveBackend();+ const isLocalBackend = backend.kind === "local";const conversationId = conversation?.id;const conversationUrl = conversation?.conversation_url;@@ -113,6 +118,7 @@ export const useLocalGitInfo = () => {const hasConversationBranch = !!conversation?.selected_branch;const queryEnabled =+ isLocalBackend &&runtimeIsReady &&!!conversationId &&(!hasConversationRepo ||